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(sheets-ui): preview large snapshots while loading (#7290)

Univer6799660d0c04
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index 38ba5ca391..49cc64fc2b 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -270,6 +270,7 @@ export { ISheetEmbedRuntimeService } from './services/sheet-embed-runtime.servic
export type { ISheetEmbedTabMountParams } from './services/sheet-embed-runtime.service';
export { ISheetHostChromeOverrideService } from './services/sheet-host-chrome-override.service';
export type { ISheetHostChromeOverride } from './services/sheet-host-chrome-override.service';
+export { ISheetLoadingRenderService } from './services/sheet-loading-render.service';
export { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';
export { SheetsRenderService } from './services/sheets-render.service';
export { IStatusBarService, StatusBarService } from './services/status-bar.service';
diff --git a/packages/sheets-ui/src/plugin.ts b/packages/sheets-ui/src/plugin.ts
index 9b4500ce63..30307b291d 100644
--- a/packages/sheets-ui/src/plugin.ts
+++ b/packages/sheets-ui/src/plugin.ts
@@ -117,6 +117,7 @@ import { SelectAllService } from './services/select-all/select-all.service';
import { ISheetSelectionRenderService } from './services/selection/base-selection-render.service';
import { SheetSelectionRenderService } from './services/selection/selection-render.service';
import { ISheetBarService, SheetBarService } from './services/sheet-bar/sheet-bar.service';
+import { ISheetLoadingRenderService, SheetLoadingRenderService } from './services/sheet-loading-render.service';
import { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';
import { SheetsRenderService } from './services/sheets-render.service';
import { ShortcutExperienceService } from './services/shortcut-experience.service';
@@ -178,6 +179,7 @@ export class UniverSheetsUIPlugin extends Plugin {
[SelectAllService],
[ISheetCellDropdownManagerService, { useClass: SheetCellDropdownManagerService }],
[SheetCellEditorResizeService],
+ [ISheetLoadingRenderService, { useClass: SheetLoadingRenderService }],
// controllers
[AutoHeightController],
diff --git a/packages/sheets-ui/src/services/__tests__/sheet-loading-render.service.spec.ts b/packages/sheets-ui/src/services/__tests__/sheet-loading-render.service.spec.ts
new file mode 100644
index 0000000000..a772526a87
--- /dev/null
+++ b/packages/sheets-ui/src/services/__tests__/sheet-loading-render.service.spec.ts
@@ -0,0 +1,168 @@
+/**
+ * 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 { IWorkbookData } from '@univerjs/core';
+import type { ILayoutService } from '@univerjs/ui';
+import {
+ ContextService,
+ DesktopLogService,
+ IContextService,
+ ILogService,
+ Injector,
+ InterceptorEffectEnum,
+ IUniverInstanceService,
+ LocaleType,
+ toDisposable,
+ UniverInstanceService,
+} from '@univerjs/core';
+import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetLoadingRenderService } from '../sheet-loading-render.service';
+
+vi.mock('@univerjs/engine-render', async (importOriginal) => {
+ const original = await importOriginal<typeof import('@univerjs/engine-render')>();
+
+ class MockScene {
+ disableObjectsEvent = vi.fn();
+ makeDirty = vi.fn();
+ dispose = vi.fn();
+ }
+
+ class MockEngine {
+ private readonly _canvasElement = document.createElement('canvas');
+
+ getCanvas() {
+ return {
+ setId: (id: string) => { this._canvasElement.id = id; },
+ getCanvasEle: () => this._canvasElement,
+ };
+ }
+
+ mount(element: HTMLElement) {
+ element.append(this._canvasElement);
+ }
+
+ dispose() {
+ this._canvasElement.remove();
+ }
+ }
+
+ class MockRenderUnit {
+ readonly components = new Map();
+ readonly mainComponent = null;
+ readonly engine: MockEngine;
+ readonly scene: MockScene;
+ private readonly _skeletonManager = {
+ setCurrent: vi.fn(),
+ makeDirty: vi.fn(),
+ reCalculate: vi.fn(),
+ };
+
+ constructor(options: { engine: MockEngine; scene: MockScene }) {
+ this.engine = options.engine;
+ this.scene = options.scene;
+ }
+
+ addRenderDependencies() { }
+
+ with() {
+ return this._skeletonManager;
+ }
+
+ dispose() { }
+ }
+
+ return {
+ ...original,
+ Engine: MockEngine,
+ RenderUnit: MockRenderUnit,
+ Scene: MockScene,
+ };
+});
+
+describe('SheetLoadingRenderService', () => {
+ it('renders intercepted display values without owning the global workbook or pointer events', () => {
+ const contentElement = document.createElement('div');
+ contentElement.style.pointerEvents = 'auto';
+ vi.spyOn(contentElement, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 640, 480));
+
+ const layoutService: ILayoutService = {
+ isFocused: false,
+ rootContainerElement: null,
+ focus() { },
+ registerFocusHandler: () => toDisposable(() => {}),
+ registerRootContainerElement: () => toDisposable(() => {}),
+ registerContentElement: () => toDisposable(() => {}),
+ registerContainerElement: () => toDisposable(() => {}),
+ getContentElement: () => contentElement,
+ checkElementInCurrentContainers: () => false,
+ checkContentIsFocused: () => false,
+ };
+ const injector = new Injector();
+ injector.add([ILogService, { useClass: DesktopLogService }]);
+ injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
+ injector.add([SheetInterceptorService]);
+ const interceptorService = injector.get(SheetInterceptorService);
+ const displayInterceptor = vi.fn((cell, context, next) => next({ ...cell, v: '1,234' }));
+ interceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {
+ effect: InterceptorEffectEnum.Value | InterceptorEffectEnum.Style,
+ handler: displayInterceptor,
+ });
+
+ const service = new SheetLoadingRenderService(injector, layoutService, interceptorService);
+ const workbookData = {
+ id: 'unit-1',
+ name: 'Workbook',
+ appVersion: '',
+ locale: LocaleType.EN_US,
+ styles: {},
+ sheetOrder: ['sheet-1'],
+ sheets: {
+ 'sheet-1': {
+ id: 'sheet-1',
+ cellData: {},
+ },
+ },
+ resources: [],
+ } satisfies IWorkbookData;
+
+ service.show(workbookData, 'sheet-1', { 2: { 3: { v: 1234 } } });
+
+ const previewWorkbook = service.workbook$.value;
+ expect(contentElement.style.pointerEvents).toBe('auto');
+ expect(contentElement.querySelector('canvas')?.style.pointerEvents).toBe('none');
+ expect(previewWorkbook?.getSheetBySheetId('sheet-1')?.getCellRaw(2, 3)?.v).toBe('1,234');
+ expect(displayInterceptor).toHaveBeenCalledWith(
+ { v: 1234 },
+ expect.objectContaining({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ workbook: previewWorkbook,
+ row: 2,
+ col: 3,
+ rawData: { v: 1234 },
+ }),
+ expect.any(Function)
+ );
+
+ service.hide('unit-1');
+
+ expect(service.loading$.value).toBe(false);
+ expect(contentElement.querySelector('canvas')).toBeNull();
+ service.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/services/sheet-loading-render.service.ts b/packages/sheets-ui/src/services/sheet-loading-render.service.ts
new file mode 100644
index 0000000000..5a3e9547d8
--- /dev/null
+++ b/packages/sheets-ui/src/services/sheet-loading-render.service.ts
@@ -0,0 +1,204 @@
+/**
+ * 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 { ICellData, IObjectMatrixPrimitiveType, IWorkbookData } from '@univerjs/core';
+import type { Observable } from 'rxjs';
+import { createIdentifier, Disposable, Inject, Injector, InterceptorEffectEnum, ObjectMatrix, Workbook } from '@univerjs/core';
+import { Engine, RenderUnit, Scene, Spreadsheet } from '@univerjs/engine-render';
+import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
+import { ILayoutService } from '@univerjs/ui';
+import { BehaviorSubject } from 'rxjs';
+import { SheetRenderController } from '../controllers/render-controllers/sheet.render-controller';
+import { SheetSkeletonRenderController } from '../controllers/render-controllers/skeleton.render-controller';
+import { SheetSkeletonManagerService } from './sheet-skeleton-manager.service';
+
+const PREVIEW_UNIT_SUFFIX = '__snapshot_loading_preview__';
+const PREVIEW_SCENE_PREFIX = '_UNIVER_SCENE_';
+
+export interface ISheetLoadingRenderService {
+ readonly workbook$: Observable<Workbook | null>;
+ readonly loading$: Observable<boolean>;
+
+ show(workbookData: IWorkbookData, activeSheetId: string, cellData?: IObjectMatrixPrimitiveType<ICellData>): void;
+ hide(sourceUnitId: string): void;
+}
+
+export const ISheetLoadingRenderService = createIdentifier<ISheetLoadingRenderService>('sheets-ui.sheet-loading-render.service');
+
+interface ILoadingRender {
+ sourceUnitId: string;
+ workbook: Workbook;
+ render: RenderUnit;
+ lastCellData?: IObjectMatrixPrimitiveType<ICellData>;
+}
+
+/**
+ * Renders a read-only workbook shell without registering it in IUniverInstanceService.
+ * The temporary workbook is therefore invisible to formulas, RPC and collaboration.
+ */
+export class SheetLoadingRenderService extends Disposable implements ISheetLoadingRenderService {
+ readonly workbook$ = new BehaviorSubject<Workbook | null>(null);
+ readonly loading$ = new BehaviorSubject(false);
+
+ private _loadingRender: ILoadingRender | null = null;
+
+ constructor(
+ @Inject(Injector) private readonly _injector: Injector,
+ @ILayoutService private readonly _layoutService: ILayoutService,
+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService
+ ) {
+ super();
+ }
+
+ show(
+ workbookData: IWorkbookData,
+ activeSheetId: string,
+ cellData?: IObjectMatrixPrimitiveType<ICellData>
+ ): void {
+ const sourceUnitId = workbookData.id;
+ if (this._loadingRender?.sourceUnitId !== sourceUnitId) {
+ this._disposeLoadingRender();
+ this._loadingRender = this._createLoadingRender(workbookData, activeSheetId);
+ this.workbook$.next(this._loadingRender.workbook);
+ this.loading$.next(true);
+ }
+
+ const loadingRender = this._loadingRender;
+ if (!loadingRender) {
+ return;
+ }
+
+ const worksheet = loadingRender.workbook.getSheetBySheetId(activeSheetId);
+ if (!worksheet) {
+ return;
+ }
+
+ if (loadingRender.workbook.getActiveSheet().getSheetId() !== activeSheetId) {
+ loadingRender.workbook.setActiveSheet(worksheet);
+ loadingRender.render.with(SheetSkeletonManagerService).setCurrent({ sheetId: activeSheetId });
+ }
+
+ if (cellData && cellData !== loadingRender.lastCellData) {
+ loadingRender.lastCellData = cellData;
+ const target = worksheet.getCellMatrix();
+ const getDisplayCell = this._sheetInterceptorService.fetchThroughInterceptors(
+ INTERCEPTOR_POINT.CELL_CONTENT,
+ InterceptorEffectEnum.Value | InterceptorEffectEnum.Style
+ );
+ new ObjectMatrix(cellData).forValue((row, column, rawData) => {
+ const displayCell = getDisplayCell(rawData, {
+ unitId: loadingRender.sourceUnitId,
+ subUnitId: activeSheetId,
+ row,
+ col: column,
+ workbook: loadingRender.workbook,
+ worksheet,
+ rawData,
+ });
+ target.setValue(row, column, displayCell);
+ });
+
+ const skeletonManager = loadingRender.render.with(SheetSkeletonManagerService);
+ skeletonManager.makeDirty({ sheetId: activeSheetId });
+ skeletonManager.reCalculate();
+ if (loadingRender.render.mainComponent instanceof Spreadsheet) {
+ loadingRender.render.mainComponent.makeForceDirty(true);
+ }
+ loadingRender.render.scene.makeDirty(true);
+ }
+ }
+
+ hide(sourceUnitId: string): void {
+ if (this._loadingRender?.sourceUnitId !== sourceUnitId) {
+ return;
+ }
+
+ this._disposeLoadingRender();
+ }
+
+ override dispose(): void {
+ this._disposeLoadingRender();
+ this.workbook$.complete();
+ this.loading$.complete();
+ super.dispose();
+ }
+
+ private _createLoadingRender(workbookData: IWorkbookData, activeSheetId: string): ILoadingRender {
+ const previewUnitId = `${workbookData.id}${PREVIEW_UNIT_SUFFIX}`;
+ const workbook = this._injector.createInstance(Workbook, {
+ ...workbookData,
+ id: previewUnitId,
+ });
+ const activeSheet = workbook.getSheetBySheetId(activeSheetId);
+ if (activeSheet) {
+ workbook.setActiveSheet(activeSheet);
+ }
+
+ const contentElement = this._layoutService.getContentElement();
+ const { width, height } = contentElement.getBoundingClientRect();
+ const engine = this._injector.createInstance(Engine, previewUnitId, undefined);
+ const scene = new Scene(`${PREVIEW_SCENE_PREFIX}${previewUnitId}`, engine, {
+ width,
+ height,
+ });
+ scene.disableObjectsEvent();
+
+ const render = this._injector.createInstance(RenderUnit, {
+ unit: workbook,
+ engine,
+ scene,
+ isMainScene: true,
+ });
+ try {
+ render.addRenderDependencies([
+ [SheetSkeletonManagerService],
+ [SheetSkeletonRenderController],
+ [SheetRenderController],
+ ]);
+
+ const canvas = engine.getCanvas();
+ canvas.setId(`univer-sheet-loading-canvas_${workbookData.id}`);
+ canvas.getCanvasEle().dataset.uUnitId = workbookData.id;
+ canvas.getCanvasEle().style.pointerEvents = 'none';
+ engine.mount(contentElement);
+ return { sourceUnitId: workbookData.id, workbook, render };
+ } catch (error) {
+ this._disposeRender(render);
+ workbook.dispose();
+ throw error;
+ }
+ }
+
+ private _disposeLoadingRender(): void {
+ const loadingRender = this._loadingRender;
+ this._loadingRender = null;
+ this.workbook$.next(null);
+ this.loading$.next(false);
+ if (!loadingRender) {
+ return;
+ }
+
+ this._disposeRender(loadingRender.render);
+ loadingRender.workbook.dispose();
+ }
+
+ private _disposeRender(render: RenderUnit): void {
+ render.components.forEach((component) => component.dispose());
+ render.scene.dispose();
+ render.dispose();
+ render.engine.dispose();
+ }
+}
diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
index 90227c53eb..2528c43321 100644
--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-import type { Workbook } from '@univerjs/core';
import type { IUniverSheetsUIConfig } from '../../config/config';
import type { IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
import {
@@ -23,8 +22,6 @@ import {
ICommandService,
IContextService,
IPermissionService,
- IUniverInstanceService,
- UniverInstanceType,
} from '@univerjs/core';
import { borderBottomClassName, borderRightClassName, clsx } from '@univerjs/design';
import { IEditorService } from '@univerjs/docs-ui';
@@ -59,6 +56,7 @@ import { IEditorBridgeService } from '../../services/editor-bridge.service';
import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';
import { DefinedName } from '../defined-name/DefinedName';
import { useKeyEventConfig } from '../editor-container/hooks';
+import { useActiveWorkbook } from '../hook';
enum ArrowDirection {
Down,
@@ -83,7 +81,6 @@ export function FormulaBar(props: IProps) {
const formulaEditorManagerService = useDependency(IFormulaEditorManagerService);
const worksheetProtectionRuleModel = useDependency(WorksheetProtectionRuleModel);
const rangeProtectionRuleModel = useDependency(RangeProtectionRuleModel);
- const univerInstanceService = useDependency(IUniverInstanceService);
const selectionManager = useDependency(SheetsSelectionsService);
const permissionService = useDependency(IPermissionService);
const rangeProtectionCache = useDependency(RangeProtectionCache);
@@ -97,7 +94,7 @@ export function FormulaBar(props: IProps) {
[editorBridgeService]
);
const componentManager = useDependency(ComponentManager);
- const workbook = useObservable(() => univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET), undefined, undefined, [])!;
+ const workbook = useActiveWorkbook();
const editState = useObservable(editorBridgeService.currentEditCellState$);
const keyCodeConfig = useKeyEventConfig(editState?.unitId);
const FormulaEditor = componentManager.get(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY);
@@ -120,56 +117,62 @@ export function FormulaBar(props: IProps) {
const disableEdit = config?.disableEdit;
const disableInfo = useObservable(
- () => workbook.activeSheet$.pipe(
- switchMap((worksheet) => {
- if (!worksheet) {
- return EMPTY;
- }
- return merge(
- worksheetProtectionRuleModel.ruleChange$,
- rangeProtectionRuleModel.ruleChange$,
- selectionManager.selectionMoveEnd$,
- selectionManager.selectionSet$
- ).pipe(
- switchMap(() => {
- const unitId = workbook.getUnitId();
- const subUnitId = worksheet.getSheetId();
- const range = selectionManager.getCurrentLastSelection()?.range;
- if (!range) return EMPTY;
- const primary = selectionManager.getCurrentLastSelection()?.primary;
- if (!primary) {
- return of(null);
- }
+ () => {
+ if (!workbook) {
+ return EMPTY;
+ }
- return of({
- unitId,
- subUnitId,
- primary,
- });
- })
- );
- }),
- map((cellInfo) => {
- if (cellInfo) {
- const { unitId, subUnitId, primary } = cellInfo;
- if (worksheetProtectionRuleModel.getRule(unitId, subUnitId)) {
- const editDisable = !(permissionService.getPermissionPoint(new WorksheetEditPermission(unitId, subUnitId).id)?.value ?? true);
- const viewDisable = !(permissionService.getPermissionPoint(new WorksheetViewPermission(unitId, subUnitId).id)?.value ?? true);
+ return workbook.activeSheet$.pipe(
+ switchMap((worksheet) => {
+ if (!worksheet) {
+ return EMPTY;
+ }
+ return merge(
+ worksheetProtectionRuleModel.ruleChange$,
+ rangeProtectionRuleModel.ruleChange$,
+ selectionManager.selectionMoveEnd$,
+ selectionManager.selectionSet$
+ ).pipe(
+ switchMap(() => {
+ const unitId = workbook.getUnitId();
+ const subUnitId = worksheet.getSheetId();
+ const range = selectionManager.getCurrentLastSelection()?.range;
+ if (!range) return EMPTY;
+ const primary = selectionManager.getCurrentLastSelection()?.primary;
+ if (!primary) {
+ return of(null);
+ }
+
+ return of({
+ unitId,
+ subUnitId,
+ primary,
+ });
+ })
+ );
+ }),
+ map((cellInfo) => {
+ if (cellInfo) {
+ const { unitId, subUnitId, primary } = cellInfo;
+ if (worksheetProtectionRuleModel.getRule(unitId, subUnitId)) {
+ const editDisable = !(permissionService.getPermissionPoint(new WorksheetEditPermission(unitId, subUnitId).id)?.value ?? true);
+ const viewDisable = !(permissionService.getPermissionPoint(new WorksheetViewPermission(unitId, subUnitId).id)?.value ?? true);
+ return {
+ viewDisable,
+ editDisable,
+ };
+ }
+ const { actualRow, actualColumn } = primary;
+ const cellInfoWithPermission = rangeProtectionCache.getCellInfo(unitId, subUnitId, actualRow, actualColumn);
return {
- viewDisable,
- editDisable,
+ editDisable: !(cellInfoWithPermission?.[UnitAction.Edit] ?? true),
+ viewDisable: !(cellInfoWithPermission?.[UnitAction.View] ?? true),
};
}
- const { actualRow, actualColumn } = primary;
- const cellInfoWithPermission = rangeProtectionCache.getCellInfo(unitId, subUnitId, actualRow, actualColumn);
- return {
- editDisable: !(cellInfoWithPermission?.[UnitAction.Edit] ?? true),
- viewDisable: !(cellInfoWithPermission?.[UnitAction.View] ?? true),
- };
- }
- return { viewDisable: false, editDisable: false };
- })
- ),
+ return { viewDisable: false, editDisable: false };
+ })
+ );
+ },
{ editDisable: false, viewDisable: false },
false,
[
diff --git a/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx b/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx
index f514a69cf3..718c58f103 100644
--- a/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx
@@ -241,7 +241,6 @@ function createFormulaBarTestBed() {
injector.add([IEditorBridgeService, { useClass: TestEditorBridgeService as never }]);
injector.add([ILayoutService, { useClass: TestLayoutService as never }]);
injector.add([IEditorService, { useClass: TestEditorService as never }]);
-
const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());
injector.get(IUniverInstanceService).focusUnit(UNIT_ID);
injector.get(IConfigService).setConfig(SHEETS_UI_PLUGIN_CONFIG_KEY, {});
diff --git a/packages/sheets-ui/src/views/hook.ts b/packages/sheets-ui/src/views/hook.ts
index 0e1de0243e..88a9e3d5bc 100644
--- a/packages/sheets-ui/src/views/hook.ts
+++ b/packages/sheets-ui/src/views/hook.ts
@@ -18,14 +18,28 @@ import type { Workbook } from '@univerjs/core';
import { IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
import { useDependency, useObservable } from '@univerjs/ui';
-import { useMemo } from 'react';
+import { createContext, useContext, useMemo } from 'react';
import { map, merge, of, startWith } from 'rxjs';
+import { ISheetLoadingRenderService } from '../services/sheet-loading-render.service';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
+export const SheetLoadingWorkbookContext = createContext<Workbook | null>(null);
+
export function useActiveWorkbook(): Workbook | null {
const univerInstanceService = useDependency(IUniverInstanceService);
+ const loadingWorkbook = useContext(SheetLoadingWorkbookContext);
const workbook = useObservable(() => univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET), undefined, undefined, []);
- return workbook ?? null;
+ return workbook ?? loadingWorkbook ?? null;
+}
+
+export function useSheetLoadingWorkbook(): Workbook | null {
+ const loadingRenderService = useDependency(ISheetLoadingRenderService);
+ return useObservable(loadingRenderService.workbook$) ?? null;
+}
+
+export function useSheetLoading(): boolean {
+ const loadingRenderService = useDependency(ISheetLoadingRenderService);
+ return useObservable(loadingRenderService.loading$) ?? false;
}
export function useActiveWorksheet(workbook?: Workbook | null) {
diff --git a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
index 02152afb49..66fdf0c253 100644
--- a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
+++ b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
@@ -17,6 +17,7 @@
import type { Workbook, Worksheet } from '@univerjs/core';
import type { IUniverSheetsUIConfig } from '../../config/config';
import { Injector, isInternalEditorID, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { clsx } from '@univerjs/design';
import { ComponentManager, ContextMenuPosition, IMenuManagerService, ToolbarItem, useConfigValue, useDependency, useObservable } from '@univerjs/ui';
import { useEffect, useMemo } from 'react';
import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';
@@ -25,7 +26,13 @@ import { ISheetEmbedRuntimeService } from '../../services/sheet-embed-runtime.se
import { AutoFillPopupMenu } from '../auto-fill-popup-menu/AutoFillPopupMenu';
import { EditorContainer } from '../editor-container/EditorContainer';
import { FormulaBar } from '../formula-bar/FormulaBar';
-import { useActiveWorkbook, useActiveWorksheet } from '../hook';
+import {
+ SheetLoadingWorkbookContext,
+ useActiveWorkbook,
+ useActiveWorksheet,
+ useSheetLoading,
+ useSheetLoadingWorkbook,
+} from '../hook';
import { SheetBar } from '../sheet-bar/SheetBar';
import { SheetZoomSlider } from '../sheet-slider/CountBar';
import { StatusBar } from '../status-bar/StatusBar';
@@ -36,7 +43,10 @@ export function RenderSheetFooter() {
const config = useConfigValue<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);
const menuManagerService = useDependency(IMenuManagerService);
const showFooter = config?.footer ?? true;
- const workbook = useActiveWorkbook();
+ const activeWorkbook = useActiveWorkbook();
+ const loadingWorkbook = useSheetLoadingWorkbook();
+ const workbook = activeWorkbook ?? loadingWorkbook;
+ const isLoading = useSheetLoading();
const activeWorkbookEmbeddedRender = useActiveWorkbookIsEmbeddedRender(workbook);
const focusedUnitType = useFocusedUnitType();
const activeEmbedTab = useActiveSheetEmbedTabData(workbook);
@@ -57,39 +67,45 @@ export function RenderSheetFooter() {
if (!sheetBar && !showStatisticBar && !showMenus && !showZoomSlider) return null;
return (
- <section
- className={`
- univer-box-border univer-grid univer-w-full univer-grid-flow-col univer-grid-cols-[1fr,auto,auto,auto]
- univer-items-center univer-justify-between univer-bg-white univer-px-5 univer-text-gray-900
- dark:!univer-bg-gray-900 dark:!univer-text-gray-200
- `}
- style={{
- height: SHEET_FOOTER_BAR_HEIGHT,
- }}
- data-range-selector
- >
- {sheetBar && <SheetBar />}
- {showStatisticBar && <StatusBar />}
- {showMenus && footerMenus.length > 0 && (
- <div className="univer-box-border univer-flex univer-gap-2 univer-px-2">
- {footerMenus.map((item) => item.children?.map((child) => (
- child?.item && (
- <ToolbarItem
- key={child.key}
- {...child.item}
- />
- )
- )))}
- </div>
- )}
- {showZoomSlider && <SheetZoomSlider />}
- </section>
+ <SheetLoadingWorkbookContext.Provider value={workbook}>
+ <section
+ className={clsx(`
+ univer-box-border univer-grid univer-w-full univer-grid-flow-col univer-grid-cols-[1fr,auto,auto,auto]
+ univer-items-center univer-justify-between univer-bg-white univer-px-5 univer-text-gray-900
+ dark:!univer-bg-gray-900 dark:!univer-text-gray-200
+ `, { 'univer-pointer-events-none': isLoading })}
+ data-range-selector
+ aria-disabled={isLoading}
+ style={{
+ height: SHEET_FOOTER_BAR_HEIGHT,
+ }}
+ >
+ {sheetBar && <SheetBar />}
+ {showStatisticBar && <StatusBar />}
+ {showMenus && footerMenus.length > 0 && (
+ <div className="univer-box-border univer-flex univer-gap-2 univer-px-2">
+ {footerMenus.map((item) => item.children?.map((child) => (
+ child?.item && (
+ <ToolbarItem
+ key={child.key}
+ {...child.item}
+ />
+ )
+ )))}
+ </div>
+ )}
+ {showZoomSlider && <SheetZoomSlider />}
+ </section>
+ </SheetLoadingWorkbookContext.Provider>
);
}
export function RenderSheetHeader() {
const config = useConfigValue<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);
- const workbook = useActiveWorkbook();
+ const activeWorkbook = useActiveWorkbook();
+ const loadingWorkbook = useSheetLoadingWorkbook();
+ const workbook = activeWorkbook ?? loadingWorkbook;
+ const isLoading = useSheetLoading();
const hasWorkbook = !!workbook;
const activeWorkbookEmbeddedRender = useActiveWorkbookIsEmbeddedRender(workbook);
const focusedUnitType = useFocusedUnitType();
@@ -110,7 +126,13 @@ export function RenderSheetHeader() {
);
}
if (config?.formulaBar !== false) {
- return <FormulaBar />;
+ return (
+ <SheetLoadingWorkbookContext.Provider value={workbook}>
+ <div aria-disabled={isLoading} className={clsx({ 'univer-pointer-events-none': isLoading })}>
+ <FormulaBar />
+ </div>
+ </SheetLoadingWorkbookContext.Provider>
+ );
}
return null;
@@ -121,7 +143,7 @@ export function RenderSheetHeader() {
*/
export function RenderSheetContent() {
const config = useConfigValue<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);
- const hasWorkbook = useHasWorkbook();
+ const isLoading = useSheetLoading();
const componentManager = useDependency(ComponentManager);
const workbook = useActiveWorkbook();
const activeEmbedTab = useActiveSheetEmbedTabData(workbook);
@@ -132,7 +154,7 @@ export function RenderSheetContent() {
const ShapeTextEditorContainer = componentManager.get('SheetShapeTextEditorContainer') ?? componentManager.get('ShapeTextEditorContainer');
useEffect(() => {
- if (!workbook || activeEmbedTab || activeWorkbookEmbeddedRender) {
+ if (!workbook || isLoading || activeEmbedTab || activeWorkbookEmbeddedRender) {
return;
}
@@ -140,9 +162,9 @@ export function RenderSheetContent() {
instanceService.setCurrentUnitForType(workbook.getUnitId());
instanceService.focusUnit(workbook.getUnitId());
tryGetSheetEmbedRuntimeService(injector)?.clearTab();
- }, [activeEmbedTab, activeWorkbookEmbeddedRender, injector, workbook]);
+ }, [activeEmbedTab, activeWorkbookEmbeddedRender, injector, isLoading, workbook]);
- if (!hasWorkbook) return null;
+ if (!workbook || isLoading) return null;
if (activeWorkbookEmbeddedRender) return null;
if (activeEmbedTab && workbook) {
return <RenderSheetEmbedTabHost workbook={workbook} worksheet={activeEmbedTab.worksheet} />;
@@ -203,12 +225,6 @@ function RenderSheetEmbedTabHost(props: { workbook: Workbook; worksheet: Workshe
);
}
-function useHasWorkbook(): boolean {
- const univerInstanceService = useDependency(IUniverInstanceService);
- const workbook = useObservable(() => univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET), null, false, []);
- return !!workbook;
-}
-
function useActiveWorkbookIsEmbeddedRender(workbook: Workbook | null): boolean {
const univerInstanceService = useDependency(IUniverInstanceService);
return useMemo(() => {