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: refactor UniverDoc to new architecture (#48)

Wenzhao Hu9a8a9d763c1e
diff --git a/examples/univer-doc-ts/src/main.tsx b/examples/univer-doc-ts/src/main.tsx
index 938da9868f..ef6ed16f24 100644
--- a/examples/univer-doc-ts/src/main.tsx
+++ b/examples/univer-doc-ts/src/main.tsx
@@ -1,29 +1,23 @@
-import { Univer, UniverDoc } from '@univerjs/core';
+import { LocaleType, Univer } from '@univerjs/core';
import { RenderEngine } from '@univerjs/base-render';
import { DocPlugin } from '@univerjs/base-docs';
import { DEFAULT_DOCUMENT_DATA_EN } from '@univerjs/common-plugin-data';
import { DocUIPlugin } from '@univerjs/ui-plugin-docs';
-import { UIPlugin } from '@univerjs/base-ui';
-// univer
-const univer = new Univer();
+const univer = new Univer({
+ locale: LocaleType.EN,
+});
-// base-render
-univer.install(new RenderEngine());
+univer.createUniverDoc(DEFAULT_DOCUMENT_DATA_EN);
-// univerdoc instance
-const univerdoc = UniverDoc.newInstance(DEFAULT_DOCUMENT_DATA_EN);
-univer.addUniverDoc(univerdoc);
-
-univerdoc.installPlugin(new DocPlugin());
-univer.install(
- new DocUIPlugin({
- container: 'univerdoc',
- layout: {
- docContainerConfig: {
- innerLeft: false,
- },
+univer.registerPlugin(RenderEngine);
+univer.registerPlugin(DocPlugin);
+univer.registerPlugin(DocUIPlugin, {
+ container: 'univerdoc',
+ layout: {
+ docContainerConfig: {
+ innerLeft: false,
},
- })
-);
+ },
+});
diff --git a/packages/base-docs/package.json b/packages/base-docs/package.json
index d60f53a7b2..09ef0ee674 100644
--- a/packages/base-docs/package.json
+++ b/packages/base-docs/package.json
@@ -58,6 +58,7 @@
"@univerjs/base-ui": "workspace:^0.0.1",
"@univerjs/common-plugin-data": "workspace:^0.0.1",
"@univerjs/core": "workspace:^0.0.1",
+ "@wendellhu/redi": "^0.10.0",
"css-vars-ponyfill": "^2.4.6",
"preact": "^10.12.1"
}
diff --git a/packages/base-docs/src/Controller/DocumentController.ts b/packages/base-docs/src/Controller/DocumentController.ts
index a5c56ce636..651d923274 100644
--- a/packages/base-docs/src/Controller/DocumentController.ts
+++ b/packages/base-docs/src/Controller/DocumentController.ts
@@ -1,14 +1,9 @@
-import { DocPlugin, IDocPluginConfig } from '../DocPlugin';
import { InputController } from './InputController';
export class DocumentController {
- private _inputController: InputController;
+ private readonly _inputController: InputController;
- constructor(private _plugin: DocPlugin, private _config: Partial<IDocPluginConfig> = {}) {
- this._initialize();
+ constructor() {
+ // this._inputController = new InputController();
}
-
- private _initialize() {
- this._inputController = new InputController(this._plugin);
- }
-}
+}
\ No newline at end of file
diff --git a/packages/base-docs/src/Controller/InfoBarController.ts b/packages/base-docs/src/Controller/InfoBarController.ts
index 81629a9d70..ea549276d5 100644
--- a/packages/base-docs/src/Controller/InfoBarController.ts
+++ b/packages/base-docs/src/Controller/InfoBarController.ts
@@ -1,5 +1,3 @@
-import { DocPlugin } from '../DocPlugin';
-
type IProps = {
locale?: string;
label?: string;
@@ -15,9 +13,4 @@ export interface BaseInfoBarProps {
}
export class InfoBarController {
- private _plugin: DocPlugin;
-
- constructor(plugin: DocPlugin) {
- this._plugin = plugin;
- }
-}
+}
\ No newline at end of file
diff --git a/packages/base-docs/src/Controller/InputController.ts b/packages/base-docs/src/Controller/InputController.ts
index 00327f1a47..28d499ffbe 100644
--- a/packages/base-docs/src/Controller/InputController.ts
+++ b/packages/base-docs/src/Controller/InputController.ts
@@ -1,16 +1,16 @@
import { Documents, IDocumentSkeletonSpan, SpanType, TextSelection } from '@univerjs/base-render';
import { KeyboardKeyType, Nullable } from '@univerjs/core';
-import { DocPlugin } from '../DocPlugin';
export class InputController {
private _previousIMEContent: string = '';
private _previousIMEStart: number;
- constructor(private _plugin: DocPlugin) {
+ constructor() {
this._initialize();
}
+ // eslint-disable-next-line max-lines-per-function
private _initialize() {
const events = this._plugin.getInputEvent();
if (!events) {
@@ -18,11 +18,9 @@ export class InputController {
}
const { onInputObservable, onCompositionstartObservable, onCompositionupdateObservable, onCompositionendObservable, onKeydownObservable } = events;
- const docsModel = this._plugin.context.getDocument();
-
onKeydownObservable.add((config) => {
const { event, document, activeSelection, selectionList } = config;
- let e = event as KeyboardEvent;
+ const e = event as KeyboardEvent;
const activeRange = activeSelection?.getRange();
@@ -222,4 +220,4 @@ export class InputController {
return spanGroup[0]?.spanType === SpanType.LIST;
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-docs/src/Controller/ToolbarController.ts b/packages/base-docs/src/Controller/ToolbarController.ts
index cb0a360f80..b064420723 100644
--- a/packages/base-docs/src/Controller/ToolbarController.ts
+++ b/packages/base-docs/src/Controller/ToolbarController.ts
@@ -1,17 +1 @@
-import { DocPlugin } from '../DocPlugin';
-
-interface BorderInfo {
- color: string;
- width: string;
-}
-
-/**
- *
- */
-export class ToolbarController {
- private _plugin: DocPlugin;
-
- constructor(plugin: DocPlugin) {
- this._plugin = plugin;
- }
-}
+export class ToolbarController {}
\ No newline at end of file
diff --git a/packages/base-docs/src/DocPlugin.ts b/packages/base-docs/src/DocPlugin.ts
index b3d1a7a812..2b7e5595b3 100644
--- a/packages/base-docs/src/DocPlugin.ts
+++ b/packages/base-docs/src/DocPlugin.ts
@@ -1,5 +1,6 @@
-import { DocContext, Plugin, PLUGIN_NAMES, UIObserver, UniverSheet } from '@univerjs/core';
-import { Engine, RenderEngine } from '@univerjs/base-render';
+import { Dependency, Inject, Injector } from '@wendellhu/redi';
+import { LocaleService, ObserverManager, Plugin, PluginType, PLUGIN_NAMES, UIObserver } from '@univerjs/core';
+import { Engine } from '@univerjs/base-render';
import { zh, en } from './Locale';
import { DocPluginObserve, install } from './Basics/Observer';
import { ToolbarController } from './Controller/ToolbarController';
@@ -14,7 +15,9 @@ export interface IDocPluginConfig extends IDocPluginConfigBase {}
const DEFAULT_DOCUMENT_PLUGIN_DATA = {};
-export class DocPlugin extends Plugin<DocPluginObserve, DocContext> {
+export class DocPlugin extends Plugin<DocPluginObserve> {
+ static override type = PluginType.Doc;
+
private _config: IDocPluginConfig;
private _infoBarControl: InfoBarController;
@@ -27,24 +30,20 @@ export class DocPlugin extends Plugin<DocPluginObserve, DocContext> {
private _documentController: DocumentController;
- constructor(config: Partial<IDocPluginConfig> = {}) {
+ constructor(
+ config: Partial<IDocPluginConfig> = {},
+ @Inject(ObserverManager) private readonly _globalObserverManager: ObserverManager,
+ @Inject(Injector) override _injector: Injector,
+ @Inject(LocaleService) private readonly _localeService: LocaleService
+ ) {
super(PLUGIN_NAMES.DOCUMENT);
this._config = Object.assign(DEFAULT_DOCUMENT_PLUGIN_DATA, config);
+ this._initializeDependencies(_injector);
}
- static create(config?: IDocPluginConfig) {
- return new DocPlugin(config);
- }
-
- installTo(universheetInstance: UniverSheet) {
- universheetInstance.installPlugin(this);
- }
-
- initialize(ctx: DocContext): void {
- this.context = ctx;
-
- this.getGlobalContext().getLocale().load({
+ initialize(): void {
+ this._localeService.getLocale().load({
en,
zh,
});
@@ -60,23 +59,17 @@ export class DocPlugin extends Plugin<DocPluginObserve, DocContext> {
}
initController() {
- this._toolbarControl = new ToolbarController(this);
- this._infoBarControl = new InfoBarController(this);
- this._documentController = new DocumentController(this, this._config);
+ this._toolbarControl = new ToolbarController();
+ this._infoBarControl = new InfoBarController();
+ this._documentController = new DocumentController();
}
initCanvasView() {
- const engine = this.getContext().getUniver().getGlobalContext().getPluginManager().getPluginByName<RenderEngine>(PLUGIN_NAMES.BASE_RENDER)?.getEngine()!;
-
- this._canvasEngine = engine;
-
- if (this._canvasView == null) {
- this._canvasView = new CanvasView(engine, this);
- }
+ this._canvasView = this._injector.get(CanvasView);
}
listenEventManager() {
- this._getCoreObserver<boolean>('onUIDidMountObservable').add(({ name, value }) => {
+ this._getCoreObserver<boolean>('onUIDidMountObservable').add(() => {
this.initializeAfterUI();
});
}
@@ -121,13 +114,22 @@ export class DocPlugin extends Plugin<DocPluginObserve, DocContext> {
return this._infoBarControl;
}
- onMounted(ctx: DocContext): void {
- this.initialize(ctx);
+ override onMounted(): void {
+ this.initialize();
}
- onDestroy(): void {}
+ override onDestroy(): void {}
+ /** @deprecated This will be removed. Modules should inject `ObserverManager` instead of getting it from plugin. */
protected _getCoreObserver<T>(type: string) {
- return this.getGlobalContext().getObserverManager().requiredObserver<UIObserver<T>>(type, 'core');
+ return this._globalObserverManager.requiredObserver<UIObserver<T>>(type, 'core');
+ }
+
+ private _initializeDependencies(docInjector: Injector) {
+ const dependencies: Dependency[] = [[CanvasView]];
+
+ dependencies.forEach((d) => {
+ docInjector.add(d);
+ });
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-docs/src/View/Render/BaseView.ts b/packages/base-docs/src/View/Render/BaseView.ts
index 26240ec63d..a37d9f1623 100644
--- a/packages/base-docs/src/View/Render/BaseView.ts
+++ b/packages/base-docs/src/View/Render/BaseView.ts
@@ -1,6 +1,5 @@
import { Scene } from '@univerjs/base-render';
import { Registry } from '@univerjs/core';
-import { DocPlugin } from '../../DocPlugin';
export class BaseView {
zIndex = 0;
@@ -9,8 +8,6 @@ export class BaseView {
private _scene: Scene;
- private _plugin: DocPlugin;
-
// constructor(private _scene: Scene, private _plugin: Plugin) {
// this._initialize();
// }
@@ -19,19 +16,10 @@ export class BaseView {
return this._scene;
}
- getPlugin() {
- return this._plugin;
- }
-
- getContext() {
- return this._plugin.getContext();
- }
-
updateToSheet() {}
- initialize(scene: Scene, plugin: DocPlugin) {
+ initialize(scene: Scene) {
this._scene = scene;
- this._plugin = plugin;
this._initialize();
return this;
}
@@ -44,4 +32,4 @@ export enum CANVAS_VIEW_KEY {
DOCS_VIEW = 'docsView',
}
-export const CanvasViewRegistry = Registry.create();
+export const CanvasViewRegistry = Registry.create();
\ No newline at end of file
diff --git a/packages/base-docs/src/View/Render/CanvasView.ts b/packages/base-docs/src/View/Render/CanvasView.ts
index 82edc6299d..4c41cd5054 100644
--- a/packages/base-docs/src/View/Render/CanvasView.ts
+++ b/packages/base-docs/src/View/Render/CanvasView.ts
@@ -1,7 +1,8 @@
-import { Engine, EVENT_TYPE, IWheelEvent, Layer, Scene, ScrollBar, Viewport } from '@univerjs/base-render';
+import { Inject, Injector } from '@wendellhu/redi';
+import { Engine, EVENT_TYPE, IRenderingEngine, IWheelEvent, Layer, Scene, ScrollBar, Viewport } from '@univerjs/base-render';
import { EventState, sortRules } from '@univerjs/core';
+
import { BaseView, CanvasViewRegistry, CANVAS_VIEW_KEY } from './BaseView';
-import { DocPlugin } from '../../DocPlugin';
import './Views';
export class CanvasView {
@@ -9,12 +10,12 @@ export class CanvasView {
private _views: BaseView[] = [];
- constructor(private _engine: Engine, private _plugin: DocPlugin) {
+ constructor(@IRenderingEngine private readonly _engine: Engine, @Inject(Injector) private readonly _injector: Injector) {
this._initialize();
}
getView(key: string) {
- for (let view of this._views) {
+ for (const view of this._views) {
if (view.viewKey === key) {
return view;
}
@@ -27,12 +28,12 @@ export class CanvasView {
private _initialize() {
const engine = this._engine;
- const context = this._plugin.getContext();
const scene = new Scene(CANVAS_VIEW_KEY.MAIN_SCENE, engine, {
width: 1200,
height: 2000,
});
+
this._scene = scene;
const viewMain = new Viewport(CANVAS_VIEW_KEY.DOCS_VIEW, scene, {
left: 0,
@@ -72,7 +73,7 @@ export class CanvasView {
scene.addLayer(Layer.create(scene, [], 0), Layer.create(scene, [], 2));
- this._viewLoader(scene, this._plugin);
+ this._viewLoader(scene);
engine.runRenderLoop(() => {
scene.render();
@@ -83,11 +84,11 @@ export class CanvasView {
});
}
- private _viewLoader(scene: Scene, plugin: DocPlugin) {
+ private _viewLoader(scene: Scene) {
CanvasViewRegistry.getData()
.sort(sortRules)
- .forEach((view) => {
- this._views.push(view.initialize(scene, plugin));
+ .forEach((viewFactory) => {
+ this._views.push(viewFactory.create(scene, this._injector));
});
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-docs/src/View/Render/Views/DocsView.ts b/packages/base-docs/src/View/Render/Views/DocsView.ts
index bf1d382539..6708f4f137 100644
--- a/packages/base-docs/src/View/Render/Views/DocsView.ts
+++ b/packages/base-docs/src/View/Render/Views/DocsView.ts
@@ -1,5 +1,6 @@
-import { Documents, DocumentSkeleton, IDocumentSkeletonDrawing, Picture } from '@univerjs/base-render';
-import { DocumentModel, IDocumentData } from '@univerjs/core';
+import { Documents, DocumentSkeleton, IDocumentSkeletonDrawing, Picture, Scene } from '@univerjs/base-render';
+import { CommandManager, DocumentModel, ICurrentUniverService, IDocumentData, LocaleService } from '@univerjs/core';
+import { Inject, Injector } from '@wendellhu/redi';
import { BaseView, CanvasViewRegistry, CANVAS_VIEW_KEY } from '../BaseView';
export enum DOCS_VIEW_KEY {
@@ -7,14 +8,22 @@ export enum DOCS_VIEW_KEY {
}
export class DocsView extends BaseView {
- zIndex = 1;
+ override zIndex = 1;
- viewKey = CANVAS_VIEW_KEY.DOCS_VIEW;
+ override viewKey = CANVAS_VIEW_KEY.DOCS_VIEW;
private _documentSkeleton: DocumentSkeleton;
private _documents: Documents;
+ constructor(
+ @Inject(CommandManager) private readonly _commandManager: CommandManager,
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @Inject(LocaleService) private readonly _localeService: LocaleService
+ ) {
+ super();
+ }
+
getDocumentSkeleton() {
return this._documentSkeleton;
}
@@ -24,11 +33,11 @@ export class DocsView extends BaseView {
}
scrollToCenter() {
- let { docsLeft, docsTop } = this._documents.calculatePagePosition();
- let pages = this._documentSkeleton.getSkeletonData().pages;
+ const { docsLeft, docsTop } = this._documents.calculatePagePosition();
+ const pages = this._documentSkeleton.getSkeletonData().pages;
for (let i = 0; i < pages.length; i++) {
const page = pages[i];
- for (let k of page.skeDrawings.keys()) {
+ for (const k of page.skeDrawings.keys()) {
const obj = this.getScene().getObject(k);
if (obj) {
const drawing = page.skeDrawings.get(k) as IDocumentSkeletonDrawing;
@@ -43,11 +52,10 @@ export class DocsView extends BaseView {
}
}
- protected _initialize() {
+ protected override _initialize() {
const scene = this.getScene();
- const context = this.getContext();
- const docsModel = context.getDocument();
+ const docsModel = this._currentUniverService.getCurrentUniverDocInstance().getDocument();
const documentSkeleton = this._buildSkeleton(docsModel.getSnapshot());
@@ -100,7 +108,7 @@ export class DocsView extends BaseView {
const { pageMarginLeft, pageMarginTop, docsLeft, docsTop } = documents.calculatePagePosition();
for (let i = 0; i < pages.length; i++) {
- for (let k of pages[i].skeDrawings.keys()) {
+ for (const k of pages[i].skeDrawings.keys()) {
const obj = this.getScene().getObject(k);
obj?.translate(obj.left + docsLeft - pageMarginLeft, obj.top + docsTop - pageMarginTop);
}
@@ -110,12 +118,21 @@ export class DocsView extends BaseView {
}
private _buildSkeleton(snapshot: IDocumentData) {
- const context = this.getContext();
- const docModel = new DocumentModel(snapshot, context);
- const docsSkeleton = DocumentSkeleton.create(docModel, context);
+ const docModel = new DocumentModel(snapshot, this._commandManager);
+ const docsSkeleton = DocumentSkeleton.create(docModel, this._localeService);
return docsSkeleton;
}
}
-CanvasViewRegistry.add(new DocsView());
+export class DocsViewFactory {
+ readonly zIndex = 0;
+
+ create(scene: Scene, injector: Injector): DocsView {
+ const docsView = injector.createInstance(DocsView);
+ docsView.initialize(scene);
+ return docsView;
+ }
+}
+
+CanvasViewRegistry.add(new DocsViewFactory());
\ No newline at end of file
diff --git a/packages/base-docs/src/View/Render/Views/DrawingsView.ts b/packages/base-docs/src/View/Render/Views/DrawingsView.ts
index c9f46f8425..da9352c18f 100644
--- a/packages/base-docs/src/View/Render/Views/DrawingsView.ts
+++ b/packages/base-docs/src/View/Render/Views/DrawingsView.ts
@@ -1,19 +1,18 @@
-import { Documents, BaseObject, Picture, Liquid } from '@univerjs/base-render';
+import { Documents, BaseObject, Picture, Liquid, Scene } from '@univerjs/base-render';
+import { Injector } from '@wendellhu/redi';
import { BaseView, CanvasViewRegistry } from '../BaseView';
import { DOCS_VIEW_KEY } from './DocsView';
const DRAWINGS_VIEW_BACKGROUND = 'drawings_view_background';
export class DrawingsView extends BaseView {
- zIndex = 3;
-
- viewKey = DRAWINGS_VIEW_BACKGROUND;
+ override viewKey = DRAWINGS_VIEW_BACKGROUND;
private _liquid = new Liquid();
- protected _initialize() {
+ // eslint-disable-next-line max-lines-per-function
+ protected override _initialize() {
const scene = this.getScene();
- const context = this.getContext();
const documents = scene.getObject(DOCS_VIEW_KEY.MAIN) as Documents;
@@ -31,8 +30,8 @@ export class DrawingsView extends BaseView {
const objectList: BaseObject[] = [];
const pageMarginCache = new Map<string, { marginLeft: number; marginTop: number }>();
- let cumPageLeft = 0;
- let cumPageTop = 0;
+ const cumPageLeft = 0;
+ const cumPageTop = 0;
for (let i = 0, len = pages.length; i < len; i++) {
const page = pages[i];
@@ -100,4 +99,12 @@ export class DrawingsView extends BaseView {
}
}
-CanvasViewRegistry.add(new DrawingsView());
+class DrawingsViewFactory {
+ zIndex = 3;
+
+ create(_scene: Scene, injector: Injector) {
+ return injector.createInstance(DrawingsView);
+ }
+}
+
+CanvasViewRegistry.add(new DrawingsViewFactory());
\ No newline at end of file
diff --git a/packages/base-docs/src/View/Render/Views/PageView.ts b/packages/base-docs/src/View/Render/Views/PageView.ts
index 4eaee94ff2..e46fbf762b 100644
--- a/packages/base-docs/src/View/Render/Views/PageView.ts
+++ b/packages/base-docs/src/View/Render/Views/PageView.ts
@@ -1,17 +1,17 @@
-import { Rect, Documents, IPageRenderConfig } from '@univerjs/base-render';
+import { Rect, Documents, IPageRenderConfig, Scene } from '@univerjs/base-render';
+import { Injector } from '@wendellhu/redi';
import { BaseView, CanvasViewRegistry } from '../BaseView';
import { DOCS_VIEW_KEY } from './DocsView';
const PAGE_VIEW_BACKGROUND = 'page_view_background';
export class PageView extends BaseView {
- zIndex = 2;
+ override zIndex = 2;
- viewKey = PAGE_VIEW_BACKGROUND;
+ override viewKey = PAGE_VIEW_BACKGROUND;
- protected _initialize() {
+ protected override _initialize() {
const scene = this.getScene();
- const context = this.getContext();
const documents = scene.getObject(DOCS_VIEW_KEY.MAIN) as Documents;
@@ -37,4 +37,10 @@ export class PageView extends BaseView {
}
}
-CanvasViewRegistry.add(new PageView());
+class PageViewFactory {
+ create(scene: Scene, injector: Injector) {
+ injector.createInstance(PageView);
+ }
+}
+
+CanvasViewRegistry.add(new PageViewFactory());
\ No newline at end of file
diff --git a/packages/base-sheets/src/SheetPlugin.ts b/packages/base-sheets/src/SheetPlugin.ts
index 4def651521..7843081ea8 100644
--- a/packages/base-sheets/src/SheetPlugin.ts
+++ b/packages/base-sheets/src/SheetPlugin.ts
@@ -73,11 +73,7 @@ export class SheetPlugin extends Plugin<SheetPluginObserve> {
this._config = Object.assign(DEFAULT_SPREADSHEET_PLUGIN_DATA, config);
- this.initializeDependencies(_injector);
- }
-
- installTo(universheetInstance: UniverSheet) {
- universheetInstance.installPlugin(this);
+ this._initializeDependencies(_injector);
}
initialize(): void {
@@ -170,7 +166,7 @@ export class SheetPlugin extends Plugin<SheetPluginObserve> {
return this._injector.get(ISelectionManager);
}
- private initializeDependencies(sheetInjector: Injector) {
+ private _initializeDependencies(sheetInjector: Injector) {
const dependencies: Dependency[] = [
[CanvasView],
diff --git a/packages/base-sheets/src/View/CanvasView.ts b/packages/base-sheets/src/View/CanvasView.ts
index b24a12b441..d7550f1d0c 100644
--- a/packages/base-sheets/src/View/CanvasView.ts
+++ b/packages/base-sheets/src/View/CanvasView.ts
@@ -23,7 +23,7 @@ export class CanvasView {
}
getView(key: string) {
- for (let view of this._views) {
+ for (const view of this._views) {
if (view.viewKey === key) {
return view;
}
@@ -35,7 +35,7 @@ export class CanvasView {
}
updateToSheet(worksheet: Worksheet) {
- for (let view of this._views) {
+ for (const view of this._views) {
view.updateToSheet(worksheet);
}
}
@@ -153,7 +153,6 @@ export class CanvasView {
}
private _viewLoader(scene: Scene) {
- // FIXME: need a plugin here
CanvasViewRegistry.getData().forEach((viewFactory) => {
this._views.push(viewFactory.create(scene, this._injector));
});
diff --git a/packages/base-slides/src/View/Render/ObjectProvider.ts b/packages/base-slides/src/View/Render/ObjectProvider.ts
index 6a9f867800..737b464255 100644
--- a/packages/base-slides/src/View/Render/ObjectProvider.ts
+++ b/packages/base-slides/src/View/Render/ObjectProvider.ts
@@ -1,7 +1,6 @@
import { BaseObject, Scene } from '@univerjs/base-render';
import { ContextBase, IPageElement, sortRules } from '@univerjs/core';
import { CanvasObjectProviderRegistry, ObjectAdaptor } from './Adaptor';
-// import './Adaptors';
export class ObjectProvider {
private _adaptors: ObjectAdaptor[] = [];
@@ -45,4 +44,4 @@ export class ObjectProvider {
this._adaptors.push(adaptor);
});
}
-}
+}
\ No newline at end of file
diff --git a/packages/core/src/Basics/DocContext.ts b/packages/core/src/Basics/DocContext.ts
deleted file mode 100644
index 1714f7d575..0000000000
--- a/packages/core/src/Basics/DocContext.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { IDocumentData } from '../Types/Interfaces';
-import { ContextBase } from './ContextBase';
-import { DocumentModel } from '../Docs/Domain/DocumentModel';
-
-/**
- * Core context, mount important instances, managers
- */
-export class DocContext extends ContextBase {
- protected _document: DocumentModel;
-
- constructor(univerDocData: Partial<IDocumentData> = {}) {
- super();
- this._document = new DocumentModel(univerDocData, this);
- }
-
- getDocument(): DocumentModel {
- return this._document;
- }
-
- protected _setObserver(): void {}
-}
diff --git a/packages/core/src/Basics/SlideContext.ts b/packages/core/src/Basics/SlideContext.ts
deleted file mode 100644
index 4155404f69..0000000000
--- a/packages/core/src/Basics/SlideContext.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { ISlideData } from '../Types/Interfaces/ISlideData';
-import { SlideModel } from '../Slides/Domain/SlideModel';
-import { ContextBase } from './ContextBase';
-
-/**
- * Core context, mount important instances, managers
- */
-export class SlideContext extends ContextBase {
- protected _slide: SlideModel;
-
- constructor(univerSlideData: Partial<ISlideData> = {}) {
- super();
- this._slide = new SlideModel(univerSlideData, this);
- }
-
- getSlide(): SlideModel {
- return this._slide;
- }
-
- protected _setObserver(): void {}
-}
diff --git a/packages/core/src/Basics/Univer.ts b/packages/core/src/Basics/Univer.ts
index b171ba1504..ff782e7ae9 100644
--- a/packages/core/src/Basics/Univer.ts
+++ b/packages/core/src/Basics/Univer.ts
@@ -4,10 +4,9 @@ import { CommandManager, UndoManager } from '../Command';
import { LocaleService } from '../Service/Locale.service';
import { UniverSheet } from './UniverSheet';
import { UniverDoc } from './UniverDoc';
-import { UniverSlide } from './UniverSlide';
import { Nullable } from '../Shared';
import { Plugin, PluginCtor, PluginRegistry, PluginStore, PluginType } from '../Plugin';
-import { IUniverData, IWorkbookConfig } from '../Types/Interfaces';
+import { IDocumentData, IUniverData, IWorkbookConfig } from '../Types/Interfaces';
import { UniverObserverImpl } from './UniverObserverImpl';
import { ObserverManager } from '../Observer';
import { CurrentUniverService, ICurrentUniverService } from '../Service/Current.service';
@@ -45,6 +44,8 @@ export class Univer {
this.registerUniverPlugin(plugin, configs);
} else if (plugin.type === PluginType.Sheet) {
this.registerSheetPlugin(plugin, configs);
+ } else if (plugin.type === PluginType.Doc) {
+ this.registerDocPlugin(plugin, configs);
} else {
throw new Error(`Unimplemented plugin system for business: "${plugin.type}".`);
}
@@ -63,18 +64,13 @@ export class Univer {
return sheet;
}
- addUniverSheet(univerSheet: UniverSheet): void {
- this._currentUniverService.addSheet(univerSheet);
- }
+ createUniverDoc(config: Partial<IDocumentData>): UniverDoc {
+ const doc = this._univerInjector.createInstance(UniverDoc, config);
- addUniverDoc(univerDoc: UniverDoc): void {
- univerDoc.context.onUniver(this);
- this._currentUniverService.addDoc(univerDoc);
- }
+ this.initializePluginsForDoc(doc);
+ this._currentUniverService.addDoc(doc);
- addUniverSlide(univerSlide: UniverSlide): void {
- univerSlide.context.onUniver(this);
- this._currentUniverService.addSlide(univerSlide);
+ return doc;
}
getUniverSheetInstance(id: string): Nullable<UniverSheet> {
@@ -136,14 +132,23 @@ export class Univer {
}
private registerSheetPlugin<T extends Plugin>(pluginCtor: PluginCtor<T>, options?: any) {
+ this._univerPluginRegistry.registerPlugin(pluginCtor, options);
// 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);
});
- } else {
- this._univerPluginRegistry.registerPlugin(pluginCtor, options);
+ }
+ }
+
+ private registerDocPlugin<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);
+ });
}
}
@@ -153,4 +158,11 @@ export class Univer {
sheet.addPlugin(p.plugin as unknown as PluginCtor<any>, p.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);
+ });
+ }
+}
\ No newline at end of file
diff --git a/packages/core/src/Basics/UniverDoc.ts b/packages/core/src/Basics/UniverDoc.ts
index 09f5070bc7..06a43e388d 100644
--- a/packages/core/src/Basics/UniverDoc.ts
+++ b/packages/core/src/Basics/UniverDoc.ts
@@ -1,8 +1,8 @@
-import { IDocumentData } from '../Types/Interfaces';
-import { Plugin } from '../Plugin';
-import { IOHttp, IOHttpConfig, Logger } from '../Shared';
-import { VersionCode, VersionEnv } from './Version';
+import { Ctor, Dependency, Injector, Optional } from '@wendellhu/redi';
+import { DocumentModel } from '../Docs';
+import { IDocumentData } from '../Types/Interfaces';
+import { Plugin, PluginCtor, PluginStore } from '../Plugin';
/**
* Externally provided UniverDoc root instance
@@ -10,68 +10,39 @@ import { VersionCode, VersionEnv } from './Version';
export class UniverDoc {
univerDocConfig: Partial<IDocumentData>;
- private _context: DocContext;
+ private readonly _document: DocumentModel;
- constructor(UniverDocData: Partial<IDocumentData> = {}) {
- this.univerDocConfig = UniverDocData;
- this._context = new DocContext(UniverDocData);
- }
+ private readonly _pluginStore = new PluginStore();
- /**
- * get DocContext
- */
- get context() {
- return this._context;
- }
+ private readonly _injector: Injector;
- static newInstance(UniverDocData: Partial<IDocumentData> = {}): UniverDoc {
- Logger.capsule(VersionEnv, VersionCode, 'powered by :: UniverDoc :: ');
- return new UniverDoc(UniverDocData);
+ constructor(docData: Partial<IDocumentData> = {}, @Optional(Injector) _injector: Injector) {
+ this.univerDocConfig = docData;
+ this._injector = this._initializeDependencies(_injector);
+ this._document = this._injector.createInstance(DocumentModel, docData);
}
- /**
- *
- * Request data
- *
- * @example
- * Get data for all tables, including core and plugin data
- *
- * @param config
- */
- static get<T = void>(config: Omit<IOHttpConfig, 'type'>): Promise<T> {
- return IOHttp({ ...config, type: 'GET' });
- }
-
- /**
- * Submit data
- * @param config
- */
- static post<T = void>(config: Omit<IOHttpConfig, 'type'>): Promise<T> {
- return IOHttp({ ...config, type: 'POST' });
+ getDocument(): DocumentModel {
+ return this._document;
}
/**
* get unit id
*/
getUnitId(): string {
- return this._context.getDocument().getUnitId();
+ return this._document.getUnitId();
}
- /**
- * install plugin
- *
- * @param plugin - install plugin
- */
- installPlugin(plugin: Plugin): void {
- this._context.getPluginManager().install(plugin);
+ addPlugin<T extends Plugin>(pluginCtor: PluginCtor<T>, options: any): void {
+ const pluginInstance: Plugin = this._injector.createInstance(pluginCtor as unknown as Ctor<any>, options);
+
+ pluginInstance.onCreate();
+ pluginInstance.onMounted();
+ this._pluginStore.addPlugin(pluginInstance);
}
- /**
- * uninstall plugin
- *
- * @param name - plugin name
- */
- uninstallPlugin(name: string): void {
- this._context.getPluginManager().uninstall(name);
+ private _initializeDependencies(parentInjector?: Injector): Injector {
+ const dependencies: Dependency[] = [];
+ return parentInjector ? parentInjector.createChild(dependencies) : new Injector(dependencies);
}
}
\ No newline at end of file
diff --git a/packages/core/src/Basics/UniverSheet.ts b/packages/core/src/Basics/UniverSheet.ts
index 6943622f90..27564b0e3f 100644
--- a/packages/core/src/Basics/UniverSheet.ts
+++ b/packages/core/src/Basics/UniverSheet.ts
@@ -23,7 +23,7 @@ export class UniverSheet implements Disposable {
constructor(univerSheetData: Partial<IWorkbookConfig> = {}, @Optional(Injector) parentInjector?: Injector) {
this.univerSheetConfig = univerSheetData;
- this._sheetInjector = this.initializeInjector(parentInjector);
+ this._sheetInjector = this._initializeDependencies(parentInjector);
this.setObserver();
this._workbook = this._sheetInjector.createInstance(Workbook, univerSheetData);
}
@@ -62,7 +62,7 @@ export class UniverSheet implements Disposable {
this._pluginStore.addPlugin(pluginInstance);
}
- private initializeInjector(parentInjector?: Injector): Injector {
+ private _initializeDependencies(parentInjector?: Injector): Injector {
const dependencies: Dependency[] = [[ObserverManager], [GenName]];
return parentInjector ? parentInjector.createChild(dependencies) : new Injector(dependencies);
}
@@ -70,4 +70,4 @@ export class UniverSheet implements Disposable {
private setObserver(): void {
new WorkBookObserverImpl().install(this._sheetInjector.get(ObserverManager));
}
-}
\ No newline at end of file
+}
diff --git a/packages/core/src/Basics/UniverSlide.ts b/packages/core/src/Basics/UniverSlide.ts
index 8f2d54cfb9..4f87e391a8 100644
--- a/packages/core/src/Basics/UniverSlide.ts
+++ b/packages/core/src/Basics/UniverSlide.ts
@@ -1,7 +1,5 @@
import { ISlideData } from '../Types/Interfaces';
-import { Plugin } from '../Plugin';
import { IOHttp, IOHttpConfig, Logger } from '../Shared';
-import { SlideContext } from './SlideContext';
import { VersionCode, VersionEnv } from './Version';
import { ColorBuilder } from '../Sheets/Domain/ColorBuilder';
@@ -11,18 +9,8 @@ import { ColorBuilder } from '../Sheets/Domain/ColorBuilder';
export class UniverSlide {
UniverSlideConfig: Partial<ISlideData>;
- private _context: SlideContext;
-
constructor(UniverSlideData: Partial<ISlideData> = {}) {
this.UniverSlideConfig = UniverSlideData;
- this._context = new SlideContext(UniverSlideData);
- }
-
- /**
- * get SlideContext
- */
- get context() {
- return this._context;
}
static newInstance(UniverSlideData: Partial<ISlideData> = {}): UniverSlide {
@@ -54,22 +42,4 @@ export class UniverSlide {
static newColor(): ColorBuilder {
return new ColorBuilder();
}
-
- /**
- * install plugin
- *
- * @param plugin - install plugin
- */
- installPlugin(plugin: Plugin): void {
- this._context.getPluginManager().install(plugin);
- }
-
- /**
- * uninstall plugin
- *
- * @param name - plugin name
- */
- uninstallPlugin(name: string): void {
- this._context.getPluginManager().uninstall(name);
- }
-}
+}
\ No newline at end of file
diff --git a/packages/core/src/Basics/index.ts b/packages/core/src/Basics/index.ts
index b6241209b5..a1c80bdf20 100644
--- a/packages/core/src/Basics/index.ts
+++ b/packages/core/src/Basics/index.ts
@@ -1,8 +1,5 @@
-// @index('./*.ts', f => `export * from '${f.path}'`)
-export * from './DocContext';
export * from './Environment';
export * from './Registry';
-export * from './SlideContext';
export * from './UniverDoc';
export * from './UniverSheet';
export * from './UniverSlide';
@@ -11,5 +8,4 @@ export * from './Version';
export * from './WorkBookObserver';
export * from './WorkBookObserverImpl';
export * from './UniverObserver';
-export * from './UniverObserverImpl';
-// @endindex
\ No newline at end of file
+export * from './UniverObserverImpl';
\ No newline at end of file
diff --git a/packages/core/src/Docs/Domain/DocumentModel.ts b/packages/core/src/Docs/Domain/DocumentModel.ts
index 7dc88f9b81..1eaf610385 100644
--- a/packages/core/src/Docs/Domain/DocumentModel.ts
+++ b/packages/core/src/Docs/Domain/DocumentModel.ts
@@ -1,10 +1,6 @@
-import { DocContext } from '../../Basics';
-import { Command } from '../../Command';
-import {
- CommonParameterAttribute,
- IDocumentBody,
- IDocumentData,
-} from '../../Types/Interfaces/IDocumentData';
+import { Inject } from '@wendellhu/redi';
+import { Command, CommandManager } from '../../Command';
+import { CommonParameterAttribute, IDocumentBody, IDocumentData } from '../../Types/Interfaces/IDocumentData';
import { ITextSelectionRange } from '../../Types/Interfaces/ISelectionData';
import { DOC_ACTION_NAMES } from '../../Types/Const/DOC_ACTION_NAMES';
import { Tools, getTextIndexByCursor } from '../../Shared';
@@ -30,7 +26,6 @@ export class DocumentModelSimple {
bodyModel: DocumentBodyModel;
constructor(snapshot: Partial<IDocumentData>) {
- // this.snapshot = snapshot;
this.snapshot = { ...DEFAULT_DOC, ...snapshot };
if (this.snapshot.body != null) {
@@ -114,13 +109,10 @@ export class DocumentModelSimple {
}
export class DocumentModel extends DocumentModelSimple {
- private _context: DocContext;
-
private _unitId: string;
- constructor(snapshot: Partial<IDocumentData>, context: DocContext) {
+ constructor(snapshot: Partial<IDocumentData>, @Inject(CommandManager) private readonly _commandManager: CommandManager) {
super(snapshot);
- this._context = context;
this._unitId = this.snapshot.id ?? Tools.generateRandomId(6);
this.initializeRowColTree();
@@ -130,13 +122,7 @@ export class DocumentModel extends DocumentModelSimple {
return this._unitId;
}
- insert(
- body: IDocumentBody,
- range: ITextSelectionRange,
- segmentId?: string
- ): DocumentModel {
- const commandManager = this._context.getCommandManager();
-
+ insert(body: IDocumentBody, range: ITextSelectionRange, segmentId?: string): DocumentModel {
const { cursorStart, cursorEnd, isEndBack, isStartBack, isCollapse } = range;
const textStart = getTextIndexByCursor(cursorStart, isStartBack);
@@ -167,13 +153,11 @@ export class DocumentModel extends DocumentModelSimple {
},
...actionList
);
- commandManager.invoke(command);
+ this._commandManager.invoke(command);
return this;
}
delete(range: ITextSelectionRange, segmentId?: string): DocumentModel {
- const commandManager = this._context.getCommandManager();
-
const deleteActionList = this._getDeleteAction(range, segmentId);
const command = new Command(
@@ -182,17 +166,11 @@ export class DocumentModel extends DocumentModelSimple {
},
...deleteActionList
);
- commandManager.invoke(command);
+ this._commandManager.invoke(command);
return this;
}
- update(
- attribute: CommonParameterAttribute,
- range: ITextSelectionRange,
- segmentId?: string
- ) {
- const commandManager = this._context.getCommandManager();
-
+ update(attribute: CommonParameterAttribute, range: ITextSelectionRange, segmentId?: string) {
const { cursorStart, cursorEnd, isEndBack, isStartBack } = range;
const actionList = [];
@@ -219,18 +197,11 @@ export class DocumentModel extends DocumentModelSimple {
},
...actionList
);
- commandManager.invoke(command);
+ this._commandManager.invoke(command);
return this;
}
- IMEInput(
- newText: string,
- oldTextLen: number,
- start: number,
- segmentId?: string
- ) {
- const _commandManager = this._context.getCommandManager();
-
+ IMEInput(newText: string, oldTextLen: number, start: number, segmentId?: string) {
const actionList = [];
actionList.push({
@@ -262,7 +233,7 @@ export class DocumentModel extends DocumentModelSimple {
},
...actionList
);
- _commandManager.invoke(command);
+ this._commandManager.invoke(command);
return this;
}
@@ -273,22 +244,16 @@ export class DocumentModel extends DocumentModelSimple {
const { headers, footers } = this.snapshot;
if (headers) {
- for (let headerId in headers) {
+ for (const headerId in headers) {
const header = headers[headerId];
- this.headerTreeMap.set(
- headerId,
- DocumentBodyModel.create(header.body)
- );
+ this.headerTreeMap.set(headerId, DocumentBodyModel.create(header.body));
}
}
if (footers) {
- for (let footerId in footers) {
+ for (const footerId in footers) {
const footer = footers[footerId];
- this.footerTreeMap.set(
- footerId,
- DocumentBodyModel.create(footer.body)
- );
+ this.footerTreeMap.set(footerId, DocumentBodyModel.create(footer.body));
}
}
}
diff --git a/packages/core/src/Observer/Observable.ts b/packages/core/src/Observer/Observable.ts
index f7a8d155cd..077a724376 100644
--- a/packages/core/src/Observer/Observable.ts
+++ b/packages/core/src/Observer/Observable.ts
@@ -369,4 +369,4 @@ export class Observable<T> {
return false;
}
-}
+}
\ No newline at end of file
diff --git a/packages/core/src/Plugin/Plugin.ts b/packages/core/src/Plugin/Plugin.ts
index 22a8948d63..dd605863c3 100644
--- a/packages/core/src/Plugin/Plugin.ts
+++ b/packages/core/src/Plugin/Plugin.ts
@@ -54,6 +54,7 @@ export abstract class Plugin<Obs = any> implements BasePlugin {
this._observeNames = [];
}
+ /** @deprecated this plugin will be removed */
getPluginByName<T extends BasePlugin>(name: string): Nullable<T> {
throw new Error('Method not implemented.');
}
diff --git a/packages/core/src/Service/Locale.service.ts b/packages/core/src/Service/Locale.service.ts
index 99253db919..f7ddf4bd36 100644
--- a/packages/core/src/Service/Locale.service.ts
+++ b/packages/core/src/Service/Locale.service.ts
@@ -1,5 +1,5 @@
-import { LocaleType } from "src/Types/Enum";
-import { Locale } from "../Shared/Locale";
+import { LocaleType } from 'src/Types/Enum';
+import { Locale } from '../Shared/Locale';
/**
* This service provides i18n and timezone / location features to other modules.
@@ -22,4 +22,4 @@ export class LocaleService {
getLocale(): Locale {
return this._locale;
}
-}
+}
\ No newline at end of file
diff --git a/packages/ui-plugin-docs/package.json b/packages/ui-plugin-docs/package.json
index 7ea63dbe23..e36f7e8211 100644
--- a/packages/ui-plugin-docs/package.json
+++ b/packages/ui-plugin-docs/package.json
@@ -58,7 +58,8 @@
"@univerjs/base-ui": "workspace:^0.0.1",
"@univerjs/core": "workspace:^0.0.1",
"@univerjs/base-docs": "workspace:^0.0.1",
+ "@wendellhu/redi": "^0.10.0",
"css-vars-ponyfill": "^2.4.6",
"preact": "^10.12.1"
}
-}
+}
\ No newline at end of file
diff --git a/packages/ui-plugin-docs/src/Controller/AppUIController.ts b/packages/ui-plugin-docs/src/Controller/AppUIController.ts
index 15ec0e2284..a43f0922c4 100644
--- a/packages/ui-plugin-docs/src/Controller/AppUIController.ts
+++ b/packages/ui-plugin-docs/src/Controller/AppUIController.ts
@@ -1,48 +1,51 @@
-import { LocaleType } from '@univerjs/core';
-import { DocUIPlugin } from '../DocUIPlugin';
+import { ComponentManager } from '@univerjs/base-ui';
+import { LocaleService, LocaleType, ObserverManager } from '@univerjs/core';
+import { Inject, Injector, SkipSelf } from '@wendellhu/redi';
+
+import { IDocUIPluginConfig } from '../Basics';
import { UI } from '../View';
import { DocContainerUIController } from './DocContainerUIController';
export class AppUIController {
- protected _plugin: DocUIPlugin;
-
private _docContainerController: DocContainerUIController;
- constructor(plugin: DocUIPlugin) {
- this._plugin = plugin;
-
- this._docContainerController = new DocContainerUIController(this._plugin);
+ constructor(
+ _config: IDocUIPluginConfig,
+ @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @SkipSelf() @Inject(ObserverManager) private readonly _globalObserverManager: ObserverManager,
+ @Inject(Injector) private readonly _injector: Injector,
+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager
+ ) {
+ this._docContainerController = this._injector.createInstance(DocContainerUIController, _config);
const UIConfig = this._docContainerController.getUIConfig();
UI.create({
- context: this._plugin.getGlobalContext(),
- locale: this._plugin.getGlobalContext().getLocale().getCurrentLocale(),
- componentManager: this._plugin.getComponentManager(),
+ injector: this._injector,
+ locale: this._localeService.getLocale().getCurrentLocale(),
+ localeService: this._localeService,
+ componentManager: this._componentManager,
changeLocale: this.changeLocale,
UIConfig,
- container: this._plugin.getConfig().container,
+ container: _config.container,
});
}
/**
* Change language
- * @param {String} lang new language
+ * @param {String} locale new language
*
* e: {target: HTMLSelectElement } reference from https://stackoverflow.com/a/48443771
*
*/
changeLocale = (locale: string) => {
- this._plugin
- .getGlobalContext()
- .getLocale()
- .change(locale as LocaleType);
+ this._localeService.getLocale().change(locale as LocaleType);
// publish
- this._plugin.getGlobalContext().getObserverManager().requiredObserver('onAfterChangeUILocaleObservable', 'core')!.notifyObservers();
+ this._globalObserverManager.requiredObserver('onAfterChangeUILocaleObservable', 'core')!.notifyObservers();
};
getDocContainerController() {
return this._docContainerController;
}
-}
+}
\ No newline at end of file
diff --git a/packages/ui-plugin-docs/src/Controller/DocContainerUIController.ts b/packages/ui-plugin-docs/src/Controller/DocContainerUIController.ts
index a14b806416..6673f7acad 100644
--- a/packages/ui-plugin-docs/src/Controller/DocContainerUIController.ts
+++ b/packages/ui-plugin-docs/src/Controller/DocContainerUIController.ts
@@ -1,37 +1,37 @@
+import { Engine, IRenderingEngine } from '@univerjs/base-render';
import { getRefElement } from '@univerjs/base-ui';
-import { LocaleType } from '@univerjs/core';
+import { LocaleService, LocaleType, ObserverManager } from '@univerjs/core';
+import { Inject, Injector, SkipSelf } from '@wendellhu/redi';
+
import { IDocUIPluginConfig } from '../Basics';
-import { DocUIPlugin } from '../DocUIPlugin';
import { DocContainer } from '../View';
import { InfoBarUIController } from './InfoBarUIController';
import { ToolbarUIController } from './ToolbarUIController';
export class DocContainerUIController {
- protected _plugin: DocUIPlugin;
-
private _docContainer: DocContainer;
private _toolbarController: ToolbarUIController;
private _infoBarController: InfoBarUIController;
- private _config: IDocUIPluginConfig;
-
- constructor(plugin: DocUIPlugin) {
- this._plugin = plugin;
-
- this._config = this._plugin.getConfig();
-
+ constructor(
+ private readonly _config: IDocUIPluginConfig,
+ @SkipSelf() @Inject(ObserverManager) private readonly _globalObserverManager: ObserverManager,
+ @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @Inject(Injector) private readonly _injector: Injector,
+ @Inject(ObserverManager) private readonly _observerManager: ObserverManager,
+ @IRenderingEngine private readonly _renderingEngine: Engine
+ ) {
this._initialize();
- this._toolbarController = new ToolbarUIController(this._plugin, this._config.layout?.toolbarConfig);
-
- this._infoBarController = new InfoBarUIController(this._plugin);
+ this._toolbarController = this._injector.createInstance(ToolbarUIController, this._config.layout?.toolbarConfig || {});
+ this._infoBarController = new InfoBarUIController();
}
getUIConfig() {
const config = {
- context: this._plugin.getContext(),
+ injector: this._injector,
config: this._config,
changeLocale: this.changeLocale,
getComponent: this.getComponent,
@@ -53,11 +53,21 @@ export class DocContainerUIController {
getComponent = (ref: DocContainer) => {
this._docContainer = ref;
- let container = getRefElement(ref.getContentRef());
- this._plugin.initRender(container);
- this._plugin.getObserver('onUIDidMount')?.notifyObservers(this._docContainer);
+ const container = getRefElement(ref.getContentRef());
+
+ const engine = this._renderingEngine;
+ engine.setContainer(container);
+
+ window.addEventListener('resize', () => {
+ engine.resize();
+ })
- this._plugin.getGlobalContext().getObserverManager().requiredObserver<boolean>('onUIDidMountObservable', 'core').notifyObservers(true);
+ setTimeout(() => {
+ engine.resize();
+ });
+
+ this._observerManager.requiredObserver<DocContainer>('onUIDidMount')?.notifyObservers(this._docContainer);
+ this._globalObserverManager.requiredObserver<boolean>('onUIDidMountObservable', 'core').notifyObservers(true);
this._initDocContainer();
};
@@ -70,13 +80,8 @@ export class DocContainerUIController {
*
*/
changeLocale = (locale: string) => {
- this._plugin
- .getContext()
- .getLocale()
- .change(locale as LocaleType);
-
- // publish
- this._plugin.getGlobalContext().getObserverManager().requiredObserver('onAfterChangeUILocaleObservable', 'core')!.notifyObservers();
+ this._localeService.getLocale().change(locale as LocaleType);
+ this._globalObserverManager.requiredObserver('onAfterChangeUILocaleObservable', 'core')!.notifyObservers();
};
getContentRef() {
@@ -88,7 +93,9 @@ export class DocContainerUIController {
}
UIDidMount(cb: Function) {
- if (this._docContainer) return cb(this._docContainer);
+ if (this._docContainer) {
+ return cb(this._docContainer);
+ }
this._plugin.getObserver('onUIDidMount')?.add(() => cb(this._docContainer));
}
@@ -102,4 +109,4 @@ export class DocContainerUIController {
private _initDocContainer() {
// handle drag event
}
-}
+}
\ No newline at end of file
diff --git a/packages/ui-plugin-docs/src/Controller/InfoBarUIController.ts b/packages/ui-plugin-docs/src/Controller/InfoBarUIController.ts
index d9243eda11..ea046f9aaa 100644
--- a/packages/ui-plugin-docs/src/Controller/InfoBarUIController.ts
+++ b/packages/ui-plugin-docs/src/Controller/InfoBarUIController.ts
@@ -20,14 +20,8 @@ export class InfoBarUIController {
private _infoBar: InfoBar;
- private _plugin: DocUIPlugin;
-
private _infoList: BaseInfoBarProps;
- constructor(plugin: DocUIPlugin) {
- this._plugin = plugin;
- }
-
getComponent = (ref: InfoBar) => {
this._infoBar = ref;
this._refreshComponent();
@@ -46,7 +40,6 @@ export class InfoBarUIController {
private _refreshComponent(): void {
const name = 'UniverDoc';
- // const name = this._plugin.getContext().getUniver().getCurrentUniverDocInstance().getWorkBook().getConfig().name;
this._infoBarModel = new InfoBarModel(name);
this._infoList = {
back: {
@@ -69,4 +62,4 @@ export class InfoBarUIController {
},
};
}
-}
+}
\ No newline at end of file
diff --git a/packages/ui-plugin-docs/src/Controller/ToolbarUIController.ts b/packages/ui-plugin-docs/src/Controller/ToolbarUIController.ts
index 1c50ad6a5b..b3865a14f4 100644
--- a/packages/ui-plugin-docs/src/Controller/ToolbarUIController.ts
+++ b/packages/ui-plugin-docs/src/Controller/ToolbarUIController.ts
@@ -1,7 +1,8 @@
-import { BaseSelectChildrenProps, BaseSelectProps, ColorPicker, ComponentChildren, CustomComponent } from '@univerjs/base-ui';
-import { DEFAULT_STYLES, HorizontalAlign, Tools, UIObserver, VerticalAlign, WrapStrategy, Range, FontWeight, FontItalic, ITextRotation } from '@univerjs/core';
+import { BaseSelectChildrenProps, BaseSelectProps, ColorPicker, ComponentChildren, ComponentManager, CustomComponent } from '@univerjs/base-ui';
+import { DEFAULT_STYLES, HorizontalAlign, ObserverManager, Tools, UIObserver, VerticalAlign, WrapStrategy } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+
import { DefaultToolbarConfig, DocToolbarConfig, DOC_UI_PLUGIN_NAME } from '../Basics';
-import { DocUIPlugin } from '../DocUIPlugin';
import { Toolbar } from '../View';
import { ColorSelect } from '../View/Common';
import { FONT_FAMILY_CHILDREN, FONT_SIZE_CHILDREN, HORIZONTAL_ALIGN_CHILDREN, VERTICAL_ALIGN_CHILDREN, TEXT_WRAP_CHILDREN, TEXT_ROTATE_CHILDREN } from '../View/Toolbar/Const';
@@ -28,8 +29,6 @@ export interface IToolbarItemProps extends BaseToolbarSelectProps {
}
export class ToolbarUIController {
- private _plugin: DocUIPlugin;
-
private _toolbar: Toolbar;
private _toolList: IToolbarItemProps[];
@@ -44,9 +43,12 @@ export class ToolbarUIController {
private _background: string = '#fff';
- constructor(plugin: DocUIPlugin, config?: DocToolbarConfig) {
- this._plugin = plugin;
-
+ // eslint-disable-next-line max-lines-per-function
+ constructor(
+ config: DocToolbarConfig,
+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,
+ @Inject(ObserverManager) private readonly _observerManager: ObserverManager
+ ) {
this._config = Tools.deepMerge({}, DefaultToolbarConfig, config);
this._toolList = [
@@ -347,7 +349,7 @@ export class ToolbarUIController {
}
setUIObserve<T>(msg: UIObserver<T>) {
- this._plugin.getContext().getObserverManager().requiredObserver<UIObserver<T>>('onUIChangeObservable', 'core').notifyObservers(msg);
+ this._observerManager.requiredObserver<UIObserver<T>>('onUIChangeObservable', 'core').notifyObservers(msg);
}
changeColor(color: string) {
@@ -480,109 +482,8 @@ export class ToolbarUIController {
});
}
- private _changeToolbarState(range: Range): void {
- const workbook = this._plugin.getContext().getUniver().getCurrentUniverSheetInstance().getWorkBook();
- const worksheet = workbook.getActiveSheet();
- if (worksheet) {
- const isBold = range.getFontWeight();
- const IsItalic = range.getFontStyle();
- const strikeThrough = range.getStrikeThrough();
- const fontSize = range.getFontSize();
- const fontWeight = range.getFontWeight();
- const fontName = range.getFontFamily();
- const fontItalic = range.getFontStyle();
- // const fontColor = range.getFontColor();
- // const background = range.getBackground();
- const underline = range.getUnderline();
- const horizontalAlign = range.getHorizontalAlignment() ?? HorizontalAlign.LEFT;
- const verticalAlign = range.getVerticalAlignment() ?? VerticalAlign.BOTTOM;
- const rotation = range.getTextRotation();
- const warp = range.getWrapStrategy() ?? WrapStrategy.CLIP;
-
- const bold = this._toolList.find((item) => item.name === 'bold');
- const italic = this._toolList.find((item) => item.name === 'italic');
- const textRotateModeItem = this._toolList.find((item) => item.name === 'textRotateMode');
- const fontSizeItem = this._toolList.find((item) => item.name === 'fontSize');
- const fontNameItem = this._toolList.find((item) => item.name === 'font');
- const fontBoldItem = this._toolList.find((item) => item.name === 'bold');
- const fontItalicItem = this._toolList.find((item) => item.name === 'italic');
- // const textColor = this._toolList.find((item) => item.name === 'textColor')
- // const fillColor = this._toolList.find((item) => item.name === 'fillColor')
- const strikethroughItem = this._toolList.find((item) => item.name === 'strikethrough');
- const underlineItem = this._toolList.find((item) => item.name === 'underline');
- const horizontalAlignModeItem = this._toolList.find((item) => item.name === 'horizontalAlignMode');
- const verticalAlignModeItem = this._toolList.find((item) => item.name === 'verticalAlignMode');
- const textWrapMode = this._toolList.find((item) => item.name === 'textWrapMode');
-
- if (bold) {
- bold.active = isBold === FontWeight.BOLD;
- }
-
- if (italic) {
- italic.active = IsItalic === FontItalic.ITALIC;
- }
-
- if (strikethroughItem) {
- strikethroughItem.active = !!(strikeThrough && strikeThrough.s);
- }
- if (fontNameItem) {
- fontNameItem.children?.forEach((item) => {
- item.selected = fontName === item.value;
- });
- }
- if (fontSizeItem) {
- fontSizeItem.label = fontSize.toString();
- }
- if (fontBoldItem) {
- fontBoldItem.active = !!fontWeight;
- }
- if (fontItalicItem) {
- fontItalicItem.active = !!fontItalic;
- }
- if (underlineItem) {
- underlineItem.active = !!(underline && underline.s);
- }
- if (horizontalAlignModeItem) {
- horizontalAlignModeItem.children?.forEach((item) => {
- item.selected = horizontalAlign === item.value;
- });
- }
- if (textRotateModeItem) {
- textRotateModeItem.children?.forEach((item) => {
- if ((rotation as ITextRotation).v) {
- item.selected = item.value === 'v';
- } else {
- item.selected = (rotation as ITextRotation).a === item.value;
- }
- });
- }
- if (verticalAlignModeItem) {
- verticalAlignModeItem.children?.forEach((item) => {
- item.selected = verticalAlign === item.value;
- });
- }
- if (textWrapMode) {
- textWrapMode.children?.forEach((item) => {
- item.selected = warp === item.value;
- });
- }
-
- this.setToolbar();
- }
- }
-
private _initialize() {
- this._plugin.getComponentManager().register(DOC_UI_PLUGIN_NAME + ColorSelect.name, ColorSelect);
- this._plugin.getComponentManager().register(DOC_UI_PLUGIN_NAME + ColorPicker.name, ColorPicker);
-
- // CommandManager.getCommandObservers().add(({ actions }) => {
- // if (!actions || actions.length === 0) return;
- // const action = actions[0] as SheetActionBase<ISheetActionData, ISheetActionData, void>;
-
- // const currentUnitId = this._plugin.getContext().getUniver().getCurrentUniverSheetInstance().getWorkBook().getUnitId();
- // const actionUnitId = action.getWorkBook().getUnitId();
-
- // if (currentUnitId !== actionUnitId) return null;
- // });
+ this._componentManager.register(DOC_UI_PLUGIN_NAME + ColorSelect.name, ColorSelect);
+ this._componentManager.register(DOC_UI_PLUGIN_NAME + ColorPicker.name, ColorPicker);
}
-}
+}
\ No newline at end of file
diff --git a/packages/ui-plugin-docs/src/DocUIPlugin.ts b/packages/ui-plugin-docs/src/DocUIPlugin.ts
index 9e538e5458..15ad838172 100644
--- a/packages/ui-plugin-docs/src/DocUIPlugin.ts
+++ b/packages/ui-plugin-docs/src/DocUIPlugin.ts
@@ -1,72 +1,56 @@
-import { Plugin, Context, PLUGIN_NAMES, Tools, Univer } from '@univerjs/core';
+import { Dependency, Inject, Injector } from '@wendellhu/redi';
+import { Plugin, PLUGIN_NAMES, Tools, PluginType, LocaleService, CommandManager } from '@univerjs/core';
import { RenderEngine } from '@univerjs/base-render';
import { ComponentManager, RegisterManager } from '@univerjs/base-ui';
+
import { zh, en } from './Locale';
import { DOC_UI_PLUGIN_NAME } from './Basics/Const/PLUGIN_NAME';
-import { DefaultDocUiConfig, IDocUIPluginConfig } from './Basics';
+import { DefaultDocUiConfig, IDocUIPluginConfig, installObserver } from './Basics';
import { AppUIController } from './Controller';
-export class DocUIPlugin extends Plugin<any, Context> {
- private _appUIController: AppUIController;
+export class DocUIPlugin extends Plugin<any> {
+ static override type = PluginType.Doc;
- private _config: IDocUIPluginConfig;
+ private _appUIController: AppUIController;
private _registerManager: RegisterManager;
private _componentManager: ComponentManager;
- constructor(config?: IDocUIPluginConfig) {
+ constructor(
+ private readonly _config: IDocUIPluginConfig,
+ @Inject(Injector) override _injector: Injector,
+ @Inject(LocaleService) private readonly _localService: LocaleService
+ ) {
super(DOC_UI_PLUGIN_NAME);
- this._config = Tools.deepMerge({}, DefaultDocUiConfig, config);
- }
- static create(config?: IDocUIPluginConfig) {
- return new DocUIPlugin(config);
+ this._config = Tools.deepMerge({}, DefaultDocUiConfig, this._config);
}
- installTo(univerInstance: Univer) {
- univerInstance.install(this);
- }
-
- initialize(ctx: Context): void {
- /**
- * load more Locale object
- */
- this.getLocale().load({
+ initialize(): void {
+ this._localService.getLocale().load({
en,
zh,
});
- this._componentManager = new ComponentManager();
- this._appUIController = new AppUIController(this);
- }
+ const dependencies: Dependency[] = [
+ [ComponentManager],
+ [
+ AppUIController,
+ {
+ useFactory: () => this._injector.createInstance(AppUIController, this._config),
+ },
+ ],
+ ];
- getConfig() {
- return this._config;
- }
+ installObserver(this);
- initRender(container: HTMLElement) {
- const engine = this.getPluginByName<RenderEngine>(PLUGIN_NAMES.BASE_RENDER)?.getEngine()!;
-
- // mount canvas to DOM container
- engine.setContainer(container);
-
- window.addEventListener('resize', () => {
- engine.resize();
+ dependencies.forEach((d) => {
+ this._injector.add(d);
});
- // should be clear
- setTimeout(() => {
- engine.resize();
- }, 0);
- }
-
- getAppUIController() {
- return this._appUIController;
- }
-
- getComponentManager() {
- return this._componentManager;
+ this._componentManager = this._injector.get(ComponentManager);
+ this._appUIController = this._injector.get(AppUIController);
}
/**
@@ -86,9 +70,10 @@ export class DocUIPlugin extends Plugin<any, Context> {
this._appUIController.getDocContainerController().UIDidMount(cb);
}
- onMounted(ctx: Context): void {
- this.initialize(ctx);
+ override onMounted(): void {
+ this.initialize();
}
- onDestroy(): void {}
-}
+ override onDestroy(): void {}
+
+}
\ No newline at end of file
diff --git a/packages/ui-plugin-docs/src/View/App.tsx b/packages/ui-plugin-docs/src/View/App.tsx
index 0c6c4ff926..39c76ef86e 100644
--- a/packages/ui-plugin-docs/src/View/App.tsx
+++ b/packages/ui-plugin-docs/src/View/App.tsx
@@ -1,9 +1,10 @@
import { AppContext, BaseComponentProps, Component, ComponentManager } from '@univerjs/base-ui';
-import { LocaleType } from '@univerjs/core';
+import { LocaleService, LocaleType } from '@univerjs/core';
import { BaseDocContainerProps, DocContainer } from './DocContainer';
export interface BaseUIProps extends BaseComponentProps {
locale: LocaleType;
+ localeService: LocaleService,
UIConfig: BaseDocContainerProps;
componentManager: ComponentManager;
changeLocale: (locale: string) => void;
@@ -30,15 +31,16 @@ export class App extends Component<BaseUIProps, IState> {
}
render() {
- const { context, UIConfig, componentManager } = this.props;
+ const { localeService, injector, UIConfig, componentManager } = this.props;
const { locale } = this.state;
return (
<AppContext.Provider
value={{
- context,
locale,
componentManager,
+ localeService,
+ injector,
}}
>
<div
@@ -69,4 +71,4 @@ export class App extends Component<BaseUIProps, IState> {
</AppContext.Provider>
);
}
-}
+}
\ No newline at end of file
diff --git a/packages/ui-plugin-sheets/src/SheetUIPlugin.ts b/packages/ui-plugin-sheets/src/SheetUIPlugin.ts
index d3a70863e8..5eeae9d626 100644
--- a/packages/ui-plugin-sheets/src/SheetUIPlugin.ts
+++ b/packages/ui-plugin-sheets/src/SheetUIPlugin.ts
@@ -54,22 +54,6 @@ export class SheetUIPlugin extends Plugin<SheetUIPluginObserve> {
});
}
- initializeDependencies(): void {
- this._injector.add([KeyboardManager]);
- this._injector.add([RegisterManager]);
- this._injector.add([ComponentManager]);
- this._injector.add([ZIndexManager]);
- this._injector.add([SlotManager]);
-
- // TODO: maybe we don't have to instantiate these dependencies manually
- this._componentManager = this._injector.get(ComponentManager);
- this._keyboardManager = this._injector.get(KeyboardManager);
- this._zIndexManager = this._injector.get(ZIndexManager);
- this._registerManager = this._injector.get(RegisterManager);
-
- this._appUIController = this._injector.createInstance(AppUIController, this._config);
- }
-
initRender() {
const engine = this._injector.get(IRenderingEngine);
const container = getRefElement(this._appUIController.getSheetContainerController().getContentRef());
@@ -163,4 +147,20 @@ export class SheetUIPlugin extends Plugin<SheetUIPluginObserve> {
deleteToolButton(name: string) {
this._appUIController.getSheetContainerController().getToolbarController().deleteToolbarConfig(name);
}
-}
+
+ private initializeDependencies(): void {
+ this._injector.add([KeyboardManager]);
+ this._injector.add([RegisterManager]);
+ this._injector.add([ComponentManager]);
+ this._injector.add([ZIndexManager]);
+ this._injector.add([SlotManager]);
+
+ // TODO: maybe we don't have to instantiate these dependencies manually
+ this._componentManager = this._injector.get(ComponentManager);
+ this._keyboardManager = this._injector.get(KeyboardManager);
+ this._zIndexManager = this._injector.get(ZIndexManager);
+ this._registerManager = this._injector.get(RegisterManager);
+
+ this._appUIController = this._injector.createInstance(AppUIController, this._config);
+ }
+}
\ No newline at end of file