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: use DI to refactor the whole system

Wenzhao Hu785468a5d020
diff --git a/docs/architecture-zh.md b/docs/architecture-zh.md
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/examples/univer-sheet-ts/src/main.tsx b/examples/univer-sheet-ts/src/main.tsx
index 97f8bd8552..86735865e1 100644
--- a/examples/univer-sheet-ts/src/main.tsx
+++ b/examples/univer-sheet-ts/src/main.tsx
@@ -10,29 +10,7 @@ import { FindPlugin } from '@univerjs/sheets-plugin-find';
import { DEFAULT_FORMULA_DATA_DEMO, FormulaPlugin } from '@univerjs/sheets-plugin-formula';
import { NumfmtPlugin } from '@univerjs/sheets-plugin-numfmt';
-const uiDefaultConfigDemo = {
- container: 'universheet',
- selections: {
- 'sheet-0001': [
- {
- selection: {
- startRow: 2,
- endRow: 2,
- startColumn: 3,
- endColumn: 3,
- },
- cell: {
- row: 2,
- column: 3,
- },
- },
- ],
- },
-};
-
-const sheetUIConfig = {
- container: 'universheet',
-};
+// TODO: @huwenzhao: change the following to new API
// univer
const univer = new Univer({
@@ -42,14 +20,14 @@ const univer = new Univer({
// base-render
univer.install(new RenderEngine());
-// universheet instance
-const universheet = UniverSheet.newInstance(DEFAULT_WORKBOOK_DATA_DEMO);
-// sheet.installPlugin(new RenderEngine());
+
+// register plugins
+univer.registerPlugin(SheetPlugin);
+
+// create univer sheet instance
+const universheet = univer.createUniverSheet(DEFAULT_WORKBOOK_DATA_DEMO);
univer.addUniverSheet(universheet);
// base-sheet
-universheet.installPlugin(new SheetPlugin());
-
-// universheet.installPlugin(new FormulaPlugin(DEFAULT_FORMULA_DATA_DEMO));
// ui-plugin-sheets
univer.install(
@@ -81,4 +59,4 @@ declare global {
univer?: any;
}
}
-window.univer = univer;
+window.univer = univer;
\ No newline at end of file
diff --git a/packages/base-sheets/src/SheetPlugin.ts b/packages/base-sheets/src/SheetPlugin.ts
index a8ff488d67..c519c98efd 100644
--- a/packages/base-sheets/src/SheetPlugin.ts
+++ b/packages/base-sheets/src/SheetPlugin.ts
@@ -1,6 +1,6 @@
import { Engine, RenderEngine } from '@univerjs/base-render';
-import { SheetContext, Plugin, PLUGIN_NAMES, DEFAULT_SELECTION, UniverSheet, UIObserver } from '@univerjs/core';
-import { Injector } from '@wendellhu/redi';
+import { SheetContext, Plugin, PLUGIN_NAMES, DEFAULT_SELECTION, UniverSheet, UIObserver, PluginType } from '@univerjs/core';
+import { Dependency, Inject, Injector, Optional } from '@wendellhu/redi';
import { SheetPluginObserve, uninstall } from './Basics/Observer';
import { CANVAS_VIEW_KEY } from './View/BaseView';
@@ -31,18 +31,19 @@ import { HideColumnRulerFactory } from './Basics/Register/HideColumnRuler';
* The main sheet base, construct the sheet container and layout, mount the rendering engine
*/
export class SheetPlugin extends Plugin<SheetPluginObserve, SheetContext> {
- private _injector: Injector;
+ static override type = PluginType.Sheet;
private _config: ISheetPluginConfig;
private _canvasEngine: Engine;
- // TODO@huwenzhao: these controllers should be removed finally after we completely refactored base-sheet plugin
+ // TODO: @wzhudev these controllers should be removed finally after we completely refactored base-sheet plugin
private _rightMenuController: RightMenuController;
private _toolbarController: ToolbarController;
+
private _editTooltipsController: EditTooltipsController;
private _formulaBarController: FormulaBarController;
@@ -63,16 +64,16 @@ export class SheetPlugin extends Plugin<SheetPluginObserve, SheetContext> {
private _hideColumnRulerFactory: HideColumnRulerFactory;
- constructor(config?: Partial<ISheetPluginConfig>) {
+ constructor(config: Partial<ISheetPluginConfig>, @Inject(Injector) private readonly sheetInjector: Injector) {
super(PLUGIN_NAMES.SPREADSHEET);
this._config = Object.assign(DEFAULT_SPREADSHEET_PLUGIN_DATA, config);
- this.initializeDependencies();
+ this.initializeDependencies(sheetInjector);
}
static create(config?: Partial<ISheetPluginConfig>) {
- return new SheetPlugin(config);
+ return new SheetPlugin(config || {}, new Injector()); // TODO: change this
}
installTo(universheetInstance: UniverSheet) {
@@ -114,15 +115,15 @@ export class SheetPlugin extends Plugin<SheetPluginObserve, SheetContext> {
// TODO@huwenzhao: We don't need to init controllers manually
initController() {
- this._sheetContainerController = this._injector.get(SheetContainerController);
- this._cellEditorController = this._injector.get(CellEditorController);
- this._formulaBarController = this._injector.get(FormulaBarController);
- this._editTooltipsController = this._injector.get(EditTooltipsController);
- this._sheetBarController = this._injector.get(SheetBarController);
- this._toolbarController = this._injector.get(ToolbarController);
- this._rightMenuController = this._injector.get(RightMenuController);
- this._countBarController = this._injector.get(CountBarController);
- this._hideColumnController = this._injector.get(HideColumnController);
+ this._sheetContainerController = this.sheetInjector.get(SheetContainerController);
+ this._cellEditorController = this.sheetInjector.get(CellEditorController);
+ this._formulaBarController = this.sheetInjector.get(FormulaBarController);
+ this._editTooltipsController = this.sheetInjector.get(EditTooltipsController);
+ this._sheetBarController = this.sheetInjector.get(SheetBarController);
+ this._toolbarController = this.sheetInjector.get(ToolbarController);
+ this._rightMenuController = this.sheetInjector.get(RightMenuController);
+ this._countBarController = this.sheetInjector.get(CountBarController);
+ this._hideColumnController = this.sheetInjector.get(HideColumnController);
}
initCanvasView() {
@@ -150,7 +151,7 @@ export class SheetPlugin extends Plugin<SheetPluginObserve, SheetContext> {
this._namedRangeActionExtensionFactory = new NamedRangeActionExtensionFactory(this);
actionRegister.add(this._namedRangeActionExtensionFactory);
- this._columnRulerManager = this._injector.get(ColumnRulerManager);
+ this._columnRulerManager = this.sheetInjector.get(ColumnRulerManager);
const rulerRegister = this._columnRulerManager.getRegister();
this._hideColumnRulerFactory = new HideColumnRulerFactory(this);
rulerRegister.add(this._hideColumnRulerFactory);
@@ -176,7 +177,7 @@ export class SheetPlugin extends Plugin<SheetPluginObserve, SheetContext> {
/** @deprecated DI */
getCanvasView() {
- return this._injector.get(CanvasView);
+ return this.sheetInjector.get(CanvasView);
}
/** @deprecated DI */
@@ -191,7 +192,7 @@ export class SheetPlugin extends Plugin<SheetPluginObserve, SheetContext> {
/** @deprecated DI */
getSelectionManager() {
- return this._injector.get(ISelectionManager);
+ return this.sheetInjector.get(ISelectionManager);
}
/** @deprecated DI */
@@ -268,10 +269,10 @@ export class SheetPlugin extends Plugin<SheetPluginObserve, SheetContext> {
return this.getGlobalContext().getObserverManager().requiredObserver<UIObserver<T>>(type, 'core');
}
- private initializeDependencies() {
+ private initializeDependencies(sheetInjector: Injector) {
const self = this;
- this._injector = new Injector([
+ const dependencies: Dependency[] = ([
[IGlobalContext, { useFactory: () => this.getGlobalContext() }],
[ISheetContext, { useFactory: () => this.getContext() }],
[IRenderingEngine, { useFactory: () => this.getGlobalContext().getPluginManager().getRequirePluginByName<RenderEngine>(PLUGIN_NAMES.BASE_RENDER).getEngine() }],
@@ -308,5 +309,13 @@ export class SheetPlugin extends Plugin<SheetPluginObserve, SheetContext> {
[ColumnRulerManager],
// #endregion Controllers
]);
+
+ dependencies.forEach(d => {
+ if (d.length === 1) {
+ sheetInjector.add(d[0]);
+ } else {
+ sheetInjector.add(d);
+ }
+ });
}
}
\ No newline at end of file
diff --git a/packages/core/src/Basics/Univer.ts b/packages/core/src/Basics/Univer.ts
index 8c445d16ed..0c79c4e673 100644
--- a/packages/core/src/Basics/Univer.ts
+++ b/packages/core/src/Basics/Univer.ts
@@ -1,19 +1,69 @@
+import { Injector, Ctor } from '@wendellhu/redi';
+
import { UniverSheet } from './UniverSheet';
import { UniverDoc } from './UniverDoc';
import { UniverSlide } from './UniverSlide';
import { Nullable } from '../Shared';
import { Context } from './Context';
-import { Plugin } from '../Plugin';
-import { IUniverData } from '../Types/Interfaces';
+import { Plugin, PluginType } from '../Plugin';
+import { IUniverData, IWorkbookConfig } from '../Types/Interfaces';
import { UniverObserverImpl } from './UniverObserverImpl';
+interface IPluginRegistryItem {
+ plugin: typeof Plugin;
+ options: any;
+}
+
+class PluginRegistry {
+ private readonly pluginsRegisteredByBusiness = new Map<PluginType, [IPluginRegistryItem]>();
+
+ registerPlugin(plugin: typeof Plugin, options: any) {
+ const type = plugin.type;
+ if (!this.pluginsRegisteredByBusiness.has(type)) {
+ this.pluginsRegisteredByBusiness.set(type, [] as unknown[] as [IPluginRegistryItem]);
+ }
+
+ this.pluginsRegisteredByBusiness.get(type)!.push({ plugin, options });
+ }
+
+ getRegisterPlugins(type: PluginType): [IPluginRegistryItem] {
+ return this.pluginsRegisteredByBusiness.get(type) || ([] as unknown[] as [IPluginRegistryItem]);
+ }
+}
+
+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;
+ }
+}
+
+/**
+ * Univer.
+ */
export class Univer {
+ private readonly _univerInjector: Injector;
+
+ private readonly _univerPluginStore = new PluginStore();
+
+ private readonly _univerPluginRegistry = new PluginRegistry();
+
private _univerSheets: UniverSheet[];
private _univerDocs: UniverDoc[];
private _univerSlides: UniverSlide[];
+ /**
+ * @deprecated
+ */
private _context: Context;
constructor(univerData: Partial<IUniverData> = {}) {
@@ -24,6 +74,40 @@ export class Univer {
this._context = new Context(univerData);
this._setObserver();
this._context.onUniver(this);
+
+ this._univerInjector = this.initializeInjector();
+ }
+
+ /** Register a plugin into univer. */
+ registerPlugin<T>(plugin: Ctor<T>, configs?: any): void {
+ // TODO: type of `configs` could be optimized here using typescript infer
+ if (plugin.type === PluginType.Univer) {
+ this.registerUniverPlugin(plugin);
+ } else if (plugin.type === PluginType.Sheet) {
+ this.registerSheetPlugin(plugin, configs);
+ } else {
+ throw new Error(`Unimplemented plugin system for business: "${plugin.type}".`);
+ }
+ }
+
+ /** Create a univer sheet instance with internal dependency injection. */
+ createUniverSheet(config: Partial<IWorkbookConfig>): UniverSheet {
+ const sheet = this._univerInjector.createInstance(UniverSheet, config);
+ sheet.context.onUniver(this);
+ this._univerSheets.push(sheet);
+
+ this.initializePluginsForSheet(sheet);
+ // TODO: initialize pligins for sheet
+
+ return sheet;
+ }
+
+ private initializePluginsForSheet(sheet: UniverSheet): void {
+ const plugins = this._univerPluginRegistry.getRegisterPlugins(PluginType.Sheet);
+ plugins.forEach(p => {
+ const pluginInstance: Plugin = this._univerInjector.createInstance(p.plugin as unknown as Ctor<any>, p.options);
+ sheet.installPlugin(pluginInstance);
+ });
}
addUniverSheet(univerSheet: UniverSheet): void {
@@ -107,4 +191,24 @@ export class Univer {
const manager = this._context.getObserverManager();
new UniverObserverImpl().install(manager);
}
-}
+
+ private initializeInjector(): Injector {
+ return new Injector();
+ }
+
+ private registerUniverPlugin<T>(plugin: Ctor<T>, options?: any): void {
+ // For plugins at Univer level. Plugins would be initialized immediately so they can register dependencies.
+ const pluginInstance: Plugin = this._univerInjector.createInstance(plugin as unknown as Ctor<any>, options);
+ pluginInstance.onCreate(this._context); // TODO: remove this later
+ this._univerPluginStore.addPlugin(pluginInstance);
+ }
+
+ private registerSheetPlugin(plugin: typeof Plugin, options?: any) {
+ // Add plugins to the plugin registration. And for each initialized UniverSheet, instantiate these dependencies immediately.
+ if (this._univerSheets.length) {
+ // TODO: add plugin to these already instantiated UniverSheet instances.
+ } else {
+ this._univerPluginRegistry.registerPlugin(plugin, options);
+ }
+ }
+}
\ No newline at end of file
diff --git a/packages/core/src/Basics/UniverSheet.ts b/packages/core/src/Basics/UniverSheet.ts
index 8f94bf7b8d..07c004f663 100644
--- a/packages/core/src/Basics/UniverSheet.ts
+++ b/packages/core/src/Basics/UniverSheet.ts
@@ -1,3 +1,4 @@
+import { Ctor, Injector, Optional, Disposable } from '@wendellhu/redi';
import { Workbook, ColorBuilder } from '../Sheets/Domain';
import { IWorkbookConfig } from '../Types/Interfaces';
import { BasePlugin, Plugin } from '../Plugin';
@@ -11,17 +12,36 @@ interface IComposedConfig {
workbookConfig: IWorkbookConfig;
}
+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;
+ }
+}
+
/**
* Externally provided UniverSheet root instance
*/
-export class UniverSheet {
+export class UniverSheet implements Disposable {
univerSheetConfig: Partial<IWorkbookConfig>;
+ private readonly _sheetInjector: Injector;
+
+ private readonly _pluginStore = new PluginStore();
+
private _context: SheetContext;
- constructor(univerSheetData: Partial<IWorkbookConfig> = {}) {
+ constructor(univerSheetData: Partial<IWorkbookConfig> = {}, @Optional(Injector) parentInjector?: Injector) {
this.univerSheetConfig = univerSheetData;
this._context = new SheetContext(univerSheetData);
+ this._sheetInjector = this.initializeInjector(parentInjector);
}
/**
@@ -101,6 +121,8 @@ export class UniverSheet {
return { workbookConfig, ...pluginConfig };
}
+ dispose(): void {}
+
/**
* get unit id
*/
@@ -108,6 +130,16 @@ export class UniverSheet {
return this.getWorkBook().getUnitId();
}
+ /**
+ * Add a plugin into UniverSheet. UniverSheet should add dependencies exposed from this plugin to its DI system.
+ * @param plugin constructor of the plugin class
+ */
+ addPlugin(plugin: typeof Plugin, options: any): void {
+ const pluginInstance: Plugin = this._sheetInjector.createInstance(plugin as unknown as Ctor<any>, options);
+ pluginInstance.onCreate(this._context); // TODO: remove context passed in here
+ this._pluginStore.addPlugin(pluginInstance);
+ }
+
/**
* install plugin
*
@@ -138,4 +170,8 @@ export class UniverSheet {
refreshWorkbook(univerSheetData: Partial<IWorkbookConfig> = {}) {
this._context.refreshWorkbook(univerSheetData);
}
+
+ private initializeInjector(parentInjector?: Injector): Injector {
+ return parentInjector ? parentInjector.createChild() : new Injector();
+ }
}
diff --git a/packages/core/src/Plugin/Plugin.ts b/packages/core/src/Plugin/Plugin.ts
index a2a6558663..8f749acb5f 100644
--- a/packages/core/src/Plugin/Plugin.ts
+++ b/packages/core/src/Plugin/Plugin.ts
@@ -4,6 +4,14 @@ import { Observable } from '../Observer';
import { Locale, Nullable, PropsFrom } from '../Shared';
import { Univer } from '../Basics';
+/** Plugin types for different kinds of business. */
+export enum PluginType {
+ Univer,
+ Doc,
+ Sheet,
+ Slide,
+}
+
/**
* Basics function of plugin
*/
@@ -13,8 +21,20 @@ export interface BasePlugin {
getGlobalContext(): Context;
getLocale(): Locale;
getPluginName(): string;
+
+ /**
+ * Could register dependencies at this lifecycle stage.
+ */
onCreate(context: ContextBase): void;
+
+ /**
+ * Could setup initialization works at this lifecycle stage.
+ */
onMounted(context: ContextBase): void;
+
+ /**
+ * Could do some initialization works at this lifecycle stage.
+ */
onDestroy(): void;
deleteObserve(...names: string[]): void;
@@ -30,11 +50,11 @@ export interface BasePlugin {
}
/**
- * Plug-in base class, all plug-ins must inherit from this base class. provides the basic method
+ * Plug-in base class, all plug-ins must inherit from this base class. Provide basic methods.
*/
-export abstract class Plugin<Obs = any, O extends ContextBase = ContextBase>
- implements BasePlugin
-{
+export abstract class Plugin<Obs = any, O extends ContextBase = ContextBase> implements BasePlugin {
+ static type: PluginType;
+
context: O;
private _name: string;
@@ -82,9 +102,7 @@ export abstract class Plugin<Obs = any, O extends ContextBase = ContextBase>
return this.context.getUniver();
}
- getObserver<K extends keyof Obs & string>(
- name: K
- ): Nullable<Observable<PropsFrom<Obs[K]>>> {
+ getObserver<K extends keyof Obs & string>(name: K): Nullable<Observable<PropsFrom<Obs[K]>>> {
const manager = this.context.getObserverManager();
return manager.getObserver(name, this._name);
}