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(facade): facade event memory usage optimize (#4616)
zhangw0cde43c83bee
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.tsindex c4a7c12a9d..059fb46064 100644--- a/examples/src/sheets/main.ts+++ b/examples/src/sheets/main.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { FUniver, LocaleType, LogLevel, Univer, UniverInstanceType, UserManagerService } from '@univerjs/core';+import { FUniver, ILogService, LocaleType, LogLevel, Univer, UniverInstanceType, UserManagerService } from '@univerjs/core';import { UniverDebuggerPlugin } from '@univerjs/debugger';import { defaultTheme } from '@univerjs/design';import { UniverDocsPlugin } from '@univerjs/docs';@@ -174,6 +174,7 @@ declare global {createNewInstance?: typeof createNewInstance;}}+const logService = window.univer!.__getInjector().get(ILogService);window.univerAPI?.addEvent(window.univerAPI.Event.BeforeSheetEditStart, (params) => {const { row, column } = params;@@ -181,3 +182,7 @@ window.univerAPI?.addEvent(window.univerAPI.Event.BeforeSheetEditStart, (params)params.cancel = true;}});++window.univerAPI?.addEvent(window.univerAPI.Event.ActiveSheetChanged, (params) => {+ logService.log('===active sheet changed', params);+});diff --git a/packages/core/src/facade/f-event-registry.ts b/packages/core/src/facade/f-event-registry.tsnew file mode 100644index 0000000000..c8cdef0ce8--- /dev/null+++ b/packages/core/src/facade/f-event-registry.ts@@ -0,0 +1,106 @@+/**+ * 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 { Subscription } from 'rxjs';+import type { IDisposable } from '../common/di';+import type { IEventParamConfig } from './f-event';+import { Registry } from '../common/registry';+import { toDisposable } from '../shared';++export class FEventRegistry {+ protected _eventRegistry: Map<string, Registry<(param: any) => void>> = new Map();+ protected _eventHandlerMap = new Map<string, Set<() => IDisposable | Subscription>>();+ protected _eventHandlerRegisted = new Map<string, Map<() => IDisposable | Subscription, IDisposable>>();++ protected _ensureEventRegistry(event: string) {+ if (!this._eventRegistry.has(event)) {+ this._eventRegistry.set(event, new Registry());+ }++ return this._eventRegistry.get(event)!;+ }++ registerEventHandler(event: string, handler: () => IDisposable | Subscription) {+ const current = this._eventHandlerMap.get(event);+ if (current) {+ current.add(handler);+ } else {+ this._eventHandlerMap.set(event, new Set([handler]));+ }++ return toDisposable(() => {+ this._eventHandlerMap.get(event)?.delete(handler);+ this._eventHandlerRegisted.get(event)?.get(handler)?.dispose();+ this._eventHandlerRegisted.get(event)?.delete(handler);+ });+ }++ removeEvent<T extends keyof IEventParamConfig>(event: T, callback: (params: IEventParamConfig[T]) => void) {+ const map = this._ensureEventRegistry(event);+ map.delete(callback);++ if (map.getData().length === 0) {+ const disposable = this._eventHandlerRegisted.get(event);+ disposable?.forEach((d) => d.dispose());+ this._eventHandlerRegisted.delete(event);+ }+ }++ /**+ * Add an event listener+ * @param {string} event key of event+ * @param {(params: IEventParamConfig[typeof event]) => void} callback callback when event triggered+ * @returns {Disposable} The Disposable instance, for remove the listener+ * @example+ * ```ts+ * univerAPI.addEvent(univerAPI.event.UnitCreated, (params) => {+ * console.log('unit created', params);+ * });+ * ```+ */+ addEvent<T extends keyof IEventParamConfig>(event: T, callback: (params: IEventParamConfig[T]) => void) {+ this._ensureEventRegistry(event).add(callback);+ let current = this._eventHandlerRegisted.get(event);+ const handlers = this._eventHandlerMap.get(event);+ if (!current) {+ current = new Map();+ this._eventHandlerRegisted.set(event, current);+ handlers?.forEach((handler) => {+ current?.set(handler, toDisposable(handler()));+ });+ }++ return toDisposable(() => this.removeEvent(event, callback));+ }++ /**+ * Fire an event, used in internal only.+ * @param {string} event key of event+ * @param {any} params params of event+ * @returns {boolean} should cancel+ * @example+ * ```ts+ * this.fireEvent(univerAPI.event.UnitCreated, params);+ * ```+ */+ fireEvent<T extends keyof IEventParamConfig>(event: T, params: IEventParamConfig[T]) {+ this._eventRegistry.get(event)?.getData().forEach((callback) => {+ callback(params);+ });++ return params.cancel;+ }+}diff --git a/packages/core/src/facade/f-univer.ts b/packages/core/src/facade/f-univer.tsindex ca43e6ac62..c41354ee3c 100644--- a/packages/core/src/facade/f-univer.ts+++ b/packages/core/src/facade/f-univer.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import type { Subscription } from 'rxjs';import type { IDisposable } from '../common/di';import type { DocumentDataModel } from '../docs';import type { CommandListener, IExecutionOptions } from '../services/command/command.service';@@ -22,31 +23,40 @@ import type { IDocumentData, IParagraphStyle, ITextDecoration, ITextStyle } fromimport type { ICommandEvent, IEventParamConfig } from './f-event';import { Inject, Injector } from '../common/di';import { CanceledError } from '../common/error';-import { Registry } from '../common/registry';import { UniverInstanceType } from '../common/unit';import { ParagraphStyleBuilder, ParagraphStyleValue, RichTextBuilder, RichTextValue, TextDecorationBuilder, TextStyleBuilder, TextStyleValue } from '../docs/data-model/rich-text-builder';import { ICommandService } from '../services/command/command.service';import { IUniverInstanceService } from '../services/instance/instance.service';import { LifecycleService } from '../services/lifecycle/lifecycle.service';import { RedoCommand, UndoCommand } from '../services/undoredo/undoredo.service';-import { ColorBuilder, toDisposable } from '../shared';+import { ColorBuilder, Disposable, toDisposable } from '../shared';import { Univer } from '../univer';-import { FBaseInitialable } from './f-base';import { FBlob } from './f-blob';import { FDoc } from './f-doc';import { FEnum } from './f-enum';import { FEventName } from './f-event';+import { FEventRegistry } from './f-event-registry';import { FHooks } from './f-hooks';import { FUserManager } from './f-usermanager';import { FUtil } from './f-util';+/**+ * @ignore+ */+const InitializerSymbol = Symbol('initializers');++/**+ * @ignore+ */+type Initializers = Array<(injector: Injector) => void>;+/*** The root Facade API object to interact with Univer. Please use `newAPI` static method* to create a new instance.** @hideconstructor*/-export class FUniver extends FBaseInitialable {+export class FUniver extends Disposable {/*** Create an FUniver instance, if the injector is not provided, it will create a new Univer instance.* @static@@ -58,115 +68,192 @@ export class FUniver extends FBaseInitialable {return injector.createInstance(FUniver);}- protected _eventRegistry: Map<string, Registry<(param: any) => void>> = new Map();+ declare private [InitializerSymbol]: Initializers | undefined;- protected _ensureEventRegistry(event: string) {- if (!this._eventRegistry.has(event)) {- this._eventRegistry.set(event, new Registry());- }+ /**+ * @ignore+ */+ _initialize(injector: Injector) { }++ /**+ * @ignore+ */+ static extend(source: any): void {+ Object.getOwnPropertyNames(source.prototype).forEach((name) => {+ if (name === '_initialize') {+ let initializers = this.prototype[InitializerSymbol];+ if (!initializers) {+ initializers = [];+ this.prototype[InitializerSymbol] = initializers;+ }++ initializers.push(source.prototype._initialize);+ } else if (name !== 'constructor') {+ // @ts-ignore+ this.prototype[name] = source.prototype[name];+ }+ });- return this._eventRegistry.get(event)!;+ Object.getOwnPropertyNames(source).forEach((name) => {+ if (name !== 'prototype' && name !== 'name' && name !== 'length') {+ // @ts-ignore+ this[name] = source[name];+ }+ });}+ protected _eventRegistry = new FEventRegistry();++ protected registerEventHandler = (event: string, handler: () => IDisposable | Subscription) => {+ return this._eventRegistry.registerEventHandler(event, handler);+ };+constructor(- @Inject(Injector) protected override readonly _injector: Injector,+ @Inject(Injector) protected readonly _injector: Injector,@ICommandService protected readonly _commandService: ICommandService,@IUniverInstanceService protected readonly _univerInstanceService: IUniverInstanceService,@Inject(LifecycleService) protected readonly _lifecycleService: LifecycleService) {- super(_injector);+ super();++ this.registerEventHandler(+ this.Event.LifeCycleChanged,+ () =>+ toDisposable(+ this._lifecycleService.lifecycle$.subscribe((stage) => {+ this.fireEvent(this.Event.LifeCycleChanged, { stage });+ })+ )+ );++ this._initUnitEvent(this._injector);+ this._initBeforeCommandEvent(this._injector);+ this._initCommandEvent(this._injector);+ this._injector.onDispose(() => {+ this.dispose();+ });- this.disposeWithMe(- this._lifecycleService.lifecycle$.subscribe((stage) => {- this.fireEvent(this.Event.LifeCycleChanged, { stage });+ const initializers = Object.getPrototypeOf(this)[InitializerSymbol];+ if (initializers) {+ const self = this;+ initializers.forEach(function (fn: (_injector: Injector) => void) {+ fn.apply(self, [_injector]);+ });+ }+ }++ private _initCommandEvent(injector: Injector): void {+ const commandService = injector.get(ICommandService);+ this.registerEventHandler(+ this.Event.Redo,+ () => commandService.onCommandExecuted((commandInfo) => {+ const { id, type: propType, params } = commandInfo;+ if (commandInfo.id === RedoCommand.id) {+ const type = propType!;+ const eventParams: ICommandEvent = { id, type, params };+ this.fireEvent(this.Event.Redo, eventParams);+ }}));- this.disposeWithMe(- this._commandService.beforeCommandExecuted((commandInfo) => {- if (- !this._eventRegistry.get(this.Event.BeforeRedo) &&- !this._eventRegistry.get(this.Event.BeforeUndo) &&- !this._eventRegistry.get(this.Event.BeforeCommandExecute)- ) {- return;- }+ this.registerEventHandler(+ this.Event.Undo,+ () => commandService.onCommandExecuted((commandInfo) => {const { id, type: propType, params } = commandInfo;- const type = propType!;- const eventParams: ICommandEvent = { id, type, params };- switch (commandInfo.id) {- case RedoCommand.id:- this.fireEvent(this.Event.BeforeRedo, eventParams);- break;- case UndoCommand.id:- this.fireEvent(this.Event.BeforeUndo, eventParams);- break;- default:- this.fireEvent(this.Event.BeforeCommandExecute, eventParams);- break;+ if (commandInfo.id === UndoCommand.id) {+ const type = propType!;+ const eventParams: ICommandEvent = { id, type, params };+ this.fireEvent(this.Event.Undo, eventParams);}+ })+ );- if (eventParams.cancel) {- throw new CanceledError();+ this.registerEventHandler(+ this.Event.CommandExecuted,+ () => commandService.onCommandExecuted((commandInfo) => {+ const { id, type: propType, params } = commandInfo;+ if (commandInfo.id !== RedoCommand.id && commandInfo.id !== UndoCommand.id) {+ const type = propType!;+ const eventParams: ICommandEvent = { id, type, params };+ this.fireEvent(this.Event.CommandExecuted, eventParams);}}));+ }++ private _initBeforeCommandEvent(injector: Injector): void {+ const commandService = injector.get(ICommandService);- this.disposeWithMe(- this._commandService.onCommandExecuted((commandInfo) => {- if (- !this._eventRegistry.get(this.Event.Redo) &&- !this._eventRegistry.get(this.Event.Undo) &&- !this._eventRegistry.get(this.Event.CommandExecuted)- ) {- return;+ this.registerEventHandler(+ this.Event.BeforeRedo,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ const { id, type: propType, params } = commandInfo;+ if (commandInfo.id === RedoCommand.id) {+ const type = propType!;+ const eventParams: ICommandEvent = { id, type, params };+ this.fireEvent(this.Event.BeforeRedo, eventParams);++ if (eventParams.cancel) {+ throw new CanceledError();+ }}+ })+ );++ this.registerEventHandler(+ this.Event.BeforeUndo,+ () => commandService.beforeCommandExecuted((commandInfo) => {const { id, type: propType, params } = commandInfo;- const type = propType!;- const eventParams: ICommandEvent = { id, type, params };- switch (commandInfo.id) {- case RedoCommand.id:- this.fireEvent(this.Event.Redo, eventParams);- break;- case UndoCommand.id:- this.fireEvent(this.Event.Undo, eventParams);- break;- default:- this.fireEvent(this.Event.CommandExecuted, eventParams);- break;+ if (commandInfo.id === UndoCommand.id) {+ const type = propType!;+ const eventParams: ICommandEvent = { id, type, params };+ this.fireEvent(this.Event.BeforeUndo, eventParams);++ if (eventParams.cancel) {+ throw new CanceledError();+ }}}));- this._initUnitEvent(this._injector);- this._injector.onDispose(() => {- this.dispose();- });+ this.registerEventHandler(+ this.Event.BeforeCommandExecute,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ const { id, type: propType, params } = commandInfo;+ if (commandInfo.id !== RedoCommand.id && commandInfo.id !== UndoCommand.id) {+ const type = propType!;+ const eventParams: ICommandEvent = { id, type, params };+ this.fireEvent(this.Event.BeforeCommandExecute, eventParams);++ if (eventParams.cancel) {+ throw new CanceledError();+ }+ }+ })+ );}private _initUnitEvent(injector: Injector): void {const univerInstanceService = injector.get(IUniverInstanceService);- this.disposeWithMe(- univerInstanceService.unitDisposed$.subscribe((unit) => {- if (!this._eventRegistry.get(this.Event.DocDisposed)) return;+ this.registerEventHandler(+ this.Event.DocDisposed,+ () => univerInstanceService.unitDisposed$.subscribe((unit) => {if (unit.type === UniverInstanceType.UNIVER_DOC) {this.fireEvent(this.Event.DocDisposed,{unitId: unit.getUnitId(),unitType: unit.type,snapshot: unit.getSnapshot() as IDocumentData,-});}}));- this.disposeWithMe(- univerInstanceService.unitAdded$.subscribe((unit) => {- if (!this._eventRegistry.get(this.Event.DocCreated)) return;-+ this.registerEventHandler(+ this.Event.DocCreated,+ () => univerInstanceService.unitAdded$.subscribe((unit) => {if (unit.type === UniverInstanceType.UNIVER_DOC) {const doc = unit as DocumentDataModel;const docUnit = injector.createInstance(FDoc, doc);@@ -183,10 +270,6 @@ export class FUniver extends FBaseInitialable {);}- protected _eventListend(key: string) {- return this._eventRegistry.get(key);- }-/*** Dispose the UniverSheet by the `unitId`. The UniverSheet would be unload from the application.* @param unitId The unit id of the UniverSheet.@@ -309,8 +392,7 @@ export class FUniver extends FBaseInitialable {* ```*/addEvent<T extends keyof IEventParamConfig>(event: T, callback: (params: IEventParamConfig[T]) => void) {- this._ensureEventRegistry(event).add(callback);- return toDisposable(() => this._ensureEventRegistry(event).delete(callback));+ return this._eventRegistry.addEvent(event, callback);}/**@@ -324,21 +406,7 @@ export class FUniver extends FBaseInitialable {* ```*/protected fireEvent<T extends keyof IEventParamConfig>(event: T, params: IEventParamConfig[T]) {- this._eventRegistry.get(event)?.getData().forEach((callback) => {- callback(params);- });-- return params.cancel;- }-- /**- * Get the callback map corresponding to the event- * @param {keyof IEventParamConfig} event- * @returns {number} The number of callbacks- */- protected hasEventCallback(event: keyof IEventParamConfig): boolean {- const eventCallbackLens = this._eventRegistry.get(event)?.getData().length ?? 0;- return eventCallbackLens > 0;+ return this._eventRegistry.fireEvent(event, params);}getUserManager(): FUserManager {diff --git a/packages/sheets-crosshair-highlight/src/facade/f-univer.ts b/packages/sheets-crosshair-highlight/src/facade/f-univer.tsindex 82cb5dbf8b..b33abe32b5 100644--- a/packages/sheets-crosshair-highlight/src/facade/f-univer.ts+++ b/packages/sheets-crosshair-highlight/src/facade/f-univer.ts@@ -163,27 +163,33 @@ export class FUniverCrosshairHighlightMixin extends FUniver implements IFUniverCoverride _initialize(injector: Injector): void {const commandService = injector.get(ICommandService);- this.disposeWithMe(commandService.onCommandExecuted((commandInfo) => {- if (commandInfo.id === EnableCrosshairHighlightOperation.id || commandInfo.id === DisableCrosshairHighlightOperation.id) {- const activeSheet = this.getActiveSheet();- if (!activeSheet) return;- if (!this._eventListend(this.Event.CrosshairHighlightEnabledChanged)) return;- this.fireEvent(this.Event.CrosshairHighlightEnabledChanged, {- enabled: this.getCrosshairHighlightEnabled(),- ...activeSheet,- });- }-- if (commandInfo.id === SetCrosshairHighlightColorOperation.id) {- const activeSheet = this.getActiveSheet();- if (!activeSheet) return;- if (!this._eventListend(this.Event.CrosshairHighlightColorChanged)) return;- this.fireEvent(this.Event.CrosshairHighlightColorChanged, {- color: this.getCrosshairHighlightColor(),- ...activeSheet,- });- }- }));+ this.registerEventHandler(+ this.Event.CrosshairHighlightEnabledChanged,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === EnableCrosshairHighlightOperation.id || commandInfo.id === DisableCrosshairHighlightOperation.id) {+ const activeSheet = this.getActiveSheet();+ if (!activeSheet) return;+ this.fireEvent(this.Event.CrosshairHighlightEnabledChanged, {+ enabled: this.getCrosshairHighlightEnabled(),+ ...activeSheet,+ });+ }+ })+ );++ this.registerEventHandler(+ this.Event.CrosshairHighlightColorChanged,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetCrosshairHighlightColorOperation.id) {+ const activeSheet = this.getActiveSheet();+ if (!activeSheet) return;+ this.fireEvent(this.Event.CrosshairHighlightColorChanged, {+ color: this.getCrosshairHighlightColor(),+ ...activeSheet,+ });+ }+ })+ );}override setCrosshairHighlightEnabled(enabled: boolean): FUniver {diff --git a/packages/sheets-data-validation/src/facade/f-univer.ts b/packages/sheets-data-validation/src/facade/f-univer.tsindex 4f5b6c7601..03f50432a9 100644--- a/packages/sheets-data-validation/src/facade/f-univer.ts+++ b/packages/sheets-data-validation/src/facade/f-univer.ts@@ -82,50 +82,57 @@ export class FUnvierDataValidationMixin extends FUniver implements IFUnvierDataVconst sheetDataValidationModel = injector.get(SheetDataValidationModel);const commadnService = injector.get(ICommandService);- this.disposeWithMe(sheetDataValidationModel.ruleChange$.subscribe((ruleChange) => {- const { unitId, subUnitId, rule, oldRule, type } = ruleChange;- const target = this.getSheetTarget(unitId, subUnitId);- if (!target) {- return;- }- const { workbook, worksheet } = target;+ this.registerEventHandler(+ this.Event.SheetDataValidationChanged,+ () => sheetDataValidationModel.ruleChange$.subscribe((ruleChange) => {+ const { unitId, subUnitId, rule, oldRule, type } = ruleChange;+ const target = this.getSheetTarget(unitId, subUnitId);+ if (!target) {+ return;+ }+ const { workbook, worksheet } = target;- const fRule = new FDataValidation(rule, worksheet.getSheet(), this._injector);- this.fireEvent(this.Event.SheetDataValidationChanged, {- origin: ruleChange,- worksheet,- workbook,- changeType: type,- oldRule,- rule: fRule,- });- }));+ const fRule = new FDataValidation(rule, worksheet.getSheet(), this._injector);+ this.fireEvent(this.Event.SheetDataValidationChanged, {+ origin: ruleChange,+ worksheet,+ workbook,+ changeType: type,+ oldRule,+ rule: fRule,+ });+ })+ );- this.disposeWithMe(sheetDataValidationModel.validStatusChange$.subscribe((statusChange) => {- const { unitId, subUnitId, ruleId, status, row, col } = statusChange;- const target = this.getSheetTarget(unitId, subUnitId);- if (!target) {- return;- }- const { workbook, worksheet } = target;- const rule = worksheet.getDataValidation(ruleId);- if (!rule) {- return;- }- this.fireEvent(this.Event.SheetDataValidatorStatusChanged, {- workbook,- worksheet,- row,- column: col,- rule,- status,- });- }));+ this.registerEventHandler(+ this.Event.SheetDataValidatorStatusChanged,+ () => sheetDataValidationModel.validStatusChange$.subscribe((statusChange) => {+ const { unitId, subUnitId, ruleId, status, row, col } = statusChange;+ const target = this.getSheetTarget(unitId, subUnitId);+ if (!target) {+ return;+ }+ const { workbook, worksheet } = target;+ const rule = worksheet.getDataValidation(ruleId);+ if (!rule) {+ return;+ }+ this.fireEvent(this.Event.SheetDataValidatorStatusChanged, {+ workbook,+ worksheet,+ row,+ column: col,+ rule,+ status,+ });+ })+ );- // eslint-disable-next-line max-lines-per-function, complexity- this.disposeWithMe(commadnService.beforeCommandExecuted((commandInfo) => {- switch (commandInfo.id) {- case AddSheetDataValidationCommand.id: {+ // Register handlers for before command events+ this.registerEventHandler(+ this.Event.BeforeSheetDataValidationAdd,+ () => commadnService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === AddSheetDataValidationCommand.id) {const params = commandInfo.params as IAddSheetDataValidationCommandParams;const target = this.getSheetTarget(params.unitId, params.subUnitId);if (!target) {@@ -141,10 +148,14 @@ export class FUnvierDataValidationMixin extends FUniver implements IFUnvierDataVif (eventParams.cancel) {throw new CanceledError();}- break;}+ })+ );- case UpdateSheetDataValidationSettingCommand.id: {+ this.registerEventHandler(+ this.Event.BeforeSheetDataValidationCriteriaUpdate,+ () => commadnService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === UpdateSheetDataValidationSettingCommand.id) {const params = commandInfo.params as IUpdateSheetDataValidationSettingCommandParams;const target = this.getSheetTarget(params.unitId, params.subUnitId);if (!target) {@@ -167,10 +178,14 @@ export class FUnvierDataValidationMixin extends FUniver implements IFUnvierDataVif (eventParams.cancel) {throw new CanceledError();}- break;}+ })+ );- case UpdateSheetDataValidationRangeCommand.id: {+ this.registerEventHandler(+ this.Event.BeforeSheetDataValidationRangeUpdate,+ () => commadnService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === UpdateSheetDataValidationRangeCommand.id) {const params = commandInfo.params as IUpdateSheetDataValidationRangeCommandParams;const target = this.getSheetTarget(params.unitId, params.subUnitId);if (!target) {@@ -192,10 +207,14 @@ export class FUnvierDataValidationMixin extends FUniver implements IFUnvierDataVif (eventParams.cancel) {throw new CanceledError();}- break;}+ })+ );- case UpdateSheetDataValidationOptionsCommand.id: {+ this.registerEventHandler(+ this.Event.BeforeSheetDataValidationOptionsUpdate,+ () => commadnService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === UpdateSheetDataValidationOptionsCommand.id) {const params = commandInfo.params as IUpdateSheetDataValidationOptionsCommandParams;const target = this.getSheetTarget(params.unitId, params.subUnitId);if (!target) {@@ -217,10 +236,14 @@ export class FUnvierDataValidationMixin extends FUniver implements IFUnvierDataVif (eventParams.cancel) {throw new CanceledError();}- break;}+ })+ );- case RemoveSheetDataValidationCommand.id: {+ this.registerEventHandler(+ this.Event.BeforeSheetDataValidationDelete,+ () => commadnService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === RemoveSheetDataValidationCommand.id) {const params = commandInfo.params as IRemoveSheetDataValidationCommandParams;const target = this.getSheetTarget(params.unitId, params.subUnitId);if (!target) {@@ -241,10 +264,14 @@ export class FUnvierDataValidationMixin extends FUniver implements IFUnvierDataVif (eventParams.cancel) {throw new CanceledError();}- break;}+ })+ );- case RemoveSheetAllDataValidationCommand.id: {+ this.registerEventHandler(+ this.Event.BeforeSheetDataValidationDeleteAll,+ () => commadnService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === RemoveSheetAllDataValidationCommand.id) {const params = commandInfo.params as IRemoveSheetAllDataValidationCommandParams;const target = this.getSheetTarget(params.unitId, params.subUnitId);if (!target) {@@ -260,13 +287,9 @@ export class FUnvierDataValidationMixin extends FUniver implements IFUnvierDataVif (eventParams.cancel) {throw new CanceledError();}- break;}-- default:- break;- }- }));+ })+ );}}diff --git a/packages/sheets-drawing-ui/src/facade/f-univer.ts b/packages/sheets-drawing-ui/src/facade/f-univer.tsindex 38cf486ad3..1208d1abbe 100644--- a/packages/sheets-drawing-ui/src/facade/f-univer.ts+++ b/packages/sheets-drawing-ui/src/facade/f-univer.ts@@ -52,247 +52,223 @@ export class FUniverDrawingMixin extends FUniver {/*** @ignore*/+ // eslint-disable-next-line max-lines-per-functionoverride _initialize(injector: Injector): void {const commandService = injector.get(ICommandService);- this.disposeWithMe(commandService.beforeCommandExecuted((commandInfo) => {- switch (commandInfo.id) {- case InsertSheetDrawingCommand.id:- this._beforeOverGridImageInsert(commandInfo.params as IInsertDrawingCommandParams);- break;- case RemoveSheetDrawingCommand.id:- this._beforeOverGridImageRemove(commandInfo.params as IDeleteDrawingCommandParams);- break;- case SetSheetDrawingCommand.id:- this._beforeOverGridImageChange(commandInfo.params as ISetDrawingCommandParams);- break;- case SetDrawingSelectedOperation.id:- this._beforeOverGridImageSelect(commandInfo.params as IDrawingSearch[]);- break;- }- }));- this.disposeWithMe(commandService.onCommandExecuted((commandInfo) => {- switch (commandInfo.id) {- case InsertSheetDrawingCommand.id:- this._overGridImageInserted(commandInfo.params as IInsertDrawingCommandParams);- break;- case RemoveSheetDrawingCommand.id:- this._overGridImageRemoved(commandInfo.params as IDeleteDrawingCommandParams);- break;- case SetSheetDrawingCommand.id:- this._overGridImageChanged(commandInfo.params as ISetDrawingCommandParams);- break;- case SetDrawingSelectedOperation.id:- this._overGridImageSelected(commandInfo.params as IDrawingSearch[]);- break;- }- }));- }-- private _beforeOverGridImageInsert(params?: IInsertDrawingCommandParams): void {- if (!this.hasEventCallback(this.Event.BeforeOverGridImageInsert)) {- return;- }-- const workbook = this.getActiveWorkbook();- if (workbook == null || params == null) {- return;- }-- const { drawings } = params;-- const eventParams: IBeforeOverGridImageInsertParam = {- workbook,- insertImageParams: drawings as ISheetImage[],- };-- this.fireEvent(this.Event.BeforeOverGridImageInsert, eventParams);-- if (eventParams.cancel) {- throw new Error('Canceled by BeforeOverGridImageInsert event');- }- }-- private _overGridImageInserted(params?: IInsertDrawingCommandParams): void {- if (!this.hasEventCallback(this.Event.OverGridImageInserted)) {- return;- }-- const workbook = this.getActiveWorkbook();- if (workbook == null || params == null) {- return;- }-- const { drawings } = params;-- this.fireEvent(this.Event.OverGridImageInserted, {- workbook,- images: this._createFOverGridImage(drawings as ISheetImage[]),- });- }-- private _beforeOverGridImageRemove(params: IDeleteDrawingCommandParams): void {- if (!this.hasEventCallback(this.Event.BeforeOverGridImageRemove)) {- return;- }-- const workbook = this.getActiveWorkbook();- if (workbook == null || params == null) {- return;- }-- const { drawings } = params;-- const drawingManagerService = this._injector.get(IDrawingManagerService);- const willRemoveDrawings = drawings.map((drawing) => {- return drawingManagerService.getDrawingByParam(drawing);- }) as ISheetImage[];-- const eventParams: IBeforeOverGridImageRemoveParam = {- workbook,- images: this._createFOverGridImage(willRemoveDrawings),- };-- this.fireEvent(this.Event.BeforeOverGridImageRemove, eventParams);-- if (eventParams.cancel) {- throw new Error('Canceled by BeforeOverGridImageRemove event');- }- }-- private _overGridImageRemoved(params: IDeleteDrawingCommandParams): void {- if (!this.hasEventCallback(this.Event.OverGridImageRemoved)) {- return;- }-- const workbook = this.getActiveWorkbook();- if (workbook == null || params == null) {- return;- }-- const { drawings } = params;-- this.fireEvent(this.Event.OverGridImageRemoved, {- workbook,- removeImageParams: drawings,- });- }-- private _beforeOverGridImageChange(params: ISetDrawingCommandParams): void {- if (!this.hasEventCallback(this.Event.BeforeOverGridImageChange)) {- return;- }-- const workbook = this.getActiveWorkbook();- if (workbook == null || params == null) {- return;- }-- const { drawings } = params;-- const drawingManagerService = this._injector.get(IDrawingManagerService);- const images: IBeforeOverGridImageChangeParamObject[] = [];- drawings.forEach((drawing) => {- const image = drawingManagerService.getDrawingByParam(drawing as IDrawingSearch) as ISheetImage;- if (image == null) {- return;- }-- images.push({- changeParam: drawing,- image: this._injector.createInstance(FOverGridImage, image),- });- });-- const eventParams: IBeforeOverGridImageChangeParam = {- workbook,- images,- };-- this.fireEvent(this.Event.BeforeOverGridImageChange, eventParams);-- if (eventParams.cancel) {- drawingManagerService.updateNotification(drawings as IDrawingSearch[]);- throw new Error('Canceled by BeforeOverGridImageChange event');- }- }-- private _overGridImageChanged(params: ISetDrawingCommandParams): void {- if (!this.hasEventCallback(this.Event.OverGridImageChanged)) {- return;- }-- const workbook = this.getActiveWorkbook();- if (workbook == null || params == null) {- return;- }-- const { drawings } = params;-- const drawingManagerService = this._injector.get(IDrawingManagerService);-- const images = drawings.map((drawing) => {- return this._injector.createInstance(FOverGridImage, drawingManagerService.getDrawingByParam(drawing as IDrawingSearch) as ISheetImage);- });-- this.fireEvent(this.Event.OverGridImageChanged, {- workbook,- images,- });- }-- private _beforeOverGridImageSelect(drawings: IDrawingSearch[]): void {- if (!this.hasEventCallback(this.Event.BeforeOverGridImageSelect)) {- return;- }-- const drawingManagerService = this._injector.get(IDrawingManagerService);-- const workbook = this.getActiveWorkbook();-- if (workbook == null) {- return;- }-- const oldSelectedDrawings = drawingManagerService.getFocusDrawings() as ISheetImage[];-- const selectedDrawings = drawings.map((drawing) => {- return drawingManagerService.getDrawingByParam(drawing);- }) as ISheetImage[];-- const eventParams: IBeforeOverGridImageSelectParam = {- workbook,- selectedImages: this._createFOverGridImage(selectedDrawings),- oldSelectedImages: this._createFOverGridImage(oldSelectedDrawings),- };-- this.fireEvent(this.Event.BeforeOverGridImageSelect, eventParams);-- if (eventParams.cancel) {- throw new Error('Canceled by BeforeOverGridImageSelect event');- }- }-- private _overGridImageSelected(drawings: IDrawingSearch[]): void {- if (!this.hasEventCallback(this.Event.OverGridImageSelected)) {- return;- }-- const workbook = this.getActiveWorkbook();- const drawingManagerService = this._injector.get(IDrawingManagerService);-- if (workbook == null) {- return;- }-- const selectedDrawings = drawings.map((drawing) => {- return drawingManagerService.getDrawingByParam(drawing);- }) as ISheetImage[];-- this.fireEvent(this.Event.OverGridImageSelected, {- workbook,- selectedImages: this._createFOverGridImage(selectedDrawings as ISheetImage[]),- });+ this.registerEventHandler(+ this.Event.BeforeOverGridImageInsert,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== InsertSheetDrawingCommand.id) return;++ const params = commandInfo.params as IInsertDrawingCommandParams;+ const workbook = this.getActiveWorkbook();+ if (workbook == null || params == null) {+ return;+ }++ const { drawings } = params;+ const eventParams: IBeforeOverGridImageInsertParam = {+ workbook,+ insertImageParams: drawings as ISheetImage[],+ };++ this.fireEvent(this.Event.BeforeOverGridImageInsert, eventParams);++ if (eventParams.cancel) {+ throw new Error('Canceled by BeforeOverGridImageInsert event');+ }+ })+ );++ this.registerEventHandler(+ this.Event.BeforeOverGridImageRemove,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== RemoveSheetDrawingCommand.id) return;++ const params = commandInfo.params as IDeleteDrawingCommandParams;+ const workbook = this.getActiveWorkbook();+ if (workbook == null || params == null) {+ return;+ }++ const drawingManagerService = injector.get(IDrawingManagerService);++ const { drawings } = params;+ const willRemoveDrawings = drawings.map((drawing) => {+ return drawingManagerService.getDrawingByParam(drawing);+ }) as ISheetImage[];++ const eventParams: IBeforeOverGridImageRemoveParam = {+ workbook,+ images: this._createFOverGridImage(willRemoveDrawings),+ };++ this.fireEvent(this.Event.BeforeOverGridImageRemove, eventParams);++ if (eventParams.cancel) {+ throw new Error('Canceled by BeforeOverGridImageRemove event');+ }+ })+ );++ this.registerEventHandler(+ this.Event.BeforeOverGridImageChange,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== SetSheetDrawingCommand.id) return;++ const params = commandInfo.params as ISetDrawingCommandParams;+ const workbook = this.getActiveWorkbook();+ if (workbook == null || params == null) {+ return;+ }++ const { drawings } = params;+ const drawingManagerService = injector.get(IDrawingManagerService);++ const images: IBeforeOverGridImageChangeParamObject[] = [];+ drawings.forEach((drawing) => {+ const image = drawingManagerService.getDrawingByParam(drawing as IDrawingSearch) as ISheetImage;+ if (image == null) {+ return;+ }++ images.push({+ changeParam: drawing,+ image: this._injector.createInstance(FOverGridImage, image),+ });+ });++ const eventParams: IBeforeOverGridImageChangeParam = {+ workbook,+ images,+ };++ this.fireEvent(this.Event.BeforeOverGridImageChange, eventParams);++ if (eventParams.cancel) {+ drawingManagerService.updateNotification(drawings as IDrawingSearch[]);+ throw new Error('Canceled by BeforeOverGridImageChange event');+ }+ })+ );++ this.registerEventHandler(+ this.Event.BeforeOverGridImageSelect,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== SetDrawingSelectedOperation.id) return;++ const drawings = commandInfo.params as IDrawingSearch[];+ const workbook = this.getActiveWorkbook();+ if (workbook == null) {+ return;+ }+ const drawingManagerService = injector.get(IDrawingManagerService);++ const oldSelectedDrawings = drawingManagerService.getFocusDrawings() as ISheetImage[];+ const selectedDrawings = drawings.map((drawing) => {+ return drawingManagerService.getDrawingByParam(drawing);+ }) as ISheetImage[];++ const eventParams: IBeforeOverGridImageSelectParam = {+ workbook,+ selectedImages: this._createFOverGridImage(selectedDrawings),+ oldSelectedImages: this._createFOverGridImage(oldSelectedDrawings),+ };++ this.fireEvent(this.Event.BeforeOverGridImageSelect, eventParams);++ if (eventParams.cancel) {+ throw new Error('Canceled by BeforeOverGridImageSelect event');+ }+ })+ );++ this.registerEventHandler(+ this.Event.OverGridImageInserted,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id !== InsertSheetDrawingCommand.id) return;++ const params = commandInfo.params as IInsertDrawingCommandParams;+ const workbook = this.getActiveWorkbook();+ if (workbook == null || params == null) {+ return;+ }++ const { drawings } = params;+ this.fireEvent(this.Event.OverGridImageInserted, {+ workbook,+ images: this._createFOverGridImage(drawings as ISheetImage[]),+ });+ })+ );++ this.registerEventHandler(+ this.Event.OverGridImageRemoved,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id !== RemoveSheetDrawingCommand.id) return;++ const params = commandInfo.params as IDeleteDrawingCommandParams;+ const workbook = this.getActiveWorkbook();+ if (workbook == null || params == null) {+ return;+ }++ const { drawings } = params;+ this.fireEvent(this.Event.OverGridImageRemoved, {+ workbook,+ removeImageParams: drawings,+ });+ })+ );++ this.registerEventHandler(+ this.Event.OverGridImageChanged,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id !== SetSheetDrawingCommand.id) return;++ const params = commandInfo.params as ISetDrawingCommandParams;+ const workbook = this.getActiveWorkbook();+ if (workbook == null || params == null) {+ return;+ }++ const { drawings } = params;+ const drawingManagerService = injector.get(IDrawingManagerService);++ const images = drawings.map((drawing) => {+ return this._injector.createInstance(FOverGridImage, drawingManagerService.getDrawingByParam(drawing as IDrawingSearch) as ISheetImage);+ });++ this.fireEvent(this.Event.OverGridImageChanged, {+ workbook,+ images,+ });+ })+ );++ this.registerEventHandler(+ this.Event.OverGridImageSelected,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id !== SetDrawingSelectedOperation.id) return;++ const drawings = commandInfo.params as IDrawingSearch[];+ const workbook = this.getActiveWorkbook();+ if (workbook == null) {+ return;+ }+ const drawingManagerService = injector.get(IDrawingManagerService);++ const selectedDrawings = drawings.map((drawing) => {+ return drawingManagerService.getDrawingByParam(drawing);+ }) as ISheetImage[];++ this.fireEvent(this.Event.OverGridImageSelected, {+ workbook,+ selectedImages: this._createFOverGridImage(selectedDrawings as ISheetImage[]),+ });+ })+ );}private _createFOverGridImage(drawings: ISheetImage[]): FOverGridImage[] {diff --git a/packages/sheets-filter/src/facade/f-event.ts b/packages/sheets-filter/src/facade/f-event.tsindex c811367075..1ac8f260f0 100644--- a/packages/sheets-filter/src/facade/f-event.ts+++ b/packages/sheets-filter/src/facade/f-event.ts@@ -138,27 +138,43 @@ class FUniverSheetsFilterEventMixin extends FUniver {override _initialize(injector: Injector): void {const commandService = injector.get(ICommandService);- this.disposeWithMe(commandService.beforeCommandExecuted((commandInfo) => {- switch (commandInfo.id) {- case SetSheetsFilterCriteriaCommand.id:+ // Register filter criteria set event handlers+ this.registerEventHandler(+ this.Event.SheetBeforeRangeFilter,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetSheetsFilterCriteriaCommand.id) {this._beforeRangeFilter(commandInfo as Readonly<ICommandInfo<ISetSheetsFilterCriteriaCommandParams>>);- break;- case ClearSheetsFilterCriteriaCommand.id:+ }+ })+ );++ this.registerEventHandler(+ this.Event.SheetBeforeRangeFilterClear,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === ClearSheetsFilterCriteriaCommand.id) {this._beforeRangeFilterClear();- break;- }- }));-- this.disposeWithMe(commandService.onCommandExecuted((commandInfo) => {- switch (commandInfo.id) {- case SetSheetsFilterCriteriaCommand.id:+ }+ })+ );++ // Register filter criteria execution event handlers+ this.registerEventHandler(+ this.Event.SheetRangeFiltered,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetSheetsFilterCriteriaCommand.id) {this._onRangeFiltered(commandInfo as Readonly<ICommandInfo<ISetSheetsFilterCriteriaCommandParams>>);- break;- case ClearSheetsFilterCriteriaCommand.id:+ }+ })+ );++ this.registerEventHandler(+ this.Event.SheetRangeFilterCleared,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === ClearSheetsFilterCriteriaCommand.id) {this._onRangeFilterCleared();- break;- }- }));+ }+ })+ );}private _beforeRangeFilter(commandInfo: Readonly<ICommandInfo<ISetSheetsFilterCriteriaCommandParams>>): void {diff --git a/packages/sheets-hyper-link/src/facade/f-univer.ts b/packages/sheets-hyper-link/src/facade/f-univer.tsindex f397c9e947..68cd168d04 100644--- a/packages/sheets-hyper-link/src/facade/f-univer.ts+++ b/packages/sheets-hyper-link/src/facade/f-univer.ts@@ -27,59 +27,72 @@ export class FSheetLinkUniver extends FUniver {override _initialize(injector: Injector): void {const commandService = injector.get(ICommandService);- this.disposeWithMe(- commandService.beforeCommandExecuted((commandInfo) => {- if (commandInfo.id === AddHyperLinkCommand.id) {- if (!this._eventListend(this.Event.BeforeSheetLinkAdd)) return;- const eventTarget = this.getCommandSheetTarget(commandInfo);- if (!eventTarget) return;- const params = commandInfo.params as IAddHyperLinkCommandParams;- const eventParams: IBeforeSheetLinkAddEvent = {- workbook: eventTarget.workbook,- worksheet: eventTarget.worksheet,- row: params.link.row,- col: params.link.column,- link: params.link,- };- this.fireEvent(this.Event.BeforeSheetLinkAdd, eventParams);- if (eventParams.cancel) {- throw new CanceledError();- }+ this.registerEventHandler(+ this.Event.BeforeSheetLinkAdd,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== AddHyperLinkCommand.id) return;++ const eventTarget = this.getCommandSheetTarget(commandInfo);+ if (!eventTarget) return;++ const params = commandInfo.params as IAddHyperLinkCommandParams;+ const eventParams: IBeforeSheetLinkAddEvent = {+ workbook: eventTarget.workbook,+ worksheet: eventTarget.worksheet,+ row: params.link.row,+ col: params.link.column,+ link: params.link,+ };+ this.fireEvent(this.Event.BeforeSheetLinkAdd, eventParams);+ if (eventParams.cancel) {+ throw new CanceledError();}+ })+ );++ this.registerEventHandler(+ this.Event.BeforeSheetLinkUpdate,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== UpdateHyperLinkCommand.id) return;- if (commandInfo.id === UpdateHyperLinkCommand.id) {- const eventTarget = this.getCommandSheetTarget(commandInfo);- if (!eventTarget) return;- const params = commandInfo.params as IUpdateHyperLinkCommandParams;- const eventParams: IBeforeSheetLinkUpdateEvent = {- workbook: eventTarget.workbook,- worksheet: eventTarget.worksheet,- row: params.row,- column: params.column,- id: params.id,- payload: params.payload,- };- this.fireEvent(this.Event.BeforeSheetLinkUpdate, eventParams);- if (eventParams.cancel) {- throw new CanceledError();- }+ const eventTarget = this.getCommandSheetTarget(commandInfo);+ if (!eventTarget) return;++ const params = commandInfo.params as IUpdateHyperLinkCommandParams;+ const eventParams: IBeforeSheetLinkUpdateEvent = {+ workbook: eventTarget.workbook,+ worksheet: eventTarget.worksheet,+ row: params.row,+ column: params.column,+ id: params.id,+ payload: params.payload,+ };+ this.fireEvent(this.Event.BeforeSheetLinkUpdate, eventParams);+ if (eventParams.cancel) {+ throw new CanceledError();}+ })+ );++ this.registerEventHandler(+ this.Event.BeforeSheetLinkCancel,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== CancelHyperLinkCommand.id) return;++ const eventTarget = this.getCommandSheetTarget(commandInfo);+ if (!eventTarget) return;- if (commandInfo.id === CancelHyperLinkCommand.id) {- const eventTarget = this.getCommandSheetTarget(commandInfo);- if (!eventTarget) return;- const params = commandInfo.params as ICancelHyperLinkCommandParams;- const eventParams: IBeforeSheetLinkCancelEvent = {- workbook: eventTarget.workbook,- worksheet: eventTarget.worksheet,- row: params.row,- column: params.column,- id: params.id,- };- this.fireEvent(this.Event.BeforeSheetLinkCancel, eventParams);- if (eventParams.cancel) {- throw new CanceledError();- }+ const params = commandInfo.params as ICancelHyperLinkCommandParams;+ const eventParams: IBeforeSheetLinkCancelEvent = {+ workbook: eventTarget.workbook,+ worksheet: eventTarget.worksheet,+ row: params.row,+ column: params.column,+ id: params.id,+ };+ this.fireEvent(this.Event.BeforeSheetLinkCancel, eventParams);+ if (eventParams.cancel) {+ throw new CanceledError();}}));diff --git a/packages/sheets-sort/src/facade/f-event.ts b/packages/sheets-sort/src/facade/f-event.tsindex 490f4c6022..65279d2736 100644--- a/packages/sheets-sort/src/facade/f-event.ts+++ b/packages/sheets-sort/src/facade/f-event.ts@@ -15,9 +15,10 @@*/import type { ICommandInfo, IEventBase, Injector } from '@univerjs/core';+import type { ISortRangeCommandParams } from '@univerjs/sheets-sort';import type { FRange, FWorkbook, FWorksheet } from '@univerjs/sheets/facade';import { FEventName, FUniver, ICommandService } from '@univerjs/core';-import { type ISortRangeCommandParams, SortRangeCommand, SortType } from '@univerjs/sheets-sort';+import { SortRangeCommand, SortType } from '@univerjs/sheets-sort';import { FSheetEventName } from '@univerjs/sheets/facade';/**@@ -94,21 +95,21 @@ class FUniverSheetsSortEventMixin extends FUniver {override _initialize(injector: Injector): void {const commandService = injector.get(ICommandService);- this.disposeWithMe(commandService.beforeCommandExecuted((commandInfo) => {- switch (commandInfo.id) {- case SortRangeCommand.id:- this._beforeRangeSort(commandInfo as Readonly<ICommandInfo<ISortRangeCommandParams>>);- break;- }- }));-- this.disposeWithMe(commandService.onCommandExecuted((commandInfo) => {- switch (commandInfo.id) {- case SortRangeCommand.id:- this._onRangeSorted(commandInfo as Readonly<ICommandInfo<ISortRangeCommandParams>>);- break;- }- }));+ this.registerEventHandler(+ this.Event.SheetBeforeRangeSort,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== SortRangeCommand.id) return;+ this._beforeRangeSort(commandInfo as Readonly<ICommandInfo<ISortRangeCommandParams>>);+ })+ );++ this.registerEventHandler(+ this.Event.SheetRangeSorted,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id !== SortRangeCommand.id) return;+ this._onRangeSorted(commandInfo as Readonly<ICommandInfo<ISortRangeCommandParams>>);+ })+ );}private _beforeRangeSort(commandInfo: Readonly<ICommandInfo<ISortRangeCommandParams>>): void {diff --git a/packages/sheets-thread-comment/src/facade/f-univer.ts b/packages/sheets-thread-comment/src/facade/f-univer.tsindex 8e95628329..0c993a13b1 100644--- a/packages/sheets-thread-comment/src/facade/f-univer.ts+++ b/packages/sheets-thread-comment/src/facade/f-univer.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICommandInfo, IDisposable, Injector } from '@univerjs/core';+import type { IDisposable, Injector } from '@univerjs/core';import type { IAddCommentCommandParams, IDeleteCommentCommandParams, IResolveCommentCommandParams, IThreadComment, IUpdateCommentCommandParams } from '@univerjs/thread-comment';import type { IBeforeSheetCommentAddEvent, IBeforeSheetCommentDeleteEvent, IBeforeSheetCommentUpdateEvent, ISheetCommentAddEvent, ISheetCommentDeleteEvent, ISheetCommentResolveEvent, ISheetCommentUpdateEvent } from './f-event';import { CanceledError, FUniver, ICommandService, RichTextValue } from '@univerjs/core';@@ -60,23 +60,22 @@ export interface IFUniverCommentMixin {* @ignore*/export class FUniverCommentMixin extends FUniver implements IFUniverCommentMixin {- // eslint-disable-next-line complexity- private _handleCommentCommand(commandInfo: ICommandInfo): void {- const params = commandInfo.params as { unitId: string; subUnitId: string; sheetId: string };- if (!params) return;- const workbook = params.unitId ? this.getUniverSheet(params.unitId) : this.getActiveWorkbook?.();- if (!workbook) {- return;- }+ // eslint-disable-next-line max-lines-per-function+ override _initialize(injector: Injector): void {+ const commandService = injector.get(ICommandService);- const worksheet = workbook.getSheetBySheetId(params.subUnitId || params.sheetId) || workbook.getActiveSheet();- if (!worksheet) {- return;- }+ // After command events+ this.registerEventHandler(+ this.Event.CommentAdded,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id !== AddCommentCommand.id) return;+ const params = commandInfo.params as { unitId: string; subUnitId: string; sheetId: string };+ if (!params) return;+ const workbook = params.unitId ? this.getUniverSheet(params.unitId) : this.getActiveWorkbook?.();+ if (!workbook) return;+ const worksheet = workbook.getSheetBySheetId(params.subUnitId || params.sheetId) || workbook.getActiveSheet();+ if (!worksheet) return;- switch (commandInfo.id) {- case AddCommentCommand.id: {- if (!this._eventListend(this.Event.CommentAdded)) return;const addParams = commandInfo.params as IAddCommentCommandParams;const { comment } = addParams;const threadComment = worksheet.getRange(comment.ref).getComment();@@ -89,10 +88,20 @@ export class FUniverCommentMixin extends FUniver implements IFUniverCommentMixincomment: threadComment,});}- break;- }- case UpdateCommentCommand.id: {- if (!this._eventListend(this.Event.CommentUpdated)) return;+ })+ );++ this.registerEventHandler(+ this.Event.CommentUpdated,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id !== UpdateCommentCommand.id) return;+ const params = commandInfo.params as { unitId: string; subUnitId: string; sheetId: string };+ if (!params) return;+ const workbook = params.unitId ? this.getUniverSheet(params.unitId) : this.getActiveWorkbook?.();+ if (!workbook) return;+ const worksheet = workbook.getSheetBySheetId(params.subUnitId || params.sheetId) || workbook.getActiveSheet();+ if (!worksheet) return;+const updateParams = commandInfo.params as IUpdateCommentCommandParams;const { commentId } = updateParams.payload;const threadComment = worksheet.getCommentById(commentId);@@ -105,10 +114,20 @@ export class FUniverCommentMixin extends FUniver implements IFUniverCommentMixincomment: threadComment,});}- break;- }- case DeleteCommentCommand.id: {- if (!this._eventListend(this.Event.CommentDeleted)) return;+ })+ );++ this.registerEventHandler(+ this.Event.CommentDeleted,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id !== DeleteCommentCommand.id) return;+ const params = commandInfo.params as { unitId: string; subUnitId: string; sheetId: string };+ if (!params) return;+ const workbook = params.unitId ? this.getUniverSheet(params.unitId) : this.getActiveWorkbook?.();+ if (!workbook) return;+ const worksheet = workbook.getSheetBySheetId(params.subUnitId || params.sheetId) || workbook.getActiveSheet();+ if (!worksheet) return;+const deleteParams = commandInfo.params as IDeleteCommentCommandParams;const { commentId } = deleteParams;this.fireEvent(this.Event.CommentDeleted, {@@ -116,10 +135,20 @@ export class FUniverCommentMixin extends FUniver implements IFUniverCommentMixinworksheet,commentId,});- break;- }- case ResolveCommentCommand.id: {- if (!this._eventListend(this.Event.CommentResolved)) return;+ })+ );++ this.registerEventHandler(+ this.Event.CommentResolved,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id !== ResolveCommentCommand.id) return;+ const params = commandInfo.params as { unitId: string; subUnitId: string; sheetId: string };+ if (!params) return;+ const workbook = params.unitId ? this.getUniverSheet(params.unitId) : this.getActiveWorkbook?.();+ if (!workbook) return;+ const worksheet = workbook.getSheetBySheetId(params.subUnitId || params.sheetId) || workbook.getActiveSheet();+ if (!worksheet) return;+const resolveParams = commandInfo.params as IResolveCommentCommandParams;const { commentId, resolved } = resolveParams;const threadComment = worksheet.getComments().find((c) => c.getCommentData().id === commentId);@@ -133,28 +162,21 @@ export class FUniverCommentMixin extends FUniver implements IFUniverCommentMixinresolved,});}- break;- }- }- }-- // eslint-disable-next-line complexity, max-lines-per-function- private _handleBeforeCommentCommand(commandInfo: ICommandInfo): void {- const params = commandInfo.params as { unitId: string; subUnitId: string; sheetId: string };- if (!params) return;- const workbook = params.unitId ? this.getUniverSheet(params.unitId) : this.getActiveWorkbook?.();- if (!workbook) {- return;- }+ })+ );- const worksheet = workbook.getSheetBySheetId(params.subUnitId || params.sheetId) || workbook.getActiveSheet();- if (!worksheet) {- return;- }+ // Before command events+ this.registerEventHandler(+ this.Event.BeforeCommentAdd,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== AddCommentCommand.id) return;+ const params = commandInfo.params as { unitId: string; subUnitId: string; sheetId: string };+ if (!params) return;+ const workbook = params.unitId ? this.getUniverSheet(params.unitId) : this.getActiveWorkbook?.();+ if (!workbook) return;+ const worksheet = workbook.getSheetBySheetId(params.subUnitId || params.sheetId) || workbook.getActiveSheet();+ if (!worksheet) return;- switch (commandInfo.id) {- case AddCommentCommand.id: {- if (!this._eventListend(this.Event.BeforeCommentAdd)) return;const addParams = commandInfo.params as IAddCommentCommandParams;const { comment } = addParams;const activeRange = worksheet.getActiveRange();@@ -170,11 +192,21 @@ export class FUniverCommentMixin extends FUniver implements IFUniverCommentMixinthis.fireEvent(this.Event.BeforeCommentAdd, eventParams);if (eventParams.cancel) {throw new CanceledError();- };- break;- }- case UpdateCommentCommand.id: {- if (!this._eventListend(this.Event.BeforeCommentUpdate)) return;+ }+ })+ );++ this.registerEventHandler(+ this.Event.BeforeCommentUpdate,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== UpdateCommentCommand.id) return;+ const params = commandInfo.params as { unitId: string; subUnitId: string; sheetId: string };+ if (!params) return;+ const workbook = params.unitId ? this.getUniverSheet(params.unitId) : this.getActiveWorkbook?.();+ if (!workbook) return;+ const worksheet = workbook.getSheetBySheetId(params.subUnitId || params.sheetId) || workbook.getActiveSheet();+ if (!worksheet) return;+const updateParams = commandInfo.params as IUpdateCommentCommandParams;const { commentId, text } = updateParams.payload;const threadComment = worksheet.getCommentById(commentId);@@ -190,12 +222,22 @@ export class FUniverCommentMixin extends FUniver implements IFUniverCommentMixinthis.fireEvent(this.Event.BeforeCommentUpdate, eventParams);if (eventParams.cancel) {throw new CanceledError();- };+ }}- break;- }- case DeleteCommentCommand.id: {- if (!this._eventListend(this.Event.BeforeCommentDeleted)) return;+ })+ );++ this.registerEventHandler(+ this.Event.BeforeCommentDeleted,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== DeleteCommentCommand.id) return;+ const params = commandInfo.params as { unitId: string; subUnitId: string; sheetId: string };+ if (!params) return;+ const workbook = params.unitId ? this.getUniverSheet(params.unitId) : this.getActiveWorkbook?.();+ if (!workbook) return;+ const worksheet = workbook.getSheetBySheetId(params.subUnitId || params.sheetId) || workbook.getActiveSheet();+ if (!worksheet) return;+const deleteParams = commandInfo.params as IDeleteCommentCommandParams;const { commentId } = deleteParams;const threadComment = worksheet.getCommentById(commentId);@@ -210,12 +252,22 @@ export class FUniverCommentMixin extends FUniver implements IFUniverCommentMixinthis.fireEvent(this.Event.BeforeCommentDeleted, eventParams);if (eventParams.cancel) {throw new CanceledError();- };+ }}- break;- }- case ResolveCommentCommand.id: {- if (!this._eventListend(this.Event.BeforeCommentResolve)) return;+ })+ );++ this.registerEventHandler(+ this.Event.BeforeCommentResolve,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== ResolveCommentCommand.id) return;+ const params = commandInfo.params as { unitId: string; subUnitId: string; sheetId: string };+ if (!params) return;+ const workbook = params.unitId ? this.getUniverSheet(params.unitId) : this.getActiveWorkbook?.();+ if (!workbook) return;+ const worksheet = workbook.getSheetBySheetId(params.subUnitId || params.sheetId) || workbook.getActiveSheet();+ if (!worksheet) return;+const resolveParams = commandInfo.params as IResolveCommentCommandParams;const { commentId, resolved } = resolveParams;const threadComment = worksheet.getComments().find((c) => c.getCommentData().id === commentId);@@ -233,29 +285,13 @@ export class FUniverCommentMixin extends FUniver implements IFUniverCommentMixinthrow new CanceledError();}}- break;- }- }+ })+ );}/*** @ignore*/- override _initialize(injector: Injector): void {- const commandService = injector.get(ICommandService);- this.disposeWithMe(- commandService.onCommandExecuted((commandInfo) => {- this._handleCommentCommand(commandInfo);- })- );-- this.disposeWithMe(- commandService.beforeCommandExecuted((commandInfo) => {- this._handleBeforeCommentCommand(commandInfo);- })- );- }-override newTheadComment(comment?: IThreadComment): FTheadCommentBuilder {return new FTheadCommentBuilder(comment);}diff --git a/packages/sheets-ui/src/facade/f-univer.ts b/packages/sheets-ui/src/facade/f-univer.tsindex fdb2f88a5b..113ba714d4 100644--- a/packages/sheets-ui/src/facade/f-univer.ts+++ b/packages/sheets-ui/src/facade/f-univer.ts@@ -97,21 +97,22 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix// eslint-disable-next-line max-lines-per-functionprivate _initSheetUIEvent(injector: Injector): void {const commandService = injector.get(ICommandService);- this.disposeWithMe(commandService.beforeCommandExecuted((commandInfo) => {- if (commandInfo.id === SetCellEditVisibleOperation.id) {- if (!this._eventListend(this.Event.BeforeSheetEditStart) && !this._eventListend(this.Event.BeforeSheetEditEnd)) {- return;- }++ // Edit events+ this.registerEventHandler(+ this.Event.BeforeSheetEditStart,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== SetCellEditVisibleOperation.id) return;+const target = this.getActiveSheet();- if (!target) {- return;- }+ if (!target) return;+const { workbook, worksheet } = target;const editorBridgeService = injector.get(IEditorBridgeService);- const univerInstanceService = injector.get(IUniverInstanceService);const params = commandInfo.params as IEditorBridgeServiceVisibleParam;const { visible, keycode, eventType } = params;const loc = editorBridgeService.getEditLocation()!;+if (visible) {const eventParams: IBeforeSheetEditStartEventParams = {row: loc.row,@@ -126,7 +127,26 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMixif (eventParams.cancel) {throw new CanceledError();}- } else {+ }+ })+ );++ this.registerEventHandler(+ this.Event.BeforeSheetEditEnd,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== SetCellEditVisibleOperation.id) return;++ const target = this.getActiveSheet();+ if (!target) return;++ const { workbook, worksheet } = target;+ const editorBridgeService = injector.get(IEditorBridgeService);+ const univerInstanceService = injector.get(IUniverInstanceService);+ const params = commandInfo.params as IEditorBridgeServiceVisibleParam;+ const { visible, keycode, eventType } = params;+ const loc = editorBridgeService.getEditLocation()!;++ if (!visible) {const eventParams: IBeforeSheetEditEndEventParams = {row: loc.row,column: loc.column,@@ -143,41 +163,23 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMixthrow new CanceledError();}}- }+ })+ );- if (commandInfo.id === SetZoomRatioCommand.id) {- if (!this._eventListend(this.Event.BeforeSheetZoomChange)) {- return;- }- const target = this.getCommandSheetTarget(commandInfo);- if (!target) {- return;- }- const { workbook, worksheet } = target;- this.fireEvent(this.Event.BeforeSheetZoomChange, {- zoom: (commandInfo.params as ISetZoomRatioCommandParams).zoomRatio,- workbook,- worksheet,- });- }- }));+ this.registerEventHandler(+ this.Event.SheetEditStarted,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id !== SetCellEditVisibleOperation.id) return;- // eslint-disable-next-line max-lines-per-function- this.disposeWithMe(commandService.onCommandExecuted((commandInfo) => {- if (commandInfo.id === SetCellEditVisibleOperation.id) {- if (!this._eventListend(this.Event.SheetEditStarted) && !this._eventListend(this.Event.SheetEditEnded)) {- return;- }const target = this.getCommandSheetTarget(commandInfo);- if (!target) {- return;- }- const { workbook, worksheet } = target;+ if (!target) return;+ const { workbook, worksheet } = target;const editorBridgeService = injector.get(IEditorBridgeService);const params = commandInfo.params as IEditorBridgeServiceVisibleParam;const { visible, keycode, eventType } = params;const loc = editorBridgeService.getEditLocation()!;+if (visible) {const eventParams: ISheetEditStartedEventParams = {row: loc.row,@@ -189,7 +191,25 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMixisZenEditor: false,};this.fireEvent(this.Event.SheetEditStarted, eventParams);- } else {+ }+ })+ );++ this.registerEventHandler(+ this.Event.SheetEditEnded,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id !== SetCellEditVisibleOperation.id) return;++ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) return;++ const { workbook, worksheet } = target;+ const editorBridgeService = injector.get(IEditorBridgeService);+ const params = commandInfo.params as IEditorBridgeServiceVisibleParam;+ const { visible, keycode, eventType } = params;+ const loc = editorBridgeService.getEditLocation()!;++ if (!visible) {const eventParams: ISheetEditEndedEventParams = {row: loc.row,column: loc.column,@@ -202,21 +222,23 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix};this.fireEvent(this.Event.SheetEditEnded, eventParams);}- }+ })+ );++ this.registerEventHandler(+ this.Event.SheetEditChanging,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id !== RichTextEditingMutation.id) return;- if (commandInfo.id === RichTextEditingMutation.id) {- if (!this._eventListend(this.Event.SheetEditChanging)) {- return;- }const target = this.getCommandSheetTarget(commandInfo);- if (!target) {- return;- }+ if (!target) return;+const { workbook, worksheet } = target;const editorBridgeService = injector.get(IEditorBridgeService);const univerInstanceService = injector.get(IUniverInstanceService);const params = commandInfo.params as IRichTextEditingMutationParams;if (!editorBridgeService.isVisible().visible) return;+const { unitId } = params;if (unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {const { row, column } = editorBridgeService.getEditLocation()!;@@ -230,26 +252,43 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix};this.fireEvent(this.Event.SheetEditChanging, eventParams);}- }+ })+ );++ // Zoom events+ this.registerEventHandler(+ this.Event.BeforeSheetZoomChange,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id !== SetZoomRatioCommand.id) return;- if (commandInfo.id === SetZoomRatioCommand.id) {- if (!this._eventListend(this.Event.SheetZoomChanged)) {- return;- }const target = this.getCommandSheetTarget(commandInfo);- if (!target) {- return;- }+ if (!target) return;++ const { workbook, worksheet } = target;+ this.fireEvent(this.Event.BeforeSheetZoomChange, {+ zoom: (commandInfo.params as ISetZoomRatioCommandParams).zoomRatio,+ workbook,+ worksheet,+ });+ })+ );++ this.registerEventHandler(+ this.Event.SheetZoomChanged,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id !== SetZoomRatioCommand.id) return;++ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) return;+const { workbook, worksheet } = target;this.fireEvent(this.Event.SheetZoomChanged, {zoom: worksheet.getZoom(),workbook,worksheet,});- }- }));-- this._initObserverListener(injector);+ })+ );}/**@@ -261,9 +300,11 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMixconst unitM = univerInstanceService.getFocusedUnit();const unitId = unitM?.getUnitId();const renderManagerService = injector.get(IRenderManagerService);+if (unitId) {const lifeCycleService = injector.get(LifecycleService);const disposable = new DisposableCollection();+// eslint-disable-next-line max-lines-per-functionthis.disposeWithMe(lifeCycleService.lifecycle$.subscribe((lifecycle) => {if (lifecycle < LifecycleStages.Rendered) return;@@ -271,11 +312,13 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMixconst hoverManagerService = injector.get(HoverManagerService);const dragManagerService = injector.get(DragManagerService);if (!hoverManagerService) return;- disposable.add(- hoverManagerService.currentClickedCell$++ // Cell events+ this.registerEventHandler(+ this.Event.CellClicked,+ () => hoverManagerService.currentClickedCell$?.pipe(filter((cell) => !!cell)).subscribe((cell) => {- if (!this._eventListend(this.Event.CellClicked)) return;const baseParams = this.getSheetTarget(cell.location.unitId, cell.location.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.CellClicked, {@@ -287,10 +330,11 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}));- disposable.add(- hoverManagerService.currentRichText$?.pipe(filter((cell) => !!cell))+ this.registerEventHandler(+ this.Event.CellHover,+ () => hoverManagerService.currentRichText$+ ?.pipe(filter((cell) => !!cell)).subscribe((cell) => {- if (!this._eventListend(this.Event.CellHover)) return;const baseParams = this.getSheetTarget(cell.unitId, cell.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.CellHover, {@@ -302,10 +346,11 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}));- disposable.add(- hoverManagerService.currentPointerDownCell$?.pipe(filter((cell) => !!cell))+ this.registerEventHandler(+ this.Event.CellPointerDown,+ () => hoverManagerService.currentPointerDownCell$+ ?.pipe(filter((cell) => !!cell)).subscribe((cell) => {- if (!this._eventListend(this.Event.CellPointerDown)) return;const baseParams = this.getSheetTarget(cell.unitId, cell.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.CellPointerDown, {@@ -317,10 +362,11 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}));- disposable.add(- hoverManagerService.currentPointerUpCell$?.pipe(filter((cell) => !!cell))+ this.registerEventHandler(+ this.Event.CellPointerUp,+ () => hoverManagerService.currentPointerUpCell$+ ?.pipe(filter((cell) => !!cell)).subscribe((cell) => {- if (!this._eventListend(this.Event.CellPointerUp)) return;const baseParams = this.getSheetTarget(cell.unitId, cell.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.CellPointerUp, {@@ -332,10 +378,11 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}));- disposable.add(- hoverManagerService.currentCellPosWithEvent$?.pipe(filter((cell) => !!cell))+ this.registerEventHandler(+ this.Event.CellPointerMove,+ () => hoverManagerService.currentCellPosWithEvent$+ ?.pipe(filter((cell) => !!cell)).subscribe((cell) => {- if (!this._eventListend(this.Event.CellPointerMove)) return;const baseParams = this.getSheetTarget(cell.unitId, cell.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.CellPointerMove, {@@ -347,11 +394,12 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}));- disposable.add(- dragManagerService.currentCell$+ // Drag events+ this.registerEventHandler(+ this.Event.DragOver,+ () => dragManagerService.currentCell$?.pipe(filter((cell) => !!cell)).subscribe((cell) => {- if (!this._eventListend(this.Event.DragOver)) return;const baseParams = this.getSheetTarget(cell.location.unitId, cell.location.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.DragOver, {@@ -363,11 +411,11 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}));- disposable.add(- dragManagerService.endCell$+ this.registerEventHandler(+ this.Event.Drop,+ () => dragManagerService.endCell$?.pipe(filter((cell) => !!cell)).subscribe((cell) => {- if (!this._eventListend(this.Event.Drop)) return;const baseParams = this.getSheetTarget(cell.location.unitId, cell.location.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.Drop, {@@ -379,12 +427,12 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}));- // Row Header Events- disposable.add(- hoverManagerService.currentRowHeaderClick$+ // Row Header events+ this.registerEventHandler(+ this.Event.RowHeaderClick,+ () => hoverManagerService.currentRowHeaderClick$?.pipe(filter((header) => !!header)).subscribe((header) => {- if (!this._eventListend(this.Event.RowHeaderClick)) return;const baseParams = this.getSheetTarget(header.unitId, header.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.RowHeaderClick, {@@ -394,11 +442,11 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}));- disposable.add(- hoverManagerService.currentRowHeaderPointerDown$+ this.registerEventHandler(+ this.Event.RowHeaderPointerDown,+ () => hoverManagerService.currentRowHeaderPointerDown$?.pipe(filter((header) => !!header)).subscribe((header) => {- if (!this._eventListend(this.Event.RowHeaderPointerDown)) return;const baseParams = this.getSheetTarget(header.unitId, header.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.RowHeaderPointerDown, {@@ -408,11 +456,11 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}));- disposable.add(- hoverManagerService.currentRowHeaderPointerUp$+ this.registerEventHandler(+ this.Event.RowHeaderPointerUp,+ () => hoverManagerService.currentRowHeaderPointerUp$?.pipe(filter((header) => !!header)).subscribe((header) => {- if (!this._eventListend(this.Event.RowHeaderPointerUp)) return;const baseParams = this.getSheetTarget(header.unitId, header.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.RowHeaderPointerUp, {@@ -422,11 +470,11 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}));- disposable.add(- hoverManagerService.currentHoveredRowHeader$+ this.registerEventHandler(+ this.Event.RowHeaderHover,+ () => hoverManagerService.currentHoveredRowHeader$?.pipe(filter((header) => !!header)).subscribe((header) => {- if (!this._eventListend(this.Event.RowHeaderHover)) return;const baseParams = this.getSheetTarget(header.unitId, header.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.RowHeaderHover, {@@ -436,12 +484,12 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}));- // Column Header Events- disposable.add(- hoverManagerService.currentColHeaderClick$+ // Column Header events+ this.registerEventHandler(+ this.Event.ColumnHeaderClick,+ () => hoverManagerService.currentColHeaderClick$?.pipe(filter((header) => !!header)).subscribe((header) => {- if (!this._eventListend(this.Event.ColumnHeaderClick)) return;const baseParams = this.getSheetTarget(header.unitId, header.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.ColumnHeaderClick, {@@ -451,11 +499,11 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}));- disposable.add(- hoverManagerService.currentColHeaderPointerDown$+ this.registerEventHandler(+ this.Event.ColumnHeaderPointerDown,+ () => hoverManagerService.currentColHeaderPointerDown$?.pipe(filter((header) => !!header)).subscribe((header) => {- if (!this._eventListend(this.Event.ColumnHeaderPointerDown)) return;const baseParams = this.getSheetTarget(header.unitId, header.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.ColumnHeaderPointerDown, {@@ -465,11 +513,11 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}));- disposable.add(- hoverManagerService.currentColHeaderPointerUp$+ this.registerEventHandler(+ this.Event.ColumnHeaderPointerUp,+ () => hoverManagerService.currentColHeaderPointerUp$?.pipe(filter((header) => !!header)).subscribe((header) => {- if (!this._eventListend(this.Event.ColumnHeaderPointerUp)) return;const baseParams = this.getSheetTarget(header.unitId, header.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.ColumnHeaderPointerUp, {@@ -479,11 +527,11 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}));- disposable.add(- hoverManagerService.currentHoveredColHeader$+ this.registerEventHandler(+ this.Event.ColumnHeaderHover,+ () => hoverManagerService.currentHoveredColHeader$?.pipe(filter((header) => !!header)).subscribe((header) => {- if (!this._eventListend(this.Event.ColumnHeaderHover)) return;const baseParams = this.getSheetTarget(header.unitId, header.subUnitId);if (!baseParams) return;this.fireEvent(this.Event.ColumnHeaderHover, {@@ -504,6 +552,7 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMixrenderManagerService.created$,lifeCycleService.lifecycle$,]);+ // eslint-disable-next-line max-lines-per-functionthis.disposeWithMe(combined$.subscribe(([created, lifecycle]) => {// univer & univer-pro are not same in life cycle.@@ -529,52 +578,65 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}unitMap.set(sheetRenderUnit.unitId, disposable);const scrollManagerService = sheetRenderUnit.with(SheetScrollManagerService);- disposable.add(scrollManagerService.validViewportScrollInfo$.subscribe((params: Nullable<IViewportScrollState>) => {- if (!params) return;- if (!this._eventListend(this.Event.Scroll)) return;- this.fireEvent(this.Event.Scroll, {- workbook,- worksheet: workbook.getActiveSheet(),- ...params,- });- }));-const selectionService = sheetRenderUnit.with(SheetsSelectionsService);- disposable.add(selectionService.selectionMoveStart$.subscribe((selections) => {- if (!this._eventListend(this.Event.SelectionMoveStart)) return;- this.fireEvent(this.Event.SelectionMoveStart, {- workbook,- worksheet: workbook.getActiveSheet(),- selections: selections?.map((s) => s.range) ?? [],- });- }));- disposable.add(selectionService.selectionMoving$.subscribe((selections) => {- if (!this._eventListend(this.Event.SelectionMoving)) return;- this.fireEvent(this.Event.SelectionMoving, {- workbook,- worksheet: workbook.getActiveSheet(),- selections: selections?.map((s) => s.range) ?? [],- });- }));-- disposable.add(selectionService.selectionMoveEnd$.subscribe((selections) => {- if (!this._eventListend(this.Event.SelectionMoveEnd)) return;- this.fireEvent(this.Event.SelectionMoveEnd, {- workbook,- worksheet: workbook.getActiveSheet(),- selections: selections?.map((s) => s.range) ?? [],- });- }));-- disposable.add(selectionService.selectionChanged$.subscribe((selections) => {- if (!this._eventListend(this.Event.SelectionChanged)) return;- this.fireEvent(this.Event.SelectionChanged, {- workbook,- worksheet: workbook.getActiveSheet(),- selections: selections?.map((s) => s.range) ?? [],- });- }));+ // Register scroll event handler+ disposable.add(this.registerEventHandler(+ this.Event.Scroll,+ () => scrollManagerService.validViewportScrollInfo$.subscribe((params: Nullable<IViewportScrollState>) => {+ if (!params) return;+ this.fireEvent(this.Event.Scroll, {+ workbook,+ worksheet: workbook.getActiveSheet(),+ ...params,+ });+ })+ ));++ // Register selection event handlers+ disposable.add(this.registerEventHandler(+ this.Event.SelectionMoveStart,+ () => selectionService.selectionMoveStart$.subscribe((selections) => {+ this.fireEvent(this.Event.SelectionMoveStart, {+ workbook,+ worksheet: workbook.getActiveSheet(),+ selections: selections?.map((s) => s.range) ?? [],+ });+ })+ ));++ disposable.add(this.registerEventHandler(+ this.Event.SelectionMoving,+ () => selectionService.selectionMoving$.subscribe((selections) => {+ this.fireEvent(this.Event.SelectionMoving, {+ workbook,+ worksheet: workbook.getActiveSheet(),+ selections: selections?.map((s) => s.range) ?? [],+ });+ })+ ));++ disposable.add(this.registerEventHandler(+ this.Event.SelectionMoveEnd,+ () => selectionService.selectionMoveEnd$.subscribe((selections) => {+ this.fireEvent(this.Event.SelectionMoveEnd, {+ workbook,+ worksheet: workbook.getActiveSheet(),+ selections: selections?.map((s) => s.range) ?? [],+ });+ })+ ));++ disposable.add(this.registerEventHandler(+ this.Event.SelectionChanged,+ () => selectionService.selectionChanged$.subscribe((selections) => {+ this.fireEvent(this.Event.SelectionChanged, {+ workbook,+ worksheet: workbook.getActiveSheet(),+ selections: selections?.map((s) => s.range) ?? [],+ });+ })+ ));// for pro, in pro, life cycle & created$ is not same as univer sdk// if not clear sheetRenderUnit, that would cause event bind twice!sheetRenderUnit = null;@@ -596,23 +658,57 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix/*** @ignore*/++ // eslint-disable-next-line max-lines-per-functionoverride _initialize(injector: Injector): void {this._initSheetUIEvent(injector);const commandService = injector.get(ICommandService);- this.disposeWithMe(commandService.beforeCommandExecuted((commandInfo) => {- switch (commandInfo.id) {- case CopyCommand.id:- case CutCommand.id:- this._beforeClipboardChange();- break;- case SheetPasteShortKeyCommand.id:- this._beforeClipboardPaste(commandInfo.params);- break;+ this.registerEventHandler(+ this.Event.BeforeClipboardChange,+ () => {+ const disposableCollection = new DisposableCollection();+ disposableCollection.add(+ commandService.beforeCommandExecuted((commandInfo) => {+ switch (commandInfo.id) {+ case CopyCommand.id:+ case CutCommand.id:+ this._beforeClipboardChange();+ break;+ }+ })+ );++ return disposableCollection;}- }));+ );++ this.registerEventHandler(+ this.Event.ClipboardChanged,+ () => {+ const disposableCollection = new DisposableCollection();+ disposableCollection.add(commandService.beforeCommandExecuted((commandInfo) => {+ switch (commandInfo.id) {+ case SheetPasteShortKeyCommand.id:+ this._beforeClipboardPaste(commandInfo.params);+ break;+ }+ }));++ disposableCollection.add(+ commandService.beforeCommandExecuted(async (commandInfo) => {+ switch (commandInfo.id) {+ case PasteCommand.id:+ await this._beforeClipboardPasteAsync();+ break;+ }+ })+ );+ return disposableCollection;+ }+ );+this.disposeWithMe(commandService.onCommandExecuted((commandInfo) => {if (COMMAND_LISTENER_SKELETON_CHANGE.indexOf(commandInfo.id) > -1) {- if (!this._eventListend(this.Event.SheetSkeletonChanged)) return;const sheet = this.getActiveSheet();if (!sheet) return;const ranges = getSkeletonChangedEffectedRange(commandInfo)@@ -627,30 +723,36 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMixskeleton: sheet.worksheet.getSkeleton()!,effectedRanges: ranges,});- return;- }-- switch (commandInfo.id) {- case CopyCommand.id:- case CutCommand.id:- this._clipboardChanged();- break;- case SheetPasteShortKeyCommand.id:- this._clipboardPaste();- break;- case PasteCommand.id:- this._clipboardPasteAsync();- break;}}));++ this.registerEventHandler(+ this.Event.ClipboardChanged,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ switch (commandInfo.id) {+ case CopyCommand.id:+ case CutCommand.id:+ this._clipboardChanged();+ break;+ }+ })+ );++ this.registerEventHandler(+ this.Event.ClipboardPasted,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ switch (commandInfo.id) {+ case SheetPasteShortKeyCommand.id:+ this._clipboardPaste(commandInfo.params);+ break;+ case PasteCommand.id:+ this._clipboardPasteAsync();+ break;+ }+ })+ );+// async listeners- this.disposeWithMe(commandService.beforeCommandExecuted(async (commandInfo) => {- switch (commandInfo.id) {- case PasteCommand.id:- await this._beforeClipboardPasteAsync();- break;- }- }));}private _generateClipboardCopyParam(): IBeforeClipboardChangeParam | undefined {@@ -679,9 +781,6 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}private _beforeClipboardChange(): void {- if (!this.hasEventCallback(this.Event.BeforeClipboardChange)) {- return;- }const eventParams = this._generateClipboardCopyParam();if (!eventParams) return;@@ -692,9 +791,6 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}private _clipboardChanged(): void {- if (!this.hasEventCallback(this.Event.ClipboardChanged)) {- return;- }const eventParams = this._generateClipboardCopyParam();if (!eventParams) return;@@ -754,9 +850,6 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}private _beforeClipboardPaste(params?: ISheetPasteByShortKeyParams): void {- if (!this.hasEventCallback(this.Event.BeforeClipboardPaste)) {- return;- }const eventParams = this._generateClipboardPasteParam(params);if (!eventParams) return;this.fireEvent(this.Event.BeforeClipboardPaste, eventParams);@@ -766,21 +859,15 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}private _clipboardPaste(params?: ISheetPasteByShortKeyParams): void {- if (!this.hasEventCallback(this.Event.BeforeClipboardPaste)) {- return;- }const eventParams = this._generateClipboardPasteParam(params);if (!eventParams) return;- this.fireEvent(this.Event.BeforeClipboardPaste, eventParams);+ this.fireEvent(this.Event.ClipboardPasted, eventParams);if (eventParams.cancel) {throw new Error('Clipboard pasted is canceled');}}private async _beforeClipboardPasteAsync(): Promise<void> {- if (!this.hasEventCallback(this.Event.BeforeClipboardPaste)) {- return;- }if (!supportClipboardAPI()) {const logService = this._injector.get(ILogService);logService.warn('[Facade]: The navigator object only supports the browser environment');@@ -795,9 +882,6 @@ export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMix}private async _clipboardPasteAsync(): Promise<void> {- if (!this.hasEventCallback(this.Event.ClipboardPasted)) {- return;- }if (!supportClipboardAPI()) {const logService = this._injector.get(ILogService);logService.warn('[Facade]: The navigator object only supports the browser environment');diff --git a/packages/sheets-zen-editor/src/facade/f-univer.ts b/packages/sheets-zen-editor/src/facade/f-univer.tsindex 5127b4b264..72eda07a68 100644--- a/packages/sheets-zen-editor/src/facade/f-univer.ts+++ b/packages/sheets-zen-editor/src/facade/f-univer.ts@@ -33,27 +33,22 @@ export class FUniverSheetsZenEditorMixin extends FUniver implements IFUniverShee// eslint-disable-next-line max-lines-per-functionprivate _initSheetZenEditorEvent(injector: Injector): void {const commandService = injector.get(ICommandService);- this.disposeWithMe(commandService.beforeCommandExecuted((commandInfo) => {- if (- commandInfo.id === OpenZenEditorCommand.id ||- commandInfo.id === CancelZenEditCommand.id ||- commandInfo.id === ConfirmZenEditCommand.id- ) {- if (!this._eventListend(this.Event.BeforeSheetEditStart) && !this._eventListend(this.Event.BeforeSheetEditEnd)) {- return;- }- const target = this.getCommandSheetTarget(commandInfo);- if (!target) {- return;- }- const { workbook, worksheet } = target;- const editorBridgeService = injector.get(IEditorBridgeService);- const univerInstanceService = injector.get(IUniverInstanceService);- const params = commandInfo.params as IEditorBridgeServiceVisibleParam;- const { keycode, eventType } = params;- const loc = editorBridgeService.getEditLocation()!;+ // Register before command execution handlers+ this.registerEventHandler(+ this.Event.BeforeSheetEditStart,+ () => commandService.beforeCommandExecuted((commandInfo) => {if (commandInfo.id === OpenZenEditorCommand.id) {+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) {+ return;+ }+ const { workbook, worksheet } = target;+ const editorBridgeService = injector.get(IEditorBridgeService);+ const params = commandInfo.params as IEditorBridgeServiceVisibleParam;+ const { keycode, eventType } = params;+ const loc = editorBridgeService.getEditLocation()!;+const eventParams: IBeforeSheetEditStartEventParams = {row: loc.row,column: loc.column,@@ -67,7 +62,28 @@ export class FUniverSheetsZenEditorMixin extends FUniver implements IFUniverSheeif (eventParams.cancel) {throw new CanceledError();}- } else {+ }+ })+ );++ this.registerEventHandler(+ this.Event.BeforeSheetEditEnd,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (+ commandInfo.id === CancelZenEditCommand.id ||+ commandInfo.id === ConfirmZenEditCommand.id+ ) {+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) {+ return;+ }+ const { workbook, worksheet } = target;+ const editorBridgeService = injector.get(IEditorBridgeService);+ const univerInstanceService = injector.get(IUniverInstanceService);+ const params = commandInfo.params as IEditorBridgeServiceVisibleParam;+ const { keycode, eventType } = params;+ const loc = editorBridgeService.getEditLocation()!;+const eventParams: IBeforeSheetEditEndEventParams = {row: loc.row,column: loc.column,@@ -84,29 +100,24 @@ export class FUniverSheetsZenEditorMixin extends FUniver implements IFUniverSheethrow new CanceledError();}}- }- }));-- this.disposeWithMe(commandService.onCommandExecuted((commandInfo) => {- if (- commandInfo.id === OpenZenEditorCommand.id ||- commandInfo.id === CancelZenEditCommand.id ||- commandInfo.id === ConfirmZenEditCommand.id- ) {- if (!this._eventListend(this.Event.SheetEditStarted) && !this._eventListend(this.Event.SheetEditEnded)) {- return;- }- const target = this.getCommandSheetTarget(commandInfo);- if (!target) {- return;- }- const { workbook, worksheet } = target;+ })+ );- const editorBridgeService = injector.get(IEditorBridgeService);- const params = commandInfo.params as IEditorBridgeServiceVisibleParam;- const { keycode, eventType } = params;- const loc = editorBridgeService.getEditLocation()!;+ // Register command execution handlers+ this.registerEventHandler(+ this.Event.SheetEditStarted,+ () => commandService.onCommandExecuted((commandInfo) => {if (commandInfo.id === OpenZenEditorCommand.id) {+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) {+ return;+ }+ const { workbook, worksheet } = target;++ const editorBridgeService = injector.get(IEditorBridgeService);+ const params = commandInfo.params as IEditorBridgeServiceVisibleParam;+ const { keycode, eventType } = params;+ const loc = editorBridgeService.getEditLocation()!;const eventParams: ISheetEditStartedEventParams = {row: loc.row,column: loc.column,@@ -117,7 +128,28 @@ export class FUniverSheetsZenEditorMixin extends FUniver implements IFUniverSheeisZenEditor: true,};this.fireEvent(this.Event.SheetEditStarted, eventParams);- } else {+ }+ })+ );++ this.registerEventHandler(+ this.Event.SheetEditEnded,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (+ commandInfo.id === CancelZenEditCommand.id ||+ commandInfo.id === ConfirmZenEditCommand.id+ ) {+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) {+ return;+ }+ const { workbook, worksheet } = target;++ const editorBridgeService = injector.get(IEditorBridgeService);+ const params = commandInfo.params as IEditorBridgeServiceVisibleParam;+ const { keycode, eventType } = params;+ const loc = editorBridgeService.getEditLocation()!;+const eventParams: ISheetEditEndedEventParams = {row: loc.row,column: loc.column,@@ -130,36 +162,39 @@ export class FUniverSheetsZenEditorMixin extends FUniver implements IFUniverShee};this.fireEvent(this.Event.SheetEditEnded, eventParams);}- }+ })+ );- if (commandInfo.id === RichTextEditingMutation.id) {- if (!this._eventListend(this.Event.SheetEditChanging)) {- return;- }- const target = this.getCommandSheetTarget(commandInfo);- if (!target) {- return;- }- const { workbook, worksheet } = target;- const editorBridgeService = injector.get(IEditorBridgeService);- const univerInstanceService = injector.get(IUniverInstanceService);- const params = commandInfo.params as IRichTextEditingMutationParams;- if (!editorBridgeService.isVisible().visible) return;- const { unitId } = params;- if (unitId === DOCS_ZEN_EDITOR_UNIT_ID_KEY) {- const { row, column } = editorBridgeService.getEditLocation()!;- const eventParams: ISheetEditChangingEventParams = {- workbook,- worksheet,- row,- column,- value: RichTextValue.create(univerInstanceService.getUnit<DocumentDataModel>(DOCS_ZEN_EDITOR_UNIT_ID_KEY)!.getSnapshot()),- isZenEditor: true,- };- this.fireEvent(this.Event.SheetEditChanging, eventParams);+ // Register rich text editing mutation handler+ this.registerEventHandler(+ this.Event.SheetEditChanging,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === RichTextEditingMutation.id) {+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) {+ return;+ }+ const { workbook, worksheet } = target;+ const editorBridgeService = injector.get(IEditorBridgeService);+ const univerInstanceService = injector.get(IUniverInstanceService);+ const params = commandInfo.params as IRichTextEditingMutationParams;+ if (!editorBridgeService.isVisible().visible) return;+ const { unitId } = params;+ if (unitId === DOCS_ZEN_EDITOR_UNIT_ID_KEY) {+ const { row, column } = editorBridgeService.getEditLocation()!;+ const eventParams: ISheetEditChangingEventParams = {+ workbook,+ worksheet,+ row,+ column,+ value: RichTextValue.create(univerInstanceService.getUnit<DocumentDataModel>(DOCS_ZEN_EDITOR_UNIT_ID_KEY)!.getSnapshot()),+ isZenEditor: true,+ };+ this.fireEvent(this.Event.SheetEditChanging, eventParams);+ }}- }- }));+ })+ );}/**diff --git a/packages/sheets/src/facade/f-univer.ts b/packages/sheets/src/facade/f-univer.tsindex 685f087c53..ff30987302 100644--- a/packages/sheets/src/facade/f-univer.ts+++ b/packages/sheets/src/facade/f-univer.ts@@ -168,27 +168,27 @@ export class FUniverSheetsMixin extends FUniver implements IFUniverSheetsMixin {private _initWorkbookEvent(injector: Injector): void {const univerInstanceService = injector.get(IUniverInstanceService);- this.disposeWithMe(- univerInstanceService.unitDisposed$.subscribe((unit) => {- if (!this._eventRegistry.get(this.Event.WorkbookDisposed)) return;+ // Register workbook disposed event handler+ this.registerEventHandler(+ this.Event.WorkbookDisposed,+ () => univerInstanceService.unitDisposed$.subscribe((unit) => {if (unit.type === UniverInstanceType.UNIVER_SHEET) {this.fireEvent(this.Event.WorkbookDisposed,{unitId: unit.getUnitId(),unitType: unit.type,snapshot: unit.getSnapshot() as IWorkbookData,-});}}));- this.disposeWithMe(- univerInstanceService.unitAdded$.subscribe((unit) => {- if (!this._eventRegistry.get(this.Event.WorkbookCreated)) return;-+ // Register workbook created event handler+ this.registerEventHandler(+ this.Event.WorkbookCreated,+ () => univerInstanceService.unitAdded$.subscribe((unit) => {if (unit.type === UniverInstanceType.UNIVER_SHEET) {const workbook = unit as Workbook;const workbookUnit = injector.createInstance(FWorkbook, workbook);@@ -211,114 +211,141 @@ export class FUniverSheetsMixin extends FUniver implements IFUniverSheetsMixin {// eslint-disable-next-line max-lines-per-functionoverride _initialize(injector: Injector): void {const commandService = injector.get(ICommandService);- this.disposeWithMe(- // eslint-disable-next-line max-lines-per-function, complexity- commandService.beforeCommandExecuted((commandInfo) => {- switch (commandInfo.id) {- case InsertSheetCommand.id: {- const params = (commandInfo.params) as IInsertSheetCommandParams;- const { unitId, index, sheet } = params || {};- const workbook = unitId ? this.getUniverSheet(unitId) : this.getActiveWorkbook?.();- if (!workbook) {- return;- }- const eventParams: IBeforeSheetCreateEventParams = {- workbook,- index,- sheet,- };- this.fireEvent(- this.Event.BeforeSheetCreate,- eventParams- );- // cancel this command- if (eventParams.cancel) {- throw new CanceledError();- }- break;- }- case SetWorksheetActiveOperation.id: {- if (!this._eventListend(this.Event.BeforeActiveSheetChange)) return;- const { subUnitId: sheetId, unitId } = commandInfo.params as ISetWorksheetActivateCommandParams;- const workbook = unitId ? this.getUniverSheet(unitId) : this.getActiveWorkbook?.();- if (!workbook || !sheetId) return;- const activeSheet = workbook.getSheetBySheetId(sheetId);- const oldActiveSheet = workbook.getActiveSheet();- if (!activeSheet || !oldActiveSheet) return;- this._fireBeforeActiveSheetChange(workbook, activeSheet, oldActiveSheet);- break;- }- case RemoveSheetCommand.id: {- if (!this._eventListend(this.Event.BeforeSheetDelete)) return;- const target = this.getCommandSheetTarget(commandInfo);- if (!target) return;- const { workbook, worksheet } = target;- this._fireBeforeSheetDelete(workbook, worksheet);- break;- }- case SetWorksheetOrderCommand.id: {- if (!this._eventListend(this.Event.BeforeSheetMove)) return;- const { fromOrder, toOrder } = commandInfo.params as ISetWorksheetOrderMutationParams;- const target = this.getCommandSheetTarget(commandInfo);- if (!target) return;- this._fireBeforeSheetMove(target.workbook, target.worksheet, toOrder, fromOrder);- break;- }- case SetWorksheetNameCommand.id: {- if (!this._eventListend(this.Event.BeforeSheetNameChange)) return;- const { name } = commandInfo.params as ISetWorksheetNameCommandParams;- const target = this.getCommandSheetTarget(commandInfo);- if (!target) return;- this._fireBeforeSheetNameChange(target.workbook, target.worksheet, name, target.worksheet.getSheetName());- break;- }- case SetTabColorCommand.id: {- if (!this._eventListend(this.Event.BeforeSheetTabColorChange)) return;- const { color } = commandInfo.params as ISetTabColorMutationParams;- const target = this.getCommandSheetTarget(commandInfo);- if (!target) return;- this._fireBeforeSheetTabColorChange(target.workbook, target.worksheet, color, target.worksheet.getTabColor());- break;- }- case SetWorksheetHideCommand.id: {- if (!this._eventListend(this.Event.BeforeSheetHideChange)) return;- const { hidden } = commandInfo.params as ISetWorksheetHideMutationParams;- const target = this.getCommandSheetTarget(commandInfo);- if (!target) return;- this._fireBeforeSheetHideChange(target.workbook, target.worksheet, Boolean(hidden));- break;- }- case SetGridlinesColorCommand.id: {- if (!this._eventListend(this.Event.BeforeGridlineColorChange)) return;- const target = this.getCommandSheetTarget(commandInfo);- if (!target) return;- this.fireEvent(this.Event.BeforeGridlineColorChange, {- ...target,- color: (commandInfo.params as ISetGridlinesColorCommandParams)?.color,- });- break;++ this.registerEventHandler(+ this.Event.BeforeSheetCreate,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === InsertSheetCommand.id) {+ const params = (commandInfo.params) as IInsertSheetCommandParams;+ const { unitId, index, sheet } = params || {};+ const workbook = unitId ? this.getUniverSheet(unitId) : this.getActiveWorkbook?.();+ if (!workbook) {+ return;}- case ToggleGridlinesCommand.id: {- if (!this._eventListend(this.Event.BeforeGridlineEnableChange)) return;- const target = this.getCommandSheetTarget(commandInfo);- if (!target) return;- this.fireEvent(this.Event.BeforeGridlineEnableChange, {- ...target,- enabled: Boolean((commandInfo.params as IToggleGridlinesCommandParams)?.showGridlines) ?? !target.worksheet.hasHiddenGridLines(),- });- break;+ const eventParams: IBeforeSheetCreateEventParams = {+ workbook,+ index,+ sheet,+ };+ this.fireEvent(+ this.Event.BeforeSheetCreate,+ eventParams+ );+ // cancel this command+ if (eventParams.cancel) {+ throw new CanceledError();}- default:- break;}}));- this.disposeWithMe(- // eslint-disable-next-line max-lines-per-function, complexity- commandService.onCommandExecuted((commandInfo) => {+ this.registerEventHandler(+ this.Event.BeforeActiveSheetChange,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetWorksheetActiveOperation.id) {+ const { subUnitId: sheetId, unitId } = commandInfo.params as ISetWorksheetActivateCommandParams;+ const workbook = unitId ? this.getUniverSheet(unitId) : this.getActiveWorkbook?.();+ if (!workbook || !sheetId) return;+ const activeSheet = workbook.getSheetBySheetId(sheetId);+ const oldActiveSheet = workbook.getActiveSheet();+ if (!activeSheet || !oldActiveSheet) return;+ this._fireBeforeActiveSheetChange(workbook, activeSheet, oldActiveSheet);+ }+ })+ );++ this.registerEventHandler(+ this.Event.BeforeSheetDelete,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === RemoveSheetCommand.id) {+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) return;+ const { workbook, worksheet } = target;+ this._fireBeforeSheetDelete(workbook, worksheet);+ }+ })+ );++ this.registerEventHandler(+ this.Event.BeforeSheetMove,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetWorksheetOrderCommand.id) {+ const { fromOrder, toOrder } = commandInfo.params as ISetWorksheetOrderMutationParams;+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) return;+ this._fireBeforeSheetMove(target.workbook, target.worksheet, toOrder, fromOrder);+ }+ })+ );++ this.registerEventHandler(+ this.Event.BeforeSheetNameChange,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetWorksheetNameCommand.id) {+ const { name } = commandInfo.params as ISetWorksheetNameCommandParams;+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) return;+ this._fireBeforeSheetNameChange(target.workbook, target.worksheet, name, target.worksheet.getSheetName());+ }+ })+ );++ this.registerEventHandler(+ this.Event.BeforeSheetTabColorChange,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetTabColorCommand.id) {+ const { color } = commandInfo.params as ISetTabColorMutationParams;+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) return;+ this._fireBeforeSheetTabColorChange(target.workbook, target.worksheet, color, target.worksheet.getTabColor());+ }+ })+ );++ this.registerEventHandler(+ this.Event.BeforeSheetHideChange,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetWorksheetHideCommand.id) {+ const { hidden } = commandInfo.params as ISetWorksheetHideMutationParams;+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) return;+ this._fireBeforeSheetHideChange(target.workbook, target.worksheet, Boolean(hidden));+ }+ })+ );++ this.registerEventHandler(+ this.Event.BeforeGridlineColorChange,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetGridlinesColorCommand.id) {+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) return;+ this.fireEvent(this.Event.BeforeGridlineColorChange, {+ ...target,+ color: (commandInfo.params as ISetGridlinesColorCommandParams)?.color,+ });+ }+ })+ );++ this.registerEventHandler(+ this.Event.BeforeGridlineEnableChange,+ () => commandService.beforeCommandExecuted((commandInfo) => {+ if (commandInfo.id === ToggleGridlinesCommand.id) {+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) return;+ this.fireEvent(this.Event.BeforeGridlineEnableChange, {+ ...target,+ enabled: Boolean((commandInfo.params as IToggleGridlinesCommandParams)?.showGridlines) ?? !target.worksheet.hasHiddenGridLines(),+ });+ }+ })+ );++ this.registerEventHandler(+ this.Event.SheetValueChanged,+ () => commandService.onCommandExecuted((commandInfo) => {if (COMMAND_LISTENER_VALUE_CHANGE.indexOf(commandInfo.id) > -1) {- if (!this._eventListend(this.Event.SheetValueChanged)) return;const sheet = this.getActiveSheet();if (!sheet) return;const ranges = getValueChangedEffectedRange(commandInfo)@@ -333,93 +360,119 @@ export class FUniverSheetsMixin extends FUniver implements IFUniverSheetsMixin {payload: commandInfo as CommandListenerValueChange,effectedRanges: ranges,});- return;}+ })+ );- switch (commandInfo.id) {- case InsertSheetCommand.id: {- const params = commandInfo.params as IInsertSheetCommandParams;- const { unitId } = params || {};- const workbook = unitId ? this.getUniverSheet(unitId) : this.getActiveWorkbook?.();- if (!workbook) {- return;- }- const worksheet = workbook.getActiveSheet();- if (!worksheet) {- return;- }- const eventParams: ISheetCreatedEventParams = {- workbook,- worksheet,- };- this.fireEvent(- this.Event.SheetCreated,- eventParams- );- break;- }- case SetWorksheetActiveOperation.id: {- if (!this._eventListend(this.Event.ActiveSheetChanged)) return;- const target = this.getActiveSheet();- if (!target) return;- const { workbook, worksheet: activeSheet } = target;- this._fireActiveSheetChanged(workbook, activeSheet);- break;- }- case RemoveSheetCommand.id: {- if (!this._eventListend(this.Event.SheetDeleted)) return;- const { subUnitId: sheetId, unitId } = commandInfo.params as IRemoveSheetCommandParams;- const workbook = unitId ? this.getUniverSheet(unitId) : this.getActiveWorkbook?.();- if (!workbook || !sheetId) return;- this._fireSheetDeleted(workbook, sheetId);- break;- }- case SetWorksheetOrderCommand.id: {- if (!this._eventListend(this.Event.SheetMoved)) return;- const { toOrder: toIndex } = commandInfo.params as ISetWorksheetOrderMutationParams;- const target = this.getCommandSheetTarget(commandInfo);- if (!target) return;- this._fireSheetMoved(target.workbook, target.worksheet, toIndex);- break;- }- case SetWorksheetNameCommand.id: {- if (!this._eventListend(this.Event.SheetNameChanged)) return;- const { name } = commandInfo.params as ISetWorksheetNameCommandParams;- const target = this.getCommandSheetTarget(commandInfo);- if (!target) return;- this._fireSheetNameChanged(target.workbook, target.worksheet, name);- break;+ this.registerEventHandler(+ this.Event.SheetCreated,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === InsertSheetCommand.id) {+ const params = commandInfo.params as IInsertSheetCommandParams;+ const { unitId } = params || {};+ const workbook = unitId ? this.getUniverSheet(unitId) : this.getActiveWorkbook?.();+ if (!workbook) {+ return;}- case SetTabColorCommand.id: {- if (!this._eventListend(this.Event.SheetTabColorChanged)) return;- const { color } = commandInfo.params as ISetTabColorMutationParams;- const target = this.getCommandSheetTarget(commandInfo);- if (!target) return;- this._fireSheetTabColorChanged(target.workbook, target.worksheet, color);- break;+ const worksheet = workbook.getActiveSheet();+ if (!worksheet) {+ return;}- case SetWorksheetHideCommand.id: {- if (!this._eventListend(this.Event.SheetHideChanged)) return;- const { hidden } = commandInfo.params as ISetWorksheetHideMutationParams;- const target = this.getCommandSheetTarget(commandInfo);- if (!target) return;- this._fireSheetHideChanged(target.workbook, target.worksheet, !!hidden);- break;- }- case SetGridlinesColorCommand.id:- case ToggleGridlinesCommand.id: {- if (!this._eventListend(this.Event.GridlineChanged)) return;- const target = this.getCommandSheetTarget(commandInfo);- if (!target) return;- this.fireEvent(this.Event.GridlineChanged, {- ...target,- enabled: !target.worksheet.hasHiddenGridLines(),- color: target.worksheet.getGridLinesColor(),- });- break;- }- default:- break;+ const eventParams: ISheetCreatedEventParams = {+ workbook,+ worksheet,+ };+ this.fireEvent(+ this.Event.SheetCreated,+ eventParams+ );+ }+ })+ );++ this.registerEventHandler(+ this.Event.ActiveSheetChanged,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetWorksheetActiveOperation.id) {+ const target = this.getActiveSheet();+ if (!target) return;+ const { workbook, worksheet: activeSheet } = target;+ this._fireActiveSheetChanged(workbook, activeSheet);+ }+ })+ );++ this.registerEventHandler(+ this.Event.SheetDeleted,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === RemoveSheetCommand.id) {+ const { subUnitId: sheetId, unitId } = commandInfo.params as IRemoveSheetCommandParams;+ const workbook = unitId ? this.getUniverSheet(unitId) : this.getActiveWorkbook?.();+ if (!workbook || !sheetId) return;+ this._fireSheetDeleted(workbook, sheetId);+ }+ })+ );++ this.registerEventHandler(+ this.Event.SheetMoved,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetWorksheetOrderCommand.id) {+ const { toOrder: toIndex } = commandInfo.params as ISetWorksheetOrderMutationParams;+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) return;+ this._fireSheetMoved(target.workbook, target.worksheet, toIndex);+ }+ })+ );++ this.registerEventHandler(+ this.Event.SheetNameChanged,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetWorksheetNameCommand.id) {+ const { name } = commandInfo.params as ISetWorksheetNameCommandParams;+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) return;+ this._fireSheetNameChanged(target.workbook, target.worksheet, name);+ }+ })+ );++ this.registerEventHandler(+ this.Event.SheetTabColorChanged,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetTabColorCommand.id) {+ const { color } = commandInfo.params as ISetTabColorMutationParams;+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) return;+ this._fireSheetTabColorChanged(target.workbook, target.worksheet, color);+ }+ })+ );++ this.registerEventHandler(+ this.Event.SheetHideChanged,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetWorksheetHideCommand.id) {+ const { hidden } = commandInfo.params as ISetWorksheetHideMutationParams;+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) return;+ this._fireSheetHideChanged(target.workbook, target.worksheet, !!hidden);+ }+ })+ );++ this.registerEventHandler(+ this.Event.GridlineChanged,+ () => commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetGridlinesColorCommand.id || commandInfo.id === ToggleGridlinesCommand.id) {+ const target = this.getCommandSheetTarget(commandInfo);+ if (!target) return;+ this.fireEvent(this.Event.GridlineChanged, {+ ...target,+ enabled: !target.worksheet.hasHiddenGridLines(),+ color: target.worksheet.getGridLinesColor(),+ });}}));