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
refactor(core): optimize plugin service (#4662)
Wenzhao Hua2e3ae08f45b
diff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.tsindex eb6958fe87..c5b48d9c38 100644--- a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts+++ b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts@@ -285,7 +285,7 @@ test('diff set text format number cell', async () => {const filename = generateSnapshotName('set-text-format-number-cell');const screenshot = await page.locator(SHEET_MAIN_CANVAS_ID).screenshot();- await expect(screenshot).toMatchSnapshot(filename, { maxDiffPixels: 5 });+ await expect(screenshot).toMatchSnapshot(filename, { maxDiffPixels: 150 });await page.waitForTimeout(2000);await browser.close();diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex c04eed4a54..122d91cbb4 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -116,9 +116,8 @@ export type { IPermissionParam } from './services/permission/type';export type { IPermissionPoint } from './services/permission/type';export type { IPermissionTypes, RangePermissionPointConstructor, WorkbookPermissionPointConstructor, WorkSheetPermissionPointConstructor } from './services/permission/type';-export { Plugin } from './services/plugin/plugin';-export type { PluginCtor } from './services/plugin/plugin';-export { DependentOn, PluginService } from './services/plugin/plugin.service';+export type { PluginCtor } from './services/plugin/plugin.service.ts';+export { DependentOn, Plugin, PluginService } from './services/plugin/plugin.service';export { type DependencyOverride, mergeOverrideWithDependencies } from './services/plugin/plugin-override';export { IResourceLoaderService } from './services/resource-loader/type';export { ResourceManagerService } from './services/resource-manager/resource-manager.service';diff --git a/packages/core/src/services/__tests__/index.ts b/packages/core/src/services/__tests__/index.tsindex 5562f64063..00b4f3501c 100644--- a/packages/core/src/services/__tests__/index.ts+++ b/packages/core/src/services/__tests__/index.ts@@ -22,7 +22,7 @@ import { LocaleType } from '../../types/enum';import { Univer } from '../../univer';import { ICommandService } from '../command/command.service';import { IUniverInstanceService } from '../instance/instance.service';-import { Plugin } from '../plugin/plugin';+import { Plugin } from '../plugin/plugin.service';const TEST_WORKBOOK_DATA_DEMO: () => IWorkbookData = () => ({id: 'test',diff --git a/packages/core/src/services/plugin/plugin.service.ts b/packages/core/src/services/plugin/plugin.service.tsindex d1e64284fd..3d1aa31387 100644--- a/packages/core/src/services/plugin/plugin.service.ts+++ b/packages/core/src/services/plugin/plugin.service.ts@@ -16,7 +16,6 @@import type { Ctor, IDisposable } from '../../common/di';import type { UnitType } from '../../common/unit';-import type { Plugin, PluginCtor } from './plugin';import { skip } from 'rxjs';import { Inject, Injector } from '../../common/di';import { UniverInstanceType } from '../../common/unit';@@ -24,10 +23,79 @@ import { Disposable } from '../../shared/lifecycle';import { LifecycleStages } from '../lifecycle/lifecycle';import { getLifecycleStagesAndBefore, LifecycleService } from '../lifecycle/lifecycle.service';import { ILogService } from '../log/log.service';-import { DependentOnSymbol, PluginRegistry, PluginStore } from './plugin';const INIT_LAZY_PLUGINS_TIMEOUT = 4;+export const DependentOnSymbol = Symbol('DependentOn');++export type PluginCtor<T extends Plugin = Plugin> = Ctor<T> & {+ type: UnitType;+ pluginName: string;+ [DependentOnSymbol]?: PluginCtor[];+};++/**+ * Plug-in base class, all plug-ins must inherit from this base class. Provide basic methods.+ */+export abstract class Plugin extends Disposable {+ static pluginName: string;++ static type: UnitType = UniverInstanceType.UNIVER_UNKNOWN;++ protected abstract _injector: Injector;++ onStarting(): void {+ // empty+ }++ onReady(): void {+ // empty+ }++ onRendered(): void {+ // empty+ }++ onSteady(): void {+ // empty+ }++ getUnitType(): UnitType {+ return (this.constructor as typeof Plugin).type;+ }++ getPluginName(): string {+ return (this.constructor as typeof Plugin).pluginName;+ }+}++interface IPluginRegistryItem {+ plugin: PluginCtor<Plugin>;+ // eslint-disable-next-line ts/no-explicit-any+ options: any;+}++/**+ * Store plugin instances.+ */+export class PluginStore {+ private readonly _plugins: Plugin[] = [];++ addPlugin(plugin: Plugin): void {+ this._plugins.push(plugin);+ }++ removePlugins(): Plugin[] {+ const plugins = this._plugins.slice();+ this._plugins.length = 0;+ return plugins;+ }++ forEachPlugin(callback: (plugin: Plugin) => void): void {+ this._plugins.forEach(callback);+ }+}+/*** Use this decorator to declare dependencies among plugins. If a dependent plugin is not registered yet,* Univer will automatically register it with no configuration.@@ -50,76 +118,67 @@ export function DependentOn(...plugins: PluginCtor<Plugin>[]) {* This service manages plugin registration.*/export class PluginService implements IDisposable {- private readonly _pluginHolderForUniver: PluginHolder;- private readonly _pluginHoldersForTypes = new Map<UnitType, PluginHolder>();- private readonly _seenPlugins = new Set<string>();+ private _pluginRegistry = new Map<string, IPluginRegistryItem>();+ private readonly _pluginStore = new PluginStore();- constructor(- @Inject(Injector) private readonly _injector: Injector- ) {- this._pluginHolderForUniver = this._injector.createInstance(PluginHolder,- this._checkPluginSeen.bind(this),- this._immediateInitPlugin.bind(this)- );+ private readonly _seenPlugins = new Set<string>();+ private readonly _loadedPlugins = new Set<string>();- this._pluginHoldersForTypes.set(UniverInstanceType.UNIVER_UNKNOWN, this._pluginHolderForUniver);+ private readonly _loadedPluginTypes = new Set<UnitType>([UniverInstanceType.UNIVER_UNKNOWN]);- this._pluginHolderForUniver.start();- }+ constructor(+ @Inject(Injector) private readonly _injector: Injector,+ @Inject(LifecycleService) private readonly _lifecycleService: LifecycleService,+ @ILogService private readonly _logService: ILogService+ ) { }dispose(): void {- this._clearFlushTimer();-- for (const holder of this._pluginHoldersForTypes.values()) {- holder.dispose();- }-- this._pluginHolderForUniver.dispose();+ this._pluginStore.removePlugins().forEach((p) => p.dispose());+ this._flushTimerByType.forEach((timer) => clearTimeout(timer));}- /** Register a plugin into univer. */+ /**+ * Register a plugin into univer.+ * @param {PluginCtor} ctor The plugin's constructor.+ * @param {ConstructorParameters} [config] The configuration for the plugin.+ */registerPlugin<T extends PluginCtor>(ctor: T, config?: ConstructorParameters<T>[0]): void {this._assertPluginValid(ctor);- this._scheduleInitPlugin();++ const item = { plugin: ctor, options: config };+ this._pluginRegistry.set(ctor.pluginName, item);++ this._logService.debug('[PluginService]', `Plugin "${ctor.pluginName}" registered.`);const { type } = ctor;- if (type === UniverInstanceType.UNIVER_UNKNOWN) {- this._pluginHolderForUniver.register(ctor, config);- this._pluginHolderForUniver.flush();- } else {- // If it's type is for specific document, we should run them at specific time.- const holder = this._ensurePluginHolderForType(type);- holder.register(ctor, config);+ if (this._loadedPluginTypes.has(type)) {+ if (type === UniverInstanceType.UNIVER_UNKNOWN) {+ this._loadFromPlugins([item]);+ } else {+ this._flushType(type);+ }}}- startPluginForType(type: UniverInstanceType): void {- const holder = this._ensurePluginHolderForType(type);- holder.start();- }-- private _ensurePluginHolderForType(type: UnitType): PluginHolder {- if (!this._pluginHoldersForTypes.has(type)) {- const pluginHolder = this._injector.createInstance(PluginHolder,- this._checkPluginSeen.bind(this),- this._immediateInitPlugin.bind(this)- );- this._pluginHoldersForTypes.set(type, pluginHolder);- return pluginHolder;+ startPluginsForType(type: UnitType): void {+ if (this._loadedPluginTypes.has(type)) {+ return;}- return this._pluginHoldersForTypes.get(type)!;+ this._loadPluginsForType(type);}- private _immediateInitPlugin(ctor: PluginCtor): void {- this._seenPlugins.add(ctor.pluginName);-- const holder = this._ensurePluginHolderForType(ctor.type);- holder.immediateInitPlugin(ctor);- }+ private _loadPluginsForType(type: UnitType): void {+ const keys = Array.from(this._pluginRegistry.keys());+ const allPluginsOfThisType: IPluginRegistryItem[] = [];+ keys.forEach((key) => {+ const item = this._pluginRegistry.get(key)!;+ if (item.plugin.type === type) {+ allPluginsOfThisType.push(item);+ }+ });- private _checkPluginSeen(ctor: PluginCtor<Plugin>): boolean {- return this._seenPlugins.has(ctor.pluginName);+ this._loadFromPlugins(allPluginsOfThisType);}private _assertPluginValid(ctor: PluginCtor<Plugin>): void {@@ -140,159 +199,94 @@ export class PluginService implements IDisposable {this._seenPlugins.add(ctor.pluginName);}- private _flushTimer?: number;- private _scheduleInitPlugin() {- if (this._flushTimer === undefined) {- this._flushTimer = setTimeout(- () => {- if (!this._pluginHolderForUniver.started) {- this._pluginHolderForUniver.start();- }-- this._flushPlugins();- this._clearFlushTimer();- },- INIT_LAZY_PLUGINS_TIMEOUT- ) as unknown as number;- }- }-- private _clearFlushTimer() {- if (this._flushTimer) {- clearTimeout(this._flushTimer);- this._flushTimer = undefined;- }- }-- private _flushPlugins() {- this._pluginHolderForUniver.flush();- for (const [_, holder] of this._pluginHoldersForTypes) {- if (holder.started) {- holder.flush();- }- }- }-}--export class PluginHolder extends Disposable {- protected _started: boolean = false;- get started(): boolean { return this._started; }-- private _warnedAboutOnStartingDeprecation = false;-- /** Plugin constructors waiting to be initialized. */- protected readonly _pluginRegistry = new PluginRegistry();- /** Stores initialized plugin instances. */- protected readonly _pluginStore = new PluginStore();- /** Plugins instances as they are registered in batches. */- private readonly _pluginsInBatches: Plugin[][] = [];-- constructor(- private _checkPluginRegistered: (pluginCtor: PluginCtor) => boolean,- private _registerPlugin: <T extends PluginCtor>(plugin: T, config?: ConstructorParameters<T>[0]) => void,- @ILogService protected readonly _logService: ILogService,- @Inject(Injector) protected readonly _injector: Injector,-- @Inject(LifecycleService) protected readonly _lifecycleService: LifecycleService- ) {- super();-- this.disposeWithMe(this._lifecycleService.lifecycle$.pipe(skip(1)).subscribe((stage) => {- // Lifecycle of plugins should be coordinated. For example, if a plugin A depends on another plugin B, B should go- // through the lifecycle first. As a temporary solution, we make sure that plugin with type Common goes through the lifecycle first.- this._pluginsInBatches.forEach((plugins) => this._runStage(plugins, stage));- }));- }-- override dispose(): void {- super.dispose();-- this._pluginStore.forEachPlugin((plugin) => plugin.dispose());- this._pluginStore.removePlugins();-- this._pluginRegistry.removePlugins();-- this._pluginsInBatches.length = 0;- }-- register<T extends PluginCtor<Plugin>>(pluginCtor: T, config?: ConstructorParameters<T>[0]): void {- this._pluginRegistry.registerPlugin(pluginCtor, config);- }-- immediateInitPlugin<T extends Plugin>(plugin: PluginCtor<T>): void {- const p = this._initPlugin(plugin, undefined);- this._pluginsRunLifecycle([p]);- }-- start(): void {- if (this._started) return;- this._started = true;-- this.flush();- }-- flush(): void {- if (!this._started) {- return;- };-- const plugins = this._pluginRegistry.getRegisterPlugins().map(({ plugin, options }) => this._initPlugin(plugin, options));- if (!plugins.length) {- return;+ private _flushTimerByType = new Map<UnitType, number>();+ private _flushType(type: UnitType): void {+ if (this._flushTimerByType.get(type) === undefined) {+ this._flushTimerByType.set(type, setTimeout(() => {+ this._loadPluginsForType(type);+ this._flushTimerByType.delete(type);+ }, INIT_LAZY_PLUGINS_TIMEOUT) as unknown as number);}-- this._pluginsRunLifecycle(plugins);- this._pluginRegistry.removePlugins();}- // eslint-disable-next-line ts/no-explicit-any- private _initPlugin<T extends Plugin>(plugin: PluginCtor<T>, options: any): Plugin {- const dependents = plugin[DependentOnSymbol];- if (dependents) {- const exhaustUnregisteredDependents = () => {- const notRegisteredPlugin = dependents.find((d) => !this._checkPluginRegistered(d));- if (!notRegisteredPlugin) {- return false;- }-- // TODO: plugin with Univer type cannot dependent on types other than Univer.- if (plugin.type === UniverInstanceType.UNIVER_UNKNOWN && notRegisteredPlugin.type !== UniverInstanceType.UNIVER_UNKNOWN) {- throw new Error('[PluginService]: cannot register a plugin with Univer type that depends on a plugin with other type. '- + `The dependent is ${plugin.pluginName} and the dependency is ${notRegisteredPlugin.pluginName}.`- );- }+ private _loadFromPlugins(plugins: IPluginRegistryItem[]): void {+ const finalPlugins: IPluginRegistryItem[] = [];- this._logService.debug(- '[PluginService]',- `Plugin "${plugin.pluginName}" depends on "${notRegisteredPlugin.pluginName}" which is not registered. Univer will automatically register it with default configuration.`- );+ // We do a topological sort here to make sure that plugins with dependencies are registered first.+ const visited = new Set<string>();+ const dfs = (item: IPluginRegistryItem) => {+ const { plugin } = item;+ const { pluginName } = plugin;- this._registerPlugin(notRegisteredPlugin, undefined);- return true;- };+ // See if the plugin has already been loaded or visited.+ if (this._loadedPlugins.has(pluginName) || visited.has(pluginName)) {+ return;+ }- while (exhaustUnregisteredDependents()) {- continue;+ // Mark it self as visited.+ visited.add(pluginName);++ // We do not need to load it again because it will be loaded in this `_loadFromPlugins`.+ this._pluginRegistry.delete(pluginName);++ const dependents = plugin[DependentOnSymbol];+ if (dependents) {+ // Loop over its dependencies.+ dependents.forEach((d) => {+ // If the dependency is among those who are already registered, we should push it to the queue.+ const dItem = this._pluginRegistry.get(d.pluginName);+ if (dItem) {+ dfs(dItem);+ } else if (!this._seenPlugins.has(d.pluginName) && !visited.has(d.pluginName)) {+ // Otherwise, it maybe a plugin that is not registered yet.+ if (plugin.type === UniverInstanceType.UNIVER_UNKNOWN && d.type !== UniverInstanceType.UNIVER_UNKNOWN) {+ throw new Error('[PluginService]: cannot register a plugin with Univer type that depends on a plugin with other type. '+ + `The dependent is ${plugin.pluginName} and the dependency is ${d.pluginName}.`+ );+ }++ if (plugin.type !== d.type && d.type !== UniverInstanceType.UNIVER_UNKNOWN) {+ this._logService.debug(+ '[PluginService]',+ `Plugin "${pluginName}" depends on "${d.pluginName}" which has different type.`+ );+ }++ this._logService.debug(+ '[PluginService]',+ `Plugin "${pluginName}" depends on "${d.pluginName}" which is not registered. Univer will automatically register it with default configuration.`+ );++ this._assertPluginValid(d);+ dfs({ plugin: d, options: undefined });+ }+ });}- }- // eslint-disable-next-line ts/no-explicit-any- const pluginInstance: Plugin = this._injector.createInstance(plugin as unknown as Ctor<any>, options);- this._pluginStore.addPlugin(pluginInstance);+ finalPlugins.push(item);+ };- this._logService.debug('[PluginService]', `Plugin "${pluginInstance.getPluginName()}" registered.`);+ plugins.forEach((p) => dfs(p));- return pluginInstance;+ const pluginInstances = finalPlugins.map((p) => this._initPlugin(p.plugin, p.options));+ this._pluginsRunLifecycle(pluginInstances);}- // Here we should be careful with the sequence of which plugin should run first. We should manually add a queue here.- // Because lately registered plugins may get executed first.-protected _pluginsRunLifecycle(plugins: Plugin[]): void {// Let plugins go through already reached lifecycle stages.- getLifecycleStagesAndBefore(this._lifecycleService.stage).subscribe((stage) => this._runStage(plugins, stage));- // Push to the queue for later lifecycle.- this._pluginsInBatches.push(plugins);+ const currentStage = this._lifecycleService.stage;+ getLifecycleStagesAndBefore(currentStage).subscribe((stage) => this._runStage(plugins, stage));++ if (currentStage !== LifecycleStages.Steady) {+ const subscription = this._lifecycleService.lifecycle$.pipe(+ skip(1)+ ).subscribe((stage) => {+ this._runStage(plugins, stage);+ if (stage === LifecycleStages.Steady) {+ subscription.unsubscribe();+ }+ });+ }}private _runStage(plugins: Plugin[], stage: LifecycleStages): void {@@ -313,4 +307,14 @@ export class PluginHolder extends Disposable {}});}++ private _initPlugin<T extends Plugin>(plugin: PluginCtor<T>, options: any): Plugin {+ // eslint-disable-next-line ts/no-explicit-any+ const pluginInstance: Plugin = this._injector.createInstance(plugin as unknown as Ctor<any>, options);+ this._pluginStore.addPlugin(pluginInstance);+ this._loadedPlugins.add(plugin.pluginName);++ this._logService.debug('[PluginService]', `Plugin "${pluginInstance.getPluginName()}" loaded.`);+ return pluginInstance;+ }}diff --git a/packages/core/src/services/plugin/plugin.ts b/packages/core/src/services/plugin/plugin.tsdeleted file mode 100644index d2ba73f30a..0000000000--- a/packages/core/src/services/plugin/plugin.ts+++ /dev/null@@ -1,109 +0,0 @@-/**- * Copyright 2023-present DreamNum Co., Ltd.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import type { Ctor, Injector } from '../../common/di';-import { UniverInstanceType } from '../../common/unit';-import { Disposable } from '../../shared';--export const DependentOnSymbol = Symbol('DependentOn');--export type PluginCtor<T extends Plugin = Plugin> = Ctor<T> & {- type: UniverInstanceType;- pluginName: string;- [DependentOnSymbol]?: PluginCtor[];-};--/**- * Plug-in base class, all plug-ins must inherit from this base class. Provide basic methods.- */-export abstract class Plugin extends Disposable {- static pluginName: string;-- static type: UniverInstanceType = UniverInstanceType.UNIVER_UNKNOWN;-- protected abstract _injector: Injector;-- onStarting(): void {- // empty- }-- onReady(): void {- // empty- }-- onRendered(): void {- // empty- }-- onSteady(): void {- // empty- }-- getUniverInstanceType(): UniverInstanceType {- return (this.constructor as typeof Plugin).type;- }-- getPluginName(): string {- return (this.constructor as typeof Plugin).pluginName;- }-}--interface IPluginRegistryItem {- plugin: PluginCtor<Plugin>;- // eslint-disable-next-line ts/no-explicit-any- options: any;-}--/**- * Store plugin instances.- */-export class PluginStore {- private readonly _plugins: Plugin[] = [];-- addPlugin(plugin: Plugin): void {- this._plugins.push(plugin);- }-- removePlugins(): Plugin[] {- const plugins = this._plugins.slice();- this._plugins.length = 0;- return plugins;- }-- forEachPlugin(callback: (plugin: Plugin) => void): void {- this._plugins.forEach(callback);- }-}--/**- * Store plugin registry items.- */-export class PluginRegistry {- private _pluginsRegistered: IPluginRegistryItem[] = [];-- // eslint-disable-next-line ts/no-explicit-any- registerPlugin(pluginCtor: PluginCtor<any>, options: any) {- this._pluginsRegistered.push({ plugin: pluginCtor, options });- }-- getRegisterPlugins(): IPluginRegistryItem[] {- return this._pluginsRegistered.slice();- }-- removePlugins(): void {- this._pluginsRegistered = [];- }-}diff --git a/packages/core/src/univer.ts b/packages/core/src/univer.tsindex 47c6ef4a83..0df9ad66a0 100644--- a/packages/core/src/univer.ts+++ b/packages/core/src/univer.ts@@ -17,9 +17,10 @@import type { Dependency, IDisposable } from './common/di';import type { UnitModel, UnitType } from './common/unit';import type { LogLevel } from './services/log/log.service';-import type { Plugin, PluginCtor } from './services/plugin/plugin';import type { DependencyOverride } from './services/plugin/plugin-override';+import type { Plugin, PluginCtor } from './services/plugin/plugin.service';import type { IStyleSheet } from './services/theme/theme.service';+import type { ILocales } from './shared';import type { IWorkbookData } from './sheets/typedef';import type { LocaleType } from './types/enum/locale-type';import type { IDocumentData, ISlideData } from './types/interfaces';@@ -50,7 +51,7 @@ import { IResourceManagerService } from './services/resource-manager/type';import { ThemeService } from './services/theme/theme.service';import { IUndoRedoService, LocalUndoRedoService } from './services/undoredo/undoredo.service';import { UserManagerService } from './services/user-manager/user-manager.service';-import { DisposableCollection, type ILocales, toDisposable } from './shared';+import { DisposableCollection, toDisposable } from './shared';import { Workbook } from './sheets/workbook';import { SlideDataModel } from './slides/slide-model';@@ -165,7 +166,7 @@ export class Univer implements IDisposable {univerInstanceService.__setCreateHandler((type: UnitType, data, ctor, options) => {if (!this._startedTypes.has(type)) {- this._pluginService.startPluginForType(type);+ this._pluginService.startPluginsForType(type);this._startedTypes.add(type);const model = injector.createInstance(ctor, data);