Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
refactor: move `SkeletonManager` into `RenderUnit` (#2410)
Wenzhao Huc65997118fc2
diff --git a/examples/esbuild.config.mjs b/examples/esbuild.config.mjsindex d666324785..1979a76b04 100644--- a/examples/esbuild.config.mjs+++ b/examples/esbuild.config.mjs@@ -88,6 +88,8 @@ const ctx = await esbuild[args.watch ? 'context' : 'build']({// slides'./src/slides/main.ts',+ // uni+ './src/uni/main.ts',],outdir: './local',diff --git a/examples/public/uni/index.html b/examples/public/uni/index.htmlnew file mode 100644index 0000000000..c228b9f521--- /dev/null+++ b/examples/public/uni/index.html@@ -0,0 +1,31 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta content="width=device-width, initial-scale=1" name="viewport" />+ <title>Univer Sheets</title>++ <link rel="icon" type="image/x-icon" href="../favicon.svg" />+ <link rel="stylesheet" href="./main.css" />+ <style>+ html,+ body {+ height: 100%;+ margin: 0;+ }+ </style>++ <script>+ new EventSource('/esbuild').addEventListener('change', () => {+ console.info('reload--');+ location.reload();+ });+ </script>+ </head>++ <body style="overflow: hidden">+ <div id="app" style="height: 100%"></div>++ <script src="./main.js"></script>+ </body>+</html>diff --git a/examples/src/main.tsx b/examples/src/main.tsxindex d052883c67..878f47ef64 100644--- a/examples/src/main.tsx+++ b/examples/src/main.tsx@@ -52,6 +52,9 @@ function Examples() {}, {title: '📚 Docs Uniscript',href: './docs-uniscript/',+ }, {+ title: '🌌 Universe',+ href: './uni/',}];return (diff --git a/examples/src/sheets/lazy.ts b/examples/src/sheets/lazy.tsindex f642604d63..f4f17dd6e5 100644--- a/examples/src/sheets/lazy.ts+++ b/examples/src/sheets/lazy.ts@@ -16,6 +16,7 @@import type { Plugin, PluginCtor } from '@univerjs/core';import { UniverSheetsFilterUIPlugin } from '@univerjs/sheets-filter-ui';+import { UniverSheetsFindReplacePlugin } from '@univerjs/sheets-find-replace';import { UniverUniscriptPlugin } from '@univerjs/uniscript';export default function getLazyPlugins(): Array<[PluginCtor<Plugin>] | [PluginCtor<Plugin>, unknown]> {@@ -33,5 +34,6 @@ export default function getLazyPlugins(): Array<[PluginCtor<Plugin>] | [PluginCt},],[UniverSheetsFilterUIPlugin],+ [UniverSheetsFindReplacePlugin],];}diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.tsindex b92babddd9..182a03ce98 100644--- a/examples/src/sheets/main.ts+++ b/examples/src/sheets/main.ts@@ -18,30 +18,26 @@ import { LocaleType, LogLevel, Univer, UniverInstanceType, UserManagerService }import { defaultTheme } from '@univerjs/design';import { UniverDocsPlugin } from '@univerjs/docs';import { UniverDocsUIPlugin } from '@univerjs/docs-ui';-import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { UniverRenderEnginePlugin } from '@univerjs/engine-render';-import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';-import type { IUniverRPCMainThreadConfig } from '@univerjs/rpc';-import { UniverRPCMainThreadPlugin } from '@univerjs/rpc';import { UniverSheetsPlugin } from '@univerjs/sheets';-import { UniverSheetsFindReplacePlugin } from '@univerjs/sheets-find-replace';-import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';-import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';-import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';import { UniverUIPlugin } from '@univerjs/ui';-import { UniverDataValidationPlugin } from '@univerjs/data-validation';-import { UniverSheetsDataValidationPlugin } from '@univerjs/sheets-data-validation';import { UniverSheetsConditionalFormattingUIPlugin } from '@univerjs/sheets-conditional-formatting-ui';import { UniverSheetsThreadCommentPlugin } from '@univerjs/sheets-thread-comment';import { UniverDebuggerPlugin } from '@univerjs/debugger';import { UniverSheetsHyperLinkUIPlugin } from '@univerjs/sheets-hyper-link-ui';-import { FUniver } from '@univerjs/facade';import { IThreadCommentMentionDataService, UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';+import type { IUniverRPCMainThreadConfig } from '@univerjs/rpc';+import { UniverRPCMainThreadPlugin } from '@univerjs/rpc';+import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';+import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';+import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';+import { UniverSheetsDataValidationPlugin } from '@univerjs/sheets-data-validation';import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui';--import { DEFAULT_WORKBOOK_DATA_DEMO } from '../data/sheets/demo/default-workbook-data-demo';+import { FUniver } from '@univerjs/facade';import { enUS, ruRU, zhCN } from '../locales';+import { DEFAULT_WORKBOOK_DATA_DEMO } from '../data/sheets/demo/default-workbook-data-demo';/* eslint-disable-next-line node/prefer-global/process */const IS_E2E: boolean = !!process.env.IS_E2E;@@ -90,16 +86,9 @@ univer.registerPlugin(UniverRPCMainThreadPlugin, {univer.registerPlugin(UniverSheetsHyperLinkUIPlugin);-// find replace-univer.registerPlugin(UniverSheetsFindReplacePlugin);-// data validation-univer.registerPlugin(UniverDataValidationPlugin);univer.registerPlugin(UniverSheetsDataValidationPlugin);-// filter-univer.registerPlugin(UniverSheetsFilterPlugin);-// sheet condition formattinguniver.registerPlugin(UniverSheetsConditionalFormattingUIPlugin);@@ -122,7 +111,7 @@ const mockUser = {class CustomMentionDataService implements IThreadCommentMentionDataService {trigger: string = '@';- async getMentions(search: string) {+ async getMentions() {return [{id: mockUser.userID,@@ -153,6 +142,7 @@ const userManagerService = injector.get(UserManagerService);userManagerService.currentUser = mockUser;declare global {+ // eslint-disable-next-line ts/naming-conventioninterface Window {univer?: Univer;univerAPI?: ReturnType<typeof FUniver.newAPI>;diff --git a/examples/src/uni/lazy.ts b/examples/src/uni/lazy.tsnew file mode 100644index 0000000000..f642604d63--- /dev/null+++ b/examples/src/uni/lazy.ts@@ -0,0 +1,37 @@+/**+ * 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 { Plugin, PluginCtor } from '@univerjs/core';+import { UniverSheetsFilterUIPlugin } from '@univerjs/sheets-filter-ui';+import { UniverUniscriptPlugin } from '@univerjs/uniscript';++export default function getLazyPlugins(): Array<[PluginCtor<Plugin>] | [PluginCtor<Plugin>, unknown]> {+ return [+ [+ UniverUniscriptPlugin,+ {+ getWorkerUrl(moduleID: string, label: string) {+ if (label === 'typescript' || label === 'javascript') {+ return './vs/language/typescript/ts.worker.js';+ }++ return './vs/editor/editor.worker.js';+ },+ },+ ],+ [UniverSheetsFilterUIPlugin],+ ];+}diff --git a/examples/src/uni/main.ts b/examples/src/uni/main.tsnew file mode 100644index 0000000000..05ddd25a71--- /dev/null+++ b/examples/src/uni/main.ts@@ -0,0 +1,94 @@+/**+ * 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 { LocaleType, LogLevel, Univer, UniverInstanceType } from '@univerjs/core';+import { defaultTheme } from '@univerjs/design';+import { UniverDocsPlugin } from '@univerjs/docs';+import { UniverDocsUIPlugin } from '@univerjs/docs-ui';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';+import { UniverRenderEnginePlugin } from '@univerjs/engine-render';+import { UniverSheetsPlugin } from '@univerjs/sheets';+import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';+import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';+import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';+import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';+import { UniverUIPlugin } from '@univerjs/ui';+import { UniverDebuggerPlugin } from '@univerjs/debugger';+import { FUniver } from '@univerjs/facade';+import { UniverDrawingPlugin } from '@univerjs/drawing';+import { DEFAULT_WORKBOOK_DATA_DEMO } from '../data/sheets/demo/default-workbook-data-demo';+import { enUS } from '../locales';++/* eslint-disable-next-line node/prefer-global/process */+const IS_E2E: boolean = !!process.env.IS_E2E;++const LOAD_LAZY_PLUGINS_TIMEOUT = 1_000;++// univer+const univer = new Univer({+ theme: defaultTheme,+ locale: LocaleType.EN_US,+ locales: {+ [LocaleType.EN_US]: enUS,+ },+ logLevel: LogLevel.VERBOSE,+});++univer.registerPlugin(UniverDocsPlugin, {+ hasScroll: false,+});+univer.registerPlugin(UniverFormulaEnginePlugin);+univer.registerPlugin(UniverRenderEnginePlugin);+univer.registerPlugin(UniverUIPlugin, {+ container: 'app',+});++univer.registerPlugin(UniverDrawingPlugin);++univer.registerPlugin(UniverDocsUIPlugin);++univer.registerPlugin(UniverSheetsPlugin);+univer.registerPlugin(UniverSheetsUIPlugin);++univer.registerPlugin(UniverSheetsNumfmtPlugin);+univer.registerPlugin(UniverSheetsZenEditorPlugin);+univer.registerPlugin(UniverSheetsFormulaPlugin);++// create univer sheet instance+if (!IS_E2E) {+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, DEFAULT_WORKBOOK_DATA_DEMO);+}++// debugger plugin+univer.registerPlugin(UniverDebuggerPlugin);++declare global {+ // eslint-disable-next-line ts/naming-convention+ interface Window {+ univer?: Univer;+ univerAPI?: ReturnType<typeof FUniver.newAPI>;+ }+}++setTimeout(() => {+ import('./lazy').then((lazy) => {+ const plugins = lazy.default();+ plugins.forEach((p) => univer.registerPlugin(p[0], p[1]));+ });+}, LOAD_LAZY_PLUGINS_TIMEOUT);++window.univer = univer;+window.univerAPI = FUniver.newAPI(univer);diff --git a/examples/src/uni/worker.ts b/examples/src/uni/worker.tsnew file mode 100644index 0000000000..98f821ce65--- /dev/null+++ b/examples/src/uni/worker.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 { LocaleType, Univer } from '@univerjs/core';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';+import { UniverRPCWorkerThreadPlugin } from '@univerjs/rpc';+import { UniverSheetsPlugin } from '@univerjs/sheets';+import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';++// Univer web worker is also a univer application.+const univer = new Univer({+ locale: LocaleType.ZH_CN,+});++univer.registerPlugin(UniverSheetsPlugin, { onlyRegisterFormulaRelatedMutations: true });+univer.registerPlugin(UniverFormulaEnginePlugin);+univer.registerPlugin(UniverRPCWorkerThreadPlugin);+univer.registerPlugin(UniverSheetsFilterPlugin);++declare let self: WorkerGlobalScope & typeof globalThis & { univer: Univer };+self.univer = univer;diff --git a/packages/debugger/src/controllers/performance-monitor.controller.ts b/packages/debugger/src/controllers/performance-monitor.controller.tsindex bb077b9575..cf5a8825d5 100644--- a/packages/debugger/src/controllers/performance-monitor.controller.ts+++ b/packages/debugger/src/controllers/performance-monitor.controller.ts@@ -94,15 +94,5 @@ export class PerformanceMonitorController extends RxDisposable {container.innerText = `FPS: ${fps}`;});}- // TODO@wzhudev: restore fps monitor- // else if (this._documentType === UniverInstanceType.UNIVER_SHEET) {- // this._injector- // .get(SheetCanvasView)- // .fps$.pipe(takeUntil(this.dispose$))- // .pipe(throttle(() => interval(THROTTLE_TIME)))- // .subscribe((fps) => {- // container.innerText = `FPS: ${fps}`;- // });- // }}}diff --git a/packages/docs/src/services/doc-skeleton-manager.service.ts b/packages/docs/src/services/doc-skeleton-manager.service.tsindex 8eb54f35bd..0b2ecef98e 100644--- a/packages/docs/src/services/doc-skeleton-manager.service.ts+++ b/packages/docs/src/services/doc-skeleton-manager.service.ts@@ -99,10 +99,6 @@ export class DocSkeletonManagerService extends RxDisposable {return this._docSkeletonMap;}- makeDirtyCurrent(state: boolean = true) {- this.makeDirty(this._currentSkeletonUnitId, state);- }-makeDirty(unitId: string, state: boolean = true) {const param = this.getSkeletonByUnitId(unitId);if (param == null) {diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.tsindex 54278e74f0..3ef063c919 100644--- a/packages/engine-render/src/index.ts+++ b/packages/engine-render/src/index.ts@@ -25,7 +25,7 @@ export * from './group';export * from './layer';export { IRenderingEngine, UniverRenderEnginePlugin } from './render-engine';export { type RenderComponentType, IRenderManagerService, RenderManagerService } from './render-manager/render-manager.service';-export { RenderUnit, type IRender, type IRenderControllerCtor, type IRenderController, type IRenderContext } from './render-manager/render-unit';+export { RenderUnit, type IRender, type IRenderModuleCtor, type IRenderModule, type IRenderContext } from './render-manager/render-unit';export * from './scene';export * from './scene-viewer';export * from './scroll-timer';diff --git a/packages/engine-render/src/render-manager/render-manager.service.ts b/packages/engine-render/src/render-manager/render-manager.service.tsindex ef4d562a67..4949eef263 100644--- a/packages/engine-render/src/render-manager/render-manager.service.ts+++ b/packages/engine-render/src/render-manager/render-manager.service.ts@@ -14,9 +14,9 @@* limitations under the License.*/-import type { Nullable, UnitModel, UnitType } from '@univerjs/core';+import type { Nullable, UnitModel, UnitType, UniverInstanceType } from '@univerjs/core';import { Disposable, IUniverInstanceService, toDisposable } from '@univerjs/core';-import type { IDisposable } from '@wendellhu/redi';+import type { DependencyIdentifier, IDisposable } from '@wendellhu/redi';import { createIdentifier, Inject, Injector } from '@wendellhu/redi';import type { Observable } from 'rxjs';import { BehaviorSubject } from 'rxjs';@@ -27,13 +27,14 @@ import type { SheetComponent } from '../components/sheets/sheet-component';import type { Slide } from '../components/slides/slide';import { Engine } from '../engine';import { Scene } from '../scene';-import { type IRender, type IRenderControllerCtor, RenderUnit } from './render-unit';+import { type IRender, type IRenderModuleCtor, RenderUnit } from './render-unit';export type RenderComponentType = SheetComponent | DocComponent | Slide | BaseObject;export interface IRenderManagerService extends IDisposable {currentRender$: Observable<Nullable<string>>;createRender$: Observable<Nullable<string>>;+ addRender(unitId: string, renderer: IRender): void;createRender(unitId: string): IRender;removeRender(unitId: string): void;setCurrent(unitId: string): void;@@ -41,11 +42,17 @@ export interface IRenderManagerService extends IDisposable {getRenderAll(): Map<string, IRender>;defaultEngine: Engine;create(unitId: Nullable<string>): void;++ /** @deprecated There will be multi units to render at the same time, so there is no *current*. */getCurrent(): Nullable<IRender>;+ /** @deprecated There will be multi units to render at the same time, so there is no *first*. */getFirst(): Nullable<IRender>;+has(unitId: string): boolean;- registerRenderController<T extends UnitModel>(type: UnitType, ctor: IRenderControllerCtor<T>): IDisposable;+ withCurrentTypeOfUnit<T>(type: UniverInstanceType, id: DependencyIdentifier<T>): Nullable<T>;++ registerRenderController<T extends UnitModel>(type: UnitType, ctor: IRenderModuleCtor<T>): IDisposable;}const DEFAULT_SCENE_SIZE = { width: 1500, height: 1000 };@@ -72,7 +79,7 @@ export class RenderManagerService extends Disposable implements IRenderManagerSereturn this._defaultEngine;}- private readonly _renderControllers = new Map<UnitType, Set<IRenderControllerCtor>>();+ private readonly _renderControllers = new Map<UnitType, Set<IRenderModuleCtor>>();constructor(@Inject(Injector) private readonly _injector: Injector,@@ -84,17 +91,13 @@ export class RenderManagerService extends Disposable implements IRenderManagerSeoverride dispose() {super.dispose();- this._renderMap.forEach((item) => {- this._disposeItem(item);- });-+ this._renderMap.forEach((item) => this._disposeItem(item));this._renderControllers.clear();this._renderMap.clear();-this._currentRender$.complete();}- registerRenderController(type: UnitType, ctor: IRenderControllerCtor): IDisposable {+ registerRenderController(type: UnitType, ctor: IRenderModuleCtor): IDisposable {if (!this._renderControllers.has(type)) {this._renderControllers.set(type, new Set());}@@ -112,14 +115,10 @@ export class RenderManagerService extends Disposable implements IRenderManagerSereturn toDisposable(() => set.delete(ctor));}- private _getRenderControllersForType(type: UnitType): Array<IRenderControllerCtor> {+ private _getRenderControllersForType(type: UnitType): Array<IRenderModuleCtor> {return Array.from(this._renderControllers.get(type) ?? []);}- createRenderWithEngine(unitId: string, engine: Engine): IRender {- return this._createRender(unitId, engine, false);- }-create(unitId: Nullable<string>) {this._createRender$.next(unitId);}@@ -128,6 +127,13 @@ export class RenderManagerService extends Disposable implements IRenderManagerSereturn this._createRender(unitId, new Engine());}+ withCurrentTypeOfUnit<T>(type: UniverInstanceType, id: DependencyIdentifier<T>): Nullable<T> {+ const current = this._univerInstanceService.getCurrentUnitForType(type);+ if (!current) return null;++ return this.getRenderById(current.getUnitId())?.with(id);+ }+private _createRender(unitId: string, engine: Engine, isMainScene: boolean = true): IRender {const existItem = this.getRenderById(unitId);let shouldDestroyEngine = true;@@ -182,6 +188,10 @@ export class RenderManagerService extends Disposable implements IRenderManagerSereturn renderUnit;}+ addRender(unitId: string, item: IRender) {+ this._addRenderUnit(unitId, item);+ }+private _addRenderUnit(unitId: string, item: IRender) {this._renderMap.set(unitId, item);}diff --git a/packages/engine-render/src/render-manager/render-unit.ts b/packages/engine-render/src/render-manager/render-unit.tsindex 0294c82004..d4eef12ea5 100644--- a/packages/engine-render/src/render-manager/render-unit.ts+++ b/packages/engine-render/src/render-manager/render-unit.ts@@ -33,8 +33,8 @@ export interface IRender {}// eslint-disable-next-line ts/no-explicit-any-export interface IRenderControllerCtor<T extends UnitModel = UnitModel> { new(unit: IRenderContext<T>, ...args: any[]): IRenderController }-export interface IRenderController extends IDisposable {}+export interface IRenderModuleCtor<T extends UnitModel = UnitModel> { new(unit: IRenderContext<T>, ...args: any[]): IRenderModule }+export interface IRenderModule extends IDisposable {}/*** This object encapsulates methods or properties to render each element.@@ -100,11 +100,11 @@ export class RenderUnit extends Disposable implements IRender {return this._injector.get(dependency);}- addRenderControllers(ctors: IRenderControllerCtor[]) {+ addRenderControllers(ctors: IRenderModuleCtor[]) {this._initControllers(ctors);}- private _initControllers(ctors: IRenderControllerCtor[]): void {+ private _initControllers(ctors: IRenderModuleCtor[]): void {const j = this._injector;ctors.forEach((ctor) => j.add([ctor, { useFactory: () => j.createInstance(ctor, this._renderContext) }]));diff --git a/packages/facade/src/apis/__tests__/create-test-bed.ts b/packages/facade/src/apis/__tests__/create-test-bed.tsindex 1b1c6b20d7..74402ec3af 100644--- a/packages/facade/src/apis/__tests__/create-test-bed.ts+++ b/packages/facade/src/apis/__tests__/create-test-bed.ts@@ -47,7 +47,7 @@ import type { Dependency } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';-import { ISelectionRenderService, SelectionRenderService, SheetCanvasView, SheetRenderController, SheetSkeletonManagerService } from '@univerjs/sheets-ui';+import { ISelectionRenderService, SelectionRenderService, SheetRenderController, SheetSkeletonManagerService, SheetsRenderService } from '@univerjs/sheets-ui';import { DesktopPlatformService, DesktopShortcutService, IPlatformService, IShortcutService } from '@univerjs/ui';import { SheetsConditionalFormattingPlugin } from '@univerjs/sheets-conditional-formatting';@@ -142,7 +142,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:injector.add([IRenderingEngine, { useFactory: () => new Engine() }]);injector.add([IRenderManagerService, { useClass: RenderManagerService }]);injector.add([ISelectionRenderService, { useClass: SelectionRenderService }]);- injector.add([SheetRenderController]);+ injector.add([SheetsRenderService]);injector.add([IShortcutService, { useClass: DesktopShortcutService }]);injector.add([IPlatformService, { useClass: DesktopPlatformService }]);injector.add([SheetSkeletonManagerService]);@@ -154,16 +154,15 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:injector.add([IAuthzIoService, { useClass: AuthzIoLocalService }]);injector.add([WorksheetProtectionRuleModel]);+ const renderManagerService = injector.get(IRenderManagerService);+ renderManagerService.registerRenderController(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService);+ renderManagerService.registerRenderController(UniverInstanceType.UNIVER_SHEET, SheetRenderController);+SheetsConditionalFormattingPlugin.dependencyList.forEach((d) => {injector.add(d);});dependencies?.forEach((d) => injector.add(d));-- const renderManagerService = injector.get(IRenderManagerService);- ([- SheetCanvasView,- ]).forEach((renderController) => renderManagerService.registerRenderController(UniverInstanceType.UNIVER_SHEET, renderController));}}diff --git a/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-range.spec.tsindex 1ddec1acdc..7529cc717d 100644--- a/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts+++ b/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts@@ -44,6 +44,7 @@ describe('Test FRange', () => {beforeEach(() => {const testBed = createFacadeTestBed();get = testBed.get;+univerAPI = testBed.univerAPI;commandService = get(ICommandService);diff --git a/packages/facade/src/apis/sheets/f-range.ts b/packages/facade/src/apis/sheets/f-range.tsindex 1f38d592d9..d5c177c7fc 100644--- a/packages/facade/src/apis/sheets/f-range.ts+++ b/packages/facade/src/apis/sheets/f-range.ts@@ -46,6 +46,7 @@ import { SetNumfmtCommand } from '@univerjs/sheets-numfmt';import { FormulaDataModel } from '@univerjs/engine-formula';import { Inject, Injector } from '@wendellhu/redi';import { ISheetClipboardService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';+import { IRenderManagerService } from '@univerjs/engine-render';import type { FHorizontalAlignment, FVerticalAlignment } from './utils';import { covertCellValue,covertCellValues,@@ -67,8 +68,8 @@ export class FRange {private readonly _range: IRange,@Inject(Injector) private readonly _injector: Injector,@ICommandService private readonly _commandService: ICommandService,- @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,- @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel) {// empty}@@ -102,7 +103,10 @@ export class FRange {* @returns The cell information*/getCell(): ISelectionCellWithCoord {- const { skeleton } = this._sheetSkeletonManagerService.getUnitSkeleton(this._workbook.getUnitId(), this._worksheet.getSheetId())!;+ const unitId = this._workbook.getUnitId();+ const subUnitId = this._worksheet.getSheetId();+ const skeleton = this._renderManagerService.getRenderById(unitId)!+ .with(SheetSkeletonManagerService).getUnitSkeleton(unitId, subUnitId)!.skeleton;return skeleton.getCellByIndex(this._range.startRow, this._range.startColumn);}diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.ref-range.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.ref-range.controller.tsindex ddcf8ceb2e..64bdac2db4 100644--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.ref-range.controller.ts+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.ref-range.controller.ts@@ -15,26 +15,23 @@*/import type { IRange, Workbook } from '@univerjs/core';-import { Disposable, DisposableCollection, IUniverInstanceService, LifecycleStages, OnLifecycle, toDisposable, UniverInstanceType } from '@univerjs/core';+import { Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle, toDisposable, UniverInstanceType } from '@univerjs/core';import type { EffectRefRangeParams } from '@univerjs/sheets';-import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { handleDefaultRangeChangeWithEffectRefCommands, RefRangeService } from '@univerjs/sheets';import { Inject, Injector } from '@wendellhu/redi';-import { merge, Observable } from 'rxjs';-import { distinctUntilChanged, map, switchMap } from 'rxjs/operators';import { ConditionalFormattingRuleModel, DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, isRangesEqual, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory } from '@univerjs/sheets-conditional-formatting';import type { IConditionFormattingRule, IDeleteConditionalRuleMutationParams, ISetConditionalRuleMutationParams } from '@univerjs/sheets-conditional-formatting';-@OnLifecycle(LifecycleStages.Rendered, RefRangeController)-export class RefRangeController extends Disposable {+@OnLifecycle(LifecycleStages.Rendered, SheetsCfRefRangeController)+export class SheetsCfRefRangeController extends Disposable {constructor(@Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel,@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,@Inject(Injector) private _injector: Injector,- @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService,-- @Inject(RefRangeService) private _refRangeService: RefRangeService) {+ @Inject(RefRangeService) private _refRangeService: RefRangeService+ ) {super();+this._initRefRange();}@@ -71,53 +68,31 @@ export class RefRangeController extends Disposable {disposableMap.set(getCfIdWithUnitId(unitId, subUnitId, rule.cfId), () => disposeList.forEach((dispose) => dispose()));};- this.disposeWithMe(- merge(- this._sheetSkeletonManagerService.currentSkeleton$.pipe(- map((skeleton) => skeleton?.sheetId),- distinctUntilChanged()- )- )- .pipe(- switchMap(- () =>- new Observable<DisposableCollection>((subscribe) => {- const disposableCollection = new DisposableCollection();- subscribe.next(disposableCollection);- return () => {- disposableCollection.dispose();- };- })- )- ).subscribe((disposableCollection) => {- disposableCollection.add(- toDisposable(- this._conditionalFormattingRuleModel.$ruleChange.subscribe((option) => {- const { unitId, subUnitId, rule } = option;- const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- const worksheet = workbook.getActiveSheet();- if (option.unitId !== workbook.getUnitId() || option.subUnitId !== worksheet.getSheetId()) {- return;- }- switch (option.type) {- case 'add':{- register(option.unitId, option.subUnitId, option.rule);- break;- }- case 'delete':{- const dispose = disposableMap.get(getCfIdWithUnitId(unitId, subUnitId, rule.cfId));- dispose && dispose();- break;- }- case 'set':{- const dispose = disposableMap.get(getCfIdWithUnitId(unitId, subUnitId, rule.cfId));- dispose && dispose();+ this.disposeWithMe(this._conditionalFormattingRuleModel.$ruleChange.subscribe((option) => {+ const { unitId, subUnitId, rule } = option;+ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const worksheet = workbook.getActiveSheet();+ if (option.unitId !== workbook.getUnitId() || option.subUnitId !== worksheet.getSheetId()) {+ return;+ }+ switch (option.type) {+ case 'add':{+ register(option.unitId, option.subUnitId, option.rule);+ break;+ }+ case 'delete':{+ const dispose = disposableMap.get(getCfIdWithUnitId(unitId, subUnitId, rule.cfId));+ dispose && dispose();+ break;+ }+ case 'set':{+ const dispose = disposableMap.get(getCfIdWithUnitId(unitId, subUnitId, rule.cfId));+ dispose && dispose();// and to add- register(option.unitId, option.subUnitId, option.rule);- }- }- })));- }));+ register(option.unitId, option.subUnitId, option.rule);+ }+ }+ }));this.disposeWithMe(toDisposable(() => {disposableMap.forEach((item) => {diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.tsindex aa379026fb..2af1b988cb 100644--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts@@ -18,44 +18,41 @@ import type { Workbook } from '@univerjs/core';import { Disposable, IPermissionService, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';import type { IRangeProtectionRule, IWorksheetProtectionRenderCellData } from '@univerjs/sheets';import { INTERCEPTOR_POINT, RangeProtectionRenderModel, RangeProtectionRuleModel, SheetInterceptorService, WorksheetEditPermission, WorksheetProtectionRuleModel, WorksheetViewPermission } from '@univerjs/sheets';-import type { IRangeProtectionRenderCellData } from '@univerjs/sheets-ui';-import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { Inject } from '@wendellhu/redi';import { bufferTime, filter } from 'rxjs/operators';import type { ISheetFontRenderExtension, ISheetRenderExtension } from '@univerjs/engine-render';import { IRenderManagerService } from '@univerjs/engine-render';-import { ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel, DEFAULT_PADDING, DEFAULT_WIDTH } from '@univerjs/sheets-conditional-formatting';-import type { IConditionalFormattingCellData, IDataBarCellData, IIconSetCellData } from '@univerjs/sheets-conditional-formatting';+import type { IRangeProtectionRenderCellData } from '@univerjs/sheets-ui';+import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { UnitAction } from '@univerjs/protocol';-/**- * @todo RenderUnit- */-@OnLifecycle(LifecycleStages.Rendered, RenderController)-export class RenderController extends Disposable {+@OnLifecycle(LifecycleStages.Rendered, SheetsCfRenderController)+export class SheetsCfRenderController extends Disposable {constructor(@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,@Inject(ConditionalFormattingService) private _conditionalFormattingService: ConditionalFormattingService,@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,@Inject(IRenderManagerService) private _renderManagerService: IRenderManagerService,@Inject(ConditionalFormattingViewModel) private _conditionalFormattingViewModel: ConditionalFormattingViewModel,@Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel,- @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService,@Inject(RangeProtectionRenderModel) private _selectionProtectionRenderModel: RangeProtectionRenderModel,@Inject(RangeProtectionRuleModel) private _rangeProtectionRuleModel: RangeProtectionRuleModel,@Inject(WorksheetProtectionRuleModel) private _worksheetProtectionRuleModel: WorksheetProtectionRuleModel,@IPermissionService private _permissionService: IPermissionService) {super();+this._initViewModelInterceptor();this._initSkeleton();+ this._initViewModelByRangeInterceptor();+ this._initViewModelBySheetInterceptor();}- _initSkeleton() {+ private _initSkeleton() {const markDirtySkeleton = () => {- this._sheetSkeletonManagerService.reCalculate();const unitId = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();+ this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).reCalculate();this._renderManagerService.getRenderById(unitId)?.mainComponent?.makeDirty();};@@ -88,7 +85,7 @@ export class RenderController extends Disposable {})).subscribe(markDirtySkeleton));}- _initViewModelInterceptor() {+ private _initViewModelInterceptor() {this.disposeWithMe(this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {handler: (cell, context, next) => {const result = this._conditionalFormattingService.composeStyle(context.unitId, context.subUnitId, context.row, context.col);diff --git a/packages/sheets-conditional-formatting-ui/src/plugin.ts b/packages/sheets-conditional-formatting-ui/src/plugin.tsindex 816bbf46ba..70b8a5ac81 100644--- a/packages/sheets-conditional-formatting-ui/src/plugin.ts+++ b/packages/sheets-conditional-formatting-ui/src/plugin.ts@@ -34,13 +34,13 @@ import { SetCfCommand } from './commands/commands/set-cf.command';import { moveCfCommand } from './commands/commands/move-cf.command';import { AddCfCommand } from './commands/commands/add-cf.command';-import { RenderController } from './controllers/cf.render.controller';+import { SheetsCfRenderController } from './controllers/cf.render.controller';import { ConditionalFormattingCopyPasteController } from './controllers/cf.copy-paste.controller';import { ConditionalFormattingAutoFillController } from './controllers/cf.auto-fill.controller';import type { IUniverSheetsConditionalFormattingUIConfig } from './controllers/cf.menu.controller';import { ConditionalFormattingMenuController, DefaultSheetConditionalFormattingUiConfig } from './controllers/cf.menu.controller';import { ConditionalFormattingI18nController } from './controllers/cf.i18n.controller';-import { RefRangeController } from './controllers/cf.ref-range.controller';+import { SheetsCfRefRangeController } from './controllers/cf.ref-range.controller';import { ConditionalFormattingEditorController } from './controllers/cf.editor.controller';import { ConditionalFormattingClearController } from './controllers/cf.clear.controller';import { ConditionalFormattingPermissionController } from './controllers/cf.permission.controller';@@ -80,8 +80,8 @@ export class UniverSheetsConditionalFormattingUIPlugin extends Plugin {SheetsConditionalFormattingPlugin.dependencyList.forEach((dependency) => {this._injector.add(dependency);});- this._injector.add([RenderController]);- this._injector.add([RefRangeController]);+ this._injector.add([SheetsCfRenderController]);+ this._injector.add([SheetsCfRefRangeController]);this._injector.add([ConditionalFormattingCopyPasteController]);this._injector.add([ConditionalFormattingAutoFillController]);this._injector.add([ConditionalFormattingPermissionController]);diff --git a/packages/sheets-conditional-formatting/src/plugin.ts b/packages/sheets-conditional-formatting/src/plugin.tsindex bd09749c62..86be7eaf94 100644--- a/packages/sheets-conditional-formatting/src/plugin.ts+++ b/packages/sheets-conditional-formatting/src/plugin.ts@@ -33,8 +33,20 @@ export class SheetsConditionalFormattingPlugin extends Plugin {static override pluginName = SHEET_CONDITIONAL_FORMATTING_PLUGIN;static override type = UniverInstanceType.UNIVER_SHEET;- static readonly dependencyList: Dependency[] = [[ConditionalFormattingService], [ConditionalFormattingFormulaService], [ConditionalFormattingRuleModel], [ConditionalFormattingViewModel]];- static readonly mutationList = [AddConditionalRuleMutation, DeleteConditionalRuleMutation, SetConditionalRuleMutation, MoveConditionalRuleMutation, ConditionalFormattingFormulaMarkDirty];+ static readonly dependencyList: Dependency[] = [+ [ConditionalFormattingService],+ [ConditionalFormattingFormulaService],+ [ConditionalFormattingRuleModel],+ [ConditionalFormattingViewModel],+ ];++ static readonly mutationList = [+ AddConditionalRuleMutation,+ DeleteConditionalRuleMutation,+ SetConditionalRuleMutation,+ MoveConditionalRuleMutation,+ ConditionalFormattingFormulaMarkDirty,+ ];constructor(_config: unknown,diff --git a/packages/sheets-data-validation/src/controllers/dv-ref-range.controller.ts b/packages/sheets-data-validation/src/controllers/dv-ref-range.controller.tsindex 4093447c1a..c9fb7c5b2c 100644--- a/packages/sheets-data-validation/src/controllers/dv-ref-range.controller.ts+++ b/packages/sheets-data-validation/src/controllers/dv-ref-range.controller.ts@@ -15,19 +15,15 @@*/import type { IRange, ISheetDataValidationRule } from '@univerjs/core';-import { DataValidationType, Disposable, DisposableCollection, ICommandService, isRangesEqual, IUniverInstanceService, LifecycleStages, OnLifecycle, toDisposable } from '@univerjs/core';+import { DataValidationType, Disposable, isRangesEqual, LifecycleStages, OnLifecycle, toDisposable } from '@univerjs/core';import type { EffectRefRangeParams } from '@univerjs/sheets';-import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { handleCommonDefaultRangeChangeWithEffectRefCommands, RefRangeService } from '@univerjs/sheets';import { Inject, Injector } from '@wendellhu/redi';-import { merge, Observable } from 'rxjs';-import { distinctUntilChanged, map, switchMap } from 'rxjs/operators';import type { IRemoveDataValidationMutationParams, IUpdateDataValidationMutationParams } from '@univerjs/data-validation';import { DataValidationModel, RemoveDataValidationMutation, removeDataValidationUndoFactory, UpdateDataValidationMutation, UpdateRuleType } from '@univerjs/data-validation';import { FormulaRefRangeService } from '@univerjs/sheets-formula';import { DataValidationCustomFormulaService } from '../services/dv-custom-formula.service';import { DataValidationFormulaService } from '../services/dv-formula.service';-import { DataValidationCacheService } from '../services/dv-cache.service';@OnLifecycle(LifecycleStages.Ready, DataValidationRefRangeController)export class DataValidationRefRangeController extends Disposable {@@ -35,15 +31,11 @@ export class DataValidationRefRangeController extends Disposable {constructor(@Inject(DataValidationModel) private _dataValidationModel: DataValidationModel,- @Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,@Inject(Injector) private _injector: Injector,- @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService,@Inject(RefRangeService) private _refRangeService: RefRangeService,@Inject(DataValidationCustomFormulaService) private _dataValidationCustomFormulaService: DataValidationCustomFormulaService,@Inject(DataValidationFormulaService) private _dataValidationFormulaService: DataValidationFormulaService,- @Inject(FormulaRefRangeService) private _formulaRefRangeService: FormulaRefRangeService,- @ICommandService private readonly _commandService: ICommandService,- @Inject(DataValidationCacheService) private readonly _dataValidationCacheService: DataValidationCacheService+ @Inject(FormulaRefRangeService) private _formulaRefRangeService: FormulaRefRangeService) {super();this._initRefRange();@@ -208,49 +200,29 @@ export class DataValidationRefRangeController extends Disposable {private _initRefRange() {this.disposeWithMe(- merge(- this._sheetSkeletonManagerService.currentSkeleton$.pipe(- map((skeleton) => skeleton?.sheetId),- distinctUntilChanged()- )- )- .pipe(- switchMap(- () =>- new Observable<DisposableCollection>((subscribe) => {- const disposableCollection = new DisposableCollection();- subscribe.next(disposableCollection);- return () => {- disposableCollection.dispose();- };- })- )- ).subscribe((disposableCollection) => {- disposableCollection.add(- toDisposable(- this._dataValidationModel.ruleChange$.subscribe((option) => {- const { unitId, subUnitId, rule } = option;- switch (option.type) {- case 'add': {- const rule = option.rule!;- this.registerRule(option.unitId, option.subUnitId, rule);- break;- }- case 'remove': {- const disposeSet = this._disposableMap.get(this._getIdWithUnitId(unitId, subUnitId, rule!.uid));- disposeSet && disposeSet.forEach((dispose) => dispose());- break;- }- case 'update': {- const rule = option.rule!;- const disposeSet = this._disposableMap.get(this._getIdWithUnitId(unitId, subUnitId, rule!.uid));- disposeSet && disposeSet.forEach((dispose) => dispose());- this.registerRule(option.unitId, option.subUnitId, rule);- break;- }- }- })));- }));+ this._dataValidationModel.ruleChange$.subscribe((option) => {+ const { unitId, subUnitId, rule } = option;+ switch (option.type) {+ case 'add': {+ const rule = option.rule!;+ this.registerRule(option.unitId, option.subUnitId, rule);+ break;+ }+ case 'remove': {+ const disposeSet = this._disposableMap.get(this._getIdWithUnitId(unitId, subUnitId, rule!.uid));+ disposeSet && disposeSet.forEach((dispose) => dispose());+ break;+ }+ case 'update': {+ const rule = option.rule!;+ const disposeSet = this._disposableMap.get(this._getIdWithUnitId(unitId, subUnitId, rule!.uid));+ disposeSet && disposeSet.forEach((dispose) => dispose());+ this.registerRule(option.unitId, option.subUnitId, rule);+ break;+ }+ }+ })+ );this.disposeWithMe(toDisposable(() => {this._disposableMap.forEach((item) => {diff --git a/packages/sheets-data-validation/src/controllers/dv-render.controller.ts b/packages/sheets-data-validation/src/controllers/dv-render.controller.tsindex 6951755f06..c02a86526c 100644--- a/packages/sheets-data-validation/src/controllers/dv-render.controller.ts+++ b/packages/sheets-data-validation/src/controllers/dv-render.controller.ts@@ -52,30 +52,25 @@ const INVALID_MARK = {/*** @todo RenderUnit*/-@OnLifecycle(LifecycleStages.Rendered, DataValidationRenderController)-export class DataValidationRenderController extends RxDisposable {+@OnLifecycle(LifecycleStages.Rendered, SheetsDataValidationRenderController)+export class SheetsDataValidationRenderController extends RxDisposable {constructor(private readonly _config: Partial<IUniverSheetsDataValidation>,- @Inject(ComponentManager) private _componentManager: ComponentManager,+ @ICommandService private readonly _commandService: ICommandService,+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,@IMenuService private _menuService: IMenuService,- @Inject(DataValidationModel) private readonly _dataValidationModel: DataValidationModel,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @Inject(DataValidatorRegistryService) private readonly _dataValidatorRegistryService: DataValidatorRegistryService,- @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,+ @Inject(AutoHeightController) private readonly _autoHeightController: AutoHeightController,+ @Inject(ComponentManager) private _componentManager: ComponentManager,@Inject(DataValidationDropdownManagerService) private readonly _dropdownManagerService: DataValidationDropdownManagerService,- @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,+ @Inject(DataValidationModel) private readonly _dataValidationModel: DataValidationModel,+ @Inject(DataValidatorRegistryService) private readonly _dataValidatorRegistryService: DataValidatorRegistryService,@Inject(Injector) private readonly _injector: Injector,- @Inject(AutoHeightController) private readonly _autoHeightController: AutoHeightController,- @ICommandService private readonly _commandService: ICommandService+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService) {super();- this._init();- }-- private _init() {this._initComponents();this._initMenu();this._initSkeletonChange();@@ -190,7 +185,9 @@ export class DataValidationRenderController extends RxDisposable {const unitId = workbook.getUnitId();const subUnitId = workbook.getActiveSheet().getSheetId();- const skeleton = this._sheetSkeletonManagerService.getOrCreateSkeleton({ unitId, sheetId: subUnitId });+ const skeleton = this._renderManagerService.getRenderById(unitId)+ ?.with(SheetSkeletonManagerService).getUnitSkeleton(unitId, subUnitId)+ ?.skeleton;const currentRender = this._renderManagerService.getRenderById(unitId);skeleton?.makeDirty(true);@@ -201,13 +198,8 @@ export class DataValidationRenderController extends RxDisposable {}};- this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe(() => {- markSkeletonDirty();- }));-- this.disposeWithMe(this._dataValidationModel.validStatusChange$.subscribe(() => {- markSkeletonDirty();- }));+ this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe(() => markSkeletonDirty()));+ this.disposeWithMe(this._dataValidationModel.validStatusChange$.subscribe(() => markSkeletonDirty()));}// eslint-disable-next-line max-lines-per-function@@ -217,14 +209,21 @@ export class DataValidationRenderController extends RxDisposable {INTERCEPTOR_POINT.CELL_CONTENT,{priority: 200,- // eslint-disable-next-line max-lines-per-function, complexity+ // eslint-disable-next-line max-lines-per-functionhandler: (cell, pos, next) => {const { row, col, unitId, subUnitId } = pos;const manager = this._dataValidationModel.ensureManager(unitId, subUnitId) as SheetDataValidationManager;- const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;- if (!manager || !skeleton) {+ if (!manager) {return next(cell);}++ const skeleton = this._renderManagerService.getRenderById(unitId)+ ?.with(SheetSkeletonManagerService).getUnitSkeleton(unitId, subUnitId)+ ?.skeleton;+ if (!skeleton) {+ return next(cell);+ }+const styleMap = pos.workbook.getStyles();const defaultStyle = (typeof cell?.s === 'string' ? styleMap.get(cell?.s) : cell?.s) || {};const ruleId = manager.getRuleIdByLocation(row, col);diff --git a/packages/sheets-data-validation/src/index.ts b/packages/sheets-data-validation/src/index.tsindex 065cdf6e1a..c26a2a6c58 100644--- a/packages/sheets-data-validation/src/index.ts+++ b/packages/sheets-data-validation/src/index.ts@@ -17,7 +17,7 @@export { UniverSheetsDataValidationPlugin } from './plugin';export type { IAddSheetDataValidationCommandParams, IUpdateSheetDataValidationRangeCommandParams } from './commands/commands/data-validation.command';export { ICommandService, LocaleService, Plugin } from '@univerjs/core';-export { DataValidationRenderController } from './controllers/dv-render.controller';+export { SheetsDataValidationRenderController } from './controllers/dv-render.controller';export { DataValidationController } from './controllers/dv.controller';export { SheetDataValidationService } from './services/dv.service';export { DataValidationAlertController } from './controllers/dv-alert.controller';diff --git a/packages/sheets-data-validation/src/plugin.ts b/packages/sheets-data-validation/src/plugin.tsindex c89a99692d..9533da7581 100644--- a/packages/sheets-data-validation/src/plugin.ts+++ b/packages/sheets-data-validation/src/plugin.ts@@ -20,7 +20,7 @@ import { UniverDataValidationPlugin } from '@univerjs/data-validation';import { UniverSheetsPlugin } from '@univerjs/sheets';import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';import type { IUniverSheetsDataValidation } from './controllers/dv-render.controller';-import { DataValidationRenderController, DefaultSheetsDataValidation } from './controllers/dv-render.controller';+import { DefaultSheetsDataValidation, SheetsDataValidationRenderController } from './controllers/dv-render.controller';import { DataValidationController } from './controllers/dv.controller';import { SheetDataValidationService } from './services/dv.service';import { DataValidationAlertController } from './controllers/dv-alert.controller';@@ -69,9 +69,9 @@ export class UniverSheetsDataValidationPlugin extends Plugin {[DataValidationModelController],[DataValidationController],[- DataValidationRenderController,+ SheetsDataValidationRenderController,{- useFactory: () => this._injector.createInstance(DataValidationRenderController, this._config),+ useFactory: () => this._injector.createInstance(SheetsDataValidationRenderController, this._config),},],[DataValidationAlertController],diff --git a/packages/sheets-data-validation/src/services/dropdown-manager.service.ts b/packages/sheets-data-validation/src/services/dropdown-manager.service.tsindex 6bea15d77e..b4eba7f4b1 100644--- a/packages/sheets-data-validation/src/services/dropdown-manager.service.ts+++ b/packages/sheets-data-validation/src/services/dropdown-manager.service.ts@@ -19,7 +19,7 @@ import type { ISheetLocation } from '@univerjs/sheets';import { Subject } from 'rxjs';import type { IDisposable } from '@wendellhu/redi';import { Inject } from '@wendellhu/redi';-import { SheetCanvasPopManagerService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';+import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';import { DataValidationModel, DataValidatorRegistryService } from '@univerjs/data-validation';import { IZenZoneService } from '@univerjs/ui';import { IRenderManagerService } from '@univerjs/engine-render';@@ -54,7 +54,6 @@ export class DataValidationDropdownManagerService extends Disposable {constructor(@Inject(SheetCanvasPopManagerService) private readonly _canvasPopupManagerService: SheetCanvasPopManagerService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@Inject(DataValidatorRegistryService) private readonly _dataValidatorRegistryService: DataValidatorRegistryService,@IZenZoneService private readonly _zenZoneService: IZenZoneService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@@ -130,23 +129,18 @@ export class DataValidationDropdownManagerService extends Disposable {if (!workbook) {return;}+const worksheet = workbook.getSheetBySheetId(subUnitId);if (!worksheet) {return;}+const manager = this._dataValidationModel.ensureManager(unitId, subUnitId) as SheetDataValidationManager;const rule = manager.getRuleByLocation(row, col);- const skeleton = this._sheetSkeletonManagerService.getOrCreateSkeleton({- unitId,- sheetId: subUnitId,- });-- if (!skeleton) {- return;- }if (!rule) {return;}+const validator = this._dataValidatorRegistryService.getValidatorItem(rule.type);if (!validator || !validator.dropdown) {this.hideDropdown();diff --git a/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts b/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.tsindex 5ffb08f1e5..39241e7c27 100644--- a/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts+++ b/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts@@ -164,7 +164,6 @@ export class SheetCanvasFloatDomManagerService extends Disposable {constructor(@Inject(IRenderManagerService) private _renderManagerService: IRenderManagerService,@IUniverInstanceService private _univerInstanceService: IUniverInstanceService,- @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService,@Inject(ICommandService) private _commandService: ICommandService,@IDrawingManagerService private _drawingManagerService: IDrawingManagerService,@ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,@@ -223,7 +222,7 @@ export class SheetCanvasFloatDomManagerService extends Disposable {const { unitId, subUnitId, drawingId } = param;const target = getSheetCommandTarget(this._univerInstanceService, { unitId, subUnitId });const floatDomParam = this._drawingManagerService.getDrawingByParam(param) as IFloatDomData;- const skeleton = this._sheetSkeletonManagerService.getUnitSkeleton(unitId, subUnitId);+ const skeleton = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getUnitSkeleton(unitId, subUnitId);if (floatDomParam == null || target == null || skeleton == null) {return;}@@ -321,7 +320,7 @@ export class SheetCanvasFloatDomManagerService extends Disposable {const map = this._ensureMap(unitId, subUnitId);const ids = Array.from(map.keys());const target = getSheetCommandTarget(this._univerInstanceService, { unitId, subUnitId });- const skeleton = this._sheetSkeletonManagerService.getUnitSkeleton(unitId, subUnitId);+ const skeleton = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getUnitSkeleton(unitId, subUnitId);if (!renderObject || !target || !skeleton) {return;}diff --git a/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts b/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.tsindex c040d0ddc4..416d3c0034 100644--- a/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts+++ b/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts@@ -16,13 +16,13 @@import type { IRange, Workbook } from '@univerjs/core';import { CommandType, fromCallback, ICommandService, RxDisposable, ThemeService } from '@univerjs/core';-import type { IRenderContext, IRenderController, SpreadsheetSkeleton } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule, SpreadsheetSkeleton } from '@univerjs/engine-render';import { IRenderManagerService } from '@univerjs/engine-render';import type { ISelectionStyle, ISheetCommandSharedParams } from '@univerjs/sheets';import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';import type { FilterModel } from '@univerjs/sheets-filter';import { FILTER_MUTATIONS, ReCalcSheetsFilterMutation, RemoveSheetsFilterMutation, SetSheetsFilterCriteriaMutation, SetSheetsFilterRangeMutation, SheetsFilterService } from '@univerjs/sheets-filter';-import { getCoordByCell, ISelectionRenderService, SelectionShape, SheetRenderController, SheetSkeletonManagerService } from '@univerjs/sheets-ui';+import { getCoordByCell, ISelectionRenderService, SelectionShape, SheetSkeletonManagerService, SheetsRenderService } from '@univerjs/sheets-ui';import type { IDisposable } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';@@ -42,7 +42,7 @@ interface ISheetsFilterRenderParams {skeleton: SpreadsheetSkeleton;}-export class SheetsFilterRenderController extends RxDisposable implements IRenderController {+export class SheetsFilterRenderController extends RxDisposable implements IRenderModule {private _filterRangeShape: SelectionShape | null = null;private _buttonRenderDisposable: IDisposable | null = null;private _filterButtonShapes: SheetsFilterButtonShape[] = [];@@ -54,7 +54,7 @@ export class SheetsFilterRenderController extends RxDisposable implements IRende@Inject(SheetsFilterService) private readonly _sheetsFilterService: SheetsFilterService,@Inject(ThemeService) private readonly _themeService: ThemeService,@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,- @Inject(SheetRenderController) private _sheetRenderController: SheetRenderController,+ @Inject(SheetsRenderService) private _sheetsRenderService: SheetsRenderService,@ICommandService private readonly _commandService: ICommandService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService@@ -66,7 +66,7 @@ export class SheetsFilterRenderController extends RxDisposable implements IRendeSetSheetsFilterCriteriaMutation,RemoveSheetsFilterMutation,ReCalcSheetsFilterMutation,- ].forEach((m) => this.disposeWithMe(this._sheetRenderController.registerSkeletonChangingMutations(m.id)));+ ].forEach((m) => this.disposeWithMe(this._sheetsRenderService.registerSkeletonChangingMutations(m.id)));this._initRenderer();}@@ -82,9 +82,7 @@ export class SheetsFilterRenderController extends RxDisposable implements IRendeswitchMap(([_, skeletonParams]) => {if (!skeletonParams) return of(null);- const { unitId } = skeletonParams;-- const workbook = this._context.unit;+ const { unit: workbook, unitId } = this._context;const worksheetId = workbook.getActiveSheet().getSheetId();const filterModel = this._sheetsFilterService.getFilterModel(unitId, worksheetId) ?? undefined;const getParams = (): ISheetsFilterRenderParams => ({diff --git a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.tsindex 4c4d497800..72aeb8fe07 100644--- a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts+++ b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts@@ -120,14 +120,13 @@ export class SheetFindModel extends FindModel {constructor(private readonly _workbook: Workbook,+ private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@ICommandService private readonly _commandService: ICommandService,@IContextService private readonly _contextService: IContextService,@Inject(ThemeService) private readonly _themeService: ThemeService,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,- @Inject(SheetsFindReplaceController) private readonly _findReplaceController: SheetsFindReplaceController+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService) {super();}@@ -918,6 +917,7 @@ class SheetsFindReplaceProvider extends Disposable implements IFindReplaceProvidconstructor(@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@Inject(Injector) private readonly _injector: Injector) {super();@@ -926,11 +926,13 @@ class SheetsFindReplaceProvider extends Disposable implements IFindReplaceProvidasync find(query: IFindQuery): Promise<SheetFindModel[]> {this._terminate();- // NOTE: If there are multi Workbook instances then we should create `SheetFindModel` for each of them.+ // TODO: If there are multi Workbook instances then we should create `SheetFindModel` for each of them.// But we don't need to implement that in the foreseeable future.const currentWorkbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const skeletonManagerService = this._renderManagerService.getRenderById(currentWorkbook.getUnitId())!.with(SheetSkeletonManagerService);+if (currentWorkbook) {- const sheetFind = this._injector.createInstance(SheetFindModel, currentWorkbook);+ const sheetFind = this._injector.createInstance(SheetFindModel, currentWorkbook, skeletonManagerService);this._findModelsByUnitId.set(currentWorkbook.getUnitId(), sheetFind);const parsedQuery = this._preprocessQuery(query);sheetFind.start(parsedQuery);diff --git a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts b/packages/sheets-formula/src/controllers/formula-editor-show.controller.tsindex 6e7cc094b0..023bc5a5f9 100644--- a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts+++ b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts@@ -31,7 +31,7 @@ import {SetArrayFormulaDataMutation,SetFormulaCalculationResultMutation,} from '@univerjs/engine-formula';-import type { IRenderContext, IRenderController } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { IRenderManagerService } from '@univerjs/engine-render';import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';import {@@ -42,7 +42,7 @@ import {} from '@univerjs/sheets-ui';import { Inject } from '@wendellhu/redi';-export class FormulaEditorShowController extends Disposable implements IRenderController {+export class FormulaEditorShowController extends Disposable implements IRenderModule {private _previousShape: Nullable<SelectionShape>;constructor(diff --git a/packages/sheets-formula/src/controllers/formula-render.controller.ts b/packages/sheets-formula/src/controllers/formula-render.controller.tsindex 0dd6bd9056..e673f0a62a 100644--- a/packages/sheets-formula/src/controllers/formula-render.controller.ts+++ b/packages/sheets-formula/src/controllers/formula-render.controller.ts@@ -16,58 +16,47 @@import { LifecycleStages, OnLifecycle, RxDisposable } from '@univerjs/core';import { Inject } from '@wendellhu/redi';-import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';import { extractFormulaError } from './utils/utils';-@OnLifecycle(LifecycleStages.Rendered, FormulaRenderController)-export class FormulaRenderController extends RxDisposable {+const FORMULA_ERROR_MARK = {+ tl: {+ size: 6,+ color: '#409f11',+ },+};++@OnLifecycle(LifecycleStages.Rendered, FormulaRenderManagerController)+export class FormulaRenderManagerController extends RxDisposable {constructor(- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,- @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService) {+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService+ ) {super();+this._init();}private _init() {- this._initViewModelIntercept();- }-- private _initViewModelIntercept() {- const FORMULA_ERROR_MARK = {- tl: {- size: 6,- color: '#409f11',- },- };-- this.disposeWithMe(- this._sheetInterceptorService.intercept(- INTERCEPTOR_POINT.CELL_CONTENT,- {- handler: (cell, pos, next) => {- const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;- if (!skeleton) {- return next(cell);- }-- const errorType = extractFormulaError(cell);-- if (!errorType) {- return next(cell);- }-- return next({- ...cell,- markers: {- ...cell?.markers,- ...FORMULA_ERROR_MARK,- },- });- },- priority: 10,- }- )- );+ this.disposeWithMe(this._sheetInterceptorService.intercept(+ INTERCEPTOR_POINT.CELL_CONTENT,+ {+ handler: (cell, pos, next) => {+ const errorType = extractFormulaError(cell);+ if (!errorType) {+ return next(cell);+ }++ return next({+ ...cell,+ markers: {+ ...cell?.markers,+ ...FORMULA_ERROR_MARK,+ },+ });+ },+ priority: 10,+ }+ ));}}+diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.tsindex 3c45050fe0..ea956ffcf2 100644--- a/packages/sheets-formula/src/controllers/prompt.controller.ts+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts@@ -164,7 +164,6 @@ export class PromptController extends Disposable {@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@Inject(ThemeService) private readonly _themeService: ThemeService,@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,@Inject(ISelectionRenderService) private readonly _selectionRenderService: ISelectionRenderService,@Inject(IDescriptionService) private readonly _descriptionService: IDescriptionService,@@ -1137,22 +1136,13 @@ export class PromptController extends Disposable {}private _getCurrentUnitIdAndSheetId() {- const current = this._sheetSkeletonManagerService.getCurrent();-- if (current == null) {- const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- const worksheet = workbook.getActiveSheet();- return {- unitId: workbook.getUnitId(),- sheetId: worksheet.getSheetId(),- };- }-- const { unitId, sheetId, skeleton } = current;+ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const worksheet = workbook.getActiveSheet();+ const skeleton = this._renderManagerService.getRenderById(workbook.getUnitId())?.with(SheetSkeletonManagerService)?.getCurrentSkeleton();return {- unitId,- sheetId,+ unitId: workbook.getUnitId(),+ sheetId: worksheet.getSheetId(),skeleton,};}diff --git a/packages/sheets-formula/src/formula-ui-plugin.ts b/packages/sheets-formula/src/formula-ui-plugin.tsindex 267b771186..8cf8e77993 100644--- a/packages/sheets-formula/src/formula-ui-plugin.ts+++ b/packages/sheets-formula/src/formula-ui-plugin.ts@@ -42,7 +42,7 @@ import { DefinedNameController } from './controllers/defined-name.controller';import { FormulaRefRangeService } from './services/formula-ref-range.service';import { RegisterOtherFormulaService } from './services/register-other-formula.service';import { FormulaAlertController } from './controllers/formula-alert.controller';-import { FormulaRenderController } from './controllers/formula-render.controller';+import { FormulaRenderManagerController } from './controllers/formula-render.controller';/*** The configuration of the formula UI plugin.@@ -98,7 +98,7 @@ export class UniverSheetsFormulaPlugin extends Plugin {[FormulaEditorShowController],[ActiveDirtyController],[DefinedNameController],- [FormulaRenderController],+ [FormulaRenderManagerController],[FormulaAlertController],];diff --git a/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.tsindex 1c750ab93f..7f10e898f1 100644--- a/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts+++ b/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts@@ -15,27 +15,57 @@*/import type { Workbook } from '@univerjs/core';-import { BooleanNumber, Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle, ThemeService, UniverInstanceType } from '@univerjs/core';+import { BooleanNumber, Disposable, LifecycleStages, OnLifecycle, ThemeService } from '@univerjs/core';import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';import { Inject } from '@wendellhu/redi';import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';-import type { Spreadsheet } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule, Spreadsheet } from '@univerjs/engine-render';import { IRenderManagerService } from '@univerjs/engine-render';import { HyperLinkModel } from '@univerjs/sheets-hyper-link';-@OnLifecycle(LifecycleStages.Ready, SheetsHyperLinkRenderController)-export class SheetsHyperLinkRenderController extends Disposable {+export class SheetsHyperLinkRenderController extends Disposable implements IRenderModule {constructor(- @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,+ private readonly _context: IRenderContext<Workbook>,@Inject(HyperLinkModel) private readonly _hyperLinkModel: HyperLinkModel,- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService+ ) {+ super();+ this._initSkeletonChange();+ }++ private _initSkeletonChange() {+ const markSkeletonDirty = () => {+ const workbook = this._context.unit;+ const unitId = workbook.getUnitId();+ const subUnitId = workbook.getActiveSheet().getSheetId();+ const skeleton = this._sheetSkeletonManagerService.getOrCreateSkeleton({ sheetId: subUnitId });+ const currentRender = this._renderManagerService.getRenderById(unitId);++ skeleton?.makeDirty(true);+ skeleton?.calculate();++ if (currentRender) {+ (currentRender.mainComponent as Spreadsheet).makeForceDirty();+ }+ };++ this.disposeWithMe(this._hyperLinkModel.linkUpdate$.subscribe(() => {+ markSkeletonDirty();+ }));+ }+}++@OnLifecycle(LifecycleStages.Ready, SheetsHyperLinkRenderManagerController)+export class SheetsHyperLinkRenderManagerController extends Disposable {+ constructor(+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,+ @Inject(HyperLinkModel) private readonly _hyperLinkModel: HyperLinkModel,@Inject(ThemeService) private readonly _themeService: ThemeService) {super();+this._initViewModelIntercept();- this._initSkeletonChange();}private _initViewModelIntercept() {@@ -69,27 +99,4 @@ export class SheetsHyperLinkRenderController extends Disposable {));}-- private _initSkeletonChange() {- const markSkeletonDirty = () => {- const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);- if (!workbook) return;-- const unitId = workbook.getUnitId();- const subUnitId = workbook.getActiveSheet().getSheetId();- const skeleton = this._sheetSkeletonManagerService.getOrCreateSkeleton({ unitId, sheetId: subUnitId });- const currentRender = this._renderManagerService.getRenderById(unitId);-- skeleton?.makeDirty(true);- skeleton?.calculate();-- if (currentRender) {- (currentRender.mainComponent as Spreadsheet).makeForceDirty();- }- };-- this.disposeWithMe(this._hyperLinkModel.linkUpdate$.subscribe(() => {- markSkeletonDirty();- }));- }}diff --git a/packages/sheets-hyper-link-ui/src/index.ts b/packages/sheets-hyper-link-ui/src/index.tsindex a2d5135798..e219c96fbc 100644--- a/packages/sheets-hyper-link-ui/src/index.ts+++ b/packages/sheets-hyper-link-ui/src/index.ts@@ -16,7 +16,7 @@export { SheetsHyperLinkRemoveSheetController } from './controllers/remove-sheet.controller';export { SheetsHyperLinkRefRangeController } from './controllers/ref-range.controller';-export { SheetsHyperLinkRenderController } from './controllers/render-controllers/render.controller';+export { SheetsHyperLinkRenderManagerController, SheetsHyperLinkRenderController } from './controllers/render-controllers/render.controller';export { SheetsHyperLinkPopupService } from './services/popup.service';export { SheetsHyperLinkResolverService } from './services/resolver.service';export { SheetHyperLinkSetRangeController } from './controllers/set-range.controller';diff --git a/packages/sheets-hyper-link-ui/src/plugin.ts b/packages/sheets-hyper-link-ui/src/plugin.tsindex dc55350c29..086b181955 100644--- a/packages/sheets-hyper-link-ui/src/plugin.ts+++ b/packages/sheets-hyper-link-ui/src/plugin.ts@@ -18,9 +18,10 @@ import type { Dependency } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';import { DependentOn, Plugin, UniverInstanceType } from '@univerjs/core';import { UniverSheetsHyperLinkPlugin } from '@univerjs/sheets-hyper-link';+import { IRenderManagerService } from '@univerjs/engine-render';import { SheetsHyperLinkRemoveSheetController } from './controllers/remove-sheet.controller';import { SheetsHyperLinkRefRangeController } from './controllers/ref-range.controller';-import { SheetsHyperLinkRenderController } from './controllers/render-controllers/render.controller';+import { SheetsHyperLinkRenderController, SheetsHyperLinkRenderManagerController } from './controllers/render-controllers/render.controller';import { SheetsHyperLinkPopupService } from './services/popup.service';import { SheetsHyperLinkResolverService } from './services/resolver.service';import { SheetHyperLinkSetRangeController } from './controllers/set-range.controller';@@ -40,7 +41,8 @@ export class UniverSheetsHyperLinkUIPlugin extends Plugin {constructor(private _config: IUniverSheetsHyperLinkUIConfig,- @Inject(Injector) protected override _injector: Injector+ @Inject(Injector) protected override _injector: Injector,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService) {super();}@@ -52,7 +54,7 @@ export class UniverSheetsHyperLinkUIPlugin extends Plugin {[SheetsHyperLinkRemoveSheetController],[SheetsHyperLinkRefRangeController],- [SheetsHyperLinkRenderController],+ [SheetsHyperLinkRenderManagerController],[SheetHyperLinkSetRangeController],[SheetsHyperLinkPopupController],[@@ -67,8 +69,8 @@ export class UniverSheetsHyperLinkUIPlugin extends Plugin {[SheetHyperLinkUrlController],];- dependencies.forEach((dep) => {- injector.add(dep);- });+ dependencies.forEach((dep) => injector.add(dep));++ this._renderManagerService.registerRenderController(UniverInstanceType.UNIVER_SHEET, SheetsHyperLinkRenderController);}}diff --git a/packages/sheets-numfmt/src/controllers/__tests__/cell-content.controller.spec.ts b/packages/sheets-numfmt/src/controllers/__tests__/cell-content.controller.spec.tsindex 16b386bd50..f8aadc5aa8 100644--- a/packages/sheets-numfmt/src/controllers/__tests__/cell-content.controller.spec.ts+++ b/packages/sheets-numfmt/src/controllers/__tests__/cell-content.controller.spec.ts@@ -20,7 +20,7 @@ import type { ISetNumfmtMutationParams } from '@univerjs/sheets';import { SetNumfmtMutation } from '@univerjs/sheets';import { beforeEach, describe, expect, it } from 'vitest';-import { NumfmtCellContent } from '../numfmt.cell-content.controller';+import { SheetsNumfmtCellContentController } from '../numfmt.cell-content.controller';import { createTestBed } from './test.util';describe('test cell-content', () => {@@ -30,7 +30,7 @@ describe('test cell-content', () => {let testBed: any;let commandService: ICommandService;beforeEach(() => {- testBed = createTestBed([[NumfmtCellContent]]);+ testBed = createTestBed([[SheetsNumfmtCellContentController]]);unitId = testBed.unitId;subUnitId = testBed.subUnitId;commandService = testBed.get(ICommandService);@@ -54,7 +54,7 @@ describe('test cell-content', () => {};const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;const worksheet = workbook.getActiveSheet();- testBed.get(NumfmtCellContent);+ testBed.get(SheetsNumfmtCellContentController);const value = worksheet.getCell(0, 0);expect(value).toEqual({ v: 0, t: 2 });commandService.syncExecuteCommand(SetNumfmtMutation.id, params);diff --git a/packages/sheets-numfmt/src/controllers/__tests__/editor.controller.spec.ts b/packages/sheets-numfmt/src/controllers/__tests__/editor.controller.spec.tsindex dd5f0f5e62..06adf8d50a 100644--- a/packages/sheets-numfmt/src/controllers/__tests__/editor.controller.spec.ts+++ b/packages/sheets-numfmt/src/controllers/__tests__/editor.controller.spec.ts@@ -21,7 +21,7 @@ import { SetNumfmtMutation } from '@univerjs/sheets';import { IEditorBridgeService } from '@univerjs/sheets-ui';import { beforeEach, describe, expect, it } from 'vitest';-import { NumfmtCellContent } from '../numfmt.cell-content.controller';+import { SheetsNumfmtCellContentController } from '../numfmt.cell-content.controller';import { NumfmtEditorController } from '../numfmt.editor.controller';import { createTestBed } from './test.util';@@ -44,7 +44,7 @@ describe('test editor', () => {beforeEach(() => {testBed = createTestBed([[NumfmtEditorController],- [NumfmtCellContent],+ [SheetsNumfmtCellContentController],[IEditorBridgeService, { useClass: MockEditorBridgeService }],]);unitId = testBed.unitId;@@ -52,7 +52,7 @@ describe('test editor', () => {commandService = testBed.get(ICommandService);const univerInstanceService = testBed.get(IUniverInstanceService);testBed.get(NumfmtEditorController);- testBed.get(NumfmtCellContent);+ testBed.get(SheetsNumfmtCellContentController);workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;worksheet = workbook.getActiveSheet();});diff --git a/packages/sheets-numfmt/src/controllers/numfmt.cell-content.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.cell-content.controller.tsindex d335569deb..442201df3f 100644--- a/packages/sheets-numfmt/src/controllers/numfmt.cell-content.controller.ts+++ b/packages/sheets-numfmt/src/controllers/numfmt.cell-content.controller.ts@@ -14,35 +14,35 @@* limitations under the License.*/-import type { ICellData, ICellDataForSheetInterceptor } from '@univerjs/core';+import type { ICellData, ICellDataForSheetInterceptor,+ Workbook } from '@univerjs/core';import {CellValueType,Disposable,ICommandService,+ IUniverInstanceService,LifecycleStages,LocaleService,ObjectMatrix,OnLifecycle,Range,ThemeService,- toDisposable,+ UniverInstanceType,} from '@univerjs/core';import type { ISetNumfmtMutationParams } from '@univerjs/sheets';import { INTERCEPTOR_POINT, INumfmtService, SetNumfmtMutation, SheetInterceptorService } from '@univerjs/sheets';-import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { Inject } from '@wendellhu/redi';-import { distinctUntilChanged, map } from 'rxjs/operators';+import { of, skip, switchMap } from 'rxjs';import { getPatternPreview } from '../utils/pattern';-@OnLifecycle(LifecycleStages.Rendered, NumfmtCellContent)-export class NumfmtCellContent extends Disposable {+@OnLifecycle(LifecycleStages.Rendered, SheetsNumfmtCellContentController)+export class SheetsNumfmtCellContentController extends Disposable {constructor(+ @IUniverInstanceService private readonly _instanceService: IUniverInstanceService,@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,@Inject(ThemeService) private _themeService: ThemeService,- @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService,@Inject(ICommandService) private _commandService: ICommandService,-@Inject(INumfmtService) private _numfmtService: INumfmtService,@Inject(LocaleService) private _localeService: LocaleService) {@@ -52,83 +52,76 @@ export class NumfmtCellContent extends Disposable {private _initInterceptorCellContent() {const renderCache = new ObjectMatrix<{ result: ICellData; parameters: string | number }>();- this.disposeWithMe(- this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {- handler: (cell, location, next) => {- const unitId = location.unitId;- const sheetId = location.subUnitId;- const numfmtValue = this._numfmtService.getValue(unitId, sheetId, location.row, location.col);- if (!numfmtValue) {- return next(cell);- }- const originCellValue = cell;- if (!originCellValue) {- return next(cell);- }- // just handle number- if (originCellValue.t !== CellValueType.NUMBER) {- return next(cell);- }+ this.disposeWithMe(this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {+ handler: (cell, location, next) => {+ const unitId = location.unitId;+ const sheetId = location.subUnitId;+ const numfmtValue = this._numfmtService.getValue(unitId, sheetId, location.row, location.col);+ if (!numfmtValue) {+ return next(cell);+ }+ const originCellValue = cell;+ if (!originCellValue) {+ return next(cell);+ }- let numfmtRes: string = '';- const cache = renderCache.getValue(location.row, location.col);- if (cache && cache.parameters === originCellValue.v) {- return next({ ...cell, ...cache.result });- }+ // just handle number+ if (originCellValue.t !== CellValueType.NUMBER) {+ return next(cell);+ }- const info = getPatternPreview(numfmtValue.pattern, Number(originCellValue.v), this._localeService.getCurrentLocale());+ let numfmtRes: string = '';+ const cache = renderCache.getValue(location.row, location.col);+ if (cache && cache.parameters === originCellValue.v) {+ return next({ ...cell, ...cache.result });+ }- numfmtRes = info.result;+ const info = getPatternPreview(numfmtValue.pattern, Number(originCellValue.v), this._localeService.getCurrentLocale());+ numfmtRes = info.result;+ if (!numfmtRes) {+ return next(cell);+ }- if (!numfmtRes) {- return next(cell);+ const res: ICellDataForSheetInterceptor = { v: numfmtRes };+ if (info.color) {+ const color = this._themeService.getCurrentTheme()[`${info.color}500`];++ if (color) {+ res.interceptorStyle = { cl: { rgb: color } };}+ }- const res: ICellDataForSheetInterceptor = { v: numfmtRes };+ renderCache.setValue(location.row, location.col, {+ result: res,+ parameters: originCellValue.v as number,+ });- if (info.color) {- const color = this._themeService.getCurrentTheme()[`${info.color}500`];+ return next({ ...cell, ...res });+ },+ priority: 10,+ }));- if (color) {- res.interceptorStyle = { cl: { rgb: color } };- }- }-- renderCache.setValue(location.row, location.col, {- result: res,- parameters: originCellValue.v as number,- });- return next({ ...cell, ...res });- },- priority: 10,- })- );- this.disposeWithMe(- this._commandService.onCommandExecuted((commandInfo) => {- if (commandInfo.id === SetNumfmtMutation.id) {- const params = commandInfo.params as ISetNumfmtMutationParams;- Object.keys(params.values).forEach((key) => {- const v = params.values[key];- v.ranges.forEach((range) => {- Range.foreach(range, (row, col) => {- renderCache.realDeleteValue(row, col);- });+ this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetNumfmtMutation.id) {+ const params = commandInfo.params as ISetNumfmtMutationParams;+ Object.keys(params.values).forEach((key) => {+ const v = params.values[key];+ v.ranges.forEach((range) => {+ Range.foreach(range, (row, col) => {+ renderCache.realDeleteValue(row, col);});});- }- })- );+ });+ }+ }));+this.disposeWithMe(- toDisposable(- this._sheetSkeletonManagerService.currentSkeleton$- .pipe(- map((skeleton) => skeleton?.sheetId),- distinctUntilChanged()- )- .subscribe(() => {- renderCache.reset();- })- )+ this._instanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET)+ .pipe(+ switchMap((workbook) => workbook?.activeSheet$ ?? of(null)),+ skip(1)+ )+ .subscribe(() => renderCache.reset()));}}diff --git a/packages/sheets-numfmt/src/controllers/numfmt.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.controller.tsindex 2897ed9c39..02ca42a9f8 100644--- a/packages/sheets-numfmt/src/controllers/numfmt.controller.ts+++ b/packages/sheets-numfmt/src/controllers/numfmt.controller.ts@@ -39,13 +39,13 @@ import {SetNumfmtMutation,SheetInterceptorService,} from '@univerjs/sheets';-import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { ComponentManager, ISidebarService } from '@univerjs/ui';import type { IDisposable } from '@wendellhu/redi';import { Inject } from '@wendellhu/redi';-import { combineLatest, merge, Observable } from 'rxjs';+import { combineLatest, Observable } from 'rxjs';import { debounceTime, map, switchMap, tap } from 'rxjs/operators';+import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { SHEET_NUMFMT_PLUGIN } from '../base/const/PLUGIN_NAME';import { AddDecimalCommand } from '../commands/commands/add-decimal.command';import { SetCurrencyCommand } from '../commands/commands/set-currency.command';@@ -73,7 +73,6 @@ export class NumfmtController extends Disposable implements INumfmtController {@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,@Inject(ThemeService) private _themeService: ThemeService,@IUniverInstanceService private _univerInstanceService: IUniverInstanceService,- @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService,@ICommandService private _commandService: ICommandService,@Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService,@IRenderManagerService private _renderManagerService: IRenderManagerService,@@ -127,8 +126,7 @@ export class NumfmtController extends Disposable implements INumfmtController {onChange: (config) => {if (config.type === 'change') {this._previewPattern = config.value;- this._sheetSkeletonManagerService.reCalculate();- this._renderManagerService.getRenderById(workbook.getUnitId())?.mainComponent?.makeDirty();+ this._forceUpdate();} else if (config.type === 'confirm') {const selections = selectionManagerService.getSelectionRanges() || [];const params: ISetNumfmtCommandParams = { values: [] };@@ -159,8 +157,7 @@ export class NumfmtController extends Disposable implements INumfmtController {...(props as any), // need passthrough to react props.},onClose: () => {- this._sheetSkeletonManagerService.reCalculate();- this._renderManagerService.getRenderById(workbook.getUnitId())?.mainComponent?.makeDirty();+ this._forceUpdate();commandService.executeCommand(CloseNumfmtPanelOperator.id);},});@@ -168,6 +165,15 @@ export class NumfmtController extends Disposable implements INumfmtController {return true;};+ private _forceUpdate(unitId?: string): void {+ const renderUnit = this._renderManagerService.getRenderById(+ unitId ?? this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId()+ );++ renderUnit?.with(SheetSkeletonManagerService).reCalculate();+ renderUnit?.mainComponent?.makeDirty();+ }+private _initCommands() {[AddDecimalCommand,@@ -289,27 +295,16 @@ export class NumfmtController extends Disposable implements INumfmtController {private _commandExecutedListener() {const commandList = [RemoveNumfmtMutation.id, SetNumfmtMutation.id];- this.disposeWithMe(- toDisposable(- merge(- new Observable<string>((subscribe) => {- const disposable = this._commandService.onCommandExecuted((command) => {- if (commandList.includes(command.id)) {- const params = command.params as ISetNumfmtMutationParams;- subscribe.next(params.unitId);- }- });- return () => {- disposable.dispose();- };- })- )- .pipe(debounceTime(16))- .subscribe((unitId) => {- this._sheetSkeletonManagerService.reCalculate();- this._renderManagerService.getRenderById(unitId)?.mainComponent?.makeDirty();- })- )+ this.disposeWithMe(new Observable<string>((subscribe) => {+ const disposable = this._commandService.onCommandExecuted((command) => {+ if (commandList.includes(command.id)) {+ const params = command.params as ISetNumfmtMutationParams;+ subscribe.next(params.unitId);+ }+ });+ return () => disposable.dispose();+ }).pipe(debounceTime(16))+ .subscribe((unitId) => this._forceUpdate(unitId)));}diff --git a/packages/sheets-numfmt/src/numfmt-plugin.ts b/packages/sheets-numfmt/src/numfmt-plugin.tsindex fc4db77445..beeef0d036 100644--- a/packages/sheets-numfmt/src/numfmt-plugin.ts+++ b/packages/sheets-numfmt/src/numfmt-plugin.ts@@ -20,7 +20,7 @@ import { Inject, Injector } from '@wendellhu/redi';import { UniverSheetsPlugin } from '@univerjs/sheets';import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';import { SHEET_NUMFMT_PLUGIN } from './base/const/PLUGIN_NAME';-import { NumfmtCellContent } from './controllers/numfmt.cell-content.controller';+import { SheetsNumfmtCellContentController } from './controllers/numfmt.cell-content.controller';import { NumfmtController } from './controllers/numfmt.controller';import { NumfmtEditorController } from './controllers/numfmt.editor.controller';import { NumfmtI18nController } from './controllers/numfmt.i18n.controller';@@ -46,7 +46,7 @@ export class UniverSheetsNumfmtPlugin extends Plugin {this._injector.add([INumfmtController, { useClass: NumfmtController, lazy: false }]);this._injector.add([NumfmtEditorController]);this._injector.add([UserHabitController]);- this._injector.add([NumfmtCellContent]);+ this._injector.add([SheetsNumfmtCellContentController]);this._injector.add([NumfmtI18nController]);this._injector.add([diff --git a/packages/sheets-thread-comment/src/controllers/render-controllers/render.controller.ts b/packages/sheets-thread-comment/src/controllers/render-controllers/render.controller.tsindex 4bd8d5b41e..99ef0c1c8d 100644--- a/packages/sheets-thread-comment/src/controllers/render-controllers/render.controller.ts+++ b/packages/sheets-thread-comment/src/controllers/render-controllers/render.controller.ts@@ -29,7 +29,6 @@ export class SheetsThreadCommentRenderController extends Disposable {@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,@Inject(SheetsThreadCommentModel) private readonly _sheetsThreadCommentModel: SheetsThreadCommentModel,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService) {super();@@ -72,8 +71,8 @@ export class SheetsThreadCommentRenderController extends Disposable {const unitId = workbook.getUnitId();const subUnitId = workbook.getActiveSheet().getSheetId();- const skeleton = this._sheetSkeletonManagerService.getOrCreateSkeleton({ unitId, sheetId: subUnitId });const currentRender = this._renderManagerService.getRenderById(unitId);+ const skeleton = currentRender?.with(SheetSkeletonManagerService).getOrCreateSkeleton({ sheetId: subUnitId });skeleton?.makeDirty(true);skeleton?.calculate();diff --git a/packages/sheets-ui/src/common/utils.ts b/packages/sheets-ui/src/common/utils.tsindex 1ebc6a5008..6fed9b6f7d 100644--- a/packages/sheets-ui/src/common/utils.ts+++ b/packages/sheets-ui/src/common/utils.ts@@ -219,7 +219,8 @@ export function transformPosition2Offset(x: number, y: number, scene: Scene, skeexport function getHoverCellPosition(currentRender: IRender, workbook: Workbook, worksheet: Worksheet, skeletonParam: ISheetSkeletonManagerParam, offsetX: number, offsetY: number) {const { scene } = currentRender;- const { skeleton, sheetId, unitId } = skeletonParam;+ const unitId = workbook.getUnitId();+ const { skeleton, sheetId } = skeletonParam;const cellIndex = getCellIndexByOffsetWithMerge(offsetX, offsetY, scene, skeleton);diff --git a/packages/sheets-ui/src/controllers/auto-height.controller.ts b/packages/sheets-ui/src/controllers/auto-height.controller.tsindex 9da848129e..9e0b9d3aff 100644--- a/packages/sheets-ui/src/controllers/auto-height.controller.ts+++ b/packages/sheets-ui/src/controllers/auto-height.controller.ts@@ -32,17 +32,18 @@ import {SheetInterceptorService,} from '@univerjs/sheets';import { Inject, Injector } from '@wendellhu/redi';-+import type { RenderManagerService } from '@univerjs/engine-render';+import { IRenderManagerService } from '@univerjs/engine-render';import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';@OnLifecycle(LifecycleStages.Ready, AutoHeightController)export class AutoHeightController extends Disposable {constructor(- @Inject(Injector) private _injector: Injector,- @Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,- @Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService,- @Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,- @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService+ @IRenderManagerService private readonly _renderManagerService: RenderManagerService,+ @Inject(Injector) private readonly _injector: Injector,+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,+ @Inject(IUniverInstanceService) private readonly _univerInstanceService: IUniverInstanceService) {super();this._initialize();@@ -51,17 +52,17 @@ export class AutoHeightController extends Disposable {getUndoRedoParamsOfAutoHeight(ranges: IRange[]) {const {_univerInstanceService: univerInstanceService,- _sheetSkeletonManagerService: sheetSkeletonService,_injector: injector,} = this;- const { skeleton } = sheetSkeletonService.getCurrent()!;- const rowsAutoHeightInfo = skeleton.calculateAutoHeightInRange(ranges);-const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;const unitId = workbook.getUnitId();const subUnitId = workbook.getActiveSheet().getSheetId();+ const sheetSkeletonService = this._renderManagerService.getRenderById(unitId)!.with(SheetSkeletonManagerService);+ const { skeleton } = sheetSkeletonService.getCurrent()!;+ const rowsAutoHeightInfo = skeleton.calculateAutoHeightInRange(ranges);+const redoParams: ISetWorksheetRowAutoHeightMutationParams = {subUnitId,unitId,diff --git a/packages/sheets-ui/src/controllers/cell-alert.controller.ts b/packages/sheets-ui/src/controllers/cell-alert.controller.tsindex af3cc1dbe5..20dde5d787 100644--- a/packages/sheets-ui/src/controllers/cell-alert.controller.ts+++ b/packages/sheets-ui/src/controllers/cell-alert.controller.ts@@ -18,12 +18,12 @@ import type { Workbook } from '@univerjs/core';import { Disposable, LifecycleStages, OnLifecycle } from '@univerjs/core';import { ComponentManager } from '@univerjs/ui';import { Inject } from '@wendellhu/redi';-import type { IRenderContext, IRenderController } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { CellAlert } from '../views/cell-alert/CellAlertPopup';import { CELL_ALERT_KEY } from '../views/cell-alert';@OnLifecycle(LifecycleStages.Starting, CellAlertRenderController)-export class CellAlertRenderController extends Disposable implements IRenderController {+export class CellAlertRenderController extends Disposable implements IRenderModule {constructor(private readonly _context: IRenderContext<Workbook>,@Inject(ComponentManager) private _componentManager: ComponentManagerdiff --git a/packages/sheets-ui/src/controllers/cell-custom-render.controller.ts b/packages/sheets-ui/src/controllers/cell-custom-render.controller.tsindex bbf08b3cd1..a42955b060 100644--- a/packages/sheets-ui/src/controllers/cell-custom-render.controller.ts+++ b/packages/sheets-ui/src/controllers/cell-custom-render.controller.ts@@ -16,17 +16,14 @@import type { ICellCustomRender, ICellRenderContext, Nullable, UniverInstanceService, Workbook } from '@univerjs/core';import { Disposable, DisposableCollection, IUniverInstanceService, LifecycleStages, OnLifecycle, sortRules } from '@univerjs/core';-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderController, RenderManagerService, Spreadsheet } from '@univerjs/engine-render';+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, RenderManagerService, Spreadsheet } from '@univerjs/engine-render';import { IRenderManagerService, Vector2 } from '@univerjs/engine-render';import { Inject } from '@wendellhu/redi';import type { ISheetSkeletonManagerParam } from '../services/sheet-skeleton-manager.service';import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';-/**- * @todo RenderUnit- */@OnLifecycle(LifecycleStages.Rendered, CellCustomRenderController)-export class CellCustomRenderController extends Disposable implements IRenderController {+export class CellCustomRenderController extends Disposable implements IRenderModule {private _enterActiveRender: Nullable<{render: ICellCustomRender;cellContext: ICellRenderContext;@@ -53,7 +50,9 @@ export class CellCustomRenderController extends Disposable implements IRenderConif (!skeletonParam) {return;}- const { unitId, skeleton } = skeletonParam;++ const unitId = this._context.unitId;+ const { skeleton } = skeletonParam;const currentRender = this._renderManagerService.getRenderById(unitId);if (currentRender && currentRender.mainComponent) {const spreadsheet = currentRender.mainComponent as Spreadsheet;diff --git a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.tsindex 5a093a50f5..e072e7a9e9 100644--- a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts+++ b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts@@ -66,7 +66,7 @@ import {import { IMessageService, textTrim } from '@univerjs/ui';import { Inject, Injector, Optional } from '@wendellhu/redi';-import { ITextSelectionRenderManager, ptToPx } from '@univerjs/engine-render';+import { IRenderManagerService, ITextSelectionRenderManager, ptToPx } from '@univerjs/engine-render';import { takeUntil } from 'rxjs';import {SheetCopyCommand,@@ -106,12 +106,12 @@ export class SheetClipboardController extends RxDisposable {constructor(@Inject(Injector) private readonly _injector: Injector,@IUniverInstanceService private readonly _currentUniverSheet: IUniverInstanceService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@ICommandService private readonly _commandService: ICommandService,@IContextService private readonly _contextService: IContextService,@IConfigService private readonly _configService: IConfigService,@ISheetClipboardService private readonly _sheetClipboardService: ISheetClipboardService,@IMessageService private readonly _messageService: IMessageService,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@Inject(LocaleService) private readonly _localService: LocaleService,@Optional(ITextSelectionRenderManager) private readonly _textSelectionRenderManager?: ITextSelectionRenderManager) {@@ -523,7 +523,7 @@ export class SheetClipboardController extends RxDisposable {}private _generateDocumentDataModelSnapshot(snapshot: Partial<IDocumentData>) {- const currentSkeleton = this._sheetSkeletonManagerService.getCurrent();+ const currentSkeleton = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)?.getCurrent();if (currentSkeleton == null) {return null;}diff --git a/packages/sheets-ui/src/controllers/drag-render.controller.ts b/packages/sheets-ui/src/controllers/drag-render.controller.tsindex 234fba4d8c..81b4ba78fe 100644--- a/packages/sheets-ui/src/controllers/drag-render.controller.ts+++ b/packages/sheets-ui/src/controllers/drag-render.controller.ts@@ -15,21 +15,19 @@*/import type { Nullable, Workbook } from '@univerjs/core';-import { Disposable, DisposableCollection, LifecycleStages, OnLifecycle } from '@univerjs/core';-import type { IRenderContext, IRenderController } from '@univerjs/engine-render';+import { Disposable, DisposableCollection } from '@univerjs/core';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { IRenderManagerService } from '@univerjs/engine-render';import { Inject } from '@wendellhu/redi';import { DragManagerService } from '../services/drag-manager.service';-import type { ISheetSkeletonManagerParam } from '../services/sheet-skeleton-manager.service';-import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';+import { type ISheetSkeletonManagerParam, SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';-@OnLifecycle(LifecycleStages.Rendered, DragRenderController)-export class DragRenderController extends Disposable implements IRenderController {+export class DragRenderController extends Disposable implements IRenderModule, IRenderModule {constructor(private readonly _context: IRenderContext<Workbook>,@IRenderManagerService private _renderManagerService: IRenderManagerService,@Inject(DragManagerService) private _dragManagerService: DragManagerService,- @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService) {super();@@ -44,13 +42,7 @@ export class DragRenderController extends Disposable implements IRenderControllereturn;}- const currentRender = this._renderManagerService.getRenderById(skeletonParam.unitId);-- if (!currentRender) {- return;- }-- const { scene } = currentRender;+ const { scene } = this._context;const dragOverObserver = scene.onDragOverObserver.add((evt) => {this._dragManagerService.onDragOver(evt);});diff --git a/packages/sheets-ui/src/controllers/force-string-alert-render.controller.ts b/packages/sheets-ui/src/controllers/force-string-alert-render.controller.tsindex 25745e1970..b237e11ad5 100644--- a/packages/sheets-ui/src/controllers/force-string-alert-render.controller.ts+++ b/packages/sheets-ui/src/controllers/force-string-alert-render.controller.ts@@ -15,22 +15,21 @@*/import type { Workbook } from '@univerjs/core';-import { CellValueType, Disposable, isRealNum, IUniverInstanceService, LifecycleStages, LocaleService, OnLifecycle } from '@univerjs/core';+import { CellValueType, Disposable, isRealNum, LifecycleStages, LocaleService, OnLifecycle } from '@univerjs/core';import { Inject } from '@wendellhu/redi';-import type { IRenderContext, IRenderController } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { HoverManagerService } from '../services/hover-manager.service';import { CellAlertManagerService, CellAlertType } from '../services/cell-alert-manager.service';const ALERT_KEY = 'SHEET_FORCE_STRING_ALERT';@OnLifecycle(LifecycleStages.Rendered, ForceStringAlertRenderController)-export class ForceStringAlertRenderController extends Disposable implements IRenderController {+export class ForceStringAlertRenderController extends Disposable implements IRenderModule {constructor(private readonly _context: IRenderContext<Workbook>,@Inject(HoverManagerService) private readonly _hoverManagerService: HoverManagerService,@Inject(CellAlertManagerService) private readonly _cellAlertManagerService: CellAlertManagerService,- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,@Inject(LocaleService) private readonly _localeService: LocaleService) {super();diff --git a/packages/sheets-ui/src/controllers/force-string-render.controller.ts b/packages/sheets-ui/src/controllers/force-string-render.controller.tsindex a19a923bf4..6e92c5a88a 100644--- a/packages/sheets-ui/src/controllers/force-string-render.controller.ts+++ b/packages/sheets-ui/src/controllers/force-string-render.controller.ts@@ -18,14 +18,11 @@ import { CellValueType, isRealNum, LifecycleStages, OnLifecycle, RxDisposable }import type { Workbook } from '@univerjs/core';import { Inject } from '@wendellhu/redi';import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';-import type { IRenderContext, IRenderController } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';-/**- * @todo RenderUnit- */@OnLifecycle(LifecycleStages.Rendered, ForceStringRenderController)-export class ForceStringRenderController extends RxDisposable implements IRenderController {+export class ForceStringRenderController extends RxDisposable implements IRenderModule {constructor(private readonly _context: IRenderContext<Workbook>,@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,diff --git a/packages/sheets-ui/src/controllers/hover-render.controller.ts b/packages/sheets-ui/src/controllers/hover-render.controller.tsindex b35d4720c8..38813a2f36 100644--- a/packages/sheets-ui/src/controllers/hover-render.controller.ts+++ b/packages/sheets-ui/src/controllers/hover-render.controller.ts@@ -15,20 +15,17 @@*/import type { Nullable, Workbook } from '@univerjs/core';-import { Disposable, DisposableCollection, LifecycleStages, OnLifecycle } from '@univerjs/core';-import type { IRenderContext, IRenderController } from '@univerjs/engine-render';-import { IRenderManagerService } from '@univerjs/engine-render';+import { Disposable, DisposableCollection } from '@univerjs/core';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { Inject } from '@wendellhu/redi';import { HoverManagerService } from '../services/hover-manager.service';import type { ISheetSkeletonManagerParam } from '../services/sheet-skeleton-manager.service';import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';import { ScrollManagerService } from '../services/scroll-manager.service';-@OnLifecycle(LifecycleStages.Rendered, HoverRenderController)-export class HoverRenderController extends Disposable implements IRenderController {+export class HoverRenderController extends Disposable implements IRenderModule {constructor(private readonly _context: IRenderContext<Workbook>,- @IRenderManagerService private _renderManagerService: IRenderManagerService,@Inject(HoverManagerService) private _hoverManagerService: HoverManagerService,@Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService,@Inject(ScrollManagerService) private _scrollManagerService: ScrollManagerService@@ -43,26 +40,17 @@ export class HoverRenderController extends Disposable implements IRenderControllconst disposeSet = new DisposableCollection();const handleSkeletonChange = (skeletonParam: Nullable<ISheetSkeletonManagerParam>) => {disposeSet.dispose();- if (!skeletonParam) {- return;- }- const currentRender = this._renderManagerService.getRenderById(skeletonParam.unitId);-- if (!currentRender) {+ if (!skeletonParam) {return;}- const { mainComponent } = currentRender;+ const { mainComponent } = this._context;const observer = mainComponent?.onPointerMoveObserver.add((evt) => {this._hoverManagerService.onMouseMove(evt.offsetX, evt.offsetY);});- disposeSet.add({- dispose() {- observer?.dispose();- },- });+ disposeSet.add(observer);};handleSkeletonChange(this._sheetSkeletonManagerService.getCurrent());@@ -72,10 +60,6 @@ export class HoverRenderController extends Disposable implements IRenderControll}private _initScrollEvent() {- this.disposeWithMe(- this._scrollManagerService.scrollInfo$.subscribe(() => {- this._hoverManagerService.onScroll();- })- );+ this.disposeWithMe(this._scrollManagerService.scrollInfo$.subscribe(() => this._hoverManagerService.onScroll()));}}diff --git a/packages/sheets-ui/src/controllers/mark-selection.controller.ts b/packages/sheets-ui/src/controllers/mark-selection.controller.tsindex 107303311e..513c484706 100644--- a/packages/sheets-ui/src/controllers/mark-selection.controller.ts+++ b/packages/sheets-ui/src/controllers/mark-selection.controller.ts@@ -18,12 +18,12 @@ import type { ICommandInfo, Workbook } from '@univerjs/core';import { Disposable, ICommandService } from '@univerjs/core';import { Inject } from '@wendellhu/redi';-import type { IRenderContext, IRenderController } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { SetCellEditVisibleOperation } from '../commands/operations/cell-edit.operation';import { IMarkSelectionService } from '../services/mark-selection/mark-selection.service';import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';-export class MarkSelectionRenderController extends Disposable implements IRenderController {+export class MarkSelectionRenderController extends Disposable implements IRenderModule {constructor(private readonly _context: IRenderContext<Workbook>,@Inject(IMarkSelectionService) private _markSelectionService: IMarkSelectionService,diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-canvas-render.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-canvas-render.controller.tsindex c38d74139e..0b5774987d 100644--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-canvas-render.controller.ts+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-canvas-render.controller.ts@@ -19,7 +19,7 @@ import { DisposableCollection, IPermissionService, IUniverInstanceService, Lifecimport { getSheetCommandTarget, RangeProtectionRuleModel, SelectionManagerService, WorkbookEditablePermission, WorksheetEditPermission, WorksheetSetColumnStylePermission, WorksheetSetRowStylePermission } from '@univerjs/sheets';import { Inject } from '@wendellhu/redi';import { IDialogService } from '@univerjs/ui';-import type { IRenderContext, IRenderController, SpreadsheetSkeleton } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule, SpreadsheetSkeleton } from '@univerjs/engine-render';import { UnitAction } from '@univerjs/protocol';import { HeaderMoveRenderController } from '../render-controllers/header-move.render-controller';@@ -32,7 +32,7 @@ type ICellPermission = Record<UnitAction, boolean> & { ruleId?: string; ranges?:export const SHEET_PERMISSION_PASTE_PLUGIN = 'SHEET_PERMISSION_PASTE_PLUGIN';@OnLifecycle(LifecycleStages.Steady, SheetPermissionInterceptorCanvasRenderController)-export class SheetPermissionInterceptorCanvasRenderController extends RxDisposable implements IRenderController {+export class SheetPermissionInterceptorCanvasRenderController extends RxDisposable implements IRenderModule {disposableCollection = new DisposableCollection();constructor(diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-formula-render.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-formula-render.controller.tsindex ccd1f02087..be8bc3ce2f 100644--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-formula-render.controller.ts+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-formula-render.controller.ts@@ -19,7 +19,7 @@ import { DisposableCollection, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, IPermissionSimport { getSheetCommandTarget, RangeProtectionPermissionViewPoint, RangeProtectionRuleModel, WorksheetViewPermission } from '@univerjs/sheets';import { Inject, Injector } from '@wendellhu/redi';import { debounceTime, filter } from 'rxjs/operators';-import type { IRenderContext, IRenderController } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { UnitAction } from '@univerjs/protocol';import { NullValueObject } from '@univerjs/engine-formula';import { StatusBarController } from '../status-bar.controller';@@ -30,7 +30,7 @@ type ICellPermission = Record<UnitAction, boolean> & { ruleId?: string; ranges?:export const SHEET_PERMISSION_PASTE_PLUGIN = 'SHEET_PERMISSION_PASTE_PLUGIN';@OnLifecycle(LifecycleStages.Steady, SheetPermissionInterceptorFormulaRenderController)-export class SheetPermissionInterceptorFormulaRenderController extends RxDisposable implements IRenderController {+export class SheetPermissionInterceptorFormulaRenderController extends RxDisposable implements IRenderModule {disposableCollection = new DisposableCollection();constructor(diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-render.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-render.controller.tsindex 6b70f747da..20a1751140 100644--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-render.controller.ts+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-render.controller.ts@@ -14,16 +14,21 @@* limitations under the License.*/-import { Disposable, LifecycleStages, OnLifecycle } from '@univerjs/core';+import { Disposable, IPermissionService, LifecycleStages, OnLifecycle } from '@univerjs/core';import type { IMenuItemFactory, MenuConfig } from '@univerjs/ui';import { ComponentManager, IMenuService } from '@univerjs/ui';import { Inject, Injector } from '@wendellhu/redi';import { CheckMarkSingle, DeleteSingle, LockSingle, ProtectSingle, WriteSingle } from '@univerjs/icons';+import { RangeProtectionRuleModel } from '@univerjs/sheets';+import type { IRenderContext, Spreadsheet } from '@univerjs/engine-render';+import { merge, throttleTime } from 'rxjs';import { sheetPermissionAddProtectContextMenuFactory, sheetPermissionChangeSheetPermissionSheetBarMenuFactory, sheetPermissionContextMenuFactory, sheetPermissionEditProtectContextMenuFactory, sheetPermissionProtectSheetInSheetBarMenuFactory, sheetPermissionRemoveProtectContextMenuFactory, sheetPermissionRemoveProtectionSheetBarMenuFactory, sheetPermissionToolbarMenuFactory, sheetPermissionViewAllProtectRuleContextMenuFactory, sheetPermissionViewAllProtectRuleSheetBarMenuFactory } from '../menu/permission.menu';import { permissionCheckIconKey, permissionDeleteIconKey, permissionEditIconKey, permissionLockIconKey, permissionMenuIconKey, UNIVER_SHEET_PERMISSION_DIALOG, UNIVER_SHEET_PERMISSION_PANEL, UNIVER_SHEET_PERMISSION_PANEL_FOOTER, UNIVER_SHEET_PERMISSION_USER_DIALOG } from '../../basics/const/permission';import { SheetPermissionDialog, SheetPermissionPanel, SheetPermissionPanelFooter, SheetPermissionUserDialog } from '../../views/permission';import { UNIVER_SHEET_PERMISSION_ALERT_DIALOG } from '../../views/permission/error-msg-dialog/interface';import { AlertDialog } from '../../views/permission/error-msg-dialog';+import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';+import { RANGE_PROTECTION_CAN_NOT_VIEW_RENDER_EXTENSION_KEY, RANGE_PROTECTION_CAN_VIEW_RENDER_EXTENSION_KEY, RangeProtectionCanNotViewRenderExtension, RangeProtectionCanViewRenderExtension } from '../../views/permission/extensions/range-protection.render';export interface IUniverSheetsPermissionMenuConfig {menu: MenuConfig;@@ -31,8 +36,8 @@ export interface IUniverSheetsPermissionMenuConfig {export const DefaultSheetPermissionMenuConfig = {};-@OnLifecycle(LifecycleStages.Rendered, SheetPermissionRenderController)-export class SheetPermissionRenderController extends Disposable {+@OnLifecycle(LifecycleStages.Rendered, SheetPermissionRenderManagerController)+export class SheetPermissionRenderManagerController extends Disposable {constructor(private readonly _config: Partial<IUniverSheetsPermissionMenuConfig>,@IMenuService private _menuService: IMenuService,@@ -77,47 +82,16 @@ export class SheetPermissionRenderController extends Disposable {private _initComponents() {([- [- permissionMenuIconKey,- ProtectSingle,- ],- [- permissionDeleteIconKey,- DeleteSingle,- ],- [- permissionEditIconKey,- WriteSingle,- ],- [- permissionCheckIconKey,- CheckMarkSingle,- ],- [- permissionLockIconKey,- LockSingle,- ],- [- UNIVER_SHEET_PERMISSION_PANEL,- SheetPermissionPanel,- ],- [- UNIVER_SHEET_PERMISSION_PANEL_FOOTER,- SheetPermissionPanelFooter,- ],- [- UNIVER_SHEET_PERMISSION_USER_DIALOG,- SheetPermissionUserDialog,- ],- [- UNIVER_SHEET_PERMISSION_DIALOG,- SheetPermissionDialog,- ],- [- UNIVER_SHEET_PERMISSION_ALERT_DIALOG,- AlertDialog,- ],-+ [permissionMenuIconKey, ProtectSingle],+ [permissionDeleteIconKey, DeleteSingle],+ [permissionEditIconKey, WriteSingle],+ [permissionCheckIconKey, CheckMarkSingle],+ [permissionLockIconKey, LockSingle],+ [UNIVER_SHEET_PERMISSION_PANEL, SheetPermissionPanel],+ [UNIVER_SHEET_PERMISSION_PANEL_FOOTER, SheetPermissionPanelFooter],+ [UNIVER_SHEET_PERMISSION_USER_DIALOG, SheetPermissionUserDialog],+ [UNIVER_SHEET_PERMISSION_DIALOG, SheetPermissionDialog],+ [UNIVER_SHEET_PERMISSION_ALERT_DIALOG, AlertDialog],] as const).forEach(([key, component]) => {this.disposeWithMe(this._componentManager.register(key,@@ -126,3 +100,53 @@ export class SheetPermissionRenderController extends Disposable {});}}++export class SheetPermissionRenderController extends Disposable {+ private _rangeProtectionCanViewRenderExtension = new RangeProtectionCanViewRenderExtension();+ private _rangeProtectionCanNotViewRenderExtension = new RangeProtectionCanNotViewRenderExtension();++ constructor(+ private readonly _context: IRenderContext,+ @Inject(RangeProtectionRuleModel) private _rangeProtectionRuleModel: RangeProtectionRuleModel,+ @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService,+ @IPermissionService private _permissionService: IPermissionService+ ) {+ super();++ this._initRender();+ this._initSkeleton();++ this._rangeProtectionRuleModel.ruleChange$.subscribe((info) => {+ if ((info.oldRule?.id && this._rangeProtectionCanViewRenderExtension.renderCache.has(info.oldRule.id)) || this._rangeProtectionCanViewRenderExtension.renderCache.has(info.rule.id)) {+ this._rangeProtectionCanViewRenderExtension.clearCache();+ }+ if ((info.oldRule?.id && this._rangeProtectionCanNotViewRenderExtension.renderCache.has(info.oldRule.id)) || this._rangeProtectionCanNotViewRenderExtension.renderCache.has(info.rule.id)) {+ this._rangeProtectionCanNotViewRenderExtension.clearCache();+ }+ });+ }++ private _initRender() {+ const spreadsheetRender = this._context.mainComponent as Spreadsheet;+ if (spreadsheetRender) {+ if (!spreadsheetRender.getExtensionByKey(RANGE_PROTECTION_CAN_VIEW_RENDER_EXTENSION_KEY)) {+ spreadsheetRender.register(this._rangeProtectionCanViewRenderExtension);+ }+ if (!spreadsheetRender.getExtensionByKey(RANGE_PROTECTION_CAN_NOT_VIEW_RENDER_EXTENSION_KEY)) {+ spreadsheetRender.register(this._rangeProtectionCanNotViewRenderExtension);+ }+ }+ }++ private _initSkeleton() {+ const markDirtySkeleton = () => {+ this._sheetSkeletonManagerService.reCalculate();+ this._context.mainComponent?.makeDirty();+ };++ this.disposeWithMe(merge(+ this._permissionService.permissionPointUpdate$.pipe(throttleTime(300, undefined, { trailing: true })),+ this._rangeProtectionRuleModel.ruleChange$+ ).pipe().subscribe(markDirtySkeleton));+ }+}diff --git a/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.tsindex eb4f1fd0f6..c6cc902fc8 100644--- a/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts@@ -21,7 +21,7 @@ import {RANGE_TYPE,toDisposable,} from '@univerjs/core';-import type { IRenderContext, IRenderController, Spreadsheet, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule, Spreadsheet, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';import { SelectionManagerService } from '@univerjs/sheets';import { IContextMenuService, MenuPosition } from '@univerjs/ui';import { Inject } from '@wendellhu/redi';@@ -31,13 +31,10 @@ import { SheetMenuPosition } from '../menu/menu';import { SHEET_VIEW_KEY } from '../../common/keys';/**- * This controller subscribe to context menu events in- * sheet rendering views and invoke context menu at a correct position- * and with correct menu type.- *- * @todo RenderUnit+ * This controller subscribe to context menu events in sheet rendering views and invoke context menu at a correct+ * position and with correct menu type.*/-export class SheetContextMenuRenderController extends Disposable implements IRenderController {+export class SheetContextMenuRenderController extends Disposable implements IRenderModule {constructor(private readonly _context: IRenderContext<Workbook>,@IContextMenuService private readonly _contextMenuService: IContextMenuService,diff --git a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.tsindex b08260a669..7d951c3d69 100644--- a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts@@ -16,7 +16,7 @@import type { ICommandInfo, IExecutionOptions, ISelectionCell, Nullable, Workbook } from '@univerjs/core';import { ICommandService, IContextService, RxDisposable } from '@univerjs/core';-import type { IRenderContext, IRenderController } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { DeviceInputEventType } from '@univerjs/engine-render';import type { ISelectionWithStyle } from '@univerjs/sheets';import {@@ -35,7 +35,7 @@ import type { ICurrentEditCellParam } from '../../services/editor-bridge.serviceimport { IEditorBridgeService } from '../../services/editor-bridge.service';import { getSheetObject } from '../utils/component-tools';-export class EditorBridgeRenderController extends RxDisposable implements IRenderController {+export class EditorBridgeRenderController extends RxDisposable implements IRenderModule {constructor(private readonly _context: IRenderContext<Workbook>,@Inject(Injector) private readonly _injector: Injector,diff --git a/packages/sheets-ui/src/controllers/render-controllers/format-painter.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/format-painter.render-controller.tsindex 931c081867..b57327d01d 100644--- a/packages/sheets-ui/src/controllers/render-controllers/format-painter.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/format-painter.render-controller.ts@@ -19,12 +19,12 @@ import {Disposable,toDisposable,} from '@univerjs/core';-import type { IRenderContext, IRenderController } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { CURSOR_TYPE } from '@univerjs/engine-render';import { FormatPainterStatus, IFormatPainterService } from '../../services/format-painter/format-painter.service';-export class FormatPainterRenderController extends Disposable implements IRenderController {+export class FormatPainterRenderController extends Disposable implements IRenderModule {constructor(private readonly _context: IRenderContext<Workbook>,@IFormatPainterService private readonly _formatPainterService: IFormatPainterServicediff --git a/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.tsindex 8adcf14d19..c67c1fb428 100644--- a/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts@@ -25,7 +25,7 @@ import {ThemeService,toDisposable,} from '@univerjs/core';-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderController, IScrollObserverParam, Viewport } from '@univerjs/engine-render';+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, IScrollObserverParam, Viewport } from '@univerjs/engine-render';import { CURSOR_TYPE, Rect, TRANSFORM_CHANGE_OBSERVABLE_TYPE, Vector2 } from '@univerjs/engine-render';import type {IInsertColCommandParams,@@ -98,7 +98,7 @@ const AUXILIARY_CLICK_HIDDEN_OBJECT_TRANSPARENCY = 0.01;export const FREEZE_PERMISSION_CHECK = createInterceptorKey<boolean, null>('freezePermissionCheck');-export class HeaderFreezeRenderController extends Disposable implements IRenderController {+export class HeaderFreezeRenderController extends Disposable implements IRenderModule {private _rowFreezeHeaderRect: Nullable<Rect>;private _rowFreezeMainRect: Nullable<Rect>;diff --git a/packages/sheets-ui/src/controllers/render-controllers/header-menu.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/header-menu.render-controller.tsindex 4526fbe0d8..3a58fabd65 100644--- a/packages/sheets-ui/src/controllers/render-controllers/header-menu.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/header-menu.render-controller.ts@@ -20,7 +20,7 @@ import {ICommandService,RANGE_TYPE,} from '@univerjs/core';-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderController, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';import { CURSOR_TYPE, Rect } from '@univerjs/engine-render';import type { ISetSelectionsOperationParams } from '@univerjs/sheets';import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService, SetSelectionsOperation } from '@univerjs/sheets';@@ -48,7 +48,7 @@ enum HEADER_HOVER_TYPE {* header highlight* column menu: show, hover and mousedown event*/-export class HeaderMenuRenderController extends Disposable implements IRenderController {+export class HeaderMenuRenderController extends Disposable implements IRenderModule {private _hoverRect: Nullable<Rect>;private _hoverMenu: Nullable<HeaderMenuShape>;diff --git a/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.tsindex d8039ce8dc..dec989e335 100644--- a/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts@@ -22,7 +22,7 @@ import {InterceptorManager,RANGE_TYPE,} from '@univerjs/core';-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderController, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';import {CURSOR_TYPE,Rect,@@ -61,7 +61,7 @@ enum HEADER_MOVE_TYPE {export const HEADER_MOVE_PERMISSION_CHECK = createInterceptorKey<boolean, IRange>('headerMovePermissionCheck');-export class HeaderMoveRenderController extends Disposable implements IRenderController {+export class HeaderMoveRenderController extends Disposable implements IRenderModule {private _startOffsetX: number = Number.NEGATIVE_INFINITY;private _startOffsetY: number = Number.NEGATIVE_INFINITY;diff --git a/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.tsindex d1881cc3be..f0c9a32989 100644--- a/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts@@ -24,7 +24,7 @@ import {InterceptorManager,toDisposable,} from '@univerjs/core';-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderController, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';import { CURSOR_TYPE, DeviceInputEventType, Rect, Vector2 } from '@univerjs/engine-render';import type {IDeltaColumnWidthCommandParams,@@ -63,7 +63,7 @@ enum HEADER_RESIZE_TYPE {export const HEADER_RESIZE_PERMISSION_CHECK = createInterceptorKey<boolean, { row?: number; col?: number }>('headerResizePermissionCheck');-export class HeaderResizeRenderController extends Disposable implements IRenderController {+export class HeaderResizeRenderController extends Disposable implements IRenderModule {private _currentRow: number = 0;private _currentColumn: number = 0;diff --git a/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.tsindex 72f408b580..019dc51e60 100644--- a/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts@@ -19,11 +19,10 @@ import {Direction,Disposable,ICommandService,- IUniverInstanceService,RANGE_TYPE,toDisposable,} from '@univerjs/core';-import type { IRenderContext, IRenderController } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { IRenderManagerService } from '@univerjs/engine-render';import { ScrollToCellOperation, SelectionManagerService } from '@univerjs/sheets';import { Inject } from '@wendellhu/redi';@@ -42,11 +41,10 @@ const SHEET_NAVIGATION_COMMANDS = [MoveSelectionCommand.id, MoveSelectionEnterAn/*** This controller handles scroll logic in sheet interaction.*/-export class SheetsScrollRenderController extends Disposable implements IRenderController {+export class SheetsScrollRenderController extends Disposable implements IRenderModule {constructor(private readonly _context: IRenderContext<Workbook>,@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,@ICommandService private readonly _commandService: ICommandService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,@@ -276,27 +274,20 @@ export class SheetsScrollRenderController extends Disposable implements IRenderC}private _initSkeletonListener() {- this.disposeWithMe(toDisposable(- this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {- if (param == null) {- return;- }-- const { unitId, sheetId } = param;- const currentRender = this._renderManagerService.getRenderById(unitId);-- if (currentRender == null) {- return;- }+ this.disposeWithMe(toDisposable(this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {+ if (param == null) {+ return;+ }- this._updateSceneSize(param);+ const { unitId } = this._context;+ const { sheetId } = param;- this._scrollManagerService.setCurrentScroll({- unitId,- sheetId,- });- })- ));+ this._updateSceneSize(param);+ this._scrollManagerService.setCurrentScroll({+ unitId,+ sheetId,+ });+ })));}private _updateSceneSize(param: ISheetSkeletonManagerParam) {@@ -304,7 +295,8 @@ export class SheetsScrollRenderController extends Disposable implements IRenderCreturn;}- const { skeleton, unitId } = param;+ const { unitId } = this._context;+ const { skeleton } = param;const scene = this._renderManagerService.getRenderById(unitId)?.scene;if (skeleton == null || scene == null) {diff --git a/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.tsindex a8c3652fe1..e69ccb2abd 100644--- a/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.ts@@ -22,7 +22,7 @@ import {ThemeService,toDisposable,} from '@univerjs/core';-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderController, SpreadsheetSkeleton } from '@univerjs/engine-render';+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, SpreadsheetSkeleton } from '@univerjs/engine-render';import { ScrollTimerType, Vector2 } from '@univerjs/engine-render';import type { ISelectionWithCoordAndStyle, ISelectionWithStyle } from '@univerjs/sheets';import {@@ -48,7 +48,7 @@ import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-managimport type { ISheetObjectParam } from '../utils/component-tools';import { getSheetObject } from '../utils/component-tools';-export class SelectionRenderController extends Disposable implements IRenderController {+export class SelectionRenderController extends Disposable implements IRenderModule {constructor(private readonly _context: IRenderContext<Workbook>,@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@@ -442,7 +442,8 @@ export class SelectionRenderController extends Disposable implements IRenderContreturn;}- const { unitId, sheetId, skeleton } = param;+ const unitId = this._context.unitId;+ const { sheetId, skeleton } = param;const { scene } = this._context;const viewportMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);diff --git a/packages/sheets-ui/src/controllers/render-controllers/sheet-render.controller.ts b/packages/sheets-ui/src/controllers/render-controllers/sheet-render.controller.tsnew file mode 100644index 0000000000..dace4df2c2--- /dev/null+++ b/packages/sheets-ui/src/controllers/render-controllers/sheet-render.controller.ts@@ -0,0 +1,483 @@+/**+ * 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 { ICommandInfo, IRange, Workbook, Worksheet } from '@univerjs/core';+import { CommandType, ICommandService, Rectangle, RxDisposable } from '@univerjs/core';+import type { IRenderContext, IRenderModule, IViewportInfos, IWheelEvent, Scene } from '@univerjs/engine-render';+import {+ Layer,+ PointerInput,+ Rect,+ RENDER_CLASS_TYPE,+ ScrollBar,+ SHEET_VIEWPORT_KEY,+ Spreadsheet,+ SpreadsheetColumnHeader,+ SpreadsheetRowHeader,+ Viewport,+} from '@univerjs/engine-render';+import { Inject } from '@wendellhu/redi';+import { COMMAND_LISTENER_SKELETON_CHANGE, COMMAND_LISTENER_VALUE_CHANGE, MoveRangeMutation, SetRangeValuesMutation, SetWorksheetActiveOperation } from '@univerjs/sheets';+import { SetScrollRelativeCommand } from '../../commands/commands/set-scroll.command';++import {+ SHEET_COMPONENT_HEADER_LAYER_INDEX,+ SHEET_COMPONENT_MAIN_LAYER_INDEX,+ SHEET_VIEW_KEY,+} from '../../common/keys';+import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';+import { SheetsRenderService } from '../../services/sheets-render.service';++interface ISetWorksheetMutationParams {+ unitId: string;+ subUnitId: string;+}++export class SheetRenderController extends RxDisposable implements IRenderModule {+ constructor(+ private readonly _context: IRenderContext<Workbook>,+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,+ @Inject(SheetsRenderService) private readonly _sheetRenderService: SheetsRenderService,+ @ICommandService private readonly _commandService: ICommandService+ ) {+ super();++ this._addNewRender(this._context.unit);+ }++ private _addNewRender(workbook: Workbook) {+ const { scene, engine } = this._context;++ scene.addLayer(new Layer(scene, [], 0), new Layer(scene, [], 2));++ this._addComponent(workbook);+ this._initRerenderScheduler();+ this._initCommandListener();++ const sheetId = this._context.unit.getActiveSheet().getSheetId();+ this._sheetSkeletonManagerService.setCurrent({ sheetId });+ const should = workbook.getShouldRenderLoopImmediately();+ if (should) {+ engine.runRenderLoop(() => scene.render());+ }+ }++ private _addComponent(workbook: Workbook) {+ const { scene, components } = this._context;++ const worksheet = workbook.getActiveSheet();+ const spreadsheet = new Spreadsheet(SHEET_VIEW_KEY.MAIN);++ this._addViewport(worksheet);++ const spreadsheetRowHeader = new SpreadsheetRowHeader(SHEET_VIEW_KEY.ROW);+ const spreadsheetColumnHeader = new SpreadsheetColumnHeader(SHEET_VIEW_KEY.COLUMN);+ const SpreadsheetLeftTopPlaceholder = new Rect(SHEET_VIEW_KEY.LEFT_TOP, {+ zIndex: 2,+ left: -1,+ top: -1,+ fill: 'rgb(248, 249, 250)',+ stroke: 'rgb(217, 217, 217)',+ strokeWidth: 1,+ });++ this._context.mainComponent = spreadsheet;+ components.set(SHEET_VIEW_KEY.MAIN, spreadsheet);+ components.set(SHEET_VIEW_KEY.ROW, spreadsheetRowHeader);+ components.set(SHEET_VIEW_KEY.COLUMN, spreadsheetColumnHeader);+ components.set(SHEET_VIEW_KEY.LEFT_TOP, SpreadsheetLeftTopPlaceholder);++ scene.addObjects([spreadsheet], SHEET_COMPONENT_MAIN_LAYER_INDEX);+ scene.addObjects(+ [spreadsheetRowHeader, spreadsheetColumnHeader, SpreadsheetLeftTopPlaceholder],+ SHEET_COMPONENT_HEADER_LAYER_INDEX+ );++ scene.enableLayerCache(SHEET_COMPONENT_MAIN_LAYER_INDEX, SHEET_COMPONENT_HEADER_LAYER_INDEX);+ }++ // eslint-disable-next-line max-lines-per-function+ private _initViewports(scene: Scene, rowHeader: { width: number }, columnHeader: { height: number }) {+ const bufferEdgeX = 100;+ const bufferEdgeY = 100;+ // window.sc = scene;+ const viewMain = new Viewport(SHEET_VIEWPORT_KEY.VIEW_MAIN, scene, {+ left: rowHeader.width,+ top: columnHeader.height,+ bottom: 0,+ right: 0,+ isWheelPreventDefaultX: true,+ isRelativeX: true,+ isRelativeY: true,+ allowCache: true,+ bufferEdgeX,+ bufferEdgeY,+ });+ const viewMainLeftTop = new Viewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP, scene, {+ isWheelPreventDefaultX: true,+ active: false,+ isRelativeX: false,+ isRelativeY: false,+ allowCache: true,+ bufferEdgeX: 0,+ bufferEdgeY: 0,+ });++ const viewMainLeft = new Viewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT, scene, {+ isWheelPreventDefaultX: true,+ active: false,+ isRelativeX: false,+ isRelativeY: true,+ allowCache: true,+ bufferEdgeX: 0,+ bufferEdgeY,+ });++ const viewMainTop = new Viewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP, scene, {+ isWheelPreventDefaultX: true,+ active: false,+ isRelativeX: true,+ isRelativeY: false,+ allowCache: true,+ bufferEdgeX,+ bufferEdgeY: 0,+ });++ const viewRowTop = new Viewport(SHEET_VIEWPORT_KEY.VIEW_ROW_TOP, scene, {+ active: false,+ isWheelPreventDefaultX: true,+ isRelativeX: false,+ isRelativeY: false,+ });++ const viewRowBottom = new Viewport(SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM, scene, {+ left: 0,+ top: columnHeader.height,+ bottom: 0,+ width: rowHeader.width,+ isWheelPreventDefaultX: true,+ isRelativeX: false,+ isRelativeY: true,+ });++ const viewColumnLeft = new Viewport(SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT, scene, {+ active: false,+ isWheelPreventDefaultX: true,+ isRelativeX: false,+ isRelativeY: false,+ });++ const viewColumnRight = new Viewport(SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT, scene, {+ left: rowHeader.width,+ top: 0,+ height: columnHeader.height,+ right: 0,+ isWheelPreventDefaultX: true,+ isRelativeX: true,+ isRelativeY: false,+ });++ const viewLeftTop = new Viewport(SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP, scene, {+ left: 0,+ top: 0,+ width: rowHeader.width,+ height: columnHeader.height,+ isWheelPreventDefaultX: true,+ isRelativeX: false,+ isRelativeY: false,+ });++ return {+ viewMain,+ viewLeftTop,+ viewMainLeftTop,+ viewMainLeft,+ viewMainTop,+ viewColumnLeft,+ viewRowTop,+ viewRowBottom,+ viewColumnRight,+ };+ }++ /**+ *+ * initViewport & wheel event+ * +-----------------+--------------------+-------------------++ * | VIEW_LEFT_TOP | VIEW_COLUMN_LEFT | VIEW_COLUMN_RIGHT |+ * +-----------------+--------------------+-------------------++ * | VIEW_ROW_TOP | VIEW_MAIN_LEFT_TOP | VIEW_MAIN_TOP |+ * +-----------------+--------------------+-------------------++ * | VIEW_ROW_BOTTOM | VIEW_MAIN_LEFT | VIEW_MAIN |+ * +-----------------+--------------------+-------------------++ */++ private _addViewport(worksheet: Worksheet) {+ const scene = this._context.scene;+ if (scene == null) {+ return;+ }+ const { rowHeader, columnHeader } = worksheet.getConfig();+ const { viewMain } = this._initViewports(scene, rowHeader, columnHeader);++ this._initMouseWheel(scene, viewMain);+ const _scrollBar = new ScrollBar(viewMain);++ scene.attachControl();++ return viewMain;+ }++ private _initRerenderScheduler(): void {+ this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {+ if (!param) return null;++ const { skeleton: spreadsheetSkeleton, sheetId } = param;+ const workbook = this._context.unit;+ const worksheet = workbook?.getSheetBySheetId(sheetId);+ if (workbook == null || worksheet == null) return;++ const { mainComponent, components } = this._context;+ const spreadsheet = mainComponent as Spreadsheet;+ const spreadsheetRowHeader = components.get(SHEET_VIEW_KEY.ROW) as SpreadsheetRowHeader;+ const spreadsheetColumnHeader = components.get(SHEET_VIEW_KEY.COLUMN) as SpreadsheetColumnHeader;+ const spreadsheetLeftTopPlaceholder = components.get(SHEET_VIEW_KEY.LEFT_TOP) as Rect;+ const { rowHeaderWidth, columnHeaderHeight } = spreadsheetSkeleton;++ spreadsheet?.updateSkeleton(spreadsheetSkeleton);+ spreadsheetRowHeader?.updateSkeleton(spreadsheetSkeleton);+ spreadsheetColumnHeader?.updateSkeleton(spreadsheetSkeleton);+ spreadsheetLeftTopPlaceholder?.transformByState({+ width: rowHeaderWidth,+ height: columnHeaderHeight,+ });+ }));+ }++ private _initCommandListener(): void {+ this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo) => {+ const workbook = this._context.unit;+ const unitId = workbook.getUnitId();+ if (COMMAND_LISTENER_SKELETON_CHANGE.includes(command.id) || this._sheetRenderService.checkMutationShouldTriggerRerender(command.id)) {+ const worksheet = workbook.getActiveSheet();+ const sheetId = worksheet.getSheetId();+ const params = command.params;+ const { unitId, subUnitId } = params as ISetWorksheetMutationParams;++ if ((unitId !== workbook.getUnitId() && subUnitId !== worksheet.getSheetId())) {+ return;+ }++ if (command.id !== SetWorksheetActiveOperation.id) {+ this._sheetSkeletonManagerService.makeDirty({+ sheetId,+ commandId: command.id,+ }, true);+ }++ // Change the skeleton to render when the sheet is changed.+ // Should also check the init sheet.+ // setCurrent ---> currentSkeletonBefore$ ---> zoom.controller.subscribe ---> scene._setTransForm ---> viewports markDirty+ // setCurrent ---> currentSkeleton$ ---> scroll.controller.subscribe ---> scene?.transformByState ---> scene._setTransFor+ this._sheetSkeletonManagerService.setCurrent({+ sheetId,+ commandId: command.id,+ });+ } else if (COMMAND_LISTENER_VALUE_CHANGE.includes(command.id)) {+ this._sheetSkeletonManagerService.reCalculate();+ }++ if (command.type === CommandType.MUTATION) {+ this._markUnitDirty(unitId, command);+ }+ }));+ }++ private _markUnitDirty(unitId: string, command: ICommandInfo) {+ const { mainComponent: spreadsheet, scene } = this._context;+ // 现在 spreadsheet.markDirty 会调用 vport.markDirty+ // 因为其他 controller 中存在 mainComponent?.makeDirty() 的调用, 不止是 sheet-render.controller 在标脏+ if (spreadsheet) {+ spreadsheet.makeDirty(); // refresh spreadsheet+ }++ scene.makeDirty();+ if (!command.params) return;++ const cmdParams = command.params as Record<string, any>;+ const viewports = this._spreadsheetViewports(scene);+ if (command.id === SetRangeValuesMutation.id && cmdParams.cellValue) {+ const dirtyRange: IRange = this._cellValueToRange(cmdParams.cellValue);+ const dirtyBounds = this._rangeToBounds([dirtyRange]);+ this._markViewportDirty(viewports, dirtyBounds);+ (spreadsheet as unknown as Spreadsheet).setDirtyArea(dirtyBounds);+ }++ if (command.id === MoveRangeMutation.id && cmdParams.from && cmdParams.to) {+ const fromRange = this._cellValueToRange(cmdParams.from.value);+ const toRange = this._cellValueToRange(cmdParams.to.value);+ const dirtyBounds = this._rangeToBounds([fromRange, toRange]);+ this._markViewportDirty(viewports, dirtyBounds);+ (spreadsheet as unknown as Spreadsheet).setDirtyArea(dirtyBounds);+ }+ }++ /**+ * cellValue data structure:+ * {[row]: { [col]: value}}+ * @param cellValue+ * @returns+ */+ private _cellValueToRange(cellValue: Record<number, Record<number, object>>) {+ const rows = Object.keys(cellValue).map(Number);+ const columns = [];++ for (const [_row, columnObj] of Object.entries(cellValue)) {+ for (const column in columnObj) {+ columns.push(Number(column));+ }+ }++ const startRow = Math.min(...rows);+ const endRow = Math.max(...rows);+ const startColumn = Math.min(...columns);+ const endColumn = Math.max(...columns);++ return {+ startRow,+ endRow,+ startColumn,+ endColumn,+ } as IRange;+ }++ private _rangeToBounds(ranges: IRange[]) {+ const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;+ const { rowHeightAccumulation, columnWidthAccumulation, rowHeaderWidth, columnHeaderHeight } = skeleton;++ // rowHeightAccumulation 已经表示的是行底部的高度+ const dirtyBounds: IViewportInfos[] = [];+ for (const r of ranges) {+ const { startRow, endRow, startColumn, endColumn } = r;+ const top = startRow === 0 ? 0 : rowHeightAccumulation[startRow - 1] + columnHeaderHeight;+ const bottom = rowHeightAccumulation[endRow] + columnHeaderHeight;+ const left = startColumn === 0 ? 0 : columnWidthAccumulation[startColumn - 1] + rowHeaderWidth;+ const right = columnWidthAccumulation[endColumn] + rowHeaderWidth;+ dirtyBounds.push({ top, left, bottom, right, width: right - left, height: bottom - top });+ }+ return dirtyBounds;+ }++ private _markViewportDirty(viewports: Viewport[], dirtyBounds: IViewportInfos[]) {+ const activeViewports = viewports.filter((vp) => vp.isActive && vp.cacheBound);+ for (const vp of activeViewports) {+ for (const b of dirtyBounds) {+ if (Rectangle.hasIntersectionBetweenTwoBounds(vp.cacheBound!, b)) {+ vp.markDirty(true);+ }+ }+ }+ }++ private _spreadsheetViewports(scene: Scene) {+ return scene.getViewports().filter((v) => ['viewMain', 'viewMainLeftTop', 'viewMainTop', 'viewMainLeft'].includes(v.viewportKey));+ }++ // mouse scroll+ private _initMouseWheel(scene: Scene, viewMain: Viewport) {+ this.disposeWithMe(+ scene.onMouseWheelObserver.add((evt: IWheelEvent, state) => {+ if (evt.ctrlKey) {+ return;+ }++ let offsetX = 0;+ let offsetY = 0;++ const isLimitedStore = viewMain.limitedScroll();+ if (evt.inputIndex === PointerInput.MouseWheelX) {+ const deltaFactor = Math.abs(evt.deltaX);+ // let magicNumber = deltaFactor < 40 ? 2 : deltaFactor < 80 ? 3 : 4;+ const scrollNum = deltaFactor;+ // 展示更多右侧内容,evt.deltaX > 0+ // 展示更多左侧内容, evt.deltaX < 0+ if (evt.deltaX > 0) {+ offsetX = scrollNum;+ } else {+ offsetX = -scrollNum;+ }+ this._commandService.executeCommand(SetScrollRelativeCommand.id, { offsetX });++ // 临界点时执行浏览器行为+ if (scene.getParent().classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {+ if (!isLimitedStore?.isLimitedX) {+ state.stopPropagation();+ }+ } else if (viewMain.isWheelPreventDefaultX) {+ evt.preventDefault();+ } else if (!isLimitedStore?.isLimitedX) {+ evt.preventDefault();+ }+ }+ if (evt.inputIndex === PointerInput.MouseWheelY) {+ const deltaFactor = Math.abs(evt.deltaY);+ // let magicNumber = deltaFactor < 40 ? 2 : deltaFactor < 80 ? 3 : 4;+ let scrollNum = deltaFactor;+ if (evt.shiftKey) {+ scrollNum *= 3;+ if (evt.deltaY > 0) {+ offsetX = scrollNum;+ } else {+ offsetX = -scrollNum;+ }+ this._commandService.executeCommand(SetScrollRelativeCommand.id, { offsetX });++ // 临界点时执行浏览器行为+ if (scene.getParent().classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {+ if (!isLimitedStore?.isLimitedX) {+ state.stopPropagation();+ }+ } else if (viewMain.isWheelPreventDefaultX) {+ evt.preventDefault();+ } else if (!isLimitedStore?.isLimitedX) {+ evt.preventDefault();+ }+ } else {+ if (evt.deltaY > 0) {+ offsetY = scrollNum;+ } else {+ offsetY = -scrollNum;+ }+ this._commandService.executeCommand(SetScrollRelativeCommand.id, { offsetY });++ // 临界点时执行浏览器行为+ if (scene.getParent().classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {+ if (!isLimitedStore?.isLimitedY) {+ state.stopPropagation();+ }+ } else if (viewMain.isWheelPreventDefaultY) {+ evt.preventDefault();+ } else if (!isLimitedStore?.isLimitedY) {+ evt.preventDefault();+ }+ }+ }++ this._context.scene.makeDirty(true);+ })+ );+ }+}diff --git a/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.tsindex 9b307b9062..d9d1fa3de5 100644--- a/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.ts@@ -16,13 +16,13 @@import type { Workbook } from '@univerjs/core';import { Disposable, ICommandService } from '@univerjs/core';-import type { IRenderContext, IRenderController, IWheelEvent } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule, IWheelEvent } from '@univerjs/engine-render';import { Inject } from '@wendellhu/redi';import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';import { getSheetObject } from '../utils/component-tools';import { SetZoomRatioCommand } from '../../commands/commands/set-zoom-ratio.command';-export class SheetsZoomRenderController extends Disposable implements IRenderController {+export class SheetsZoomRenderController extends Disposable implements IRenderModule {constructor(private readonly _context: IRenderContext<Workbook>,@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,diff --git a/packages/sheets-ui/src/controllers/sheet-render.controller.ts b/packages/sheets-ui/src/controllers/sheet-render.controller.tsdeleted file mode 100644index 993bcc0ec6..0000000000--- a/packages/sheets-ui/src/controllers/sheet-render.controller.ts+++ /dev/null@@ -1,294 +0,0 @@-/**- * 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 { ICommandInfo,- IRange,- Workbook } from '@univerjs/core';-import { CommandType,- ICommandService,- IContextService,- IUniverInstanceService,- LifecycleStages,- OnLifecycle,- Rectangle,- RxDisposable,- toDisposable,- UniverInstanceType,-} from '@univerjs/core';-import type { IViewportInfos, Rect, Scene, SpreadsheetColumnHeader, SpreadsheetRowHeader, Viewport } from '@univerjs/engine-render';-import { IRenderManagerService, RENDER_RAW_FORMULA_KEY, Spreadsheet } from '@univerjs/engine-render';-import {- COMMAND_LISTENER_SKELETON_CHANGE,- COMMAND_LISTENER_VALUE_CHANGE,- MoveRangeMutation,- SetRangeValuesMutation,- SetWorksheetActiveOperation,-} from '@univerjs/sheets';-import type { IDisposable } from '@wendellhu/redi';-import { Inject } from '@wendellhu/redi';--import { distinctUntilChanged, takeUntil } from 'rxjs';-import { SHEET_VIEW_KEY } from '../common/keys';-import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';--interface ISetWorksheetMutationParams {- unitId: string;- subUnitId: string;-}--@OnLifecycle(LifecycleStages.Ready, SheetRenderController)-export class SheetRenderController extends RxDisposable {- private _skeletonChangeMutations = new Set<string>();-- constructor(- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,- @IContextService private readonly _contextService: IContextService,- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,- @ICommandService private readonly _commandService: ICommandService- ) {- super();- Promise.resolve().then(() => this._init());- }-- /**- * Register a mutation id that will trigger the skeleton change.- *- * @param mutationId the id of the mutation- * @returns a disposable to unregister the mutation- */- registerSkeletonChangingMutations(mutationId: string): IDisposable {- if (this._skeletonChangeMutations.has(mutationId)) {- throw new Error(`[SheetRenderController]: the mutationId ${mutationId} has already been registered!`);- }-- this._skeletonChangeMutations.add(mutationId);- return toDisposable(() => this._skeletonChangeMutations.delete(mutationId));- }-- private _init() {- this._initialRenderRefresh();- this._initWorkbookListener();- this._initCommandListener();- this._initContextListener();- }-- private _initialRenderRefresh(): void {- this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {- if (!param) return null;-- const { skeleton: spreadsheetSkeleton, unitId, sheetId } = param;- const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);- const worksheet = workbook?.getSheetBySheetId(sheetId);- if (workbook == null || worksheet == null) return;-- const currentRender = this._renderManagerService.getRenderById(unitId);- if (currentRender == null) return;-- const { mainComponent, components } = currentRender;- const spreadsheet = mainComponent as Spreadsheet;- const spreadsheetRowHeader = components.get(SHEET_VIEW_KEY.ROW) as SpreadsheetRowHeader;- const spreadsheetColumnHeader = components.get(SHEET_VIEW_KEY.COLUMN) as SpreadsheetColumnHeader;- const spreadsheetLeftTopPlaceholder = components.get(SHEET_VIEW_KEY.LEFT_TOP) as Rect;- const { rowHeaderWidth, columnHeaderHeight } = spreadsheetSkeleton;-- spreadsheet?.updateSkeleton(spreadsheetSkeleton);- spreadsheetRowHeader?.updateSkeleton(spreadsheetSkeleton);- spreadsheetColumnHeader?.updateSkeleton(spreadsheetSkeleton);- spreadsheetLeftTopPlaceholder?.transformByState({- width: rowHeaderWidth,- height: columnHeaderHeight,- });- }));- }-- private _initWorkbookListener(): void {- this._univerInstanceService.getTypeOfUnitAdded$<Workbook>(UniverInstanceType.UNIVER_SHEET)- .pipe(takeUntil(this.dispose$))- .subscribe((workbook) => this._createSheetRenderer(workbook));-- this._univerInstanceService.getTypeOfUnitDisposed$<Workbook>(UniverInstanceType.UNIVER_SHEET)- .pipe(takeUntil(this.dispose$))- .subscribe((workbook) => {- const unitId = workbook.getUnitId();-- this._sheetSkeletonManagerService.removeSkeleton({ unitId });- this._renderManagerService.removeRender(unitId);- });-- this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET)- .forEach((workbook) => this._createSheetRenderer(workbook));- }-- private _createSheetRenderer(workbook: Workbook): void {- const unitId = workbook.getUnitId();- this._renderManagerService.createRender(unitId);- this._renderManagerService.setCurrent(unitId);- const sheetId = workbook.getActiveSheet().getSheetId();- this._sheetSkeletonManagerService.setCurrent({ sheetId, unitId });- }-- private _initCommandListener(): void {- this.disposeWithMe(- this._commandService.onCommandExecuted((command: ICommandInfo) => {- const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);- if (!workbook) return;-- const unitId = workbook.getUnitId();- if (COMMAND_LISTENER_SKELETON_CHANGE.includes(command.id) || this._skeletonChangeMutations.has(command.id)) {- const worksheet = workbook.getActiveSheet();- const sheetId = worksheet.getSheetId();- const params = command.params;- const { unitId, subUnitId } = params as ISetWorksheetMutationParams;-- if (!(unitId === workbook.getUnitId() && subUnitId === worksheet.getSheetId())) {- return;- }-- if (command.id !== SetWorksheetActiveOperation.id) {- this._sheetSkeletonManagerService.makeDirty(- {- unitId,- sheetId,- commandId: command.id,- },- true- );- }-- // Change the skeleton to render when the sheet is changed.- // Should also check the init sheet.- // setCurrent ---> currentSkeletonBefore$ ---> zoom.controller.subscribe ---> scene._setTransForm ---> viewports markDirty- // setCurrent ---> currentSkeleton$ ---> scroll.controller.subscribe ---> scene?.transformByState ---> scene._setTransFor- this._sheetSkeletonManagerService.setCurrent({- unitId,- sheetId,- commandId: command.id,- });- } else if (COMMAND_LISTENER_VALUE_CHANGE.includes(command.id)) {- this._sheetSkeletonManagerService.reCalculate();- }-- if (command.type === CommandType.MUTATION) {- this._markSpreadsheetDirty(unitId, command);- }- })- );- }-- private _initContextListener(): void {- // If we toggle the raw formula, we need to refresh all spreadsheets.- this._contextService.subscribeContextValue$(RENDER_RAW_FORMULA_KEY)- .pipe(distinctUntilChanged(), takeUntil(this.dispose$))- .subscribe(() => {- this._renderManagerService.getRenderAll().forEach((renderer) => {- if (renderer.mainComponent instanceof Spreadsheet) {- (renderer.mainComponent as Spreadsheet).makeForceDirty(true);- }- });- });- }-- private _spreadsheetViewports(scene: Scene) {- return scene.getViewports().filter((v) => ['viewMain', 'viewMainLeftTop', 'viewMainTop', 'viewMainLeft'].includes(v.viewportKey));- }-- private _markSpreadsheetDirty(unitId: string, command: ICommandInfo) {- const currentRender = this._renderManagerService.getRenderById(unitId);- if (!currentRender) return;- const { mainComponent: spreadsheet, scene } = currentRender;- // 现在 spreadsheet.markDirty 会调用 vport.markDirty- // 因为其他 controller 中存在 mainComponent?.makeDirty() 的调用, 不止是 sheet-render.controller 在标脏- if (spreadsheet) {- spreadsheet.makeDirty(); // refresh spreadsheet- }- scene.makeDirty();- if (!command.params) return;- const cmdParams = command.params as Record<string, any>;- const viewports = this._spreadsheetViewports(scene);- if (command.id === SetRangeValuesMutation.id && cmdParams.cellValue) {- const dirtyRange: IRange = this._cellValueToRange(cmdParams.cellValue);- const dirtyBounds = this._rangeToBounds([dirtyRange]);- this._markViewportDirty(viewports, dirtyBounds);- (spreadsheet as unknown as Spreadsheet).setDirtyArea(dirtyBounds);- }-- if (command.id === MoveRangeMutation.id && cmdParams.from && cmdParams.to) {- const fromRange = this._cellValueToRange(cmdParams.from.value);- const toRange = this._cellValueToRange(cmdParams.to.value);- const dirtyBounds = this._rangeToBounds([fromRange, toRange]);- this._markViewportDirty(viewports, dirtyBounds);- (spreadsheet as unknown as Spreadsheet).setDirtyArea(dirtyBounds);- }- }-- /**- * cellValue data structure:- * {[row]: { [col]: value}}- * @param cellValue- * @returns- */- private _cellValueToRange(cellValue: Record<number, Record<number, object>>) {- const rows = Object.keys(cellValue).map(Number);- const columns = [];-- for (const [_row, columnObj] of Object.entries(cellValue)) {- for (const column in columnObj) {- columns.push(Number(column));- }- }-- const startRow = Math.min(...rows);- const endRow = Math.max(...rows);- const startColumn = Math.min(...columns);- const endColumn = Math.max(...columns);-- return {- startRow,- endRow,- startColumn,- endColumn,- } as IRange;- }-- private _rangeToBounds(ranges: IRange[]) {- const sk = this._sheetSkeletonManagerService.getCurrent()?.skeleton!;-- const { rowHeightAccumulation, columnWidthAccumulation, rowHeaderWidth, columnHeaderHeight } = sk;- // rowHeightAccumulation 已经表示的是行底部的高度- const dirtyBounds: IViewportInfos[] = [];- for (const r of ranges) {- const { startRow, endRow, startColumn, endColumn } = r;- const top = startRow === 0 ? 0 : rowHeightAccumulation[startRow - 1] + columnHeaderHeight;- const bottom = rowHeightAccumulation[endRow] + columnHeaderHeight;- const left = startColumn === 0 ? 0 : columnWidthAccumulation[startColumn - 1] + rowHeaderWidth;- const right = columnWidthAccumulation[endColumn] + rowHeaderWidth;- dirtyBounds.push({ top, left, bottom, right, width: right - left, height: bottom - top });- }- return dirtyBounds;- }-- private _markViewportDirty(viewports: Viewport[], dirtyBounds: IViewportInfos[]) {- const activeViewports = viewports.filter((vp) => vp.isActive && vp.cacheBound);- for (const vp of activeViewports) {- for (const b of dirtyBounds) {- if (Rectangle.hasIntersectionBetweenTwoBounds(vp.cacheBound!, b)) {- vp.markDirty(true);- }- }- }- }-}diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.tsindex baf11d4f2d..8ef7c5faf2 100644--- a/packages/sheets-ui/src/index.ts+++ b/packages/sheets-ui/src/index.ts@@ -24,7 +24,7 @@ export { SetCellEditVisibleArrowOperation, SetCellEditVisibleOperation } from '.export { SetScrollOperation } from './commands/operations/scroll.operation';export { SheetsScrollRenderController } from './controllers/render-controllers/scroll.render-controller';export { deriveStateFromActiveSheet$, getCurrentRangeDisable$, getCommentDisable$ } from './controllers/menu/menu-util';-export { SheetRenderController } from './controllers/sheet-render.controller';+export { SheetsRenderService } from './services/sheets-render.service';export { SetZoomRatioOperation } from './commands/operations/set-zoom-ratio.operation';export {ResetScrollCommand,@@ -77,7 +77,7 @@ export { SelectionShape } from './services/selection/selection-shape';export type { ISheetSkeletonManagerParam } from './services/sheet-skeleton-manager.service';export { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';export { UniverSheetsUIPlugin } from './sheets-ui-plugin';-export { SheetCanvasView } from './views/sheet-canvas-view';+export { SheetRenderController } from './controllers/render-controllers/sheet-render.controller';export { HoverManagerService } from './services/hover-manager.service';export { DragManagerService } from './services/drag-manager.service';export { CellAlertManagerService, CellAlertType, type ICellAlert } from './services/cell-alert-manager.service';diff --git a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts b/packages/sheets-ui/src/services/canvas-pop-manager.service.tsindex db98eab479..82820cde88 100644--- a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts+++ b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts@@ -42,7 +42,6 @@ export class SheetCanvasPopManagerService extends Disposable {@Inject(ICanvasPopupService) private readonly _globalPopupManagerService: ICanvasPopupService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@Inject(RefRangeService) private readonly _refRangeService: RefRangeService,@ICommandService private readonly _commandService: ICommandService) {@@ -107,10 +106,10 @@ export class SheetCanvasPopManagerService extends Disposable {const worksheet = workbook.getActiveSheet();const unitId = workbook.getUnitId();const subUnitId = worksheet.getSheetId();- const skeleton = this._sheetSkeletonManagerService.getOrCreateSkeleton({- unitId,+ const skeleton = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getOrCreateSkeleton({sheetId: subUnitId,});+const currentRender = this._renderManagerService.getRenderById(unitId);if (!currentRender || !skeleton) {return {@@ -156,8 +155,7 @@ export class SheetCanvasPopManagerService extends Disposable {const worksheet = workbook.getActiveSheet();const unitId = workbook.getUnitId();const subUnitId = worksheet.getSheetId();- const skeleton = this._sheetSkeletonManagerService.getOrCreateSkeleton({- unitId,+ const skeleton = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getOrCreateSkeleton({sheetId: subUnitId,});diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-alignment.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-alignment.spec.tsindex 79fd8c8c2d..ddcb0edc09 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-alignment.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-alignment.spec.ts@@ -130,7 +130,6 @@ describe('Test clipboard', () => {]);sheetSkeletonManagerService.setCurrent({- unitId: 'test',sheetId: 'sheet1',});});diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-border.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-border.spec.tsindex cf5b76dbe4..1506ebf972 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-border.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-border.spec.ts@@ -139,7 +139,6 @@ describe('Test clipboard', () => {]);sheetSkeletonManagerService.setCurrent({- unitId: 'test',sheetId: 'sheet1',});});diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-font.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-font.spec.tsindex a6feb1c0bc..fa56e4d579 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-font.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-font.spec.ts@@ -139,7 +139,6 @@ describe('Test clipboard', () => {]);sheetSkeletonManagerService.setCurrent({- unitId: 'test',sheetId: 'sheet1',});});diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.tsindex 1363e62e29..d7146501ff 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.ts@@ -145,7 +145,6 @@ describe('Test clipboard', () => {]);sheetSkeletonManagerService.setCurrent({- unitId: 'test',sheetId: 'sheet1',});});diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.tsindex 0976fcdfe2..9010c1e6fb 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.ts@@ -146,7 +146,6 @@ describe('Test clipboard', () => {]);sheetSkeletonManagerService.setCurrent({- unitId: 'test',sheetId: 'sheet1',});});diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-rotate.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-rotate.spec.tsindex e34b4cda00..eddb086644 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-rotate.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-rotate.spec.ts@@ -72,6 +72,7 @@ describe('Test clipboard', () => {sheetOrder: [],styles: {},});+univer = testBed.univer;get = testBed.get;@@ -82,7 +83,8 @@ describe('Test clipboard', () => {commandService.registerCommand(AddWorksheetMergeMutation);commandService.registerCommand(RemoveWorksheetMergeMutation);commandService.registerCommand(SetSelectionsOperation);- sheetSkeletonManagerService = get(SheetSkeletonManagerService);++ sheetSkeletonManagerService = get(SheetSkeletonManagerService)!;sheetClipboardService = get(ISheetClipboardService);getValues = (@@ -98,9 +100,7 @@ describe('Test clipboard', () => {.getValues();getStyles = (key) => {- if (!key) return;- const styles = get(IUniverInstanceService).getUniverSheetInstance('test')?.getStyles();- return styles?.get(key);+ return get(IUniverInstanceService).getUniverSheetInstance('test')!.getStyles().get(key);};convertColor = (color) => {@@ -139,23 +139,22 @@ describe('Test clipboard', () => {]);sheetSkeletonManagerService.setCurrent({- unitId: 'test',sheetId: 'sheet1',});});+it('test font style paste from univer', async () => {- const worksheet = get(IUniverInstanceService).getUniverSheetInstance('test')?.getSheetBySheetId('sheet1');- if (!worksheet) return false;+ const worksheet = get(IUniverInstanceService).getUniverSheetInstance('test')!.getSheetBySheetId('sheet1')!;const res = await sheetClipboardService.legacyPaste(rotateSampleByUniver);expect(res).toBeTruthy();+const cellData = worksheet.getCellMatrix();- expect(getStyles(cellData.getValue(1, 1)?.s)?.tr?.a).toBeFalsy();- expect(getStyles(cellData.getValue(2, 1)?.s)?.tr?.a).toBe(-45);- expect(getStyles(cellData.getValue(3, 1)?.s)?.tr?.a).toBe(45);- expect(getStyles(cellData.getValue(4, 1)?.s)?.tr).toStrictEqual(- { a: 0, v: 1 });- expect(getStyles(cellData.getValue(5, 1)?.s)?.tr?.a).toBe(-90);- expect(getStyles(cellData.getValue(6, 1)?.s)?.tr?.a).toBe(90);+ expect(getStyles(cellData.getValue(1, 1)!.s)?.tr!.a).toBeFalsy();+ expect(getStyles(cellData.getValue(2, 1)!.s)?.tr!.a).toBe(-45);+ expect(getStyles(cellData.getValue(3, 1)!.s)?.tr!.a).toBe(45);+ expect(getStyles(cellData.getValue(4, 1)!.s)?.tr).toStrictEqual({ a: 0, v: 1 });+ expect(getStyles(cellData.getValue(5, 1)!.s)?.tr!.a).toBe(-90);+ expect(getStyles(cellData.getValue(6, 1)!.s)?.tr!.a).toBe(90);});});});diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.tsindex 4001d912f8..e95728b8f1 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts@@ -14,8 +14,10 @@* limitations under the License.*/+/* eslint-disable ts/no-explicit-any */+import type { IWorkbookData } from '@univerjs/core';-import { ILogService, IUniverInstanceService, LocaleService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';+import { DisposableCollection, ILogService, IUniverInstanceService, LocaleService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import { SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';import {@@ -33,8 +35,8 @@ import { CalculateFormulaService, DefinedNamesService, FormulaCurrentConfigServiimport { SheetClipboardController } from '../../../controllers/clipboard/clipboard.controller';import { IMarkSelectionService } from '../../mark-selection/mark-selection.service';import { ISelectionRenderService, SelectionRenderService } from '../../selection/selection-render.service';-import { SheetSkeletonManagerService } from '../../sheet-skeleton-manager.service';import { ISheetClipboardService, SheetClipboardService } from '../clipboard.service';+import { SheetSkeletonManagerService } from '../../sheet-skeleton-manager.service';const cellData = {0: {@@ -517,6 +519,7 @@ export class testPlatformService {isLinux: boolean = false;}+// eslint-disable-next-line max-lines-per-functionexport function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]) {const univer = new Univer();const injector = univer.__getInjector();@@ -537,7 +540,6 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: De}override onStarting(injector: Injector): void {- injector.add([SheetSkeletonManagerService]);injector.add([SelectionManagerService]);injector.add([IClipboardInterfaceService, { useClass: BrowserClipboardService, lazy: true }]);injector.add([ISheetClipboardService, { useClass: SheetClipboardService }]);@@ -552,8 +554,10 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: Deinjector.add([ISelectionRenderService, { useClass: SelectionRenderService }]);injector.add([INotificationService, { useClass: testNotificationService }]);injector.add([IPlatformService, { useClass: testPlatformService }]);+// Because SheetClipboardController is initialized in the rendered life cycle, here we need to initialize it manuallyconst sheetClipboardController = injector.createInstance(SheetClipboardController);+injector.add([SheetClipboardController, { useValue: sheetClipboardController }]);injector.add([SheetInterceptorService]);injector.add([CalculateFormulaService]);@@ -579,6 +583,30 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: Deconst logService = get(ILogService);logService.setLogLevel(LogLevel.SILENT); // change this to `LogLevel.VERBOSE` to debug tests via logs+ // NOTE: This is pretty hack for the test. But with these hacks we can avoid to create+ // real canvas-environment in univerjs/sheets-ui. If some we have to do that, this hack could be removed.+ const fakeSheetSkeletonManagerService = new SheetSkeletonManagerService({+ unit: sheet,+ unitId: 'test',+ type: UniverInstanceType.UNIVER_SHEET,+ engine: null as any,+ scene: null as any,+ mainComponent: null as any,+ components: null as any,+ isMainScene: true,+ }, injector);++ injector.add([SheetSkeletonManagerService, { useValue: fakeSheetSkeletonManagerService }]);+ injector.get(IRenderManagerService).addRender('test', {+ unitId: 'test',+ engine: new DisposableCollection() as any,+ scene: new DisposableCollection() as any,+ mainComponent: null as any,+ components: new Map(),+ isMainScene: true,+ with: injector.get.bind(injector),+ });+return {univer,get,diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.tsindex e4b232e2f2..a9f242246b 100644--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts@@ -42,6 +42,7 @@ import { createIdentifier, Inject, Injector } from '@wendellhu/redi';import { BehaviorSubject } from 'rxjs';import { PastePluginLark, PastePluginUniver, PastePluginWord } from '@univerjs/docs-ui';+import { IRenderManagerService } from '@univerjs/engine-render';import { IMarkSelectionService } from '../mark-selection/mark-selection.service';import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';import type { IDiscreteRange } from '../../controllers/utils/range-tools';@@ -120,17 +121,18 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard@IUndoRedoService private readonly _undoRedoService: IUndoRedoService,@ICommandService private readonly _commandService: ICommandService,@IMarkSelectionService private readonly _markSelectionService: IMarkSelectionService,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@INotificationService private readonly _notificationService: INotificationService,@IPlatformService private readonly _platformService: IPlatformService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@Inject(LocaleService) private readonly _localeService: LocaleService,@Inject(ErrorService) private readonly _errorService: ErrorService,@Inject(Injector) private readonly _injector: Injector) {super();this._htmlToUSM = new HtmlToUSMService({- getCurrentSkeleton: () => this._sheetSkeletonManagerService.getCurrent(),+ getCurrentSkeleton: () => this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)?.getCurrent(),});+this._usmToHtml = new USMToHtmlService();this._copyContentCache = new CopyContentCache();@@ -388,13 +390,11 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard}private async _pasteHTML(html: string, pasteType: string): Promise<boolean> {- // this._logService.log('[SheetClipboardService]', 'pasting html content', html);-const copyId = extractId(html);-if (copyId && this._copyContentCache.get(copyId)) {return this._pasteInternal(copyId, pasteType);}+return this._pasteExternal(html, pasteType);}diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.tsindex bce1db2073..9ac5ba6dfc 100644--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts@@ -101,36 +101,36 @@ export class HtmlToUSMService {this.pluginList.push(plugin);}- private styleCache: Map<ChildNode, ITextStyle> = new Map();+ private _styleCache: Map<ChildNode, ITextStyle> = new Map();- private styleRules: IStyleRule[] = [];+ private _styleRules: IStyleRule[] = [];- private afterProcessRules: IAfterProcessRule[] = [];+ private _afterProcessRules: IAfterProcessRule[] = [];- private htmlElement: HTMLIFrameElement;+ private _htmlElement: HTMLIFrameElement;- private getCurrentSkeleton: () => Nullable<ISheetSkeletonManagerParam>;+ private _getCurrentSkeleton: () => Nullable<ISheetSkeletonManagerParam>;constructor(props: IHtmlToUSMServiceProps) {- this.getCurrentSkeleton = props.getCurrentSkeleton;- this.htmlElement = document.createElement('iframe');- this.htmlElement.style.display = 'none';- document.body.appendChild(this.htmlElement);- hideIframe(this.htmlElement);+ this._getCurrentSkeleton = props.getCurrentSkeleton;+ this._htmlElement = document.createElement('iframe');+ this._htmlElement.style.display = 'none';+ document.body.appendChild(this._htmlElement);+ hideIframe(this._htmlElement);}convert(html: string): IUniverSheetCopyDataModel {- if (this.htmlElement.contentDocument) {- this.htmlElement.contentDocument.open();- this.htmlElement.contentDocument.write(html);- this.htmlElement.contentDocument.close();+ if (this._htmlElement.contentDocument) {+ this._htmlElement.contentDocument.open();+ this._htmlElement.contentDocument.write(html);+ this._htmlElement.contentDocument.close();}html = html.replace(/<!--[\s\S]*?-->/g, '').replace(/<style[\s\S]*?<\/style>/g, '');const pastePlugin = HtmlToUSMService.pluginList.find((plugin) => plugin.checkPasteType(html));if (pastePlugin) {- this.styleRules = [...pastePlugin.stylesRules];- this.afterProcessRules = [...pastePlugin.afterProcessRules];+ this._styleRules = [...pastePlugin.stylesRules];+ this._afterProcessRules = [...pastePlugin.afterProcessRules];}const valueMatrix = new ObjectMatrix<ICellDataWithSpanInfo>();const dom = parseToDom(html);@@ -226,7 +226,7 @@ export class HtmlToUSMService {const valueMatrix = new ObjectMatrix<ICellDataWithSpanInfo>();const colProperties = parseColGroup(html) ?? [];const { rowProperties = [] } = parseTableRows(html);- const parsedCellMatrix = parseTableByHtml(this.htmlElement, this.getCurrentSkeleton()?.skeleton);+ const parsedCellMatrix = parseTableByHtml(this._htmlElement, this._getCurrentSkeleton()?.skeleton);parsedCellMatrix &&parsedCellMatrix.forValue((row, col, value) => {let style = handleStringToStyle(undefined, value.style);@@ -270,7 +270,7 @@ export class HtmlToUSMService {}private _generateDocumentDataModelSnapshot(snapshot: Partial<IDocumentData>) {- const currentSkeleton = this.getCurrentSkeleton();+ const currentSkeleton = this._getCurrentSkeleton();if (currentSkeleton == null) {return null;}@@ -298,8 +298,8 @@ export class HtmlToUSMService {const text = node.nodeValue?.replace(/[\r\n]/g, '');let style;- if (parent && this.styleCache.has(parent)) {- style = this.styleCache.get(parent);+ if (parent && this._styleCache.has(parent)) {+ style = this._styleCache.get(parent);}const newDoc: IDocumentBody = {dataStream: '',@@ -324,19 +324,19 @@ export class HtmlToUSMService {if (node.nodeName === 'STYLE') {continue;}- const parentStyles = parent ? this.styleCache.get(parent) : {};- const styleRule = this.styleRules.find(({ filter }) => matchFilter(node as HTMLElement, filter));+ const parentStyles = parent ? this._styleCache.get(parent) : {};+ const styleRule = this._styleRules.find(({ filter }) => matchFilter(node as HTMLElement, filter));const nodeStyles = styleRule? styleRule.getStyle(node as HTMLElement): extractNodeStyle(node as HTMLElement);- this.styleCache.set(node, { ...parentStyles, ...nodeStyles });+ this._styleCache.set(node, { ...parentStyles, ...nodeStyles });const { childNodes } = node;this.process(node, childNodes, doc, tables);- const afterProcessRule = this.afterProcessRules.find(({ filter }) =>+ const afterProcessRule = this._afterProcessRules.find(({ filter }) =>matchFilter(node as HTMLElement, filter));@@ -348,7 +348,7 @@ export class HtmlToUSMService {}dispose() {- document.body.removeChild(this.htmlElement);+ document.body.removeChild(this._htmlElement);}}diff --git a/packages/sheets-ui/src/services/drag-manager.service.ts b/packages/sheets-ui/src/services/drag-manager.service.tsindex 14039e4e4a..7946337b04 100644--- a/packages/sheets-ui/src/services/drag-manager.service.ts+++ b/packages/sheets-ui/src/services/drag-manager.service.ts@@ -46,7 +46,6 @@ export class DragManagerService extends Disposable {constructor(@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,@Inject(ScrollManagerService) private readonly _scrollManagerService: ScrollManagerService,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService) {super();@@ -76,9 +75,8 @@ export class DragManagerService extends Disposable {}const worksheet = workbook.getActiveSheet();- const skeletonParam = this._sheetSkeletonManagerService.getCurrent();const currentRender = this._renderManagerService.getRenderById(workbook.getUnitId());-+ const skeletonParam = currentRender?.with(SheetSkeletonManagerService)?.getCurrent();const scrollInfo = this._scrollManagerService.getCurrentScroll();if (!skeletonParam || !scrollInfo || !currentRender) return;diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.tsindex a4d50becbc..78c4fce70c 100644--- a/packages/sheets-ui/src/services/editor-bridge.service.ts+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts@@ -28,7 +28,7 @@ import {UniverInstanceType,} from '@univerjs/core';import type { Engine, IDocumentLayoutObject, Scene } from '@univerjs/engine-render';-import { convertTextRotation, DeviceInputEventType, getCanvasOffsetByEngine } from '@univerjs/engine-render';+import { convertTextRotation, DeviceInputEventType, getCanvasOffsetByEngine, IRenderManagerService } from '@univerjs/engine-render';import type { ISheetLocation } from '@univerjs/sheets';import { IEditorService } from '@univerjs/ui';import type { KeyCode } from '@univerjs/ui';@@ -119,14 +119,14 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServprivate readonly _afterVisible$ = new BehaviorSubject<IEditorBridgeServiceVisibleParam>(this._visible);readonly afterVisible$ = this._afterVisible$.asObservable();- interceptor = new InterceptorManager({+ readonly interceptor = new InterceptorManager({BEFORE_CELL_EDIT,AFTER_CELL_EDIT,AFTER_CELL_EDIT_ASYNC,});constructor(- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,@Inject(ThemeService) private readonly _themeService: ThemeService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,@@ -182,14 +182,11 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServreturn;}- const currentSkeleton = this._sheetSkeletonManagerService.getCurrent();-- if (currentSkeleton == null) {+ const skeleton = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)?.getCurrentSkeleton();+ if (skeleton == null) {return;}- const { skeleton } = currentSkeleton;-const { primary, unitId, sheetId, scene, engine } = currentEditCell;const { startRow, startColumn } = primary;const primaryWithCoord = this._selectionRenderService.attachPrimaryWithCoord(primary);diff --git a/packages/sheets-ui/src/services/hover-manager.service.ts b/packages/sheets-ui/src/services/hover-manager.service.tsindex c3ee3dc7a0..1ca5342413 100644--- a/packages/sheets-ui/src/services/hover-manager.service.ts+++ b/packages/sheets-ui/src/services/hover-manager.service.ts@@ -50,7 +50,6 @@ export class HoverManagerService extends Disposable {constructor(@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,@Inject(ScrollManagerService) private readonly _scrollManagerService: ScrollManagerService,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService) {super();@@ -81,9 +80,8 @@ export class HoverManagerService extends Disposable {}const worksheet = workbook.getActiveSheet();- const skeletonParam = this._sheetSkeletonManagerService.getCurrent();const currentRender = this._renderManagerService.getRenderById(workbook.getUnitId());-+ const skeletonParam = currentRender?.with(SheetSkeletonManagerService).getUnitSkeleton(workbook.getUnitId(), worksheet.getSheetId());const scrollInfo = this._scrollManagerService.getCurrentScroll();if (!skeletonParam || !scrollInfo || !currentRender) return;diff --git a/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts b/packages/sheets-ui/src/services/mark-selection/mark-selection.service.tsindex 6a193f6c9b..81d9000906 100644--- a/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts+++ b/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts@@ -51,7 +51,6 @@ export class MarkSelectionService extends Disposable implements IMarkSelectionSe@IUniverInstanceService private readonly _currentService: IUniverInstanceService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,@Inject(ThemeService) private readonly _themeService: ThemeService) {super();@@ -86,11 +85,14 @@ export class MarkSelectionService extends Disposable implements IMarkSelectionSe}const { style } = selection;- const { scene } = this._renderManagerService.getRenderById(unitId) || {};+ const renderUnit = this._renderManagerService.getRenderById(unitId);+ const scene = renderUnit?.scene;const { rangeWithCoord, primaryWithCoord } =this._selectionRenderService.attachSelectionWithCoord(selection);- const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;++ const skeleton = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)?.getCurrentSkeleton();if (!scene || !skeleton) return;+const { rowHeaderWidth, columnHeaderHeight } = skeleton;const control = new SelectionShape(scene, zIndex, false, this._themeService);control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);diff --git a/packages/sheets-ui/src/services/permission/permission-render.service.ts b/packages/sheets-ui/src/services/permission/permission-render.service.tsdeleted file mode 100644index 4ca9c72016..0000000000--- a/packages/sheets-ui/src/services/permission/permission-render.service.ts+++ /dev/null@@ -1,82 +0,0 @@-/**- * 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 { Inject } from '@wendellhu/redi';-import { IRenderManagerService } from '@univerjs/engine-render';-import type { Spreadsheet } from '@univerjs/engine-render';-import { throttleTime } from 'rxjs/operators';-import type { Workbook } from '@univerjs/core';-import { Disposable, IPermissionService, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';-import { merge } from 'rxjs';-import { RangeProtectionRuleModel } from '@univerjs/sheets';-import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';-import { RANGE_PROTECTION_CAN_NOT_VIEW_RENDER_EXTENSION_KEY, RANGE_PROTECTION_CAN_VIEW_RENDER_EXTENSION_KEY, RangeProtectionCanNotViewRenderExtension, RangeProtectionCanViewRenderExtension } from '../../views/permission/extensions/range-protection.render';--@OnLifecycle(LifecycleStages.Ready, PermissionRenderService)-export class PermissionRenderService extends Disposable {- private _rangeProtectionCanViewRenderExtension = new RangeProtectionCanViewRenderExtension();- private _rangeProtectionCanNotViewRenderExtension = new RangeProtectionCanNotViewRenderExtension();- constructor(- @Inject(IRenderManagerService) private _renderManagerService: IRenderManagerService,- @Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,- @Inject(RangeProtectionRuleModel) private _rangeProtectionRuleModel: RangeProtectionRuleModel,- @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService,- @IPermissionService private _permissionService: IPermissionService- ) {- super();- this._initRender();- this._initSkeleton();- this._rangeProtectionRuleModel.ruleChange$.subscribe((info) => {- if ((info.oldRule?.id && this._rangeProtectionCanViewRenderExtension.renderCache.has(info.oldRule.id)) || this._rangeProtectionCanViewRenderExtension.renderCache.has(info.rule.id)) {- this._rangeProtectionCanViewRenderExtension.clearCache();- }- if ((info.oldRule?.id && this._rangeProtectionCanNotViewRenderExtension.renderCache.has(info.oldRule.id)) || this._rangeProtectionCanNotViewRenderExtension.renderCache.has(info.rule.id)) {- this._rangeProtectionCanNotViewRenderExtension.clearCache();- }- });- }-- private _initRender() {- const register = (renderId: string) => {- const render = renderId && this._renderManagerService.getRenderById(renderId);- const spreadsheetRender = render && render.mainComponent as Spreadsheet;- if (spreadsheetRender) {- if (!spreadsheetRender.getExtensionByKey(RANGE_PROTECTION_CAN_VIEW_RENDER_EXTENSION_KEY)) {- spreadsheetRender.register(this._rangeProtectionCanViewRenderExtension);- }- if (!spreadsheetRender.getExtensionByKey(RANGE_PROTECTION_CAN_NOT_VIEW_RENDER_EXTENSION_KEY)) {- spreadsheetRender.register(this._rangeProtectionCanNotViewRenderExtension);- }- }- };- this.disposeWithMe(this._renderManagerService.currentRender$.subscribe((renderId) => {- renderId && register(renderId);- }));- const workbook = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SHEET)!;- if (workbook) {- register(workbook.getUnitId());- }- }-- private _initSkeleton() {- const markDirtySkeleton = () => {- this._sheetSkeletonManagerService.reCalculate();- const unitId = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();- this._renderManagerService.getRenderById(unitId)?.mainComponent?.makeDirty();- };- this.disposeWithMe(merge(this._permissionService.permissionPointUpdate$.pipe(throttleTime(300, undefined, { trailing: true })), this._rangeProtectionRuleModel.ruleChange$).pipe().subscribe(markDirtySkeleton));- }-}diff --git a/packages/sheets-ui/src/services/selection/selection-render.service.ts b/packages/sheets-ui/src/services/selection/selection-render.service.tsindex 6d220004ec..f627de8ff6 100644--- a/packages/sheets-ui/src/services/selection/selection-render.service.ts+++ b/packages/sheets-ui/src/services/selection/selection-render.service.ts@@ -28,9 +28,9 @@ import type {Nullable,Observer,} from '@univerjs/core';-import { createInterceptorKey, InterceptorManager, makeCellToSelection, RANGE_TYPE, ThemeService } from '@univerjs/core';+import { createInterceptorKey, InterceptorManager, IUniverInstanceService, makeCellToSelection, RANGE_TYPE, ThemeService, UniverInstanceType } from '@univerjs/core';import type { IMouseEvent, IPointerEvent, Scene, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';-import { ScrollTimer, ScrollTimerType, Vector2 } from '@univerjs/engine-render';+import { IRenderManagerService, ScrollTimer, ScrollTimerType, Vector2 } from '@univerjs/engine-render';import type { ISelectionStyle, ISelectionWithCoordAndStyle, ISelectionWithStyle } from '@univerjs/sheets';import { getNormalSelectionStyle } from '@univerjs/sheets';import { IShortcutService } from '@univerjs/ui';@@ -221,7 +221,8 @@ export class SelectionRenderService implements ISelectionRenderService {constructor(@Inject(ThemeService) private readonly _themeService: ThemeService,@IShortcutService private readonly _shortcutService: IShortcutService,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,+ @IUniverInstanceService private readonly _instanceService: IUniverInstanceService,@Inject(Injector) private readonly _injector: Injector) {this._selectionStyle = getNormalSelectionStyle(this._themeService);@@ -408,7 +409,8 @@ export class SelectionRenderService implements ISelectionRenderService {}private _getFreeze() {- const freeze = this._sheetSkeletonManagerService.getCurrent()?.skeleton.getWorksheetConfig().freeze;+ const freeze = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)+ ?.getCurrent()?.skeleton.getWorksheetConfig().freeze;return freeze;}@@ -796,7 +798,7 @@ export class SelectionRenderService implements ISelectionRenderService {let scrollOffsetY = newMoveOffsetY;const currentSelection = this.getActiveSelection();- const freeze = this._sheetSkeletonManagerService.getCurrent()?.skeleton.getWorksheetConfig().freeze;+ const freeze = this._getFreeze();const selection = currentSelection?.model;const endViewport =@@ -1020,7 +1022,7 @@ export class SelectionRenderService implements ISelectionRenderService {return;}- const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;+ const skeleton = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)?.getCurrent()?.skeleton;if (skeleton == null) {return;}@@ -1088,7 +1090,7 @@ export class SelectionRenderService implements ISelectionRenderService {return false;}- const { rangeWithCoord: moveRangeWithCoord, primaryWithCoord: movePrimaryWithCoord } = selectionData;+ const { rangeWithCoord: moveRangeWithCoord } = selectionData;const {startRow: moveStartRow,@@ -1173,19 +1175,16 @@ export class SelectionRenderService implements ISelectionRenderService {if (scene == null) {return;}+const mainScene = scene.getEngine()?.activeScene;if (mainScene == null || mainScene === scene) {return;}+mainScene.onPointerDownObserver.remove(this._cancelDownObserver);mainScene.onPointerUpObserver.remove(this._cancelUpObserver);- this._cancelDownObserver = mainScene.onPointerDownObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {- this._endSelection();- });-- this._cancelUpObserver = mainScene.onPointerUpObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {- this._endSelection();- });+ this._cancelDownObserver = mainScene.onPointerDownObserver.add(() => this._endSelection());+ this._cancelUpObserver = mainScene.onPointerUpObserver.add(() => this._endSelection());}private _getSelectedRangeWithMerge(diff --git a/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts b/packages/sheets-ui/src/services/sheet-skeleton-manager.service.tsindex 1feaf426fd..0db09dbe49 100644--- a/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts+++ b/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts@@ -15,14 +15,13 @@*/import type { Nullable, Workbook, Worksheet } from '@univerjs/core';-import { IUniverInstanceService } from '@univerjs/core';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { SpreadsheetSkeleton } from '@univerjs/engine-render';import type { IDisposable } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';import { BehaviorSubject } from 'rxjs';export interface ISheetSkeletonManagerParam {- unitId: string;sheetId: string;skeleton: SpreadsheetSkeleton;dirty: boolean;@@ -30,25 +29,22 @@ export interface ISheetSkeletonManagerParam {}export interface ISheetSkeletonManagerSearch {- unitId: string;sheetId: string;commandId?: string; // WTF: why?}-// TODO@wzhudev: this should be moved to a `RenderUnit` as well.-/*** This service manages the drawing of the sheet's viewModel (skeleton).+ ** Each time there is a content change, it will trigger the viewModel of the render to recalculate.+ ** Each application and sub-table has its own viewModel (skeleton).+ ** The viewModel is also a temporary storage variable, which does not need to be persisted,* so it is managed uniformly through the service.- *- * @todo RenderUnit - We should move this to RenderUnit as well after all dependents have been moved.*/-export class SheetSkeletonManagerService implements IDisposable {+export class SheetSkeletonManagerService implements IDisposable, IRenderModule {private _currentSkeleton: ISheetSkeletonManagerSearch = {- unitId: '',sheetId: '',};@@ -64,7 +60,7 @@ export class SheetSkeletonManagerService implements IDisposable {readonly currentSkeletonBefore$ = this._currentSkeletonBefore$.asObservable();constructor(- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ private readonly _context: IRenderContext<Workbook>,@Inject(Injector) private readonly _injector: Injector) {// empty@@ -76,60 +72,37 @@ export class SheetSkeletonManagerService implements IDisposable {this._sheetSkeletonParam = [];}+ getCurrentSkeleton(): SpreadsheetSkeleton {+ return this.getCurrent()!.skeleton;+ }+/** @deprecated */getCurrent(): Nullable<ISheetSkeletonManagerParam> {return this._getSkeleton(this._currentSkeleton);}getUnitSkeleton(unitId: string, sheetId: string): Nullable<ISheetSkeletonManagerParam> {- return this._getSkeleton({ unitId, sheetId });+ return this._getSkeleton({ sheetId });}setCurrent(searchParam: ISheetSkeletonManagerSearch): Nullable<ISheetSkeletonManagerParam> {this._setCurrent(searchParam);}- removeSkeleton(searchParam: Pick<ISheetSkeletonManagerSearch, 'unitId'>) {- const index = this._sheetSkeletonParam.findIndex((param) => param.unitId === searchParam.unitId);- if (index !== -1) {- const skeletonParam = this._sheetSkeletonParam[index];- skeletonParam.skeleton.dispose();-- this._sheetSkeletonParam.splice(index, 1);- this._currentSkeletonBefore$.next(null);- this._currentSkeleton$.next(null);- }- }-- private _compareSearch(param1: Nullable<ISheetSkeletonManagerSearch>, param2: Nullable<ISheetSkeletonManagerSearch>) {- if (param1 == null || param2 == null) {- return false;- }-- if (param1.commandId === param2.commandId && param1.sheetId === param2.sheetId && param1.unitId === param2.unitId) {- return true;- }- return false;- }-private _setCurrent(searchParam: ISheetSkeletonManagerSearch): Nullable<ISheetSkeletonManagerParam> {const param = this._getSkeleton(searchParam);if (param != null) {this._reCalculate(param);} else {- const { unitId, sheetId } = searchParam;-- const workbook = this._univerInstanceService.getUniverSheetInstance(searchParam.unitId);-- const worksheet = workbook?.getSheetBySheetId(searchParam.sheetId);- if (worksheet == null || workbook == null) {+ const { sheetId } = searchParam;+ const workbook = this._context.unit;+ const worksheet = workbook.getSheetBySheetId(searchParam.sheetId);+ if (worksheet == null) {return;}- const skeleton = this._buildSkeleton(worksheet, workbook);-+ const skeleton = this._buildSkeleton(worksheet);this._sheetSkeletonParam.push({- unitId,sheetId,skeleton,dirty: false,@@ -159,10 +132,6 @@ export class SheetSkeletonManagerService implements IDisposable {param.skeleton.calculate();}- makeDirtyCurrent(state: boolean = true) {- this.makeDirty(this._currentSkeleton, state);- }-makeDirty(searchParm: ISheetSkeletonManagerSearch, state: boolean = true) {const param = this._getSkeleton(searchParm);if (param == null) {@@ -177,15 +146,14 @@ export class SheetSkeletonManagerService implements IDisposable {return skeleton.skeleton;}- const workbook = this._univerInstanceService.getUniverSheetInstance(searchParam.unitId);- const worksheet = workbook?.getSheetBySheetId(searchParam.sheetId);- if (!worksheet || !workbook) {+ const workbook = this._context.unit;+ const worksheet = workbook.getSheetBySheetId(searchParam.sheetId);+ if (!worksheet) {return;}- const newSkeleton = this._buildSkeleton(worksheet, workbook);+ const newSkeleton = this._buildSkeleton(worksheet);this._sheetSkeletonParam.push({- unitId: searchParam.unitId,sheetId: searchParam.sheetId,skeleton: newSkeleton,dirty: false,@@ -195,10 +163,7 @@ export class SheetSkeletonManagerService implements IDisposable {}private _getSkeleton(searchParm: ISheetSkeletonManagerSearch): Nullable<ISheetSkeletonManagerParam> {- const item = this._sheetSkeletonParam.find(- (param) => param.unitId === searchParm.unitId && param.sheetId === searchParm.sheetId- );-+ const item = this._sheetSkeletonParam.find((param) => param.sheetId === searchParm.sheetId);if (item != null) {item.commandId = searchParm.commandId;}@@ -206,14 +171,14 @@ export class SheetSkeletonManagerService implements IDisposable {return item;}- private _buildSkeleton(worksheet: Worksheet, workbook: Workbook) {+ private _buildSkeleton(worksheet: Worksheet) {const config = worksheet.getConfig();const spreadsheetSkeleton = this._injector.createInstance(SpreadsheetSkeleton,worksheet,config,worksheet.getCellMatrix(),- workbook.getStyles()+ this._context.unit.getStyles());return spreadsheetSkeleton;diff --git a/packages/sheets-ui/src/services/sheets-render.service.ts b/packages/sheets-ui/src/services/sheets-render.service.tsnew file mode 100644index 0000000000..3e1cf129a5--- /dev/null+++ b/packages/sheets-ui/src/services/sheets-render.service.ts@@ -0,0 +1,109 @@+/**+ * 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 { Workbook } from '@univerjs/core';+import {+ IContextService,+ IUniverInstanceService,+ LifecycleStages,+ OnLifecycle,+ RxDisposable,+ toDisposable,+ UniverInstanceType,+} from '@univerjs/core';+import { IRenderManagerService, RENDER_RAW_FORMULA_KEY, Spreadsheet } from '@univerjs/engine-render';+import type { IDisposable } from '@wendellhu/redi';+import { distinctUntilChanged, takeUntil } from 'rxjs';++/**+ * This controller is responsible for managing units of a specific kind to be rendered on the canvas.+ */+@OnLifecycle(LifecycleStages.Ready, SheetsRenderService)+export class SheetsRenderService extends RxDisposable {+ private _skeletonChangeMutations = new Set<string>();++ constructor(+ @IContextService private readonly _contextService: IContextService,+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService+ ) {+ super();++ // It should be initialized after all other plugins are ready.+ Promise.resolve().then(() => this._init());+ }++ /**+ * Register a mutation id that will trigger the skeleton change.+ *+ * @param mutationId the id of the mutation+ * @returns a disposable to unregister the mutation+ */+ registerSkeletonChangingMutations(mutationId: string): IDisposable {+ if (this._skeletonChangeMutations.has(mutationId)) {+ throw new Error(`[SheetsRenderService]: the mutationId ${mutationId} has already been registered!`);+ }++ this._skeletonChangeMutations.add(mutationId);+ return toDisposable(() => this._skeletonChangeMutations.delete(mutationId));+ }++ checkMutationShouldTriggerRerender(id: string): boolean {+ return this._skeletonChangeMutations.has(id);+ }++ private _init() {+ this._initWorkbookListener();+ this._initContextListener();+ }++ private _initWorkbookListener(): void {+ this._univerInstanceService.getTypeOfUnitAdded$<Workbook>(UniverInstanceType.UNIVER_SHEET)+ .pipe(takeUntil(this.dispose$))+ .subscribe((workbook) => this._createRenderer(workbook));+ this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET)+ .forEach((workbook) => this._createRenderer(workbook));++ this._univerInstanceService.getTypeOfUnitDisposed$<Workbook>(UniverInstanceType.UNIVER_SHEET)+ .pipe(takeUntil(this.dispose$))+ .subscribe((workbook) => this._disposeRenderer(workbook));+ }++ private _createRenderer(workbook: Workbook): void {+ const unitId = workbook.getUnitId();+ this._renderManagerService.createRender(unitId);+ this._renderManagerService.setCurrent(unitId); // NOTE@wzhudev: maybe not in uni mode+ }++ private _disposeRenderer(workbook: Workbook): void {+ const unitId = workbook.getUnitId();++ this._renderManagerService.removeRender(unitId);+ }++ private _initContextListener(): void {+ // If we toggle the raw formula, we need to refresh all spreadsheets.+ this._contextService.subscribeContextValue$(RENDER_RAW_FORMULA_KEY)+ .pipe(distinctUntilChanged(), takeUntil(this.dispose$))+ .subscribe(() => {+ this._renderManagerService.getRenderAll().forEach((renderer) => {+ if (renderer.mainComponent instanceof Spreadsheet) {+ (renderer.mainComponent as Spreadsheet).makeForceDirty(true);+ }+ });+ });+ }+}diff --git a/packages/sheets-ui/src/sheets-ui-plugin.ts b/packages/sheets-ui/src/sheets-ui-plugin.tsindex 30bc5788aa..b114355456 100644--- a/packages/sheets-ui/src/sheets-ui-plugin.ts+++ b/packages/sheets-ui/src/sheets-ui-plugin.ts@@ -38,7 +38,7 @@ import { HeaderResizeRenderController } from './controllers/render-controllers/himport { HeaderUnhideRenderController } from './controllers/render-controllers/header-unhide.render-controller';import { MarkSelectionRenderController } from './controllers/mark-selection.controller';import { SelectionRenderController } from './controllers/render-controllers/selection.render-controller';-import { SheetRenderController } from './controllers/sheet-render.controller';+import { SheetsRenderService } from './services/sheets-render.service';import type { IUniverSheetsUIConfig } from './controllers/sheet-ui.controller';import { DefaultSheetUiConfig, SheetUIController } from './controllers/sheet-ui.controller';import { StatusBarController } from './controllers/status-bar.controller';@@ -58,7 +58,7 @@ import { ISheetBarService, SheetBarService } from './services/sheet-bar/sheet-baimport { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';import { ShortcutExperienceService } from './services/shortcut-experience.service';import { IStatusBarService, StatusBarService } from './services/status-bar.service';-import { SheetCanvasView } from './views/sheet-canvas-view';+import { SheetRenderController } from './controllers/render-controllers/sheet-render.controller';import { HoverRenderController } from './controllers/hover-render.controller';import { HoverManagerService } from './services/hover-manager.service';import { CellAlertManagerService } from './services/cell-alert-manager.service';@@ -78,12 +78,11 @@ import { DragManagerService } from './services/drag-manager.service';import { SheetPermissionInterceptorClipboardController } from './controllers/permission/sheet-permission-interceptor-clipboard.controller';import { SheetPermissionInterceptorBaseController } from './controllers/permission/sheet-permission-interceptor-base.controller';import { SheetPermissionInitController } from './controllers/permission/sheet-permission-init.controller';-import { SheetPermissionRenderController } from './controllers/permission/sheet-permission-render.controller';+import { SheetPermissionRenderController, SheetPermissionRenderManagerController } from './controllers/permission/sheet-permission-render.controller';import { SheetPermissionInterceptorCanvasRenderController } from './controllers/permission/sheet-permission-interceptor-canvas-render.controller';import { SheetPermissionInterceptorFormulaRenderController } from './controllers/permission/sheet-permission-interceptor-formula-render.controller';import { SheetPermissionPanelModel } from './services/permission/sheet-permission-panel.model';import { SheetPermissionUserManagerService } from './services/permission/sheet-permission-user-list.service';-import { PermissionRenderService } from './services/permission/permission-render.service';import { WorksheetProtectionRenderService } from './services/permission/worksheet-permission-render.service';@DependentOn(UniverSheetsPlugin, UniverUIPlugin)@@ -117,7 +116,8 @@ export class UniverSheetsUIPlugin extends Plugin {[IAutoFillService, { useClass: AutoFillService }],[ScrollManagerService],- [SheetSkeletonManagerService],+ // This would be removed from global injector and moved into RenderUnit provider.+ // [SheetSkeletonManagerService],[ISelectionRenderService, { useClass: SelectionRenderService }],[IStatusBarService, { useClass: StatusBarService }],[IMarkSelectionService, { useClass: MarkSelectionService }],@@ -133,7 +133,7 @@ export class UniverSheetsUIPlugin extends Plugin {[FormulaEditorController],[HeaderFreezeRenderController],[SheetClipboardController],- [SheetRenderController],+ [SheetsRenderService],[SheetUIController,{@@ -149,7 +149,6 @@ export class UniverSheetsUIPlugin extends Plugin {// permission[SheetPermissionPanelModel],[SheetPermissionUserManagerService],- [PermissionRenderService],[WorksheetProtectionRenderService],[SheetPermissionInterceptorClipboardController],[SheetPermissionInterceptorBaseController],@@ -159,9 +158,9 @@ export class UniverSheetsUIPlugin extends Plugin {this._injector.add([- SheetPermissionRenderController,+ SheetPermissionRenderManagerController,{- useFactory: () => this._injector.createInstance(SheetPermissionRenderController, this._config),+ useFactory: () => this._injector.createInstance(SheetPermissionRenderManagerController, this._config),},]@@ -170,14 +169,28 @@ export class UniverSheetsUIPlugin extends Plugin {override onReady(): void {this._markSheetAsFocused();+ this._registerRenderBasics();+ }++ override onRendered(): void {this._registerRenderControllers();}+ private _registerRenderBasics(): void {+ ([+ SheetSkeletonManagerService,+ SheetRenderController,+ ]).forEach((controller) => {+ this.disposeWithMe(this._renderManagerService.registerRenderController(UniverInstanceType.UNIVER_SHEET, controller));+ });+ }++ // We have to let render basics get bootstrapped before. Because some render controllers relies on+ // a correct skeleton when they get loaded.private _registerRenderControllers(): void {([- SheetCanvasView,// https://github.com/dream-num/univer-pro/issues/669- // HeaderMoveRenderController must be initialized before SelectionRenderController.+ // HeaderMoveRenderController(HMRC) must be initialized before SelectionRenderController(SRC).// Before HMRC expected selections remain unchanged when user clicks on the header. If we don't initialize HMRC before SRC,// the selections will be changed by SRC first. Maybe we should merge row/col header related render controllers to one class.HeaderMoveRenderController,@@ -199,9 +212,9 @@ export class UniverSheetsUIPlugin extends Plugin {SheetContextMenuRenderController,EditorBridgeRenderController,- // permissionSheetPermissionInterceptorCanvasRenderController,SheetPermissionInterceptorFormulaRenderController,+ SheetPermissionRenderController,]).forEach((controller) => {this.disposeWithMe(this._renderManagerService.registerRenderController(UniverInstanceType.UNIVER_SHEET, controller));});diff --git a/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx b/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsxindex 279ccd4444..7d5b793580 100644--- a/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx+++ b/packages/sheets-ui/src/views/operate-container/AutoFillPopupMenu.tsx@@ -21,7 +21,7 @@ import { IRenderManagerService } from '@univerjs/engine-render';import { Autofill, CheckMarkSingle, MoreDownSingle } from '@univerjs/icons';import { useDependency } from '@wendellhu/redi/react-bindings';import clsx from 'clsx';-import React, { useCallback, useEffect, useState } from 'react';+import React, { useCallback, useEffect, useMemo, useState } from 'react';import { RefillCommand } from '../../commands/commands/refill.command';import { SetScrollOperation } from '../../commands/operations/scroll.operation';@@ -30,6 +30,7 @@ import { IAutoFillService } from '../../services/auto-fill/auto-fill.service';import { APPLY_TYPE } from '../../services/auto-fill/type';import { ISelectionRenderService } from '../../services/selection/selection-render.service';import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';+import { useActiveWorkbook } from '../../components/hook';import styles from './index.module.less';export interface IAnchorPoint {@@ -51,18 +52,24 @@ const useUpdate = () => {export const AutoFillPopupMenu: React.FC<{}> = () => {const commandService = useDependency(ICommandService);- const sheetSkeletonManagerService = useDependency(SheetSkeletonManagerService);const univerInstanceService = useDependency(IUniverInstanceService);const renderManagerService = useDependency(IRenderManagerService);const selectionRenderService = useDependency(ISelectionRenderService);const autoFillService = useDependency(IAutoFillService);const localeService = useDependency(LocaleService);const [menu, setMenu] = useState<IAutoFillPopupMenuItem[]>([]);-const [visible, setVisible] = useState(false);const [anchor, setAnchor] = useState<IAnchorPoint>({ row: -1, col: -1 });const [selected, setSelected] = useState<APPLY_TYPE>(APPLY_TYPE.SERIES);const [isHovered, setHovered] = useState(false);+ const workbook = useActiveWorkbook();+ const sheetSkeletonManagerService = useMemo(() => {+ if (workbook) {+ return renderManagerService.getRenderById(workbook.getUnitId())?.with(SheetSkeletonManagerService);+ }++ return null;+ }, [workbook, renderManagerService]);const handleMouseEnter = () => {setHovered(true);@@ -84,7 +91,7 @@ export const AutoFillPopupMenu: React.FC<{}> = () => {useEffect(() => {const disposable = toDisposable(- sheetSkeletonManagerService.currentSkeleton$.subscribe((skeleton) => {+ sheetSkeletonManagerService?.currentSkeleton$.subscribe((skeleton) => {if (skeleton) {forceUpdate();}@@ -146,7 +153,7 @@ export const AutoFillPopupMenu: React.FC<{}> = () => {if (!sheetObject) return null;const { scene } = sheetObject;- const skeleton = sheetSkeletonManagerService.getCurrent()?.skeleton;+ const skeleton = sheetSkeletonManagerService?.getCurrentSkeleton();const viewport = selectionRenderService.getViewPort();const scaleX = scene?.scaleX;const scaleY = scene?.scaleY;diff --git a/packages/sheets-ui/src/views/sheet-canvas-view.ts b/packages/sheets-ui/src/views/sheet-canvas-view.tsdeleted file mode 100644index 6d7cac245a..0000000000--- a/packages/sheets-ui/src/views/sheet-canvas-view.ts+++ /dev/null@@ -1,337 +0,0 @@-/**- * 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 { Workbook, Worksheet } from '@univerjs/core';-import { ICommandService, RxDisposable, toDisposable } from '@univerjs/core';-import type { IRenderContext, IRenderController, IWheelEvent, Scene } from '@univerjs/engine-render';-import {- IRenderManagerService,- Layer,- PointerInput,- Rect,- RENDER_CLASS_TYPE,- ScrollBar,- SHEET_VIEWPORT_KEY,- Spreadsheet,- SpreadsheetColumnHeader,- SpreadsheetRowHeader,- Viewport,-} from '@univerjs/engine-render';-import { Inject } from '@wendellhu/redi';-import { BehaviorSubject } from 'rxjs';--import { SetScrollRelativeCommand } from '../commands/commands/set-scroll.command';-import {- SHEET_COMPONENT_HEADER_LAYER_INDEX,- SHEET_COMPONENT_MAIN_LAYER_INDEX,- SHEET_VIEW_KEY,-} from '../common/keys';-import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';--export class SheetCanvasView extends RxDisposable implements IRenderController {- private readonly _fps$ = new BehaviorSubject<string>('');- readonly fps$ = this._fps$.asObservable();-- constructor(- private readonly _context: IRenderContext<Workbook>,- @ICommandService private readonly _commandService: ICommandService,- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService- ) {- super();-- this._addNewRender(this._context.unit);- }-- override dispose(): void {- this._fps$.complete();- }-- private _addNewRender(workbook: Workbook) {- const { scene, engine } = this._context;-- scene.addLayer(new Layer(scene, [], 0), new Layer(scene, [], 2));-- this._addComponent(workbook);-- const should = workbook.getShouldRenderLoopImmediately();- if (should) {- engine.runRenderLoop(() => {- scene.render();- this._fps$.next(Math.round(engine.getFps()).toString());- });- }- }-- private _addComponent(workbook: Workbook) {- const { scene, components } = this._context;-- const worksheet = workbook.getActiveSheet();-- const unitId = workbook.getUnitId();-- const sheetId = worksheet.getSheetId();-- const spreadsheet = new Spreadsheet(SHEET_VIEW_KEY.MAIN);- const _viewMain = this._addViewport(worksheet);-- const spreadsheetRowHeader = new SpreadsheetRowHeader(SHEET_VIEW_KEY.ROW);- const spreadsheetColumnHeader = new SpreadsheetColumnHeader(SHEET_VIEW_KEY.COLUMN);- const SpreadsheetLeftTopPlaceholder = new Rect(SHEET_VIEW_KEY.LEFT_TOP, {- zIndex: 2,- left: -1,- top: -1,- fill: 'rgb(248, 249, 250)',- stroke: 'rgb(217, 217, 217)',- strokeWidth: 1,- });-- this._context.mainComponent = spreadsheet;- components.set(SHEET_VIEW_KEY.MAIN, spreadsheet);- components.set(SHEET_VIEW_KEY.ROW, spreadsheetRowHeader);- components.set(SHEET_VIEW_KEY.COLUMN, spreadsheetColumnHeader);- components.set(SHEET_VIEW_KEY.LEFT_TOP, SpreadsheetLeftTopPlaceholder);-- scene.addObjects([spreadsheet], SHEET_COMPONENT_MAIN_LAYER_INDEX);- scene.addObjects(- [spreadsheetRowHeader, spreadsheetColumnHeader, SpreadsheetLeftTopPlaceholder],- SHEET_COMPONENT_HEADER_LAYER_INDEX- );-- scene.enableLayerCache(SHEET_COMPONENT_MAIN_LAYER_INDEX, SHEET_COMPONENT_HEADER_LAYER_INDEX);- }-- // eslint-disable-next-line max-lines-per-function- private _initViewports(scene: Scene, rowHeader: { width: number }, columnHeader: { height: number }) {- const bufferEdgeX = 100;- const bufferEdgeY = 100;- // window.sc = scene;- const viewMain = new Viewport(SHEET_VIEWPORT_KEY.VIEW_MAIN, scene, {- left: rowHeader.width,- top: columnHeader.height,- bottom: 0,- right: 0,- isWheelPreventDefaultX: true,- isRelativeX: true,- isRelativeY: true,- allowCache: true,- bufferEdgeX,- bufferEdgeY,- });- const viewMainLeftTop = new Viewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP, scene, {- isWheelPreventDefaultX: true,- active: false,- isRelativeX: false,- isRelativeY: false,- allowCache: true,- bufferEdgeX: 0,- bufferEdgeY: 0,- });-- const viewMainLeft = new Viewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT, scene, {- isWheelPreventDefaultX: true,- active: false,- isRelativeX: false,- isRelativeY: true,- allowCache: true,- bufferEdgeX: 0,- bufferEdgeY,- });-- const viewMainTop = new Viewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP, scene, {- isWheelPreventDefaultX: true,- active: false,- isRelativeX: true,- isRelativeY: false,- allowCache: true,- bufferEdgeX,- bufferEdgeY: 0,- });-- const viewRowTop = new Viewport(SHEET_VIEWPORT_KEY.VIEW_ROW_TOP, scene, {- active: false,- isWheelPreventDefaultX: true,- isRelativeX: false,- isRelativeY: false,- });-- const viewRowBottom = new Viewport(SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM, scene, {- left: 0,- top: columnHeader.height,- bottom: 0,- width: rowHeader.width,- isWheelPreventDefaultX: true,- isRelativeX: false,- isRelativeY: true,- });-- const viewColumnLeft = new Viewport(SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT, scene, {- active: false,- isWheelPreventDefaultX: true,- isRelativeX: false,- isRelativeY: false,- });-- const viewColumnRight = new Viewport(SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT, scene, {- left: rowHeader.width,- top: 0,- height: columnHeader.height,- right: 0,- isWheelPreventDefaultX: true,- isRelativeX: true,- isRelativeY: false,- });-- const viewLeftTop = new Viewport(SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP, scene, {- left: 0,- top: 0,- width: rowHeader.width,- height: columnHeader.height,- isWheelPreventDefaultX: true,- isRelativeX: false,- isRelativeY: false,- });-- return {- viewMain,- viewLeftTop,- viewMainLeftTop,- viewMainLeft,- viewMainTop,- viewColumnLeft,- viewRowTop,- viewRowBottom,- viewColumnRight,- };- }-- /**- *- * initViewport & wheel event- * +-----------------+--------------------+-------------------+- * | VIEW_LEFT_TOP | VIEW_COLUMN_LEFT | VIEW_COLUMN_RIGHT |- * +-----------------+--------------------+-------------------+- * | VIEW_ROW_TOP | VIEW_MAIN_LEFT_TOP | VIEW_MAIN_TOP |- * +-----------------+--------------------+-------------------+- * | VIEW_ROW_BOTTOM | VIEW_MAIN_LEFT | VIEW_MAIN |- * +-----------------+--------------------+-------------------+- */-- private _addViewport(worksheet: Worksheet) {- const scene = this._context.scene;- if (scene == null) {- return;- }- const { rowHeader, columnHeader } = worksheet.getConfig();- const { viewMain } = this._initViewports(scene, rowHeader, columnHeader);-- this._initMouseWheel(scene, viewMain);-- // create a scroll bar- const scrollBar = new ScrollBar(viewMain);-- scene.attachControl();-- return viewMain;- }-- // mouse scroll- private _initMouseWheel(scene: Scene, viewMain: Viewport) {- this.disposeWithMe(- toDisposable(- scene.onMouseWheelObserver.add((evt: IWheelEvent, state) => {- if (evt.ctrlKey) {- return;- }-- let offsetX = 0;- let offsetY = 0;-- const isLimitedStore = viewMain.limitedScroll();- if (evt.inputIndex === PointerInput.MouseWheelX) {- const deltaFactor = Math.abs(evt.deltaX);- // let magicNumber = deltaFactor < 40 ? 2 : deltaFactor < 80 ? 3 : 4;- const scrollNum = deltaFactor;- // 展示更多右侧内容,evt.deltaX > 0- // 展示更多左侧内容, evt.deltaX < 0- if (evt.deltaX > 0) {- offsetX = scrollNum;- } else {- offsetX = -scrollNum;- }- this._commandService.executeCommand(SetScrollRelativeCommand.id, { offsetX });-- // 临界点时执行浏览器行为- if (scene.getParent().classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {- if (!isLimitedStore?.isLimitedX) {- state.stopPropagation();- }- } else if (viewMain.isWheelPreventDefaultX) {- evt.preventDefault();- } else if (!isLimitedStore?.isLimitedX) {- evt.preventDefault();- }- }- if (evt.inputIndex === PointerInput.MouseWheelY) {- const deltaFactor = Math.abs(evt.deltaY);- // let magicNumber = deltaFactor < 40 ? 2 : deltaFactor < 80 ? 3 : 4;- let scrollNum = deltaFactor;- if (evt.shiftKey) {- scrollNum *= 3;- if (evt.deltaY > 0) {- offsetX = scrollNum;- } else {- offsetX = -scrollNum;- }- this._commandService.executeCommand(SetScrollRelativeCommand.id, { offsetX });-- // 临界点时执行浏览器行为- if (scene.getParent().classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {- if (!isLimitedStore?.isLimitedX) {- state.stopPropagation();- }- } else if (viewMain.isWheelPreventDefaultX) {- evt.preventDefault();- } else if (!isLimitedStore?.isLimitedX) {- evt.preventDefault();- }- } else {- if (evt.deltaY > 0) {- offsetY = scrollNum;- } else {- offsetY = -scrollNum;- }- this._commandService.executeCommand(SetScrollRelativeCommand.id, { offsetY });-- // 临界点时执行浏览器行为- if (scene.getParent().classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {- if (!isLimitedStore?.isLimitedY) {- state.stopPropagation();- }- } else if (viewMain.isWheelPreventDefaultY) {- evt.preventDefault();- } else if (!isLimitedStore?.isLimitedY) {- evt.preventDefault();- }- }- }-- this._context.scene.makeDirty(true);- })- )- );- }-}diff --git a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx b/packages/ui/src/controllers/ui/ui-desktop.controller.tsxindex 825214e905..24a82b78fe 100644--- a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx+++ b/packages/ui/src/controllers/ui/ui-desktop.controller.tsx@@ -66,7 +66,11 @@ export class DesktopUIController extends Disposable {}});- this._lifecycleService.lifecycle$.pipe(filter((lifecycle) => lifecycle === LifecycleStages.Ready), delay(300), take(1)).subscribe(() => {+ this._lifecycleService.lifecycle$.pipe(+ filter((lifecycle) => lifecycle === LifecycleStages.Ready),+ delay(300),+ take(1)+ ).subscribe(() => {const engine = this._renderManagerService.getFirst()?.engine;engine?.setContainer(canvasElement);this._lifecycleService.stage = LifecycleStages.Rendered;