Skip to content

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

feat(ui): support switching render unit (#4580)

Wenzhao Hu45a1c14bd9da
diff --git a/e2e/visual-comparison/sheets/sheets-switching-render-unit.spec.ts b/e2e/visual-comparison/sheets/sheets-switching-render-unit.spec.ts
new file mode 100644
index 0000000000..da9aa05b50
--- /dev/null
+++ b/e2e/visual-comparison/sheets/sheets-switching-render-unit.spec.ts
@@ -0,0 +1,48 @@
+/**
+ * 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 { chromium, expect, test } from '@playwright/test';
+import { generateSnapshotName } from '../const';
+
+const isCI = !!process.env.CI;
+
+test('ensure switching render unit successful with no errors', async () => {
+ const browser = await chromium.launch({
+ headless: isCI, // Set to false to see the browser window
+ });
+ const context = await browser.newContext({
+ viewport: { width: 1280, height: 720 },
+ deviceScaleFactor: 2, // Set your desired DPR
+ });
+ const page = await context.newPage();
+
+ await page.goto('http://localhost:3000/sheets/');
+ await page.waitForTimeout(2000);
+
+ await page.evaluate(() => window.E2EControllerAPI.loadDemoSheet());
+ await page.waitForTimeout(1000);
+
+ await page.evaluate(() => window.E2EControllerAPI.loadDefaultSheet());
+ const filename = generateSnapshotName('switching-render-unit');
+ const firstScreenshot = await page.screenshot({
+ mask: [
+ page.locator('.univer-headerbar'),
+ page.locator('.univer-defined-name'),
+ ],
+ fullPage: true,
+ });
+ expect(firstScreenshot).toMatchSnapshot(filename, { maxDiffPixels: 50 });
+});
diff --git a/e2e/visual-comparison/sheets/sheets-switching-render-unit.spec.ts-snapshots/switching-render-unit-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-switching-render-unit.spec.ts-snapshots/switching-render-unit-ci-chromium-linux.png
new file mode 100644
index 0000000000..53903187ad
Binary files /dev/null and b/e2e/visual-comparison/sheets/sheets-switching-render-unit.spec.ts-snapshots/switching-render-unit-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts
index b86fe0a748..99bcd099a6 100644
--- a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts
+++ b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts
@@ -43,7 +43,7 @@ test('diff default sheet toolbar', async () => {
],
fullPage: true,
});
- await expect(screenshot).toMatchSnapshot(filename, { maxDiffPixels: 100 });
+ expect(screenshot).toMatchSnapshot(filename, { maxDiffPixels: 100 });
});
test('diff default sheet content', async ({ page }) => {
diff --git a/mockdata/src/sheets/demo/default-workbook-data-demo4.ts b/mockdata/src/sheets/demo/default-workbook-data-demo4.ts
index 885446d5c5..605c274b27 100644
--- a/mockdata/src/sheets/demo/default-workbook-data-demo4.ts
+++ b/mockdata/src/sheets/demo/default-workbook-data-demo4.ts
@@ -62,7 +62,7 @@ const richTextDemo1: IDocumentData = {
};
export const DEFAULT_WORKBOOK_DATA_DEMO4: IWorkbookData = {
- id: 'workbook-01',
+ id: 'workbook-04',
locale: LocaleType.ZH_CN,
name: 'universheet',
sheetOrder: ['sheet-0004'],
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 84b137472e..6f40e38a45 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -105,8 +105,7 @@ export { ConfigService } from './services/config/config.service';
export * from './services/context/context';
export { ContextService, IContextService } from './services/context/context.service';
export { ErrorService, type IError } from './services/error/error.service';
-export { IUniverInstanceService } from './services/instance/instance.service';
-export { UniverInstanceService } from './services/instance/instance.service';
+export { type ICreateUnitOptions, IUniverInstanceService, UniverInstanceService } from './services/instance/instance.service';
export { LifecycleStages } from './services/lifecycle/lifecycle';
export { LifecycleService } from './services/lifecycle/lifecycle.service';
export { ILocalStorageService } from './services/local-storage/local-storage.service';
diff --git a/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts
index 2f51f921e2..3980e2347f 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts
@@ -150,6 +150,9 @@ export function createCommandTestBed(docData?: IDocumentData, dependencies?: Dep
mainComponent: null as any,
components: null as any,
isMainScene: true,
+ activated$: new BehaviorSubject(true),
+ activate: () => {},
+ deactivate: () => {},
}, univerInstanceService);
injector.add([DocSkeletonManagerService, { useValue: fakeDocSkeletonManager as unknown as DocSkeletonManagerService }]);
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
index 62026d5b8b..24e89c4d39 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
@@ -125,9 +125,16 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
this._addComponent();
- engine.runRenderLoop(() => {
- scene.render();
- });
+ const frameFn = () => scene.render();
+ this.disposeWithMe(this._context.activated$.subscribe((activated) => {
+ if (activated) {
+ // TODO: we should attach the context object to the RenderContext object on scene.canvas.
+ engine.runRenderLoop(frameFn);
+ } else {
+ // Stop the render loop when the render unit is deactivated.
+ engine.stopRenderLoop(frameFn);
+ }
+ }));
// Attach scroll event after main viewport created.
this._docSelectionRenderService.__attachScrollEvent();
diff --git a/packages/engine-render/src/engine.ts b/packages/engine-render/src/engine.ts
index c7d1bf5eb7..ae89a2f7bd 100644
--- a/packages/engine-render/src/engine.ts
+++ b/packages/engine-render/src/engine.ts
@@ -14,15 +14,16 @@
* limitations under the License.
*/
-import type { Nullable } from '@univerjs/core';
+import type { IDisposable, Nullable } from '@univerjs/core';
+import type { CURSOR_TYPE } from './basics/const';
import type { IEvent, IKeyboardEvent, IPointerEvent } from './basics/i-events';
import type { ITimeMetric, ITransformChangeState } from './basics/interfaces';
import type { IBasicFrameInfo } from './basics/performance-monitor';
import type { Scene } from './scene';
import { Disposable, EventSubject, toDisposable, Tools } from '@univerjs/core';
import { Observable, shareReplay, Subject } from 'rxjs';
-import { type CURSOR_TYPE, RENDER_CLASS_TYPE } from './basics/const';
+import { RENDER_CLASS_TYPE } from './basics/const';
import { DeviceType, PointerInput } from './basics/i-events';
import { TRANSFORM_CHANGE_OBSERVABLE_TYPE } from './basics/interfaces';
import { PerformanceMonitor } from './basics/performance-monitor';
@@ -298,20 +299,50 @@ export class Engine extends Disposable {
return this.getCanvas().getPixelRatio();
}
- setContainer(elem: HTMLElement, resize = true) {
- if (this._container === elem) {
+ private _resizeListenerDisposable: IDisposable | undefined;
+
+ /**
+ * Mount the canvas to the element so it would be rendered on UI.
+ * @param {HTMLElement} element - The element the canvas will mount on.
+ * @param {true} [resize] If should perform resize when mounted and observe resize event.
+ */
+ mount(element: HTMLElement, resize = true): void {
+ this.setContainer(element, resize);
+ }
+
+ /**
+ * Unmount the canvas without disposing it so it can be mounted again.
+ */
+ unmount(): void {
+ this._clearResizeListener();
+
+ if (!this._container) {
+ throw new Error('[Engine]: cannot unmount when container is not set!');
+ }
+
+ this._container.removeChild(this.getCanvasElement());
+ this._container = null;
+ }
+
+ /**
+ * Mount the canvas to the element so it would be rendered on UI.
+ * @deprecated Please use `mount` instead.
+ * @param {HTMLElement} element - The element the canvas will mount on.
+ * @param {true} [resize] If should perform resize when mounted and observe resize event.
+ */
+ setContainer(element: HTMLElement, resize = true) {
+ if (this._container === element) {
return;
}
- this._container = elem;
+ this._container = element;
this._container.appendChild(this.getCanvasElement());
+ this._clearResizeListener();
+
if (resize) {
this.resize();
- this._resizeObserver?.unobserve(this._container as HTMLElement);
- this._resizeObserver = null;
-
let timer: number | undefined;
this._resizeObserver = new ResizeObserver(() => {
if (!timer) {
@@ -323,13 +354,18 @@ export class Engine extends Disposable {
});
this._resizeObserver.observe(this._container);
- this.disposeWithMe(() => {
- this._resizeObserver?.unobserve(this._container as HTMLElement);
+ this._resizeListenerDisposable = toDisposable(() => {
+ this._resizeObserver!.unobserve(this._container as HTMLElement);
if (timer !== undefined) window.cancelIdleCallback(timer);
});
}
}
+ private _clearResizeListener(): void {
+ this._resizeListenerDisposable?.dispose();
+ this._resizeListenerDisposable = undefined;
+ }
+
resize() {
if (!this._container) {
return;
@@ -408,7 +444,7 @@ export class Engine extends Disposable {
this._beginFrame$.complete();
this._endFrame$.complete();
- this._resizeObserver?.disconnect();
+ this._clearResizeListener();
this._container = null;
}
diff --git a/packages/engine-render/src/render-manager/render-manager.service.ts b/packages/engine-render/src/render-manager/render-manager.service.ts
index b20d6f279c..92432104cb 100644
--- a/packages/engine-render/src/render-manager/render-manager.service.ts
+++ b/packages/engine-render/src/render-manager/render-manager.service.ts
@@ -21,17 +21,18 @@ import type { DocComponent } from '../components/docs/doc-component';
import type { SheetComponent } from '../components/sheets/sheet-component';
import type { Slide } from '../components/slides/slide';
+import type { IRender } from './render-unit';
import { createIdentifier, Disposable, Inject, Injector, IUniverInstanceService, remove, toDisposable, UniverInstanceType } from '@univerjs/core';
import { BehaviorSubject, Subject } from 'rxjs';
import { Engine } from '../engine';
import { Scene } from '../scene';
-import { type IRender, RenderUnit } from './render-unit';
+import { RenderUnit } from './render-unit';
export type RenderComponentType = SheetComponent | DocComponent | Slide | BaseObject;
export interface IRenderManagerService extends IDisposable {
- /** @deprecated */
currentRender$: Observable<Nullable<string>>;
+ getCurrent(): Nullable<IRender>;
addRender(unitId: string, renderer: IRender): void;
@@ -71,8 +72,6 @@ export interface IRenderManagerService extends IDisposable {
created$: Observable<IRender>;
disposed$: Observable<string>;
- /** @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>;
@@ -332,7 +331,6 @@ export class RenderManagerService extends Disposable implements IRenderManagerSe
setCurrent(unitId: string): void {
this._currentUnitId = unitId;
-
this._currentRender$.next(unitId);
}
diff --git a/packages/engine-render/src/render-manager/render-unit.ts b/packages/engine-render/src/render-manager/render-unit.ts
index 5aac810d45..31d9c6e1b2 100644
--- a/packages/engine-render/src/render-manager/render-unit.ts
+++ b/packages/engine-render/src/render-manager/render-unit.ts
@@ -15,10 +15,12 @@
*/
import type { Dependency, DependencyIdentifier, IDisposable, Nullable, UnitModel, UnitType, UniverInstanceType } from '@univerjs/core';
+import type { Observable } from 'rxjs';
import type { Engine } from '../engine';
import type { Scene } from '../scene';
import type { RenderComponentType } from './render-manager.service';
import { Disposable, Inject, Injector, isClassDependencyItem } from '@univerjs/core';
+import { BehaviorSubject, distinctUntilChanged } from 'rxjs';
/**
* Public interface of a {@link RenderUnit}.
@@ -35,8 +37,24 @@ export interface IRender {
isMainScene: boolean;
isThumbNail?: boolean;
+ /**
+ * Whether the render unit is activated. It should emit value when subscribed immediately.
+ * When created, the render unit is activated by default.
+ */
+ activated$: Observable<boolean>;
+
with<T>(dependency: DependencyIdentifier<T>): T;
getRenderContext?(): IRenderContext;
+ /**
+ * Deactivate the render unit, means the render unit would be freezed and not updated,
+ * even removed from the webpage. However, the render unit is still in the memory and
+ * could be activated again.
+ */
+ deactivate(): void;
+ /**
+ * Activate the render unit, means the render unit would be updated and rendered.
+ */
+ activate(): void;
}
/**
@@ -60,6 +78,9 @@ export interface IRenderContext<T extends UnitModel = UnitModel> extends Omit<IR
export class RenderUnit extends Disposable implements IRender {
readonly isRenderUnit: boolean = true;
+ private readonly _activated$ = new BehaviorSubject<boolean>(true);
+ readonly activated$ = this._activated$.pipe(distinctUntilChanged());
+
get unitId(): string { return this._renderContext.unitId; }
get type(): UnitType { return this._renderContext.type; }
@@ -94,12 +115,28 @@ export class RenderUnit extends Disposable implements IRender {
isMainScene: init.isMainScene,
engine: init.engine,
scene: init.scene,
+ activated$: this.activated$,
+ activate: () => this._activated$.next(true),
+ deactivate: () => this._activated$.next(false),
};
}
override dispose(): void {
this._injector.dispose();
+
super.dispose();
+
+ this._activated$.next(false);
+ this._activated$.complete();
+
+ // Avoid memory leak. Basically it is because RenderUnit itself is leaking.
+ // We use this as a temporary solution to make CI pass.
+ // @ts-ignore
+ this._renderContext.activated$ = null;
+ // @ts-ignore
+ this._renderContext.activate = null;
+ // @ts-ignore
+ this._renderContext.deactivate = null;
}
/**
@@ -145,4 +182,12 @@ export class RenderUnit extends Disposable implements IRender {
getRenderContext(): IRenderContext {
return this._renderContext;
}
+
+ activate(): void {
+ this._renderContext.activate();
+ }
+
+ deactivate(): void {
+ this._renderContext.deactivate();
+ }
}
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-transform-affected.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-transform-affected.controller.ts
index 950d89ce9f..14a3f7dfd4 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-transform-affected.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-transform-affected.controller.ts
@@ -15,11 +15,13 @@
*/
import type { ICommandInfo, IDrawingParam, IMutationInfo, IRange, ITransformState, Nullable, Workbook } from '@univerjs/core';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
import type { IInsertColCommandParams, IInsertRowCommandParams, IMoveColsCommandParams, IMoveRangeCommandParams, IMoveRowsCommandParams, IRemoveRowColCommandParams, ISetColHiddenMutationParams, ISetColVisibleMutationParams, ISetRowHiddenMutationParams, ISetRowVisibleMutationParams, ISetSpecificColsVisibleCommandParams, ISetSpecificRowsVisibleCommandParams, ISetWorksheetActiveOperationParams, ISetWorksheetColWidthMutationParams, ISetWorksheetRowHeightMutationParams, ISetWorksheetRowIsAutoHeightMutationParams } from '@univerjs/sheets';
import type { ISheetDrawing, ISheetDrawingPosition } from '@univerjs/sheets-drawing';
import { Disposable, ICommandService, Inject, IUniverInstanceService, Rectangle } from '@univerjs/core';
-import { type IDrawingJsonUndo1, IDrawingManagerService } from '@univerjs/drawing';
-import { type IRenderContext, IRenderManagerService, type IRenderModule } from '@univerjs/engine-render';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import { IRenderManagerService } from '@univerjs/engine-render';
import { DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, DeltaColumnWidthCommand, DeltaRowHeightCommand, getSheetCommandTarget, InsertColCommand, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, InsertRowCommand, MoveColsCommand, MoveRangeCommand, MoveRowsCommand, RemoveColCommand, RemoveRowCommand, SetColHiddenCommand, SetColHiddenMutation, SetColVisibleMutation, SetColWidthCommand, SetRowHeightCommand, SetRowHiddenCommand, SetRowHiddenMutation, SetRowVisibleMutation, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetWorksheetActiveOperation, SetWorksheetColWidthMutation, SetWorksheetRowHeightMutation, SheetInterceptorService } from '@univerjs/sheets';
import { DrawingApplyType, ISheetDrawingService, SetDrawingApplyMutation, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
import { attachRangeWithCoord, ISheetSelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
@@ -1107,46 +1109,93 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen
private _commandListener() {
this.disposeWithMe(
+ // TODO@weird94: this should subscribe to the command service
+ // but the skeleton changes like other render modules. These two signals are not equivalent.
+ // As a temp solution, I subscribed to activate$ here.
this._commandService.onCommandExecuted((command: ICommandInfo) => {
if (command.id === SetWorksheetActiveOperation.id) {
- setTimeout(() => {
- const params = command.params as ISetWorksheetActiveOperationParams;
- const { unitId: showUnitId, subUnitId: showSubunitId } = params;
+ const { unitId, subUnitId } = command.params as ISetWorksheetActiveOperationParams;
+ this._updateDrawings(unitId, subUnitId);
+ }
+ })
+ );
- const drawingMap = this._drawingManagerService.drawingManagerData;
+ this.disposeWithMe(
+ this._context.activated$.subscribe((activated) => {
+ const { unit, unitId } = this._context;
+ if (activated) {
+ const subUnitId = unit.getActiveSheet().getSheetId();
+ this._updateDrawings(unitId, subUnitId);
+ } else {
+ // Better, dispose the command service listener here.
+ this._clearDrawings(unitId);
+ }
+ })
+ );
+ }
- const insertDrawings: IDrawingParam[] = [];
+ private _clearDrawings(selfUnitId: string): void {
+ setTimeout(() => {
+ const drawingMap = this._drawingManagerService.drawingManagerData;
+ const removeDrawings: IDrawingParam[] = [];
- const removeDrawings: IDrawingParam[] = [];
+ // TODO@weird94: should add a iterating function
+ Object.keys(drawingMap).forEach((unitId) => {
+ const subUnitMap = drawingMap[unitId];
+ if (subUnitMap == null) {
+ return;
+ }
- Object.keys(drawingMap).forEach((unitId) => {
- const subUnitMap = drawingMap[unitId];
- if (subUnitMap == null) {
- return;
- }
- Object.keys(subUnitMap).forEach((subUnitId) => {
- const drawingData = subUnitMap[subUnitId].data;
- if (drawingData == null) {
- return;
- }
- Object.keys(drawingData).forEach((drawingId) => {
- if (unitId === showUnitId && subUnitId === showSubunitId) {
- const drawing = drawingData[drawingId] as ISheetDrawing;
- drawing.transform = drawingPositionToTransform(drawing.sheetTransform, this._selectionRenderService, this._skeletonManagerService);
- insertDrawings.push(drawingData[drawingId]);
- } else {
- removeDrawings.push(drawingData[drawingId]);
- }
- });
- });
- });
+ Object.keys(subUnitMap).forEach((subUnitId) => {
+ const drawingData = subUnitMap[subUnitId].data;
+ if (drawingData == null) {
+ return;
+ }
- this._drawingManagerService.removeNotification(removeDrawings);
- this._drawingManagerService.addNotification(insertDrawings);
- }, 0);
+ Object.keys(drawingData).forEach((drawingId) => {
+ if (unitId === selfUnitId) {
+ removeDrawings.push(drawingData[drawingId]);
+ }
+ });
+ });
+ });
+
+ this._drawingManagerService.removeNotification(removeDrawings);
+ });
+ }
+
+ private _updateDrawings(showUnitId: string, showSubunitId: string): void {
+ // TODO@weird94: remove the setTimeout here
+ setTimeout(() => {
+ const drawingMap = this._drawingManagerService.drawingManagerData;
+ const insertDrawings: IDrawingParam[] = [];
+ const removeDrawings: IDrawingParam[] = [];
+
+ Object.keys(drawingMap).forEach((unitId) => {
+ const subUnitMap = drawingMap[unitId];
+ if (subUnitMap == null) {
+ return;
}
- })
- );
+ Object.keys(subUnitMap).forEach((subUnitId) => {
+ const drawingData = subUnitMap[subUnitId].data;
+ if (drawingData == null) {
+ return;
+ }
+ Object.keys(drawingData).forEach((drawingId) => {
+ if (unitId === showUnitId && subUnitId === showSubunitId) {
+ const drawing = drawingData[drawingId] as ISheetDrawing;
+ drawing.transform = drawingPositionToTransform(drawing.sheetTransform, this._selectionRenderService, this._skeletonManagerService);
+ insertDrawings.push(drawingData[drawingId]);
+ } else {
+ removeDrawings.push(drawingData[drawingId]);
+ }
+ });
+ });
+ });
+
+ this._drawingManagerService.removeNotification(removeDrawings);
+ this._drawingManagerService.addNotification(insertDrawings);
+ }, 0);
}
private _sheetRefreshListener() {
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts
index 0464a9fed8..cf29a03ff1 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts
@@ -15,6 +15,7 @@
*/
import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';
+import type { IRenderContext } from '@univerjs/engine-render';
import {
BooleanNumber,
DisposableCollection,
@@ -30,6 +31,8 @@ import {
Univer,
UniverInstanceType,
} from '@univerjs/core';
+
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
import {
BorderStyleManagerService,
IRefSelectionsService,
@@ -38,9 +41,7 @@ import {
SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel,
} from '@univerjs/sheets';
-
-import { LexerTreeBuilder } from '@univerjs/engine-formula';
-import type { IRenderContext } from '@univerjs/engine-render';
+import { BehaviorSubject } from 'rxjs';
import enUS from '../../../locale/en-US';
import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
import { SheetSelectionRenderService } from '../../../services/selection/selection-render.service';
@@ -139,6 +140,9 @@ export function createCommandTestBed(
mainComponent: null as any,
components: new Map(),
isMainScene: true,
+ activated$: new BehaviorSubject(true),
+ activate: () => { },
+ deactivate: () => { },
};
injector.add([ISheetSelectionRenderService, { useFactory: () => injector.createInstance(SheetSelectionRenderService, context) }]);
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/create-selection-command-test-bed.ts b/packages/sheets-ui/src/commands/commands/__tests__/create-selection-command-test-bed.ts
index 769a9a445d..8c082085db 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/create-selection-command-test-bed.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/create-selection-command-test-bed.ts
@@ -19,6 +19,7 @@ import { Disposable, DisposableCollection, ICommandService, LocaleType, UniverIn
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { CancelFrozenCommand, SetFrozenMutation, SetSelectionsOperation } from '@univerjs/sheets';
+import { BehaviorSubject } from 'rxjs';
import { SheetScrollManagerService } from '../../../services/scroll-manager.service';
import { SelectAllService } from '../../../services/select-all/select-all.service';
import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
@@ -203,6 +204,9 @@ export function createFrozenCommandTestBed(workbookData?: IWorkbookData) {
mainComponent: null as any,
components: null as any,
isMainScene: true,
+ activated$: new BehaviorSubject(true),
+ activate: () => {},
+ deactivate: () => {},
}, injector);
injector.add([SheetSkeletonManagerService, { useValue: fakeSheetSkeletonManagerService }]);
@@ -215,6 +219,9 @@ export function createFrozenCommandTestBed(workbookData?: IWorkbookData) {
components: new Map(),
isMainScene: true,
with: injector.get.bind(injector),
+ activated$: new BehaviorSubject(true),
+ activate: () => {},
+ deactivate: () => {},
});
return {
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.ts
index c73b06b931..c0bdc1ab53 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/sheet.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/sheet.render-controller.ts
@@ -78,8 +78,16 @@ export class SheetRenderController extends RxDisposable implements IRenderModule
const sheetId = worksheet.getSheetId();
this._sheetSkeletonManagerService.setCurrent({ sheetId });
- // TODO: we should attach the context object to the RenderContext object on scene.canvas.
- engine.runRenderLoop(() => scene.render());
+ const frameFn = () => scene.render();
+ this.disposeWithMe(this._context.activated$.subscribe((activated) => {
+ if (activated) {
+ // TODO: we should attach the context object to the RenderContext object on scene.canvas.
+ engine.runRenderLoop(frameFn);
+ } else {
+ // Stop the render loop when the render unit is deactivated.
+ engine.stopRenderLoop(frameFn);
+ }
+ }));
}
private _renderFrameTimeMetric: Nullable<Record<string, number[]>> = null;
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.ts
index 83a4b012f6..a5f374e411 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
@@ -32,6 +32,7 @@ import {
IUIPartsService,
UIPartsService,
} from '@univerjs/ui';
+import { BehaviorSubject } from 'rxjs';
import { SheetClipboardController } from '../../../controllers/clipboard/clipboard.controller';
import { IMarkSelectionService } from '../../mark-selection/mark-selection.service';
import { ISheetSelectionRenderService } from '../../selection/base-selection-render.service';
@@ -603,6 +604,9 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: De
mainComponent: null as any,
components: null as any,
isMainScene: true,
+ activated$: new BehaviorSubject(true),
+ activate: () => {},
+ deactivate: () => {},
}, injector);
injector.add([SheetSkeletonManagerService, { useValue: fakeSheetSkeletonManagerService }]);
@@ -615,6 +619,9 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: De
components: new Map(),
isMainScene: true,
with: injector.get.bind(injector),
+ activated$: new BehaviorSubject(true),
+ activate: () => {},
+ deactivate: () => {},
});
return {
diff --git a/packages/sheets-ui/src/services/sheets-render.service.ts b/packages/sheets-ui/src/services/sheets-render.service.ts
index bb363a5dee..23304a5744 100644
--- a/packages/sheets-ui/src/services/sheets-render.service.ts
+++ b/packages/sheets-ui/src/services/sheets-render.service.ts
@@ -28,7 +28,7 @@ import { distinctUntilChanged, takeUntil } from 'rxjs';
const SHEET_MAIN_CANVAS_ID = 'univer-sheet-main-canvas';
/**
- * This controller is responsible for managing units of a specific kind (UnierSheet) to be rendered on the canvas.
+ * This controller is responsible for managing units of a specific kind (UniverSheet) to be rendered on the canvas.
*/
export class SheetsRenderService extends RxDisposable {
private _skeletonChangeMutations = new Set<string>();
@@ -81,6 +81,14 @@ export class SheetsRenderService extends RxDisposable {
this._instanceSrv.getTypeOfUnitDisposed$<Workbook>(UniverInstanceType.UNIVER_SHEET)
.pipe(takeUntil(this.dispose$))
.subscribe((workbook) => this._disposeRenderer(workbook));
+
+ this.disposeWithMe(
+ this._instanceSrv.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET)
+ .subscribe((workbook) => {
+ if (workbook) {
+ this._renderManagerService.setCurrent(workbook.getUnitId());
+ }
+ }));
}
private _createRenderer(workbook: Workbook): void {
@@ -91,10 +99,8 @@ export class SheetsRenderService extends RxDisposable {
renderer.engine.getCanvas().getContext().setId(`${SHEET_MAIN_CANVAS_ID}_${unitId}`);
}
});
- this._renderManagerService.createRender(unitId);
- // NOTE@wzhudev: maybe not in univer mode
- this._renderManagerService.setCurrent(unitId);
+ this._renderManagerService.createRender(unitId);
}
private _disposeRenderer(workbook: Workbook): void {
diff --git a/packages/sheets/src/facade/f-univer.ts b/packages/sheets/src/facade/f-univer.ts
index c151d0b65f..447cb10bba 100644
--- a/packages/sheets/src/facade/f-univer.ts
+++ b/packages/sheets/src/facade/f-univer.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICommandInfo, IDisposable, Injector, IWorkbookData, Nullable, Workbook } from '@univerjs/core';
+import type { ICommandInfo, ICreateUnitOptions, IDisposable, Injector, IWorkbookData, Nullable, Workbook } from '@univerjs/core';
import type { CommandListenerValueChange, IInsertSheetCommandParams, IRemoveSheetCommandParams, ISetGridlinesColorCommandParams, ISetTabColorMutationParams, ISetWorksheetActivateCommandParams, ISetWorksheetHideMutationParams, ISetWorksheetNameCommandParams, ISetWorksheetOrderMutationParams, IToggleGridlinesCommandParams } from '@univerjs/sheets';
import type { IBeforeSheetCreateEventParams, ISheetCreatedEventParams } from './f-event';
import type { FRange } from './f-range';
@@ -37,13 +37,19 @@ export interface IFUniverSheetsMixin {
/**
* Create a new spreadsheet and get the API handler of that spreadsheet.
* @param {Partial<IWorkbookData>} data The snapshot of the spreadsheet.
+ * @param {ICreateUnitOptions} options The options of creating the spreadsheet.
* @returns {FWorkbook} FWorkbook API instance.
* @example
* ```ts
* univerAPI.createWorkbook({ id: 'Sheet1', name: 'Sheet1' });
* ```
+ *
+ * Add you can make the workbook not as the active workbook by setting options:
+ * ```ts
+ * univerAPI.createWorkbook({ id: 'Sheet1', name: 'Sheet1' }, { makeCurrent: false });
+ * ```
*/
- createWorkbook(data: Partial<IWorkbookData>): FWorkbook;
+ createWorkbook(data: Partial<IWorkbookData>, options?: ICreateUnitOptions): FWorkbook;
/**
* Get the currently focused Univer spreadsheet.
@@ -421,14 +427,14 @@ export class FUniverSheetsMixin extends FUniver implements IFUniverSheetsMixin {
this._initWorkbookEvent(injector);
}
- override createUniverSheet(data: Partial<IWorkbookData>): FWorkbook {
+ override createUniverSheet(data: Partial<IWorkbookData>, options?: ICreateUnitOptions): FWorkbook {
const instanceService = this._injector.get(IUniverInstanceService);
- const workbook = instanceService.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, data);
+ const workbook = instanceService.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, data, options);
return this._injector.createInstance(FWorkbook, workbook);
};
- override createWorkbook(data: Partial<IWorkbookData>): FWorkbook {
- return this.createUniverSheet(data);
+ override createWorkbook(data: Partial<IWorkbookData>, options?: ICreateUnitOptions): FWorkbook {
+ return this.createUniverSheet(data, options);
}
override getActiveWorkbook(): FWorkbook | null {
diff --git a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx b/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
index 1d5ab8e538..7645bdde99 100644
--- a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
+++ b/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
@@ -60,6 +60,8 @@ export class DesktopUIController extends Disposable {
this._menuManagerService.mergeMenu(menuSchema);
}
+ private _currentRenderId: string | null = null;
+
private _bootstrapWorkbench(): void {
this.disposeWithMe(this._instanceSrv.unitDisposed$.subscribe((_unit: UnitModel) => {
clearTimeout(this._steadyTimeout);
@@ -72,23 +74,22 @@ export class DesktopUIController extends Disposable {
this.disposeWithMe(this._layoutService.registerContentElement(contentElement));
}
- // TODO: this is subject to change in the future for Uni-mode
+ // When current render changes, we need to update the render unit.
this._renderManagerService.currentRender$.subscribe((renderId) => {
if (renderId) {
- const render = this._renderManagerService.getRenderById(renderId)!;
- if (!render.unitId) return;
- if (isInternalEditorID(render.unitId)) return;
- render.engine.setContainer(contentElement);
+ this._changeRenderUnit(renderId, contentElement);
}
});
+ // First render.
this.disposeWithMe(this._lifecycleService.lifecycle$.pipe(filter((stage) => stage === LifecycleStages.Ready), take(1)).subscribe(() => {
this._renderTimeout = setTimeout(() => {
const allRenders = this._renderManagerService.getRenderAll();
for (const [key, render] of allRenders) {
if (isInternalEditorID(key) || !((render) as RenderUnit).isRenderUnit) continue;
- render.engine.setContainer(contentElement);
+ this._changeRenderUnit(key, contentElement);
+ break; // We only render the first renderer when bootstrapping.
}
this._lifecycleService.stage = LifecycleStages.Rendered;
@@ -101,6 +102,22 @@ export class DesktopUIController extends Disposable {
);
}
+ private _changeRenderUnit(rendererId: string, contentElement: HTMLElement): void {
+ if (this._currentRenderId === rendererId) return;
+
+ const currentRenderer = this._currentRenderId ? this._renderManagerService.getRenderById(this._currentRenderId) : null;
+ const renderer = this._renderManagerService.getRenderById(rendererId)!;
+ if (!renderer.unitId || isInternalEditorID(renderer.unitId)) return;
+
+ currentRenderer?.deactivate();
+ currentRenderer?.engine.unmount();
+
+ renderer.engine.mount(contentElement);
+ renderer.activate();
+
+ this._currentRenderId = rendererId;
+ }
+
private _initBuiltinComponents(): void {
this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.FLOATING, () => connectInjector(CanvasPopup, this._injector)));
// this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(ContentDOMPopup, this._injector)));
diff --git a/packages/ui/src/facade/f-univer.ts b/packages/ui/src/facade/f-univer.ts
index 6e9baaf3e2..fc45831f00 100644
--- a/packages/ui/src/facade/f-univer.ts
+++ b/packages/ui/src/facade/f-univer.ts
@@ -19,6 +19,7 @@ import type { IMessageProps } from '@univerjs/design';
import type { BuiltInUIPart, ComponentType, IComponentOptions, IDialogPartMethodOptions, ISidebarMethodOptions } from '@univerjs/ui';
import type { IFacadeMenuItem, IFacadeSubmenuItem } from './f-menu-builder';
import { connectInjector, FUniver } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
import { ComponentManager, CopyCommand, IDialogService, IMessageService, ISidebarService, IUIPartsService, PasteCommand } from '@univerjs/ui';
import { FMenu, FSubmenu } from './f-menu-builder';
import { FShortcut } from './f-shortcut';
@@ -153,6 +154,23 @@ export interface IFUniverUIMixin {
* ```
*/
registerComponent(name: string, component: ComponentType, options?: IComponentOptions): IDisposable;
+
+ /**
+ * Set a unit as the current unit and render a unit in the workbench's main area. If you have multiple units in Univer,
+ * you should call this method to render the unit.
+ * @param unitId Unit to be rendered.
+ *
+ * @example
+ * Let's assume you have created two units, `unit1` and `unit2`. Univer is rendering `unit1` and you want to
+ * render `unit2`.
+ *
+ * ```ts
+ * univerAPI.setCurrent('unit2');
+ * ```
+ *
+ * This will render `unit2` in the workbench's main area.
+ */
+ setCurrent(unitId: string): void;
}
/**
@@ -233,6 +251,16 @@ export class FUniverUIMixin extends FUniver implements IFUniverUIMixin {
const componentManager = this._injector.get(ComponentManager);
return this.disposeWithMe(componentManager.register(name, component, options));
}
+
+ override setCurrent(unitId: string): void {
+ const rendererManagerService = this._injector.get(IRenderManagerService);
+ const renderUnit = rendererManagerService.getRenderById(unitId);
+ if (!renderUnit) {
+ throw new Error('Unit not found');
+ }
+
+ this._univerInstanceService.setCurrentUnitForType(unitId);
+ }
}
FUniver.extend(FUniverUIMixin);