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
feat(ui): add workbench skeleton service and disabled UI parts API (#7332)
白熱2201594311da
diff --git a/packages/engine-render/src/__tests__/scene.transformer.spec.ts b/packages/engine-render/src/__tests__/scene.transformer.spec.tsnew file mode 100644index 0000000000..63d61be955--- /dev/null+++ b/packages/engine-render/src/__tests__/scene.transformer.spec.ts@@ -0,0 +1,55 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { afterEach, describe, expect, it, vi } from 'vitest';+import { Engine } from '../engine';+import { Scene } from '../scene';+import { Transformer } from '../scene.transformer';+import { Rect } from '../shape/rect';+import { setupRenderTestEnv } from './render-test-utils';++describe('Transformer', () => {+ const env = setupRenderTestEnv();++ afterEach(() => {+ env.restore();+ });++ it('releases hover subscriptions with its object subscription', () => {+ const engine = new Engine('transformer-engine', { elementWidth: 100, elementHeight: 100, dpr: 1 });+ const scene = new Scene('transformer-scene', engine);+ const rect = new Rect('transformer-rect', { width: 10, height: 10 });+ const transformer = new Transformer(scene, {+ hoverEnabled: true,+ hoverEnterFunc: vi.fn(),+ hoverLeaveFunc: vi.fn(),+ });++ transformer.attachTo(rect);++ expect((rect.onPointerEnter$ as any).observers).toHaveLength(1);+ expect((rect.onPointerLeave$ as any).observers).toHaveLength(1);++ transformer.dispose();++ expect((rect.onPointerEnter$ as any).observers).toHaveLength(0);+ expect((rect.onPointerLeave$ as any).observers).toHaveLength(0);++ rect.dispose();+ scene.dispose();+ engine.dispose();+ });+});diff --git a/packages/engine-render/src/__tests__/viewport.spec.ts b/packages/engine-render/src/__tests__/viewport.spec.tsnew file mode 100644index 0000000000..26618ffca4--- /dev/null+++ b/packages/engine-render/src/__tests__/viewport.spec.ts@@ -0,0 +1,45 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { afterEach, describe, expect, it } from 'vitest';+import { Engine } from '../engine';+import { Scene } from '../scene';+import { Viewport } from '../viewport';+import { setupRenderTestEnv } from './render-test-utils';++describe('Viewport', () => {+ const env = setupRenderTestEnv();++ afterEach(() => {+ env.restore();+ });++ it('releases its engine transform subscription on disposal', () => {+ const engine = new Engine('viewport-engine', { elementWidth: 100, elementHeight: 100, dpr: 1 });+ const scene = new Scene('viewport-scene', engine);+ const initialObserverCount = (engine.onTransformChange$ as any).observers.length;+ const viewport = new Viewport('viewport', scene, { width: 100, height: 100 });++ expect((engine.onTransformChange$ as any).observers).toHaveLength(initialObserverCount + 1);++ viewport.dispose();++ expect((engine.onTransformChange$ as any).observers).toHaveLength(initialObserverCount);++ scene.dispose();+ engine.dispose();+ });+});diff --git a/packages/engine-render/src/scene.transformer.ts b/packages/engine-render/src/scene.transformer.tsindex 02e17705dc..da2396d00f 100644--- a/packages/engine-render/src/scene.transformer.ts+++ b/packages/engine-render/src/scene.transformer.ts@@ -502,11 +502,6 @@ export class Transformer extends Disposable implements ITransformerConfig {// eslint-disable-next-line max-lines-per-functionattachTo(applyObject: BaseObject) {- if (this.hoverEnabled) {- this.hoverEnterFunc && applyObject.onPointerEnter$.subscribeEvent(this.hoverEnterFunc);- this.hoverLeaveFunc && applyObject.onPointerLeave$.subscribeEvent(this.hoverLeaveFunc);- }-// First check if there is an old subscription to avoid duplicate subscriptionsthis.detachFrom(applyObject);@@ -596,7 +591,10 @@ export class Transformer extends Disposable implements ITransformerConfig {state.stopPropagation();});- this.disposeWithMe(toDisposable(observer));+ if (this.hoverEnabled) {+ this.hoverEnterFunc && observer.add(applyObject.onPointerEnter$.subscribeEvent(this.hoverEnterFunc));+ this.hoverLeaveFunc && observer.add(applyObject.onPointerLeave$.subscribeEvent(this.hoverLeaveFunc));+ }this._subscriptionObjectMap.set(applyObject.oKey, observer);@@ -616,6 +614,9 @@ export class Transformer extends Disposable implements ITransformerConfig {override dispose() {super.dispose();+ this._subscriptionObjectMap.forEach((subscription) => subscription?.unsubscribe());+ this._subscriptionObjectMap.clear();+this._topScenePointerMoveSub?.unsubscribe();this._topScenePointerUpSub?.unsubscribe();diff --git a/packages/engine-render/src/viewport.ts b/packages/engine-render/src/viewport.tsindex 391fc2d12d..1b67426d34 100644--- a/packages/engine-render/src/viewport.ts+++ b/packages/engine-render/src/viewport.ts@@ -15,6 +15,7 @@*/import type { EventState, IPosition, IRange, Nullable } from '@univerjs/core';+import type { Subscription } from 'rxjs';import type { BaseObject } from './base-object';import type { IWheelEvent } from './basics/i-events';import type { IBoundRectNoAngle, IViewportInfo } from './basics/vector2';@@ -118,6 +119,7 @@ const WHEEL_CROSS_AXIS_LOCK_RATIO = 2;export class Viewport {private _viewportKey: string = '';+ private _transformChangeSubscription?: Subscription;/*** scrollX means scroll x value for scrollbar in viewMain@@ -267,7 +269,7 @@ export class Viewport {this.resetCanvasSizeAndUpdateScroll();this.getBounding();- this.scene.getEngine()?.onTransformChange$.subscribeEvent(() => {+ this._transformChangeSubscription = this.scene.getEngine()?.onTransformChange$.subscribeEvent(() => {this.markForceDirty(true);});this.markForceDirty(true);@@ -1069,6 +1071,8 @@ export class Viewport {}dispose() {+ this._transformChangeSubscription?.unsubscribe();+ this._transformChangeSubscription = undefined;this.onMouseWheel$.complete();this.onScrollAfter$.complete();// this.onScrollBefore$.complete();diff --git a/packages/sheets/src/models/__tests__/range-protection-render.model.spec.ts b/packages/sheets/src/models/__tests__/range-protection-render.model.spec.tsnew file mode 100644index 0000000000..245b90f471--- /dev/null+++ b/packages/sheets/src/models/__tests__/range-protection-render.model.spec.ts@@ -0,0 +1,57 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { IDisposable, Injector, Univer } from '@univerjs/core';+import { IPermissionService } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createTestBase, TEST_WORKBOOK_DATA_DEMO } from '../../services/__tests__/util';+import { RangeProtectionRenderModel } from '../range-protection-render.model';+import { RangeProtectionRuleModel } from '../range-protection-rule.model';++describe('RangeProtectionRenderModel', () => {+ let univer: Univer;+ let get: Injector['get'];++ beforeEach(() => {+ const testBed = createTestBase(TEST_WORKBOOK_DATA_DEMO, [+ [RangeProtectionRuleModel],+ [RangeProtectionRenderModel],+ ]);++ univer = testBed.univer;+ get = testBed.get;+ });++ afterEach(() => {+ univer.dispose();+ });++ it('releases its cache invalidation subscriptions on disposal', () => {+ const permissionService = get(IPermissionService) as any;+ const ruleModel = get(RangeProtectionRuleModel) as any;+ const permissionObserverCount = permissionService._permissionPointUpdate$.observers.length;+ const ruleObserverCount = ruleModel._ruleChange$.observers.length;+ const renderModel = get(RangeProtectionRenderModel);++ expect(permissionService._permissionPointUpdate$.observers).toHaveLength(permissionObserverCount + 1);+ expect(ruleModel._ruleChange$.observers).toHaveLength(ruleObserverCount + 1);++ (renderModel as unknown as IDisposable).dispose();++ expect(permissionService._permissionPointUpdate$.observers).toHaveLength(permissionObserverCount);+ expect(ruleModel._ruleChange$.observers).toHaveLength(ruleObserverCount);+ });+});diff --git a/packages/sheets/src/models/range-protection-render.model.ts b/packages/sheets/src/models/range-protection-render.model.tsindex 0bdf21a8b2..22d9c8e5b0 100644--- a/packages/sheets/src/models/range-protection-render.model.ts+++ b/packages/sheets/src/models/range-protection-render.model.ts@@ -17,7 +17,7 @@import type { IRange } from '@univerjs/core';import type { UnitAction } from '@univerjs/protocol';import type { getDefaultRangePermission, IRangePermissionPoint } from '../services/permission/range-permission/util';-import { Inject, IPermissionService, LRUMap, Range } from '@univerjs/core';+import { Disposable, Inject, IPermissionService, LRUMap, Range } from '@univerjs/core';import { UnitObject } from '@univerjs/protocol';import { filter, map } from 'rxjs/operators';import { getAllRangePermissionPoint } from '../services/permission/range-permission/util';@@ -25,17 +25,18 @@ import { RangeProtectionRuleModel } from './range-protection-rule.model';export type ICellPermission = Record<UnitAction, boolean> & { ruleId?: string; ranges?: IRange[] };-export class RangeProtectionRenderModel {+export class RangeProtectionRenderModel extends Disposable {private _cache = new LRUMap<string, ICellPermission[]>(10000);constructor(@Inject(RangeProtectionRuleModel) private _selectionProtectionRuleModel: RangeProtectionRuleModel,@Inject(IPermissionService) private _permissionService: IPermissionService) {+ super();this._init();}private _init() {- this._permissionService.permissionPointUpdate$.pipe(+ this.disposeWithMe(this._permissionService.permissionPointUpdate$.pipe(filter((permission) => permission.type === UnitObject.SelectRange),filter((permission) => getAllRangePermissionPoint().some((F) => permission instanceof F)),map((permission) => permission as IRangePermissionPoint)@@ -52,9 +53,9 @@ export class RangeProtectionRenderModel {});}}- });+ }));- this._selectionProtectionRuleModel.ruleChange$.subscribe((info) => {+ this.disposeWithMe(this._selectionProtectionRuleModel.ruleChange$.subscribe((info) => {info.rule.ranges.forEach((range) => {Range.foreach(range, (row, col) => {const key = this._createKey(info.unitId, info.subUnitId, row, col);@@ -69,7 +70,7 @@ export class RangeProtectionRenderModel {});});}- });+ }));}private _createKey(unitId: string, subUnitId: string, row: number, col: number) {@@ -106,4 +107,9 @@ export class RangeProtectionRenderModel {public clear() {this._cache.clear();}++ override dispose(): void {+ super.dispose();+ this._cache.clear();+ }}diff --git a/packages/ui/src/controllers/ui/__tests__/ui-desktop-mobile.controller.spec.tsx b/packages/ui/src/controllers/ui/__tests__/ui-desktop-mobile.controller.spec.tsxindex 4d169e5675..656042699d 100644--- a/packages/ui/src/controllers/ui/__tests__/ui-desktop-mobile.controller.spec.tsx+++ b/packages/ui/src/controllers/ui/__tests__/ui-desktop-mobile.controller.spec.tsx@@ -14,7 +14,7 @@* limitations under the License.*/-import { LifecycleStages } from '@univerjs/core';+import { Injector, LifecycleStages } from '@univerjs/core';import { render, unmount } from '@univerjs/design';import { Subject } from 'rxjs';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -39,7 +39,7 @@ vi.mock('@univerjs/design', async (importOriginal) => {function createCommonDeps() {return {- injector: {},+ injector: new Injector(),lifecycleService: {onStage: vi.fn().mockResolvedValue(undefined),stage: LifecycleStages.Starting,diff --git a/packages/ui/src/controllers/ui/__tests__/ui-shared.controller.spec.ts b/packages/ui/src/controllers/ui/__tests__/ui-shared.controller.spec.tsindex c4ff0e3458..f21199366c 100644--- a/packages/ui/src/controllers/ui/__tests__/ui-shared.controller.spec.ts+++ b/packages/ui/src/controllers/ui/__tests__/ui-shared.controller.spec.ts@@ -15,9 +15,10 @@*/import type { IDisposable } from '@univerjs/core';-import { LifecycleStages, LifecycleUnreachableError } from '@univerjs/core';+import { Injector, LifecycleStages, LifecycleUnreachableError } from '@univerjs/core';import { Subject } from 'rxjs';import { afterEach, describe, expect, it, vi } from 'vitest';+import { IWorkbenchService, WorkbenchService } from '../../../services/workbench/workbench.service';import { SingleUnitUIController } from '../ui-shared.controller';class TestSingleUnitUIController extends SingleUnitUIController {@@ -67,6 +68,16 @@ describe('SingleUnitUIController', () => {it('should bootstrap and switch renderers with lifecycle updates', async () => {vi.useFakeTimers();+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ callback(0);+ return 0;+ });++ const injector = new Injector([+ [IWorkbenchService, { useClass: WorkbenchService }],+ ]);+ const skeletonStates: boolean[] = [];+ injector.get(IWorkbenchService).skeletonVisible$.subscribe((visible) => skeletonStates.push(visible));const layoutService = {registerRootContainerElement: vi.fn(() => ({ dispose: vi.fn() })),@@ -105,7 +116,7 @@ describe('SingleUnitUIController', () => {};const controller = new TestSingleUnitUIController(- {} as any,+ injector,instanceService,layoutService,lifecycleService,@@ -115,6 +126,7 @@ describe('SingleUnitUIController', () => {);controller.runBootstrap();+ expect(skeletonStates).toEqual([false, true]);await controller.callbackPromise;expect(layoutService.registerRootContainerElement).toHaveBeenCalledTimes(1);@@ -124,6 +136,7 @@ describe('SingleUnitUIController', () => {expect(render2.engine.mount).toHaveBeenCalledTimes(1);expect(render2.activate).toHaveBeenCalledTimes(1);expect(lifecycleService.stage).toBe(LifecycleStages.Rendered);+ expect(skeletonStates).toEqual([false, true, false]);focused$.next('render-2');expect(render2.engine.mount).toHaveBeenCalledTimes(1);@@ -184,7 +197,7 @@ describe('SingleUnitUIController', () => {};const controller = new TestSingleUnitUIController(- {} as any,+ new Injector(),instanceService,layoutService,lifecycleService,@@ -216,7 +229,7 @@ describe('SingleUnitUIController', () => {};const controller = new TestSingleUnitUIController(- {} as any,+ new Injector(),{focused$: new Subject<string>(),getFocusedUnit: vi.fn(() => null),@@ -244,7 +257,7 @@ describe('SingleUnitUIController', () => {it('should rethrow non-lifecycle errors from bootstrap callback', async () => {const error = new Error('unexpected');const controller = new TestSingleUnitUIController(- {} as any,+ new Injector(),{focused$: new Subject<string>(),getFocusedUnit: vi.fn(() => null),diff --git a/packages/ui/src/controllers/ui/ui-shared.controller.ts b/packages/ui/src/controllers/ui/ui-shared.controller.tsindex dd2e9a6db5..f7a95955ed 100644--- a/packages/ui/src/controllers/ui/ui-shared.controller.ts+++ b/packages/ui/src/controllers/ui/ui-shared.controller.ts@@ -17,7 +17,8 @@import type { IDisposable, Injector, IUniverInstanceService, LifecycleService } from '@univerjs/core';import type { IRenderManagerService } from '@univerjs/engine-render';import type { ILayoutService } from '../../services/layout/layout.service';-import { Disposable, isInternalEditorID, LifecycleStages, LifecycleUnreachableError } from '@univerjs/core';+import { Disposable, isInternalEditorID, LifecycleStages, LifecycleUnreachableError, Quantity } from '@univerjs/core';+import { IWorkbenchService } from '../../services/workbench/workbench.service';const STEADY_TIMEOUT = 3000;@@ -54,6 +55,11 @@ export abstract class SingleUnitUIController extends Disposable {}protected _bootstrapWorkbench() {+ const initialSkeleton = this._injector.get(IWorkbenchService, Quantity.OPTIONAL)?.acquireSkeleton();+ if (initialSkeleton) {+ this.disposeWithMe(initialSkeleton);+ }+this.disposeWithMe(this.bootstrap(async (contentElement, containerElement) => {if (this._layoutService) {this.disposeWithMe(this._layoutService.registerRootContainerElement(containerElement));@@ -68,6 +74,7 @@ export abstract class SingleUnitUIController extends Disposable {for (const [key] of allRenders) {if (this._changeRenderUnit(key, contentElement)) break;}+ requestAnimationFrame(() => requestAnimationFrame(() => initialSkeleton?.dispose()));// Render as focus shifts.this.disposeWithMe(this._instanceService.focused$.subscribe((unit) => {diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex 951e5bf5b4..04ff1fc759 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -126,6 +126,7 @@ export { DesktopSidebarService } from './services/sidebar/desktop-sidebar.servicexport { useSidebarClick } from './services/sidebar/hooks/use-sidebar-click';export { ILeftSidebarService, ISidebarService } from './services/sidebar/sidebar.service';export { ThemeSwitcherService } from './services/theme-switcher/theme-switcher.service';+export { IWorkbenchService, WorkbenchService } from './services/workbench/workbench.service';export * from './utils';export { COLOR_PICKER_COMPONENT } from './views/color-picker/interface';export { ComponentContainer, useComponentsOfPart } from './views/components/ComponentContainer';diff --git a/packages/ui/src/mobile-plugin.ts b/packages/ui/src/mobile-plugin.tsindex 498fcbd084..838461e9fd 100644--- a/packages/ui/src/mobile-plugin.ts+++ b/packages/ui/src/mobile-plugin.ts@@ -73,6 +73,7 @@ import { IShortcutService, ShortcutService } from './services/shortcut/shortcut.import { DesktopSidebarService } from './services/sidebar/desktop-sidebar.service';import { ISidebarService } from './services/sidebar/sidebar.service';import { ThemeSwitcherService } from './services/theme-switcher/theme-switcher.service';+import { IWorkbenchService, WorkbenchService } from './services/workbench/workbench.service';export const DISABLE_AUTO_FOCUS_KEY = 'DISABLE_AUTO_FOCUS';@@ -117,6 +118,7 @@ export class UniverMobileUIPlugin extends Plugin {[IconManager],[ComponentsController],[ThemeSwitcherService],+ [IWorkbenchService, { useClass: WorkbenchService }],[ZIndexManager],[ShortcutPanelService],[IUIPartsService, { useClass: UIPartsService }],diff --git a/packages/ui/src/plugin.ts b/packages/ui/src/plugin.tsindex 6788735409..e680a4c652 100644--- a/packages/ui/src/plugin.ts+++ b/packages/ui/src/plugin.ts@@ -74,6 +74,7 @@ import { IShortcutService, ShortcutService } from './services/shortcut/shortcut.import { DesktopSidebarService } from './services/sidebar/desktop-sidebar.service';import { ISidebarService } from './services/sidebar/sidebar.service';import { ThemeSwitcherService } from './services/theme-switcher/theme-switcher.service';+import { IWorkbenchService, WorkbenchService } from './services/workbench/workbench.service';export const DISABLE_AUTO_FOCUS_KEY = 'DISABLE_AUTO_FOCUS';@@ -121,6 +122,7 @@ export class UniverUIPlugin extends Plugin {[ZIndexManager],[ShortcutPanelService],[IUIPartsService, { useClass: UIPartsService }],+ [IWorkbenchService, { useClass: WorkbenchService }],[ILayoutService, { useClass: DesktopLayoutService }],[IRibbonService, { useClass: DesktopRibbonService }],[IRibbonOverrideService, { useClass: RibbonOverrideService }],diff --git a/packages/ui/src/services/parts/__tests__/parts.service.spec.ts b/packages/ui/src/services/parts/__tests__/parts.service.spec.tsindex 7cdce25e77..fa440c0f69 100644--- a/packages/ui/src/services/parts/__tests__/parts.service.spec.ts+++ b/packages/ui/src/services/parts/__tests__/parts.service.spec.ts@@ -16,6 +16,7 @@import type { ComponentType } from '../../../common/component-manager';import { Injector } from '@univerjs/core';+import { BehaviorSubject } from 'rxjs';import { beforeEach, describe, expect, it } from 'vitest';import { BuiltInUIPart, IUIPartsService, UIPartsService } from '../parts.service';@@ -51,4 +52,16 @@ describe('UIPartsService', () => {expect(service.isUIVisible(BuiltInUIPart.FOOTER)).toBe(true);expect(changes).toEqual([{ ui: BuiltInUIPart.HEADER, visible: false }]);});++ it('disables registered UI parts synchronously and restores them on disposal', () => {+ const disabled$ = new BehaviorSubject(false);+ const disposable = service.registerDisabledUIParts([BuiltInUIPart.TOOLBAR], disabled$);++ disabled$.next(true);+ expect(service.isUIVisible(BuiltInUIPart.TOOLBAR)).toBe(false);++ disposable.dispose();+ expect(service.isUIVisible(BuiltInUIPart.TOOLBAR)).toBe(true);+ expect((service as any)._collection._disposables).toHaveLength(0);+ });});diff --git a/packages/ui/src/services/parts/parts.service.ts b/packages/ui/src/services/parts/parts.service.tsindex 3a1c928873..e2a10238cc 100644--- a/packages/ui/src/services/parts/parts.service.ts+++ b/packages/ui/src/services/parts/parts.service.ts@@ -44,6 +44,7 @@ export interface IUIPartsService {uiVisibleChange$: Observable<{ ui: ComponentPartKey; visible: boolean }>;registerComponent(part: ComponentPartKey, componentFactory: () => ComponentType): IDisposable;+ registerDisabledUIParts(parts: readonly ComponentPartKey[], disabled$: Observable<boolean>): IDisposable;getComponents(part: ComponentPartKey): Set<ComponentRenderer>;setUIVisible(part: ComponentPartKey, visible: boolean): void;@@ -55,6 +56,7 @@ export const IUIPartsService = createIdentifier<IUIPartsService>('ui.parts.serviexport class UIPartsService extends Disposable implements IUIPartsService {private _componentsByPart: Map<ComponentPartKey, Set<ComponentType>> = new Map();+ private _disabledUIParts = new Map<ComponentPartKey, Set<symbol>>();private readonly _componentRegistered$ = new Subject<ComponentPartKey>();readonly componentRegistered$ = this._componentRegistered$.asObservable();@@ -66,18 +68,61 @@ export class UIPartsService extends Disposable implements IUIPartsService {super.dispose();this._componentsByPart.clear();+ this._disabledUIParts.clear();this._uiVisible.clear();this._componentRegistered$.complete();this._uiVisibleChange$.complete();}setUIVisible(part: ComponentPartKey, visible: boolean): void {+ const wasVisible = this.isUIVisible(part);this._uiVisible.set(part, visible);- this._uiVisibleChange$.next({ ui: part, visible });+ const isVisible = this.isUIVisible(part);+ if (wasVisible !== isVisible) {+ this._uiVisibleChange$.next({ ui: part, visible: isVisible });+ }}isUIVisible(part: ComponentPartKey): boolean {- return this._uiVisible.get(part) ?? true;+ return (this._uiVisible.get(part) ?? true) && !this._disabledUIParts.get(part)?.size;+ }++ registerDisabledUIParts(parts: readonly ComponentPartKey[], disabled$: Observable<boolean>): IDisposable {+ const uniqueParts = [...new Set(parts)];+ const registration = Symbol('disabled-ui-parts');+ let disabled = false;++ const update = (nextDisabled: boolean) => {+ if (disabled === nextDisabled) {+ return;+ }+ disabled = nextDisabled;++ uniqueParts.forEach((part) => {+ const wasVisible = this.isUIVisible(part);+ const registrations = this._disabledUIParts.get(part) ?? new Set<symbol>();+ if (disabled) {+ registrations.add(registration);+ this._disabledUIParts.set(part, registrations);+ } else {+ registrations.delete(registration);+ if (registrations.size === 0) {+ this._disabledUIParts.delete(part);+ }+ }+ const isVisible = this.isUIVisible(part);+ if (wasVisible !== isVisible) {+ this._uiVisibleChange$.next({ ui: part, visible: isVisible });+ }+ });+ };++ const subscription = disabled$.subscribe(update);+ const disposable = toDisposable(() => {+ subscription.unsubscribe();+ update(false);+ });+ return this.disposeWithMe(disposable);}registerComponent<T>(part: ComponentPartKey, componentFactory: () => React.ComponentType<T>): IDisposable {diff --git a/packages/ui/src/services/workbench/__tests__/workbench.service.spec.ts b/packages/ui/src/services/workbench/__tests__/workbench.service.spec.tsnew file mode 100644index 0000000000..ec4590ef27--- /dev/null+++ b/packages/ui/src/services/workbench/__tests__/workbench.service.spec.ts@@ -0,0 +1,44 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { IWorkbenchService, WorkbenchService } from '../workbench.service';++describe('WorkbenchService', () => {+ let service: IWorkbenchService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([IWorkbenchService, { useClass: WorkbenchService }]);+ service = injector.get(IWorkbenchService);+ });++ it('keeps the skeleton visible until every loading token is disposed', () => {+ const states: boolean[] = [];+ service.skeletonVisible$.subscribe((visible) => states.push(visible));++ const first = service.acquireSkeleton();+ const second = service.acquireSkeleton();+ first.dispose();++ expect(states).toEqual([false, true]);++ second.dispose();+ expect(states).toEqual([false, true, false]);+ expect((service as any)._collection._disposables).toHaveLength(0);+ });+});diff --git a/packages/ui/src/services/workbench/workbench.service.ts b/packages/ui/src/services/workbench/workbench.service.tsnew file mode 100644index 0000000000..5b4aa48de8--- /dev/null+++ b/packages/ui/src/services/workbench/workbench.service.ts@@ -0,0 +1,58 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { IDisposable } from '@univerjs/core';+import type { Observable } from 'rxjs';+import { createIdentifier, Disposable, toDisposable } from '@univerjs/core';+import { BehaviorSubject } from 'rxjs';++export interface IWorkbenchService {+ readonly skeletonVisible$: Observable<boolean>;++ acquireSkeleton(): IDisposable;+}++export const IWorkbenchService = createIdentifier<IWorkbenchService>('univer.ui.workbench.service');++export class WorkbenchService extends Disposable implements IWorkbenchService {+ private readonly _tokens = new Set<symbol>();+ private readonly _skeletonVisible$ = new BehaviorSubject(false);++ readonly skeletonVisible$ = this._skeletonVisible$.asObservable();++ acquireSkeleton(): IDisposable {+ const token = Symbol('workbench-skeleton');+ this._tokens.add(token);+ if (this._tokens.size === 1) {+ this._skeletonVisible$.next(true);+ }++ const disposable = toDisposable(() => {+ if (!this._tokens.delete(token) || this._tokens.size > 0) {+ return;+ }++ this._skeletonVisible$.next(false);+ });+ return this.disposeWithMe(disposable);+ }++ override dispose(): void {+ super.dispose();+ this._tokens.clear();+ this._skeletonVisible$.complete();+ }+}diff --git a/packages/ui/src/views/components/ribbon/ribbon-grid-layout.ts b/packages/ui/src/views/components/ribbon/ribbon-grid-layout.tsindex cd511a2df0..e45e52aa41 100644--- a/packages/ui/src/views/components/ribbon/ribbon-grid-layout.ts+++ b/packages/ui/src/views/components/ribbon/ribbon-grid-layout.ts@@ -32,37 +32,29 @@ export interface IRibbonGridPlacement {export function placeRibbonGridItems(items: IMenuSchema[]): IRibbonGridPlacement[] {const occupied = new Set<string>();const placements = new Map<IMenuSchema, IRibbonGridPlacement>();- const fallbackItems: IMenuSchema[] = [];- let maxExplicitColumn = 0;+ const fallbackItems: Array<{ item: IMenuSchema; layout?: IRibbonGridPlacement }> = [];for (const item of items) {const layout = item.gridLayout;if (!layout) {- fallbackItems.push(item);+ fallbackItems.push({ item });continue;}const rowSpan = layout.rowSpan ?? 1;const columnSpan = layout.columnSpan ?? 1;const cells = getCells(layout.row, layout.column, rowSpan, columnSpan);- const valid = cells.length > 0- && layout.row + rowSpan - 1 <= RIBBON_GRID_ROWS- && (layout.width === undefined || (Number.isFinite(layout.width) && layout.width > 0))- && (layout.iconSize === undefined || (Number.isFinite(layout.iconSize) && layout.iconSize > 0))- && cells.every((cell) => !occupied.has(cell));- if (!valid) {+ if (!isValidGridGeometry(layout, rowSpan, cells)) {// eslint-disable-next-line node/prefer-global/processif (process.env.NODE_ENV !== 'production') {globalThis.console.warn(`[RibbonGrid] Invalid gridLayout for "${item.key}"; using fallback placement.`);}- fallbackItems.push(item);+ fallbackItems.push({ item });continue;}- cells.forEach((cell) => occupied.add(cell));- maxExplicitColumn = Math.max(maxExplicitColumn, layout.column + columnSpan - 1);- placements.set(item, {+ const placement = {item,row: layout.row,column: layout.column,@@ -71,30 +63,54 @@ export function placeRibbonGridItems(items: IMenuSchema[]): IRibbonGridPlacementshowLabel: layout.showLabel ?? false,width: layout.width,iconSize: layout.iconSize,- });+ };+ if (cells.some((cell) => occupied.has(cell))) {+ fallbackItems.push({ item, layout: placement });+ continue;+ }++ cells.forEach((cell) => occupied.add(cell));+ placements.set(item, placement);}- let fallbackRow = 1;- let fallbackColumn = maxExplicitColumn + 1;- for (const item of fallbackItems) {+ for (const { item, layout } of fallbackItems) {+ const rowSpan = layout?.rowSpan ?? 1;+ const columnSpan = layout?.columnSpan ?? 1;+ const { row, column, cells } = findFirstAvailableCells(occupied, rowSpan, columnSpan);+ cells.forEach((cell) => occupied.add(cell));placements.set(item, {item,- row: fallbackRow,- column: fallbackColumn,- rowSpan: 1,- columnSpan: 1,- showLabel: false,+ row,+ column,+ rowSpan,+ columnSpan,+ showLabel: layout?.showLabel ?? false,+ width: layout?.width,+ iconSize: layout?.iconSize,});- fallbackRow += 1;- if (fallbackRow > RIBBON_GRID_ROWS) {- fallbackRow = 1;- fallbackColumn += 1;- }}return items.map((item) => placements.get(item)!);}+function isValidGridGeometry(layout: NonNullable<IMenuSchema['gridLayout']>, rowSpan: number, cells: string[]) {+ return cells.length > 0+ && layout.row + rowSpan - 1 <= RIBBON_GRID_ROWS+ && (layout.width === undefined || (Number.isFinite(layout.width) && layout.width > 0))+ && (layout.iconSize === undefined || (Number.isFinite(layout.iconSize) && layout.iconSize > 0));+}++function findFirstAvailableCells(occupied: Set<string>, rowSpan: number, columnSpan: number) {+ for (let column = 1; ; column++) {+ for (let row = 1; row + rowSpan - 1 <= RIBBON_GRID_ROWS; row++) {+ const cells = getCells(row, column, rowSpan, columnSpan);+ if (cells.every((cell) => !occupied.has(cell))) {+ return { row, column, cells };+ }+ }+ }+}+function getCells(row: number, column: number, rowSpan: number, columnSpan: number): string[] {if (![row, column, rowSpan, columnSpan].every(Number.isInteger) || Math.min(row, column, rowSpan, columnSpan) < 1) {return [];diff --git a/packages/ui/src/views/components/workbench-skeleton/WorkbenchSkeleton.tsx b/packages/ui/src/views/components/workbench-skeleton/WorkbenchSkeleton.tsxnew file mode 100644index 0000000000..3acbf4c21a--- /dev/null+++ b/packages/ui/src/views/components/workbench-skeleton/WorkbenchSkeleton.tsx@@ -0,0 +1,128 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { LocaleService } from '@univerjs/core';+import { clsx } from '@univerjs/design';++export interface IWorkbenchSkeletonProps {+ darkMode: boolean;+ direction: ReturnType<LocaleService['getDirection']>;+ overlay?: boolean;+}++export function WorkbenchSkeleton({ darkMode, direction, overlay = false }: IWorkbenchSkeletonProps) {+ const shimmerClassName = `+ univer-animate-pulse univer-bg-gray-100 motion-reduce:univer-animate-none+ dark:!univer-bg-gray-700+ `;+ const shimmerStyle = { animationDuration: '1.2s' };++ return (+ <div+ aria-busy="true"+ className={clsx(`+ univer-flex univer-h-full univer-min-h-0 univer-flex-col univer-overflow-hidden univer-bg-gray-50+ dark:!univer-bg-gray-900+ `, {+ 'univer-absolute univer-inset-0 univer-z-50': overlay,+ 'univer-dark': darkMode,+ })}+ dir={direction}+ >+ <header+ data-u-comp="workbench-skeleton-toolbar"+ className="+ univer-flex univer-h-11 univer-shrink-0 univer-items-center univer-gap-2 univer-border-0+ univer-border-b univer-border-solid univer-border-gray-200 univer-bg-white univer-px-4+ dark:!univer-border-gray-700 dark:!univer-bg-gray-800+ "+ >+ <div+ data-u-comp="workbench-skeleton-shimmer"+ className={clsx(shimmerClassName, 'univer-h-4 univer-w-24 univer-rounded')}+ style={shimmerStyle}+ />+ <div+ data-u-comp="workbench-skeleton-shimmer"+ className={clsx(shimmerClassName, 'univer-ml-2 univer-size-6 univer-rounded')}+ style={shimmerStyle}+ />+ <div+ data-u-comp="workbench-skeleton-shimmer"+ className={clsx(shimmerClassName, 'univer-size-6 univer-rounded')}+ style={shimmerStyle}+ />+ </header>++ <main+ data-u-comp="workbench-skeleton-content"+ className="+ univer-flex univer-min-h-0 univer-min-w-0 univer-flex-1 univer-flex-col univer-gap-4 univer-p-4+ "+ >+ <div+ data-u-comp="workbench-skeleton-shimmer"+ className={clsx(shimmerClassName, 'univer-h-4 univer-w-1/3 univer-rounded')}+ style={shimmerStyle}+ />+ <div+ data-u-comp="workbench-skeleton-shimmer"+ className={clsx(shimmerClassName, 'univer-flex-1 univer-rounded-md')}+ style={shimmerStyle}+ />+ </main>++ <footer+ data-u-comp="workbench-skeleton-footer"+ className="+ univer-flex univer-h-10 univer-shrink-0 univer-items-center univer-justify-between univer-border-0+ univer-border-t univer-border-solid univer-border-gray-200 univer-bg-white univer-px-4+ dark:!univer-border-gray-700 dark:!univer-bg-gray-800+ "+ >+ <div className="univer-flex univer-items-center univer-gap-2">+ <div+ data-u-comp="workbench-skeleton-shimmer"+ className={clsx(shimmerClassName, 'univer-size-5 univer-rounded')}+ style={shimmerStyle}+ />+ <div+ data-u-comp="workbench-skeleton-shimmer"+ className={clsx(shimmerClassName, 'univer-h-5 univer-w-14 univer-rounded')}+ style={shimmerStyle}+ />+ </div>+ <div className="univer-flex univer-items-center univer-gap-2">+ <div+ data-u-comp="workbench-skeleton-shimmer"+ className={clsx(shimmerClassName, 'univer-size-5 univer-rounded')}+ style={shimmerStyle}+ />+ <div+ data-u-comp="workbench-skeleton-shimmer"+ className={clsx(shimmerClassName, 'univer-h-2 univer-w-24 univer-rounded-full')}+ style={shimmerStyle}+ />+ <div+ data-u-comp="workbench-skeleton-shimmer"+ className={clsx(shimmerClassName, 'univer-size-5 univer-rounded')}+ style={shimmerStyle}+ />+ </div>+ </footer>+ </div>+ );+}diff --git a/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx b/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsxindex 23be2458a1..1c1338d897 100644--- a/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx+++ b/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx@@ -17,16 +17,18 @@import type { Injector } from '@univerjs/core';import type { ComponentType } from 'react';import type { IWorkbenchOptions } from '../../controllers/ui/ui.controller';-import { LocaleService, ThemeService } from '@univerjs/core';+import { LifecycleService, LifecycleStages, LocaleService, ThemeService } from '@univerjs/core';import { borderBottomClassName, clsx, ConfigProvider, render } from '@univerjs/design';import { useEffect, useLayoutEffect, useMemo, useRef } from 'react';import { map } from 'rxjs';import { BuiltInUIPart } from '../../services/parts/parts.service';import { ThemeSwitcherService } from '../../services/theme-switcher/theme-switcher.service';+import { IWorkbenchService } from '../../services/workbench/workbench.service';import { connectInjector, useDependency, useObservable } from '../../utils/di';import { ComponentContainer, useComponentsOfPart } from '../components/ComponentContainer';import { MobileContextMenu } from '../components/context-menu/MobileContextMenu';import { Sidebar } from '../components/sidebar/Sidebar';+import { WorkbenchSkeleton } from '../components/workbench-skeleton/WorkbenchSkeleton';export interface IUniverAppProps extends IWorkbenchOptions {mountContainer: HTMLElement;@@ -65,6 +67,8 @@ export function MobileWorkbench(props: IUniverAppProps) {} = props;const localeService = useDependency(LocaleService);+ const lifecycleService = useDependency(LifecycleService);+ const workbenchService = useDependency(IWorkbenchService);const themeService = useDependency(ThemeService);const themeSwitcherService = useDependency(ThemeSwitcherService);@@ -79,12 +83,15 @@ export function MobileWorkbench(props: IUniverAppProps) {const toolbarComponents = useComponentsOfPart(BuiltInUIPart.TOOLBAR);const darkMode = useObservable(themeService.darkMode$, themeService.darkMode);+ const lifecycleStage = useObservable(lifecycleService.lifecycle$, lifecycleService.stage);+ const externalSkeletonVisible = useObservable(workbenchService.skeletonVisible$, undefined, true);+ const ready = lifecycleStage >= LifecycleStages.Ready;useEffect(() => {- if (contentRef.current) {+ if (ready && contentRef.current) {onRendered?.(contentRef.current);}- }, [onRendered]);+ }, [ready, onRendered]);const locale = useObservable(() => localeService.localeChanged$.pipe(map(() => localeService.getLocales())),@@ -121,87 +128,92 @@ export function MobileWorkbench(props: IUniverAppProps) {return (<ConfigProvider locale={locale?.design} direction={direction} mountContainer={portalContainer}>- {/**- * IMPORTANT! This `tabIndex` should not be moved. This attribute allows the element to catch- * all focusin event merged from its descendants. The DesktopLayoutService would listen to focusin events- * bubbled to this element and refocus the input element.- */}- <div- data-u-comp="app-layout"- className={clsx(`- univer-relative univer-flex univer-h-full univer-min-h-0 univer-flex-col univer-bg-white- dark:!univer-bg-gray-800- `, {- 'univer-dark': darkMode,- })}- tabIndex={-1}- onBlur={(e) => e.stopPropagation()}- onContextMenu={(e) => e.preventDefault()}- dir={direction}- >- {/* header */}- {header && toolbar && (- <header- data-u-comp="headerbar"- className="univer-relative univer-z-10 univer-w-full univer-overflow-hidden"- >- <ComponentContainer- key="toolbar"- components={toolbarComponents}- sharedProps={{- ribbonType,- headerMenuComponents,- headerMenu,- }}- />- </header>- )}+ <div className="univer-relative univer-h-full univer-min-h-0">+ {/**+ * IMPORTANT! This `tabIndex` should not be moved. This attribute allows the element to catch+ * all focusin event merged from its descendants. The DesktopLayoutService would listen to focusin events+ * bubbled to this element and refocus the input element.+ */}+ <div+ data-u-comp="app-layout"+ className={clsx(`+ univer-relative univer-flex univer-h-full univer-min-h-0 univer-flex-col univer-bg-white+ dark:!univer-bg-gray-800+ `, {+ 'univer-dark': darkMode,+ })}+ tabIndex={-1}+ onBlur={(e) => e.stopPropagation()}+ onContextMenu={(e) => e.preventDefault()}+ dir={direction}+ >+ {/* header */}+ {header && toolbar && (+ <header+ data-u-comp="headerbar"+ className="univer-relative univer-z-10 univer-w-full univer-overflow-hidden"+ >+ <ComponentContainer+ key="toolbar"+ components={toolbarComponents}+ sharedProps={{+ ribbonType,+ headerMenuComponents,+ headerMenu,+ }}+ />+ </header>+ )}- {/* content */}- <section className="univer-relative univer-flex univer-min-h-0 univer-flex-1 univer-flex-col">- <div- className={`- univer-grid univer-h-full univer-grid-cols-[auto_1fr_auto] univer-grid-rows-[100%]- univer-overflow-hidden- `}- >- <aside className="univer-h-full">- <ComponentContainer key="left-sidebar" components={leftSidebarComponents} />- </aside>-- <section- className={clsx(`- univer-relative univer-grid univer-flex-1 univer-grid-rows-[auto_1fr]- univer-overflow-hidden univer-bg-white- dark:!univer-bg-gray-800- `, borderBottomClassName)}+ {/* content */}+ <section className="univer-relative univer-flex univer-min-h-0 univer-flex-1 univer-flex-col">+ <div+ className={`+ univer-grid univer-h-full univer-grid-cols-[auto_1fr_auto] univer-grid-rows-[100%]+ univer-overflow-hidden+ `}>- <header className="univer-w-screen">- {header && <ComponentContainer key="header" components={headerComponents} />}- </header>+ <aside className="univer-h-full">+ <ComponentContainer key="left-sidebar" components={leftSidebarComponents} />+ </aside><section- ref={contentRef}- className="univer-relative univer-overflow-hidden"- data-range-selector- onContextMenu={(e) => e.preventDefault()}+ className={clsx(`+ univer-relative univer-grid univer-flex-1 univer-grid-rows-[auto_1fr]+ univer-overflow-hidden univer-bg-white+ dark:!univer-bg-gray-800+ `, borderBottomClassName)}>- <ComponentContainer key="content" components={contentComponents} />+ <header className="univer-w-screen">+ {header && <ComponentContainer key="header" components={headerComponents} />}+ </header>++ <section+ ref={contentRef}+ className="univer-relative univer-overflow-hidden"+ data-range-selector+ onContextMenu={(e) => e.preventDefault()}+ >+ <ComponentContainer key="content" components={contentComponents} />+ </section></section>- </section>-- <aside className="univer-h-full">- <Sidebar />- </aside>- </div>-- {/* footer */}- {footer && (- <footer>- <ComponentContainer key="footer" components={footerComponents} />- </footer>- )}- </section>++ <aside className="univer-h-full">+ <Sidebar />+ </aside>+ </div>++ {/* footer */}+ {footer && (+ <footer>+ <ComponentContainer key="footer" components={footerComponents} />+ </footer>+ )}+ </section>+ </div>+ {(!ready || externalSkeletonVisible) && (+ <WorkbenchSkeleton darkMode={darkMode} direction={direction} overlay />+ )}</div><div dir={direction}><ComponentContainer key="global" components={globalComponents} />diff --git a/packages/ui/src/views/workbench/Workbench.tsx b/packages/ui/src/views/workbench/Workbench.tsxindex 86e59f2d19..dcfea6a213 100644--- a/packages/ui/src/views/workbench/Workbench.tsx+++ b/packages/ui/src/views/workbench/Workbench.tsx@@ -18,7 +18,7 @@ import type { Injector } from '@univerjs/core';import type { ComponentType } from 'react';import type { IUniverUIConfig } from '../../config/config';import type { IWorkbenchOptions } from '../../controllers/ui/ui.controller';-import { IConfigService, LocaleService, ThemeService } from '@univerjs/core';+import { IConfigService, LifecycleService, LifecycleStages, LocaleService, ThemeService } from '@univerjs/core';import { borderBottomClassName, clsx, ConfigContext, ConfigProvider, render } from '@univerjs/design';import { useContext, useEffect, useLayoutEffect, useMemo, useRef } from 'react';import { createPortal } from 'react-dom';@@ -26,10 +26,12 @@ import { map } from 'rxjs';import { UI_PLUGIN_CONFIG_KEY } from '../../config/config';import { BuiltInUIPart } from '../../services/parts/parts.service';import { ThemeSwitcherService } from '../../services/theme-switcher/theme-switcher.service';+import { IWorkbenchService } from '../../services/workbench/workbench.service';import { connectInjector, useDependency, useObservable } from '../../utils/di';import { ComponentContainer, useComponentsOfPart } from '../components/ComponentContainer';import { DesktopContextMenu } from '../components/context-menu/ContextMenu';import { Sidebar } from '../components/sidebar/Sidebar';+import { WorkbenchSkeleton } from '../components/workbench-skeleton/WorkbenchSkeleton';import { useConfigValue } from '../hooks/index';export interface IUniverWorkbenchProps extends IWorkbenchOptions {@@ -74,6 +76,8 @@ export function DesktopWorkbenchContent(props: IUniverWorkbenchProps) {} = props;const localeService = useDependency(LocaleService);+ const lifecycleService = useDependency(LifecycleService);+ const workbenchService = useDependency(IWorkbenchService);const themeService = useDependency(ThemeService);const themeSwitcherService = useDependency(ThemeSwitcherService);const contentRef = useRef<HTMLDivElement>(null);@@ -87,6 +91,9 @@ export function DesktopWorkbenchContent(props: IUniverWorkbenchProps) {const leftSidebarComponents = useComponentsOfPart(BuiltInUIPart.LEFT_SIDEBAR);const globalComponents = useComponentsOfPart(BuiltInUIPart.GLOBAL);const toolbarComponents = useComponentsOfPart(BuiltInUIPart.TOOLBAR);+ const lifecycleStage = useObservable(lifecycleService.lifecycle$, lifecycleService.stage);+ const externalSkeletonVisible = useObservable(workbenchService.skeletonVisible$, undefined, true);+ const ready = lifecycleStage >= LifecycleStages.Ready;const popupRootId = uiConfig?.popupRootId ?? 'univer-popup-portal';@@ -110,10 +117,10 @@ export function DesktopWorkbenchContent(props: IUniverWorkbenchProps) {}, [darkMode]);useEffect(() => {- if (contentRef.current) {+ if (ready && contentRef.current) {onRendered?.(contentRef.current);}- }, [onRendered]);+ }, [ready, onRendered]);const locale = useObservable(() => localeService.localeChanged$.pipe(map(() => localeService.getLocales())),@@ -140,101 +147,106 @@ export function DesktopWorkbenchContent(props: IUniverWorkbenchProps) {return (<ConfigProvider locale={locale?.design} direction={direction} mountContainer={portalContainer}>- {/**- * IMPORTANT! This `tabIndex` should not be moved. This attribute allows the element to catch- * all focusin event merged from its descendants. The DesktopLayoutService would listen to focusin events- * bubbled to this element and refocus the input element.- */}- <div- data-u-comp="workbench-layout"- className={clsx(`- univer-flex univer-h-full univer-min-h-0 univer-flex-col univer-bg-white- dark:!univer-bg-gray-800- `, {- 'univer-dark': darkMode,- })}- tabIndex={-1}- onBlur={(e) => e.stopPropagation()}- onContextMenu={(e) => e.preventDefault()}- dir={direction}- >- {/* user header */}+ <div className="univer-relative univer-h-full univer-min-h-0">+ {/**+ * IMPORTANT! This `tabIndex` should not be moved. This attribute allows the element to catch+ * all focusin event merged from its descendants. The DesktopLayoutService would listen to focusin events+ * bubbled to this element and refocus the input element.+ */}<div- className={`- univer-relative univer-flex univer-min-h-0 univer-flex-col univer-bg-white+ data-u-comp="workbench-layout"+ className={clsx(`+ univer-flex univer-h-full univer-min-h-0 univer-flex-col univer-bg-whitedark:!univer-bg-gray-800- `}+ `, {+ 'univer-dark': darkMode,+ })}+ tabIndex={-1}+ onBlur={(e) => e.stopPropagation()}+ onContextMenu={(e) => e.preventDefault()}+ dir={direction}>- <ComponentContainer key="custom-header" components={customHeaderComponents} />- </div>-- {/* header */}- {header && toolbar && (- <header- data-u-comp="headerbar"- className="univer-relative univer-z-10 univer-w-full univer-overflow-hidden"- >- <ComponentContainer- key="toolbar"- components={toolbarComponents}- sharedProps={{- ribbonType,- headerMenuComponents,- headerMenu,- }}- />- </header>- )}-- {/* content */}- <section className="univer-relative univer-flex univer-min-h-0 univer-flex-1 univer-flex-col">+ {/* user header */}<divclassName={`- univer-grid univer-h-full univer-grid-cols-[auto_1fr_auto] univer-grid-rows-[100%]- univer-overflow-hidden+ univer-relative univer-flex univer-min-h-0 univer-flex-col univer-bg-white+ dark:!univer-bg-gray-800`}>- <aside data-u-comp="left-sidebar" className="univer-h-full">- <ComponentContainer key="left-sidebar" components={leftSidebarComponents} />- </aside>-- <section- className={clsx(`- univer-relative univer-grid univer-flex-1 univer-grid-rows-[auto_1fr]- univer-overflow-hidden univer-bg-white- dark:!univer-bg-gray-800- `, borderBottomClassName)}+ <ComponentContainer key="custom-header" components={customHeaderComponents} />+ </div>++ {/* header */}+ {header && toolbar && (+ <header+ data-u-comp="headerbar"+ className="univer-relative univer-z-10 univer-w-full univer-overflow-hidden">- <header>- {header && <ComponentContainer key="header" components={headerComponents} />}- </header>+ <ComponentContainer+ key="toolbar"+ components={toolbarComponents}+ sharedProps={{+ ribbonType,+ headerMenuComponents,+ headerMenu,+ }}+ />+ </header>+ )}++ {/* content */}+ <section className="univer-relative univer-flex univer-min-h-0 univer-flex-1 univer-flex-col">+ <div+ className={`+ univer-grid univer-h-full univer-grid-cols-[auto_1fr_auto] univer-grid-rows-[100%]+ univer-overflow-hidden+ `}+ >+ <aside data-u-comp="left-sidebar" className="univer-h-full">+ <ComponentContainer key="left-sidebar" components={leftSidebarComponents} />+ </aside><section- className={`- univer-relative univer-overflow-hidden- dark:!univer-bg-gray-900- `}- ref={contentRef}- data-range-selector- onContextMenu={(e) => e.preventDefault()}+ className={clsx(`+ univer-relative univer-grid univer-flex-1 univer-grid-rows-[auto_1fr]+ univer-overflow-hidden univer-bg-white+ dark:!univer-bg-gray-800+ `, borderBottomClassName)}>- <ComponentContainer key="content" components={contentComponents} />- </section>+ <header>+ {header && <ComponentContainer key="header" components={headerComponents} />}+ </header>- </section>+ <section+ className={`+ univer-relative univer-overflow-hidden+ dark:!univer-bg-gray-900+ `}+ ref={contentRef}+ data-range-selector+ onContextMenu={(e) => e.preventDefault()}+ >+ <ComponentContainer key="content" components={contentComponents} />+ </section>- <aside data-u-comp="right-sidebar" className="univer-z-[100] univer-h-full">- <Sidebar />- </aside>- </div>+ </section>- {/* footer */}- {footer && (- <footer>- <ComponentContainer key="footer" components={footerComponents} sharedProps={{ contextMenu }} />- </footer>- )}- </section>+ <aside data-u-comp="right-sidebar" className="univer-z-[100] univer-h-full">+ <Sidebar />+ </aside>+ </div>++ {/* footer */}+ {footer && (+ <footer>+ <ComponentContainer key="footer" components={footerComponents} sharedProps={{ contextMenu }} />+ </footer>+ )}+ </section>+ </div>+ {(!ready || externalSkeletonVisible) && (+ <WorkbenchSkeleton darkMode={darkMode} direction={direction} overlay />+ )}</div><div dir={direction}>diff --git a/packages/ui/src/views/workbench/__tests__/Workbench.spec.tsx b/packages/ui/src/views/workbench/__tests__/Workbench.spec.tsxnew file mode 100644index 0000000000..1378cc1540--- /dev/null+++ b/packages/ui/src/views/workbench/__tests__/Workbench.spec.tsx@@ -0,0 +1,128 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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.+ */++/**+ * @vitest-environment jsdom+ */++import type { IDisposable } from '@univerjs/core';+import type { ComponentType } from 'react';+import { act, cleanup, render } from '@testing-library/react';+import {+ IConfigService,+ Injector,+ LifecycleService,+ LifecycleStages,+ LocaleService,+ ThemeService,+} from '@univerjs/core';+import { BehaviorSubject, of, Subject } from 'rxjs';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { IUIPartsService, UIPartsService } from '../../../services/parts/parts.service';+import { ISidebarService } from '../../../services/sidebar/sidebar.service';+import { ThemeSwitcherService } from '../../../services/theme-switcher/theme-switcher.service';+import { IWorkbenchService, WorkbenchService } from '../../../services/workbench/workbench.service';+import { connectInjector } from '../../../utils/di';+import { DesktopWorkbenchContent } from '../Workbench';++describe('DesktopWorkbenchContent lifecycle', () => {+ afterEach(cleanup);++ it('renders lifecycle and externally requested skeletons without unmounting ready content', () => {+ const lifecycle$ = new BehaviorSubject(LifecycleStages.Starting);+ const lifecycleService = {+ lifecycle$: lifecycle$.asObservable(),+ stage: LifecycleStages.Starting,+ };+ const injector = new Injector([+ [LifecycleService, { useValue: lifecycleService }],+ [LocaleService, {+ useValue: {+ direction$: of('ltr'),+ getDirection: () => 'ltr',+ getLocales: () => ({ design: {} }),+ localeChanged$: new Subject<void>(),+ t: (key: string) => key,+ },+ }],+ [ThemeService, {+ useValue: {+ currentTheme$: of({}),+ darkMode$: of(false),+ darkMode: false,+ },+ }],+ [ThemeSwitcherService, { useValue: { injectThemeToHead: () => {} } }],+ [IConfigService, { useValue: { getConfig: () => ({ popupRootId: 'test-popup-root' }) } }],+ [IUIPartsService, { useClass: UIPartsService }],+ [IWorkbenchService, { useClass: WorkbenchService }],+ [ISidebarService, {+ useValue: {+ sidebarOptions$: of(null),+ scrollEvent$: new Subject<Event>(),+ visible: false,+ close: () => {},+ setContainer: () => {},+ setWidth: () => {},+ },+ }],+ ]);+ const ConnectedWorkbench = connectInjector(DesktopWorkbenchContent, injector) as ComponentType<{+ mountContainer: HTMLElement;+ contextMenu: boolean;+ onRendered: (containerElement: HTMLElement) => void;+ }>;+ const mountContainer = document.createElement('div');+ const onRendered = vi.fn();+ const result = render(+ <ConnectedWorkbench+ mountContainer={mountContainer}+ contextMenu={false}+ onRendered={onRendered}+ />+ );++ expect(result.container.querySelector('[aria-busy="true"]')).not.toBeNull();+ expect(result.container.querySelector('[data-u-comp="workbench-layout"]')).not.toBeNull();+ expect(onRendered).not.toHaveBeenCalled();++ lifecycleService.stage = LifecycleStages.Ready;+ act(() => lifecycle$.next(LifecycleStages.Ready));++ expect(result.container.querySelector('[aria-busy="true"]')).toBeNull();+ expect(result.container.querySelector('[data-u-comp="workbench-layout"]')).not.toBeNull();+ expect(onRendered).toHaveBeenCalledTimes(1);++ lifecycleService.stage = LifecycleStages.Rendered;+ act(() => lifecycle$.next(LifecycleStages.Rendered));++ expect(onRendered).toHaveBeenCalledTimes(1);++ const workbenchService = injector.get(IWorkbenchService);+ let loadingToken!: IDisposable;+ act(() => {+ loadingToken = workbenchService.acquireSkeleton();+ });++ expect(result.container.querySelector('[aria-busy="true"]')).not.toBeNull();+ expect(result.container.querySelector('[data-u-comp="workbench-layout"]')).not.toBeNull();++ act(() => loadingToken.dispose());++ expect(result.container.querySelector('[aria-busy="true"]')).toBeNull();+ expect(result.container.querySelector('[data-u-comp="workbench-layout"]')).not.toBeNull();+ });+});