Skip to content

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

refactor(core): support lazy load plugins (#768)

Wenzhao Hube18b70a302b
diff --git a/examples/src/sheets/lazy.ts b/examples/src/sheets/lazy.ts
new file mode 100644
index 0000000000..4fbb76de66
--- /dev/null
+++ b/examples/src/sheets/lazy.ts
@@ -0,0 +1,34 @@
+/**
+ * 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 { PluginCtor } from '@univerjs/core';
+import type { IUniscriptConfig } from '@univerjs/uniscript';
+import { UniverUniscriptPlugin } from '@univerjs/uniscript';
+
+export default function getLazyPlugins(): [PluginCtor<UniverUniscriptPlugin>, IUniscriptConfig] {
+ return [
+ UniverUniscriptPlugin,
+ {
+ getWorkerUrl(moduleID, label) {
+ if (label === 'typescript' || label === 'javascript') {
+ return './vs/language/typescript/ts.worker.js';
+ }
+
+ return './vs/editor/editor.worker.js';
+ },
+ },
+ ];
+}
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index f0aebcbc55..fab96bfbf2 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -26,13 +26,12 @@ import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';
import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';
import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';
import { UniverUIPlugin } from '@univerjs/ui';
-import type { IUniscriptConfig } from '@univerjs/uniscript';
-import { UniverUniscriptPlugin } from '@univerjs/uniscript';
import { DEFAULT_WORKBOOK_DATA_DEMO } from '../data';
import { DebuggerPlugin } from '../plugins/debugger';
import { locales } from './locales';
+const LOAD_LAZY_PLUGINS_TIMEOUT = 5_000;
// univer
const univer = new Univer({
theme: defaultTheme,
@@ -70,16 +69,6 @@ univer.registerPlugin(UniverRPCMainThreadPlugin, {
unsyncMutations: new Set([RichTextEditingMutation.id]),
} as IUniverRPCMainThreadConfig);
-univer.registerPlugin(UniverUniscriptPlugin, {
- getWorkerUrl(moduleID, label) {
- if (label === 'typescript' || label === 'javascript') {
- return './vs/language/typescript/ts.worker.js';
- }
-
- return './vs/editor/editor.worker.js';
- },
-} as IUniscriptConfig);
-
// create univer sheet instance
univer.createUniverSheet(DEFAULT_WORKBOOK_DATA_DEMO);
@@ -89,4 +78,11 @@ declare global {
}
}
+setTimeout(() => {
+ import('./lazy').then((lazy) => {
+ const plugin = lazy.default();
+ univer.registerPlugin(plugin[0], plugin[1]);
+ });
+}, LOAD_LAZY_PLUGINS_TIMEOUT);
+
window.univer = univer;
diff --git a/packages/core/src/basics/plugin-holder.ts b/packages/core/src/basics/plugin-holder.ts
new file mode 100644
index 0000000000..42413afeb5
--- /dev/null
+++ b/packages/core/src/basics/plugin-holder.ts
@@ -0,0 +1,84 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+import type { Ctor, Injector } from '@wendellhu/redi';
+
+import type { Plugin, PluginCtor } from '../plugin/plugin';
+import { LifecycleStages } from '../services/lifecycle/lifecycle';
+import type { LifecycleInitializerService, LifecycleService } from '../services/lifecycle/lifecycle.service';
+import { Disposable, toDisposable } from '../shared/lifecycle';
+
+export abstract class PluginHolder extends Disposable {
+ protected abstract get _lifecycleService(): LifecycleService;
+ protected abstract get _lifecycleInitializerService(): LifecycleInitializerService;
+ protected abstract get _injector(): Injector;
+
+ protected _started: boolean = false;
+
+ addPlugins(plugins: Array<[PluginCtor<any>, any]>): void {
+ if (!this._started) {
+ const pluginInstances = plugins.map(([plugin, options]) => this._initPlugin(plugin, options));
+ this._takePluginsThroughLifecycle(pluginInstances);
+ this._started = true;
+ } else {
+ const lazyPlugins = plugins.map(([plugin, options]) => this._initPlugin(plugin, options));
+ this._pluginsRunLifecycle(lazyPlugins, LifecycleStages.Starting);
+ setTimeout(() => this._takePluginsThroughLifecycle(lazyPlugins));
+ }
+ }
+
+ protected _takePluginsThroughLifecycle(plugins: Plugin[], skipStarting = false): void {
+ this.disposeWithMe(
+ toDisposable(
+ this._lifecycleService.subscribeWithPrevious().subscribe((stage) => {
+ if (skipStarting && stage === LifecycleStages.Starting) {
+ return;
+ }
+
+ this._pluginsRunLifecycle(plugins, stage);
+ })
+ )
+ );
+ }
+
+ protected _pluginsRunLifecycle(plugins: Plugin[], lifecycle: LifecycleStages): void {
+ plugins.forEach((p) => {
+ switch (lifecycle) {
+ case LifecycleStages.Starting:
+ p.onStarting(this._injector);
+ break;
+ case LifecycleStages.Ready:
+ p.onReady();
+ break;
+ case LifecycleStages.Rendered:
+ p.onRendered();
+ break;
+ case LifecycleStages.Steady:
+ p.onSteady();
+ break;
+ }
+ });
+
+ this._lifecycleInitializerService.initModulesOnStage(lifecycle);
+ }
+
+ protected _initPlugin<T extends Plugin>(plugin: PluginCtor<T>, options: any): Plugin {
+ const pluginInstance: Plugin = this._injector.createInstance(plugin as unknown as Ctor<any>, options);
+ return pluginInstance;
+ }
+}
diff --git a/packages/core/src/basics/univer-doc.ts b/packages/core/src/basics/univer-doc.ts
index 00757cbdc5..c59f87b6d7 100644
--- a/packages/core/src/basics/univer-doc.ts
+++ b/packages/core/src/basics/univer-doc.ts
@@ -14,72 +14,27 @@
* limitations under the License.
*/
-import type { Ctor } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
import { DocumentDataModel } from '../docs/data-model/document-data-model';
-import type { Plugin, PluginCtor } from '../plugin/plugin';
-import { PluginStore } from '../plugin/plugin';
-import { LifecycleStages } from '../services/lifecycle/lifecycle';
import { LifecycleInitializerService, LifecycleService } from '../services/lifecycle/lifecycle.service';
-import { Disposable, toDisposable } from '../shared/lifecycle';
import type { IDocumentData } from '../types/interfaces/i-document-data';
+import { PluginHolder } from './plugin-holder';
/**
* Externally provided UniverDoc root instance
*/
-export class UniverDoc extends Disposable {
- private readonly _pluginStore = new PluginStore();
-
+export class UniverDoc extends PluginHolder {
constructor(
- @Inject(Injector) private readonly _injector: Injector,
- @Inject(LifecycleInitializerService) private readonly _initService: LifecycleInitializerService
+ @Inject(Injector) protected readonly _injector: Injector,
+ @Inject(LifecycleService) protected readonly _lifecycleService: LifecycleService,
+ @Inject(LifecycleInitializerService)
+ protected readonly _lifecycleInitializerService: LifecycleInitializerService
) {
super();
}
- start(): void {
- this._pluginStore.forEachPlugin((p) => p.onStarting(this._injector));
- this._initService.initModulesOnStage(LifecycleStages.Starting);
- }
-
- ready(): void {
- this.disposeWithMe(
- toDisposable(
- this._injector
- .get(LifecycleService)
- .subscribeWithPrevious()
- .subscribe((stage) => {
- if (stage === LifecycleStages.Ready) {
- this._pluginStore.forEachPlugin((p) => p.onReady());
- this._initService.initModulesOnStage(LifecycleStages.Ready);
- return;
- }
-
- if (stage === LifecycleStages.Rendered) {
- this._pluginStore.forEachPlugin((p) => p.onRendered());
- this._initService.initModulesOnStage(LifecycleStages.Rendered);
- return;
- }
-
- if (stage === LifecycleStages.Steady) {
- this._pluginStore.forEachPlugin((p) => p.onSteady());
- this._initService.initModulesOnStage(LifecycleStages.Steady);
- }
- })
- )
- );
- }
-
createDoc(docData: Partial<IDocumentData>): DocumentDataModel {
return this._injector.createInstance(DocumentDataModel, docData);
}
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- addPlugin<T extends Plugin>(pluginCtor: PluginCtor<T>, options: any): void {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const pluginInstance: Plugin = this._injector.createInstance(pluginCtor as unknown as Ctor<any>, options);
- pluginInstance.onStarting(this._injector);
- this._pluginStore.addPlugin(pluginInstance);
- }
}
diff --git a/packages/core/src/basics/univer-sheet.ts b/packages/core/src/basics/univer-sheet.ts
index 57f78780f6..26db7ecf1a 100644
--- a/packages/core/src/basics/univer-sheet.ts
+++ b/packages/core/src/basics/univer-sheet.ts
@@ -14,91 +14,31 @@
* limitations under the License.
*/
-import type { Ctor, Dependency, IDisposable } from '@wendellhu/redi';
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+import type { IDisposable } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
-import type { Plugin, PluginCtor } from '../plugin/plugin';
-import { PluginStore } from '../plugin/plugin';
-import { LifecycleStages } from '../services/lifecycle/lifecycle';
import { LifecycleInitializerService, LifecycleService } from '../services/lifecycle/lifecycle.service';
-import { Disposable, toDisposable } from '../shared/lifecycle';
import { Workbook } from '../sheets/workbook';
import type { IWorkbookData } from '../types/interfaces/i-workbook-data';
+import { PluginHolder } from './plugin-holder';
/**
* Externally provided UniverSheet root instance
*/
-export class UniverSheet extends Disposable implements IDisposable {
- private readonly _pluginStore = new PluginStore();
-
+export class UniverSheet extends PluginHolder implements IDisposable {
constructor(
- @Inject(Injector) private readonly _injector: Injector,
- @Inject(LifecycleInitializerService) private readonly _initService: LifecycleInitializerService
+ @Inject(Injector) protected readonly _injector: Injector,
+ @Inject(LifecycleService) protected readonly _lifecycleService: LifecycleService,
+ @Inject(LifecycleInitializerService)
+ protected readonly _lifecycleInitializerService: LifecycleInitializerService
) {
super();
-
- this._initDependencies(_injector);
- }
-
- start(): void {
- this._pluginStore.forEachPlugin((p) => p.onStarting(this._injector));
- this._initService.initModulesOnStage(LifecycleStages.Starting);
- }
-
- ready(): void {
- this.disposeWithMe(
- toDisposable(
- this._injector
- .get(LifecycleService)
- .subscribeWithPrevious()
- .subscribe((stage) => {
- if (stage === LifecycleStages.Ready) {
- this._pluginStore.forEachPlugin((p) => p.onReady());
- this._initService.initModulesOnStage(LifecycleStages.Ready);
- return;
- }
-
- if (stage === LifecycleStages.Rendered) {
- this._pluginStore.forEachPlugin((p) => p.onRendered());
- this._initService.initModulesOnStage(LifecycleStages.Rendered);
- return;
- }
-
- if (stage === LifecycleStages.Steady) {
- this._pluginStore.forEachPlugin((p) => p.onSteady());
- this._initService.initModulesOnStage(LifecycleStages.Steady);
- }
- })
- )
- );
}
createSheet(workbookConfig: Partial<IWorkbookData>): Workbook {
const workbook = this._injector.createInstance(Workbook, workbookConfig);
return workbook;
}
-
- override dispose(): void {
- super.dispose();
-
- this._pluginStore.removePlugins();
- }
-
- /**
- * Add a plugin into UniverSheet. UniverSheet should add dependencies exposed from this plugin to its DI system.
- *
- * @param plugin constructor of the plugin class
- * @param options options to this plugin
- *
- * @internal
- */
- addPlugin<T extends Plugin>(plugin: PluginCtor<T>, options: any): void {
- const pluginInstance: Plugin = this._injector.createInstance(plugin as unknown as Ctor<any>, options);
- this._pluginStore.addPlugin(pluginInstance);
- }
-
- private _initDependencies(injector: Injector): void {
- const dependencies: Dependency[] = [];
- dependencies.forEach((d) => injector.add(d));
- }
}
diff --git a/packages/core/src/basics/univer-slide.ts b/packages/core/src/basics/univer-slide.ts
index d7c7f1b7fe..ce49741a1d 100644
--- a/packages/core/src/basics/univer-slide.ts
+++ b/packages/core/src/basics/univer-slide.ts
@@ -14,78 +14,28 @@
* limitations under the License.
*/
-import type { Ctor } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
-import type { Plugin, PluginCtor } from '../plugin/plugin';
-import { PluginStore } from '../plugin/plugin';
-import { LifecycleStages } from '../services/lifecycle/lifecycle';
import { LifecycleInitializerService, LifecycleService } from '../services/lifecycle/lifecycle.service';
-import { Disposable, toDisposable } from '../shared/lifecycle';
import { Slide } from '../slides/domain/slide-model';
import type { ISlideData } from '../types/interfaces/i-slide-data';
+import { PluginHolder } from './plugin-holder';
/**
* Externally provided UniverSlide root instance
*/
-export class UniverSlide extends Disposable {
- private readonly _pluginStore = new PluginStore();
-
+export class UniverSlide extends PluginHolder {
constructor(
- @Inject(Injector) private readonly _injector: Injector,
- @Inject(LifecycleService) private readonly _lifecycleService: LifecycleService,
- @Inject(LifecycleInitializerService) private readonly _initializerService: LifecycleInitializerService
+ @Inject(Injector) protected readonly _injector: Injector,
+ @Inject(LifecycleService) protected readonly _lifecycleService: LifecycleService,
+ @Inject(LifecycleInitializerService)
+ protected readonly _lifecycleInitializerService: LifecycleInitializerService
) {
super();
}
- start(): void {
- this._pluginStore.forEachPlugin((p) => p.onStarting(this._injector));
- this._initializerService.initModulesOnStage(LifecycleStages.Starting);
- }
-
- ready(): void {
- this.disposeWithMe(
- toDisposable(
- this._lifecycleService.subscribeWithPrevious().subscribe((stage) => {
- if (stage === LifecycleStages.Ready) {
- this._pluginStore.forEachPlugin((p) => p.onReady());
- this._initializerService.initModulesOnStage(LifecycleStages.Ready);
- return;
- }
-
- if (stage === LifecycleStages.Rendered) {
- this._pluginStore.forEachPlugin((p) => p.onRendered());
- this._initializerService.initModulesOnStage(LifecycleStages.Rendered);
- return;
- }
-
- if (stage === LifecycleStages.Steady) {
- this._pluginStore.forEachPlugin((p) => p.onSteady());
- this._initializerService.initModulesOnStage(LifecycleStages.Steady);
- }
- })
- )
- );
- }
-
createSlide(data: Partial<ISlideData>): Slide {
const slide = this._injector.createInstance(Slide, data);
return slide;
}
-
- /**
- * Add a plugin into UniverSlide. UniverSlide should add dependencies exposed from this plugin to its DI system.
- *
- * @param plugin constructor of the plugin class
- * @param options options to this plugin
- *
- * @internal
- */
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- addPlugin<T extends Plugin>(plugin: PluginCtor<T>, options: any): void {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const pluginInstance: Plugin = this._injector.createInstance(plugin as unknown as Ctor<any>, options);
- this._pluginStore.addPlugin(pluginInstance);
- }
}
diff --git a/packages/core/src/basics/univer.ts b/packages/core/src/basics/univer.ts
index aa9449a1fb..6e2f77ac18 100644
--- a/packages/core/src/basics/univer.ts
+++ b/packages/core/src/basics/univer.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import type { Ctor } from '@wendellhu/redi';
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
import { Injector } from '@wendellhu/redi';
import type { DocumentDataModel } from '../docs/data-model/document-data-model';
@@ -43,15 +44,15 @@ import type { Workbook } from '../sheets/workbook';
import type { Slide } from '../slides/domain/slide-model';
import type { LocaleType } from '../types/enum/locale-type';
import type { IDocumentData, ISlideData, IUniverData, IWorkbookData } from '../types/interfaces';
+import { PluginHolder } from './plugin-holder';
import { UniverDoc } from './univer-doc';
import { UniverSheet } from './univer-sheet';
import { UniverSlide } from './univer-slide';
-/**
- * Univer.
- */
-export class Univer {
- private readonly _rootInjector: Injector;
+const INIT_LAZY_PLUGINS_TIMEOUT = 200;
+
+export class Univer extends PluginHolder {
+ protected readonly _injector: Injector;
private readonly _univerPluginStore = new PluginStore();
private readonly _univerPluginRegistry = new PluginRegistry();
@@ -61,45 +62,40 @@ export class Univer {
private _univerSlide: UniverSlide | null = null;
private get _univerInstanceService(): IUniverInstanceService {
- return this._rootInjector.get(IUniverInstanceService);
+ return this._injector.get(IUniverInstanceService);
+ }
+
+ protected get _lifecycleService(): LifecycleService {
+ return this._injector.get(LifecycleService);
+ }
+
+ protected get _lifecycleInitializerService(): LifecycleInitializerService {
+ return this._injector.get(LifecycleInitializerService);
}
constructor(univerData: Partial<IUniverData> = {}) {
- this._rootInjector = this._initDependencies();
+ super();
+
+ this._injector = this._initDependencies();
const { theme, locale, locales, logLevel } = univerData;
- theme && this._rootInjector.get(ThemeService).setTheme(theme);
- locales && this._rootInjector.get(LocaleService).load(locales);
- locale && this._rootInjector.get(LocaleService).setLocale(locale);
- logLevel && this._rootInjector.get(ILogService).setLogLevel(logLevel);
+ theme && this._injector.get(ThemeService).setTheme(theme);
+ locales && this._injector.get(LocaleService).load(locales);
+ locale && this._injector.get(LocaleService).setLocale(locale);
+ logLevel && this._injector.get(ILogService).setLogLevel(logLevel);
}
__getInjector(): Injector {
- return this._rootInjector;
+ return this._injector;
}
- dispose(): void {
- this._rootInjector.dispose();
- }
-
- /** Register a plugin into univer. */
- registerPlugin<T extends Plugin>(plugin: PluginCtor<T>, configs?: any): void {
- if (plugin.type === PluginType.Univer) {
- this._registerUniverPlugin(plugin, configs);
- } else if (plugin.type === PluginType.Sheet) {
- this._registerUniverSheets(plugin, configs);
- } else if (plugin.type === PluginType.Doc) {
- this._registerUniverDocs(plugin, configs);
- } else if (plugin.type === PluginType.Slide) {
- this._registerUniverSlides(plugin, configs);
- } else {
- throw new Error(`Unimplemented plugin system for business: "${plugin.type}".`);
- }
+ override dispose(): void {
+ this._injector.dispose();
}
setLocale(locale: LocaleType) {
- this._rootInjector.get(LocaleService).setLocale(locale);
+ this._injector.get(LocaleService).setLocale(locale);
}
/**
@@ -113,17 +109,18 @@ export class Univer {
};
if (!this._univerSheet) {
- this._univerSheet = this._rootInjector.createInstance(UniverSheet);
- this._univerPluginRegistry
+ this._tryProgressToStart();
+
+ const univerSheet = (this._univerSheet = this._injector.createInstance(UniverSheet));
+ const sheetPlugins: Array<[PluginCtor<any>, any]> = this._univerPluginRegistry
.getRegisterPlugins(PluginType.Sheet)
- .forEach((p) => this._univerSheet!.addPlugin(p.plugin as unknown as PluginCtor<any>, p.options));
- this._tryStart();
- this._univerSheet.start();
+ .map((p) => [p.plugin, p.options]);
+ this._univerPluginRegistry.clearPluginsOfType(PluginType.Sheet);
+ univerSheet.addPlugins(sheetPlugins);
addSheet();
this._tryProgressToReady();
- this._univerSheet.ready();
} else {
addSheet();
}
@@ -139,17 +136,18 @@ export class Univer {
};
if (!this._univerDoc) {
- this._univerDoc = this._rootInjector.createInstance(UniverDoc);
- this._univerPluginRegistry
+ this._tryProgressToStart();
+
+ const univerDoc = (this._univerDoc = this._injector.createInstance(UniverDoc));
+ const docPlugins: Array<[PluginCtor<any>, any]> = this._univerPluginRegistry
.getRegisterPlugins(PluginType.Doc)
- .forEach((p) => this._univerDoc!.addPlugin(p.plugin as unknown as PluginCtor<any>, p.options));
- this._tryStart();
- this._univerDoc.start();
+ .map((p) => [p.plugin, p.options]);
+ this._univerPluginRegistry.clearPluginsOfType(PluginType.Doc);
+ univerDoc.addPlugins(docPlugins);
addDoc();
this._tryProgressToReady();
- this._univerDoc.ready();
} else {
addDoc();
}
@@ -165,13 +163,15 @@ export class Univer {
};
if (!this._univerSlide) {
- this._univerSlide = this._rootInjector.createInstance(UniverSlide);
+ this._tryProgressToStart();
- this._univerPluginRegistry
+ const univerSlide = (this._univerSlide = this._injector.createInstance(UniverSlide));
+ const slidePlugins: Array<[PluginCtor<any>, any]> = this._univerPluginRegistry
.getRegisterPlugins(PluginType.Slide)
- .forEach((p) => this._univerSlide!.addPlugin(p.plugin as unknown as PluginCtor<any>, p.options));
- this._tryStart();
- this._univerSlide.ready();
+ .map((p) => [p.plugin, p.options]);
+ this._univerPluginRegistry.clearPluginsOfType(PluginType.Slide);
+ univerSlide.addPlugins(slidePlugins);
+
addSlide();
this._tryProgressToReady();
@@ -216,68 +216,126 @@ export class Univer {
]);
}
- private _tryStart(): void {
- this._rootInjector.get(LifecycleInitializerService).start();
+ /**
+ * Initialize modules provided by Univer-type plugins.
+ */
+ private _tryProgressToStart(): void {
+ if (this._started) {
+ return;
+ }
+
+ this._injector.get(LifecycleInitializerService).start();
+ this._started = true;
}
private _tryProgressToReady(): void {
- const lifecycleService = this._rootInjector.get(LifecycleService);
+ const lifecycleService = this._injector.get(LifecycleService);
if (lifecycleService.stage < LifecycleStages.Ready) {
- this._rootInjector.get(LifecycleService).stage = LifecycleStages.Ready;
+ this._injector.get(LifecycleService).stage = LifecycleStages.Ready;
this._univerPluginStore.forEachPlugin((p) => p.onReady());
}
}
- private _registerUniverPlugin<T extends Plugin>(plugin: PluginCtor<T>, options?: any): void {
- // For plugins at Univer level. Plugins would be initialized immediately so they can register dependencies.
- const pluginInstance: Plugin = this._rootInjector.createInstance(plugin as unknown as Ctor<any>, options);
- pluginInstance.onStarting(this._rootInjector);
- this._univerPluginStore.addPlugin(pluginInstance);
+ // #region register plugins
+
+ /** Register a plugin into univer. */
+ registerPlugin<T extends Plugin>(plugin: PluginCtor<T>, config?: any): void {
+ if (plugin.type === PluginType.Univer) {
+ this._registerUniverPlugin(plugin, config);
+ } else if (plugin.type === PluginType.Sheet) {
+ this._registerSheetsPlugin(plugin, config);
+ } else if (plugin.type === PluginType.Doc) {
+ this._registerDocsPlugin(plugin, config);
+ } else if (plugin.type === PluginType.Slide) {
+ this._registerSlidesPlugin(plugin, config);
+ } else {
+ throw new Error(`Unimplemented plugin system for business: "${plugin.type}".`);
+ }
+
+ // If Univer has already started, we should manually call onStarting for the plugin.
+ // We do that in an asynchronous way, because user may lazy load several plugins at the same time.
+ if (this._started) {
+ return this._scheduleInitPluginAfterStarted();
+ }
+ }
+
+ private _initLazyPluginsTimer?: number;
+
+ private _scheduleInitPluginAfterStarted() {
+ if (this._initLazyPluginsTimer === undefined) {
+ this._initLazyPluginsTimer = setTimeout(
+ () => this._flushLazyPlugins(),
+ INIT_LAZY_PLUGINS_TIMEOUT
+ ) as unknown as number;
+ }
}
- private _registerUniverSheets<T extends Plugin>(pluginCtor: PluginCtor<T>, options?: any) {
- this._univerPluginRegistry.registerPlugin(pluginCtor, options);
- // TODO: implement add plugin when Univer business object is created
- // Add plugins to the plugin registration. And for each initialized UniverSheet, instantiate these dependencies immediately.
- // const sheets = this._currentUniverService.getAllUniverSheetsInstance();
- // if (sheets.length) {
- // sheets.forEach((sheet) => {
- // sheet.addPlugin(pluginCtor, options);
- // });
- // }
+ private _flushLazyPlugins() {
+ this._initLazyPluginsTimer = undefined;
+
+ const univerLazyPlugins = this._univerPluginRegistry.getRegisterPlugins(PluginType.Univer);
+ if (univerLazyPlugins.length) {
+ this._univerPluginRegistry.clearPluginsOfType(PluginType.Univer);
+ const pluginInstances = univerLazyPlugins.map((p) => this._injector.createInstance(p.plugin, p.options));
+ this._takePluginsThroughLifecycle(pluginInstances);
+ }
+
+ if (this._univerSheet) {
+ const sheetPlugins: Array<[PluginCtor<any>, any]> = this._univerPluginRegistry
+ .getRegisterPlugins(PluginType.Sheet)
+ .map((p) => [p.plugin, p.options]);
+
+ if (sheetPlugins.length) {
+ this._univerSheet.addPlugins(sheetPlugins);
+ this._univerPluginRegistry.clearPluginsOfType(PluginType.Sheet);
+ }
+ }
+
+ if (this._univerDoc) {
+ const docPlugins: Array<[PluginCtor<any>, any]> = this._univerPluginRegistry
+ .getRegisterPlugins(PluginType.Doc)
+ .map((p) => [p.plugin, p.options]);
+
+ if (docPlugins.length) {
+ this._univerDoc.addPlugins(docPlugins);
+ this._univerPluginRegistry.clearPluginsOfType(PluginType.Doc);
+ }
+ }
+
+ if (this._univerSlide) {
+ const slidePlugins: Array<[PluginCtor<any>, any]> = this._univerPluginRegistry
+ .getRegisterPlugins(PluginType.Slide)
+ .map((p) => [p.plugin, p.options]);
+
+ if (slidePlugins.length) {
+ this._univerSlide.addPlugins(slidePlugins);
+ this._univerPluginRegistry.clearPluginsOfType(PluginType.Slide);
+ }
+ }
}
- private _registerUniverDocs<T extends Plugin>(pluginCtor: PluginCtor<T>, options?: any) {
- this._univerPluginRegistry.registerPlugin(pluginCtor, options);
- // const docs = this._currentUniverService.getAllUniverDocsInstance();
- // if (docs.length) {
- // docs.forEach((doc) => {
- // doc.addPlugin(pluginCtor, options);
- // });
- // }
+ private _registerUniverPlugin<T extends Plugin>(pluginCtor: PluginCtor<T>, options?: any): void {
+ if (this._started) {
+ this._univerPluginRegistry.registerPlugin(pluginCtor, options);
+ } else {
+ // For plugins at Univer level. Plugins would be initialized immediately so they can register dependencies.
+ const pluginInstance: Plugin = this._injector.createInstance(pluginCtor, options);
+ pluginInstance.onStarting(this._injector);
+ this._univerPluginStore.addPlugin(pluginInstance);
+ }
}
- private _registerUniverSlides<T extends Plugin>(pluginCtor: PluginCtor<T>, options?: any) {
+ private _registerSheetsPlugin<T extends Plugin>(pluginCtor: PluginCtor<T>, options?: any) {
this._univerPluginRegistry.registerPlugin(pluginCtor, options);
- // const slides = this._currentUniverService.getAllUniverSlidesInstance();
- // if (slides.length) {
- // slides.forEach((slide) => {
- // slide.addPlugin(pluginCtor, options);
- // });
- // }
}
- private _initializePluginsForDoc(doc: UniverDoc): void {
- const plugins = this._univerPluginRegistry.getRegisterPlugins(PluginType.Doc);
- plugins.forEach((p) => {
- doc.addPlugin(p.plugin as unknown as PluginCtor<any>, p.options);
- });
+ private _registerDocsPlugin<T extends Plugin>(pluginCtor: PluginCtor<T>, options?: any) {
+ this._univerPluginRegistry.registerPlugin(pluginCtor, options);
}
- private _initializePluginsForSlide(slide: UniverSlide): void {
- const plugins = this._univerPluginRegistry.getRegisterPlugins(PluginType.Slide);
- plugins.forEach((p) => {
- slide.addPlugin(p.plugin as unknown as PluginCtor<any>, p.options);
- });
+ private _registerSlidesPlugin<T extends Plugin>(pluginCtor: PluginCtor<T>, options?: any) {
+ this._univerPluginRegistry.registerPlugin(pluginCtor, options);
}
+
+ // #endregion
}
diff --git a/packages/core/src/plugin/plugin.ts b/packages/core/src/plugin/plugin.ts
index 7fc4f5c65f..25af066c71 100644
--- a/packages/core/src/plugin/plugin.ts
+++ b/packages/core/src/plugin/plugin.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
import type { Ctor, Injector } from '@wendellhu/redi';
export type PluginCtor<T extends Plugin> = Ctor<T> & { type: PluginType };
@@ -57,7 +59,7 @@ export abstract class Plugin {
}
interface IPluginRegistryItem {
- plugin: typeof Plugin;
+ plugin: PluginCtor<Plugin>;
options: any;
}
@@ -65,20 +67,20 @@ interface IPluginRegistryItem {
* Store plugin instances.
*/
export class PluginStore {
- private readonly plugins: Plugin[] = [];
+ private readonly _plugins: Plugin[] = [];
addPlugin(plugin: Plugin): void {
- this.plugins.push(plugin);
+ this._plugins.push(plugin);
}
removePlugins(): Plugin[] {
- const plugins = this.plugins.slice();
- this.plugins.length = 0;
+ const plugins = this._plugins.slice();
+ this._plugins.length = 0;
return plugins;
}
forEachPlugin(callback: (plugin: Plugin) => void): void {
- this.plugins.forEach(callback);
+ this._plugins.forEach(callback);
}
}
@@ -86,18 +88,22 @@ export class PluginStore {
* Store plugin registry items.
*/
export class PluginRegistry {
- private readonly pluginsRegisteredByBusiness = new Map<PluginType, [IPluginRegistryItem]>();
+ private readonly _pluginsRegisteredByBusiness = new Map<PluginType, [IPluginRegistryItem]>();
registerPlugin(pluginCtor: PluginCtor<any>, options: any) {
const type = pluginCtor.type;
- if (!this.pluginsRegisteredByBusiness.has(type)) {
- this.pluginsRegisteredByBusiness.set(type, [] as unknown[] as [IPluginRegistryItem]);
+ if (!this._pluginsRegisteredByBusiness.has(type)) {
+ this._pluginsRegisteredByBusiness.set(type, [] as unknown[] as [IPluginRegistryItem]);
}
- this.pluginsRegisteredByBusiness.get(type)!.push({ plugin: pluginCtor, options });
+ this._pluginsRegisteredByBusiness.get(type)!.push({ plugin: pluginCtor, options });
}
getRegisterPlugins(type: PluginType): [IPluginRegistryItem] {
- return this.pluginsRegisteredByBusiness.get(type) || ([] as unknown[] as [IPluginRegistryItem]);
+ return this._pluginsRegisteredByBusiness.get(type) || ([] as unknown[] as [IPluginRegistryItem]);
+ }
+
+ clearPluginsOfType(type: PluginType): void {
+ this._pluginsRegisteredByBusiness.delete(type);
}
}