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
fix(ui): constrain sheet popups to canvas content (#7523)
wpxp12345626404c5fb4b3
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.tsindex 677ecfa66a..9cf2d2a011 100644--- a/packages/sheets-ui/src/index.ts+++ b/packages/sheets-ui/src/index.ts@@ -271,7 +271,6 @@ export { ISheetEmbedRuntimeService } from './services/sheet-embed-runtime.servicexport 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/mobile-plugin.ts b/packages/sheets-ui/src/mobile-plugin.tsindex 3a09e11423..ed800c762e 100644--- a/packages/sheets-ui/src/mobile-plugin.ts+++ b/packages/sheets-ui/src/mobile-plugin.ts@@ -124,7 +124,6 @@ import { SelectAllService } from './services/select-all/select-all.service';import { ISheetSelectionRenderService } from './services/selection/base-selection-render.service';import { MobileSheetsSelectionRenderService } from './services/selection/mobile-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';@@ -192,8 +191,6 @@ export class UniverSheetsMobileUIPlugin extends Plugin {[SelectAllService],[ISheetCellDropdownManagerService, { useClass: SheetCellDropdownManagerService }],[SheetCellEditorResizeService],- [ISheetLoadingRenderService, { useClass: SheetLoadingRenderService }],-// controllers[AutoHeightController],[AutoWidthController],diff --git a/packages/sheets-ui/src/plugin.ts b/packages/sheets-ui/src/plugin.tsindex a630ea7f84..65932bd774 100644--- a/packages/sheets-ui/src/plugin.ts+++ b/packages/sheets-ui/src/plugin.ts@@ -120,7 +120,6 @@ 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';@@ -188,8 +187,6 @@ export class UniverSheetsUIPlugin extends Plugin {[SelectAllService],[ISheetCellDropdownManagerService, { useClass: SheetCellDropdownManagerService }],[SheetCellEditorResizeService],- [ISheetLoadingRenderService, { useClass: SheetLoadingRenderService }],-// controllers[AutoHeightController],[AutoWidthController],diff --git a/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.tsindex 460bac7d6b..e8966ac6e1 100644--- a/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts+++ b/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts@@ -335,6 +335,25 @@ describe('SheetCanvasPopManagerService', () => {expect(popupService.popups.size).toBe(0);});+ it('adds scaled sheet header insets to a canvas-constrained drawing popup', () => {+ const { service, popupService } = createSheetHarness();+ const targetObject = {+ left: 20,+ top: 10,+ width: 40,+ height: 30,+ classType: RENDER_CLASS_TYPE.SHAPE,+ getPropByKey: () => 'image',+ };++ service.attachPopupToObject(targetObject as never, {+ componentKey: 'drawing-toolbar',+ constrainToCanvas: true,+ });++ expect(popupService.lastPopup()?.boundaryInsets).toEqual({ left: 40, top: 40 });+ });+it('keeps absolute-position popups hidden while a selection is being dragged unless the popup opts in', () => {const { service, popupService, refSelectionService, sheetSelectionService } = createSheetHarness();const bound = { top: 10, left: 20, right: 30, bottom: 40 };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.tsdeleted file mode 100644index 06e27d4a68..0000000000--- a/packages/sheets-ui/src/services/__tests__/sheet-loading-render.service.spec.ts+++ /dev/null@@ -1,380 +0,0 @@-/**- * 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 {- ContextService,- DesktopLogService,- IContextService,- ILogService,- Injector,- InterceptorEffectEnum,- IUniverInstanceService,- LocaleType,- ThemeService,- toDisposable,- UniverInstanceService,- Workbook,-} from '@univerjs/core';-import { Engine, IRenderManagerService, RenderManagerService, RenderUnit, Scene } from '@univerjs/engine-render';-import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';-import { ILayoutService } from '@univerjs/ui';-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();- render = vi.fn();- requestRender = vi.fn(async () => {});- dispose = vi.fn();- }-- class MockEngine {- private readonly _canvasElement = document.createElement('canvas');-- constructor() {- this._canvasElement.style.position = 'absolute';- this._canvasElement.style.zIndex = '8';- }-- getCanvas() {- return {- setId: (id: string) => { this._canvasElement.id = id; },- getCanvasEle: () => this._canvasElement,- };- }-- getCanvasElement() {- return 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,- };-});--function createLayoutService(getContentElement: () => HTMLElement): ILayoutService {- return {- isFocused: false,- rootContainerElement: null,- focus() { },- registerFocusHandler: () => toDisposable(() => {}),- registerRootContainerElement: () => toDisposable(() => {}),- registerContentElement: () => toDisposable(() => {}),- registerContainerElement: () => toDisposable(() => {}),- getContentElement,- checkElementInCurrentContainers: () => false,- checkContentIsFocused: () => false,- };-}--describe('SheetLoadingRenderService', () => {- it('skips the preview and completes handoff when workbench content is not registered', async () => {- const contentElements: HTMLElement[] = [];- const injector = new Injector();- injector.add([ILogService, { useClass: DesktopLogService }]);- injector.add([IContextService, { useClass: ContextService }]);- injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);- injector.add([ThemeService]);- injector.add([SheetInterceptorService]);- injector.add([ILayoutService, { useValue: createLayoutService(() => contentElements[0]) }]);- injector.add([IRenderManagerService, { useClass: RenderManagerService }]);- const service = injector.createInstance(SheetLoadingRenderService);- 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.showSkeleton(workbookData, 'sheet-1');- service.show(workbookData, 'sheet-1', {});-- expect(service.loading$.value).toBe(true);- expect(service.previewReady$.value).toBe(false);- await expect(service.handoff('unit-1', 10_000)).resolves.toBe(true);- expect(service.loading$.value).toBe(false);- service.dispose();- injector.get(IRenderManagerService).dispose();- });-- it('renders intercepted display values without owning the global workbook or pointer events', async () => {- const contentElement = document.createElement('div');- contentElement.style.pointerEvents = 'auto';- vi.spyOn(contentElement, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 640, 480));- const animationFrames: FrameRequestCallback[] = [];- const requestAnimationFrame = vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {- animationFrames.push(callback);- return animationFrames.length;- });-- const layoutService = createLayoutService(() => contentElement);- const injector = new Injector();- injector.add([ILogService, { useClass: DesktopLogService }]);- injector.add([IContextService, { useClass: ContextService }]);- injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);- injector.add([ThemeService]);- 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,- });-- injector.add([ILayoutService, { useValue: layoutService }]);- injector.add([IRenderManagerService, { useClass: RenderManagerService }]);- const service = injector.createInstance(SheetLoadingRenderService);- 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;- const finalWorkbook = injector.createInstance(Workbook, workbookData);- const finalEngine = new Engine('unit-1');- const finalScene = new Scene('unit-1-scene', finalEngine);- const finalRender = injector.createInstance(RenderUnit, {- unit: finalWorkbook,- engine: finalEngine,- scene: finalScene,- isMainScene: true,- });- injector.get(IRenderManagerService).addRender('unit-1', finalRender);-- service.showSkeleton(workbookData, 'sheet-1');-- expect(service.loading$.value).toBe(true);- expect(service.previewReady$.value).toBe(false);- expect(contentElement.querySelector('canvas')).toBeNull();-- service.show(workbookData, 'sheet-1', { 2: { 3: { v: 1234 } } });- finalEngine.mount(contentElement);- animationFrames[0](0);- await vi.waitFor(() => expect(finalEngine.getCanvasElement().style.visibility).toBe('hidden'));-- const previewWorkbook = service.workbook$.value;- expect(contentElement.style.pointerEvents).toBe('auto');- expect(contentElement.querySelector('canvas')?.style.pointerEvents).toBe('none');- expect(Array.from(contentElement.querySelectorAll('canvas')).map((canvas) => canvas.style.zIndex)).toEqual(['9', '8']);- expect(service.previewReady$.value).toBe(true);- 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)- );-- const handoff = service.handoff('unit-1', 10_000);- await vi.waitFor(() => expect(animationFrames).toHaveLength(2));-- expect(finalScene.makeDirty).toHaveBeenCalledWith(true);- expect(finalScene.requestRender).toHaveBeenCalledTimes(1);- expect(service.loading$.value).toBe(true);- expect(contentElement.querySelectorAll('canvas')).toHaveLength(2);- expect(finalEngine.getCanvasElement().style.visibility).toBe('hidden');-- animationFrames[1](0);- await expect(handoff).resolves.toBe(true);-- expect(service.loading$.value).toBe(false);- expect(service.previewReady$.value).toBe(false);- expect(contentElement.querySelectorAll('canvas')).toHaveLength(1);- expect(contentElement.querySelector('canvas')?.style.zIndex).toBe('8');- expect(finalEngine.getCanvasElement().style.visibility).toBe('');- service.dispose();- injector.get(IRenderManagerService).dispose();- finalWorkbook.dispose();- finalEngine.dispose();- requestAnimationFrame.mockRestore();- });-- it('keeps the preview mounted when the final renderer times out', async () => {- vi.useFakeTimers();- const contentElement = document.createElement('div');- vi.spyOn(contentElement, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 640, 480));- const injector = new Injector();- injector.add([ILogService, { useClass: DesktopLogService }]);- injector.add([IContextService, { useClass: ContextService }]);- injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);- injector.add([ThemeService]);- injector.add([SheetInterceptorService]);- injector.add([ILayoutService, { useValue: createLayoutService(() => contentElement) }]);- injector.add([IRenderManagerService, { useClass: RenderManagerService }]);- const service = injector.createInstance(SheetLoadingRenderService);- 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.showSkeleton(workbookData, 'sheet-1');- service.show(workbookData, 'sheet-1', {});-- const handoff = service.handoff('unit-1', 10_000);- await vi.advanceTimersByTimeAsync(10_000);-- await expect(handoff).resolves.toBe(false);- expect(service.loading$.value).toBe(true);- expect(contentElement.querySelector('canvas')).not.toBeNull();- service.dispose();- injector.get(IRenderManagerService).dispose();- vi.useRealTimers();- });-- it('keeps the preview mounted until workbench content and the final canvas are mounted', async () => {- const contentElement = document.createElement('div');- const contentElements = [contentElement];- vi.spyOn(contentElement, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 640, 480));- const animationFrames: FrameRequestCallback[] = [];- const requestAnimationFrame = vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {- animationFrames.push(callback);- return animationFrames.length;- });-- const injector = new Injector();- injector.add([ILogService, { useClass: DesktopLogService }]);- injector.add([IContextService, { useClass: ContextService }]);- injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);- injector.add([ThemeService]);- injector.add([SheetInterceptorService]);- injector.add([ILayoutService, { useValue: createLayoutService(() => contentElements[0]) }]);- injector.add([IRenderManagerService, { useClass: RenderManagerService }]);- const service = injector.createInstance(SheetLoadingRenderService);- 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;- const finalWorkbook = injector.createInstance(Workbook, workbookData);- const finalEngine = new Engine('unit-1');- const finalScene = new Scene('unit-1-scene', finalEngine);- const finalRender = injector.createInstance(RenderUnit, {- unit: finalWorkbook,- engine: finalEngine,- scene: finalScene,- isMainScene: true,- });- injector.get(IRenderManagerService).addRender('unit-1', finalRender);-- service.showSkeleton(workbookData, 'sheet-1');- service.show(workbookData, 'sheet-1', {});-- contentElements.length = 0;- const handoff = service.handoff('unit-1', 10_000);- await vi.waitFor(() => expect(animationFrames).toHaveLength(2));-- expect(finalScene.requestRender).not.toHaveBeenCalled();- expect(service.loading$.value).toBe(true);- expect(contentElement.querySelectorAll('canvas')).toHaveLength(1);-- animationFrames[1](0);- await vi.waitFor(() => expect(animationFrames).toHaveLength(3));- expect(finalScene.requestRender).not.toHaveBeenCalled();-- contentElements.push(contentElement);- finalEngine.mount(contentElement);- animationFrames[2](0);- await vi.waitFor(() => expect(animationFrames).toHaveLength(4));-- expect(finalScene.requestRender).toHaveBeenCalledTimes(1);- expect(service.loading$.value).toBe(true);- expect(contentElement.querySelectorAll('canvas')).toHaveLength(2);- expect(finalEngine.getCanvasElement().style.visibility).toBe('hidden');-- animationFrames[3](0);- await expect(handoff).resolves.toBe(true);-- expect(service.loading$.value).toBe(false);- expect(contentElement.querySelectorAll('canvas')).toHaveLength(1);- expect(finalEngine.getCanvasElement().style.visibility).toBe('');- service.dispose();- injector.get(IRenderManagerService).dispose();- finalWorkbook.dispose();- finalEngine.dispose();- requestAnimationFrame.mockRestore();- });-});diff --git a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts b/packages/sheets-ui/src/services/canvas-pop-manager.service.tsindex 2db521bb81..7bf30b7ca2 100644--- a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts+++ b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts@@ -343,6 +343,9 @@ export class SheetCanvasPopManagerService extends Disposable {const { position, position$, disposable } = this._createPositionObserver(bound, currentRender, skeleton, worksheet);const popupInjector = this._resolveEmbeddedPopupInjector(unitId, currentRender);+ const canvasElement = currentRender.engine.getCanvasElement();+ const scaleAdjust = canvasElement.getBoundingClientRect().width / pxToNum(canvasElement.style.width);+ const { scaleX, scaleY } = currentRender.scene.getAncestorScale();const id = this._globalPopupManagerService.addPopup({...popup,@@ -351,7 +354,13 @@ export class SheetCanvasPopManagerService extends Disposable {connectorInjector: popupInjector,anchorRect: position,anchorRect$: position$,- canvasElement: currentRender.engine.getCanvasElement(),+ canvasElement,+ boundaryInsets: popup.constrainToCanvas+ ? {+ left: skeleton.rowHeaderWidth * scaleAdjust * scaleX,+ top: skeleton.columnHeaderHeight * scaleAdjust * scaleY,+ }+ : popup.boundaryInsets,});const disposableCollection = new DisposableCollection();disposableCollection.add(disposable);diff --git a/packages/sheets-ui/src/services/sheet-loading-render.service.ts b/packages/sheets-ui/src/services/sheet-loading-render.service.tsdeleted file mode 100644index a517c8f55c..0000000000--- a/packages/sheets-ui/src/services/sheet-loading-render.service.ts+++ /dev/null@@ -1,390 +0,0 @@-/**- * 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 { IRender } from '@univerjs/engine-render';-import type { Subscription } from 'rxjs';-import { createIdentifier, Disposable, Inject, Injector, InterceptorEffectEnum, ObjectMatrix, Workbook } from '@univerjs/core';-import { Engine, IRenderManagerService, RenderUnit, Scene, Spreadsheet } from '@univerjs/engine-render';-import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';-import { ILayoutService } from '@univerjs/ui';-import { BehaviorSubject, filter, firstValueFrom, from, map, Observable, of, switchMap, take, timeout } 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_';-const PREVIEW_CANVAS_Z_INDEX = '9';--export interface ISheetLoadingRenderService {- readonly workbook$: Observable<Workbook | null>;- readonly loading$: Observable<boolean>;- readonly previewReady$: Observable<boolean>;-- showSkeleton(workbookData: IWorkbookData, activeSheetId: string): void;- show(workbookData: IWorkbookData, activeSheetId: string, cellData?: IObjectMatrixPrimitiveType<ICellData>): void;- handoff(sourceUnitId: string, timeoutMs: number): Promise<boolean>;- hide(sourceUnitId: string): void;-}--export const ISheetLoadingRenderService = createIdentifier<ISheetLoadingRenderService>('sheets-ui.sheet-loading-render.service');--interface ILoadingRender {- sourceUnitId: string;- workbook: Workbook;- render: RenderUnit | null;- 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);- readonly previewReady$ = new BehaviorSubject(false);-- private _loadingRender: ILoadingRender | null = null;- private _finalCanvasGuard: Subscription | null = null;- private _hiddenFinalCanvas: HTMLCanvasElement | null = null;- private _finalCanvasVisibility = '';-- constructor(- @Inject(Injector) private readonly _injector: Injector,- @ILayoutService private readonly _layoutService: ILayoutService,- @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService- ) {- super();- }-- showSkeleton(workbookData: IWorkbookData, activeSheetId: string): void {- const sourceUnitId = workbookData.id;- if (this._loadingRender?.sourceUnitId !== sourceUnitId) {- this._disposeLoadingRender();- this.previewReady$.next(false);- this._loadingRender = {- sourceUnitId,- workbook: this._createLoadingWorkbook(workbookData, activeSheetId),- render: null,- };- this.workbook$.next(this._loadingRender.workbook);- this.loading$.next(true);- this._guardFinalCanvas(sourceUnitId);- }-- const worksheet = this._loadingRender.workbook.getSheetBySheetId(activeSheetId);- if (worksheet && this._loadingRender.workbook.getActiveSheet().getSheetId() !== activeSheetId) {- this._loadingRender.workbook.setActiveSheet(worksheet);- }- }-- show(- workbookData: IWorkbookData,- activeSheetId: string,- cellData?: IObjectMatrixPrimitiveType<ICellData>- ): void {- this.showSkeleton(workbookData, activeSheetId);-- const loadingRender = this._loadingRender;- if (!loadingRender) {- return;- }-- let shouldRender = false;- if (!loadingRender.render) {- const contentElement = this._layoutService.getContentElement();- if (!contentElement) {- return;- }-- loadingRender.render = this._createLoadingRender(- loadingRender.workbook,- loadingRender.sourceUnitId,- contentElement- );- shouldRender = true;- }-- 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 });- shouldRender = true;- }-- 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);- shouldRender = true;- }-- if (shouldRender) {- loadingRender.render.scene.render();- }- if (!this.previewReady$.value) {- this.previewReady$.next(true);- }- }-- async handoff(sourceUnitId: string, timeoutMs: number): Promise<boolean> {- if (this._loadingRender?.sourceUnitId !== sourceUnitId) {- return true;- }-- if (!this._loadingRender.render) {- this.hide(sourceUnitId);- return true;- }-- this._finalCanvasGuard?.unsubscribe();- this._finalCanvasGuard = null;-- try {- await firstValueFrom(this._getFinalRender$(sourceUnitId).pipe(- take(1),- switchMap((render) => this._waitForFinalCanvas(render).pipe(- switchMap(() => {- this._hideFinalCanvas(render);- return this._requestFinalRender(render);- })- )),- timeout(timeoutMs)- ));- this.hide(sourceUnitId);- return true;- } catch {- return false;- }- }-- hide(sourceUnitId: string): void {- if (this._loadingRender?.sourceUnitId !== sourceUnitId) {- return;- }-- this._disposeLoadingRender();- }-- override dispose(): void {- this._disposeLoadingRender();- this.workbook$.complete();- this.loading$.complete();- this.previewReady$.complete();- super.dispose();- }-- private _createLoadingWorkbook(workbookData: IWorkbookData, activeSheetId: string): Workbook {- 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);- }-- return workbook;- }-- private _createLoadingRender(- workbook: Workbook,- sourceUnitId: string,- contentElement: HTMLElement- ): RenderUnit {- const previewUnitId = workbook.getUnitId();- 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_${sourceUnitId}`);- canvas.getCanvasEle().dataset.uUnitId = sourceUnitId;- canvas.getCanvasEle().style.pointerEvents = 'none';- canvas.getCanvasEle().style.zIndex = PREVIEW_CANVAS_Z_INDEX;- engine.mount(contentElement);- return render;- } catch (error) {- this._disposeRender(render);- throw error;- }- }-- private _waitForFinalCanvas(render: IRender): Observable<void> {- return new Observable((subscriber) => {- let frameId: number | undefined;- const canvasElement = render.engine.getCanvasElement();-- const checkMounted = () => {- const contentElement = this._layoutService.getContentElement();- if (- contentElement &&- canvasElement.parentElement === contentElement &&- canvasElement.width > 0 &&- canvasElement.height > 0- ) {- subscriber.next();- subscriber.complete();- return;- }-- frameId = window.requestAnimationFrame(checkMounted);- };-- checkMounted();-- return () => {- if (frameId !== undefined) {- window.cancelAnimationFrame(frameId);- }- };- });- }-- private _getFinalRender$(sourceUnitId: string): Observable<IRender> {- const existingRender = this._renderManagerService.getRenderUnitById(sourceUnitId);- return existingRender- ? of(existingRender)- : this._renderManagerService.created$.pipe(- filter((render) => render.unitId === sourceUnitId)- );- }-- private _guardFinalCanvas(sourceUnitId: string): void {- this._finalCanvasGuard?.unsubscribe();- this._finalCanvasGuard = this._getFinalRender$(sourceUnitId).pipe(- take(1),- switchMap((render) => this._waitForFinalCanvas(render).pipe(map(() => render)))- ).subscribe((render) => this._hideFinalCanvas(render));- }-- private _requestFinalRender(render: IRender): Observable<unknown> {- render.scene.makeDirty(true);- return from(render.scene.requestRender()).pipe(- // Scene.requestRender resolves from a requestAnimationFrame callback, before that- // frame is painted. Keep the preview above the final canvas for one more frame so- // the browser paints the final canvas before the preview is disposed.- switchMap(() => this._waitForNextAnimationFrame())- );- }-- private _hideFinalCanvas(render: IRender): void {- const canvasElement = render.engine.getCanvasElement();- if (this._hiddenFinalCanvas === canvasElement) {- return;- }-- this._restoreFinalCanvas();- this._hiddenFinalCanvas = canvasElement;- this._finalCanvasVisibility = canvasElement.style.visibility;- canvasElement.style.visibility = 'hidden';- }-- private _restoreFinalCanvas(): void {- if (!this._hiddenFinalCanvas) {- return;- }-- this._hiddenFinalCanvas.style.visibility = this._finalCanvasVisibility;- this._hiddenFinalCanvas = null;- this._finalCanvasVisibility = '';- }-- private _waitForNextAnimationFrame(): Observable<void> {- return new Observable((subscriber) => {- const frameId = window.requestAnimationFrame(() => {- subscriber.next();- subscriber.complete();- });-- return () => window.cancelAnimationFrame(frameId);- });- }-- private _disposeLoadingRender(): void {- this._finalCanvasGuard?.unsubscribe();- this._finalCanvasGuard = null;- this._restoreFinalCanvas();- const loadingRender = this._loadingRender;- this._loadingRender = null;- this.workbook$.next(null);- this.loading$.next(false);- this.previewReady$.next(false);- if (!loadingRender) {- return;- }-- if (loadingRender.render) {- 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/hook.ts b/packages/sheets-ui/src/views/hook.tsindex 2a138d3673..e578b72531 100644--- a/packages/sheets-ui/src/views/hook.ts+++ b/packages/sheets-ui/src/views/hook.ts@@ -18,33 +18,14 @@ 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 { createContext, useContext, useMemo } from 'react';+import { 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 loadingWorkbook ?? workbook ?? 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 useSheetLoadingPreviewReady(): boolean {- const loadingRenderService = useDependency(ISheetLoadingRenderService);- return useObservable(loadingRenderService.previewReady$) ?? false;+ return workbook ?? null;}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.tsxindex 836d5a675e..377bb7a410 100644--- a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx+++ b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx@@ -17,18 +17,12 @@import type { Workbook, Worksheet } from '@univerjs/core';import type { IUniverSheetsUIConfig } from '../../config/config';import {- DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT,- DEFAULT_WORKSHEET_COLUMN_WIDTH,- DEFAULT_WORKSHEET_ROW_HEIGHT,- DEFAULT_WORKSHEET_ROW_TITLE_WIDTH,Injector,isInternalEditorID,IUniverInstanceService,UniverInstanceType,} from '@univerjs/core';-import { clsx } from '@univerjs/design';import { IRenderManagerService } from '@univerjs/engine-render';-import { LoadingMultiIcon } from '@univerjs/icons';import { ComponentManager, ContextMenuPosition, IMenuManagerService, ToolbarItem, useConfigValue, useDependency, useObservable } from '@univerjs/ui';import { useEffect, useMemo } from 'react';import { EMPTY, merge } from 'rxjs';@@ -39,14 +33,7 @@ import { ISheetEmbedRuntimeService } from '../../services/sheet-embed-runtime.seimport { AutoFillPopupMenu } from '../auto-fill-popup-menu/AutoFillPopupMenu';import { EditorContainer } from '../editor-container/EditorContainer';import { FormulaBar } from '../formula-bar/FormulaBar';-import {- SheetLoadingWorkbookContext,- useActiveWorkbook,- useActiveWorksheet,- useSheetLoading,- useSheetLoadingPreviewReady,- useSheetLoadingWorkbook,-} from '../hook';+import { useActiveWorkbook, useActiveWorksheet } from '../hook';import { SheetBar } from '../sheet-bar/SheetBar';import { SheetZoomSlider } from '../sheet-slider/CountBar';import { StatusBar } from '../status-bar/StatusBar';@@ -57,10 +44,7 @@ export function RenderSheetFooter() {const config = useConfigValue<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);const menuManagerService = useDependency(IMenuManagerService);const showFooter = config?.footer ?? true;- const activeWorkbook = useRootWorkbenchWorkbook();- const loadingWorkbook = useSheetLoadingWorkbook();- const workbook = loadingWorkbook ?? activeWorkbook;- const isLoading = useSheetLoading();+ const workbook = useRootWorkbenchWorkbook();const activeWorkbookEmbeddedRender = useActiveWorkbookIsEmbeddedRender(workbook);const focusedUnitType = useFocusedUnitType();const activeEmbedTab = useActiveSheetEmbedTabData(workbook);@@ -81,45 +65,39 @@ export function RenderSheetFooter() {if (!sheetBar && !showStatisticBar && !showMenus && !showZoomSlider) return null;return (- <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-gray-0 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>+ <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-gray-0 univer-px-5 univer-text-gray-900+ dark:!univer-bg-gray-900 dark:!univer-text-gray-200+ "+ data-range-selector+ 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>);}export function RenderSheetHeader() {const config = useConfigValue<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);- const activeWorkbook = useRootWorkbenchWorkbook();- const loadingWorkbook = useSheetLoadingWorkbook();- const workbook = loadingWorkbook ?? activeWorkbook;- const isLoading = useSheetLoading();+ const workbook = useRootWorkbenchWorkbook();const hasWorkbook = !!workbook;const activeWorkbookEmbeddedRender = useActiveWorkbookIsEmbeddedRender(workbook);const focusedUnitType = useFocusedUnitType();@@ -140,13 +118,7 @@ export function RenderSheetHeader() {);}if (config?.formulaBar !== false) {- return (- <SheetLoadingWorkbookContext.Provider value={workbook}>- <div aria-disabled={isLoading} className={clsx({ 'univer-pointer-events-none': isLoading })}>- <FormulaBar />- </div>- </SheetLoadingWorkbookContext.Provider>- );+ return <FormulaBar />;}return null;@@ -157,12 +129,8 @@ export function RenderSheetHeader() {*/export function RenderSheetContent() {const config = useConfigValue<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);- const isLoading = useSheetLoading();- const isPreviewReady = useSheetLoadingPreviewReady();const componentManager = useDependency(ComponentManager);- const activeWorkbook = useRootWorkbenchWorkbook();- const loadingWorkbook = useSheetLoadingWorkbook();- const workbook = loadingWorkbook ?? activeWorkbook;+ const workbook = useRootWorkbenchWorkbook();const activeEmbedTab = useActiveSheetEmbedTabData(workbook);const injector = useDependency(Injector);const activeWorkbookEmbeddedRender = useActiveWorkbookIsEmbeddedRender(workbook);@@ -174,7 +142,7 @@ export function RenderSheetContent() {const ShapeTextEditorContainer = componentManager.get('SheetShapeTextEditorContainer') ?? componentManager.get('ShapeTextEditorContainer');useEffect(() => {- if (!workbook || isLoading || activeEmbedTab || activeWorkbookEmbeddedRender || !rootWorkbenchOwnsSheet) {+ if (!workbook || activeEmbedTab || activeWorkbookEmbeddedRender || !rootWorkbenchOwnsSheet) {return;}@@ -182,11 +150,10 @@ export function RenderSheetContent() {instanceService.setCurrentUnitForType(workbook.getUnitId());instanceService.focusUnit(workbook.getUnitId());tryGetSheetEmbedRuntimeService(injector)?.clearTab();- }, [activeEmbedTab, activeWorkbookEmbeddedRender, injector, isLoading, rootWorkbenchOwnsSheet, workbook]);+ }, [activeEmbedTab, activeWorkbookEmbeddedRender, injector, rootWorkbenchOwnsSheet, workbook]);if (!workbook) return null;if (!rootWorkbenchOwnsSheet) return null;- if (isLoading) return isPreviewReady ? null : <SheetLoadingSkeleton />;if (activeWorkbookEmbeddedRender) return null;if (activeEmbedTab && workbook) {return <RenderSheetEmbedTabHost workbook={workbook} worksheet={activeEmbedTab.worksheet} />;@@ -201,53 +168,6 @@ export function RenderSheetContent() {);}-function SheetLoadingSkeleton() {- return (- <div- data-u-comp="sheet-loading-skeleton"- aria-busy- className="- univer-absolute univer-inset-0 univer-z-10 univer-overflow-hidden univer-bg-gray-0- dark:!univer-bg-gray-900- "- >- <div- className="- univer-absolute univer-right-0 univer-top-0 univer-border-b univer-border-gray-200 univer-bg-gray-50- dark:!univer-border-gray-700 dark:!univer-bg-gray-800- "- style={{ left: DEFAULT_WORKSHEET_ROW_TITLE_WIDTH, height: DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT }}- />- <div- className="- univer-absolute univer-bottom-0 univer-left-0 univer-border-r univer-border-gray-200 univer-bg-gray-50- dark:!univer-border-gray-700 dark:!univer-bg-gray-800- "- style={{ top: DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT, width: DEFAULT_WORKSHEET_ROW_TITLE_WIDTH }}- />- <div- className="- univer-absolute univer-bottom-0 univer-right-0 univer-animate-pulse univer-text-gray-200- dark:!univer-text-gray-700- "- style={{- top: DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT,- left: DEFAULT_WORKSHEET_ROW_TITLE_WIDTH,- backgroundImage: 'linear-gradient(to right, currentColor 1px, transparent 1px), linear-gradient(to bottom, currentColor 1px, transparent 1px)',- backgroundSize: `${DEFAULT_WORKSHEET_COLUMN_WIDTH}px ${DEFAULT_WORKSHEET_ROW_HEIGHT}px`,- }}- />- <LoadingMultiIcon- aria-hidden- className="- univer-absolute univer-left-1/2 univer-top-1/2 univer-size-6 -univer-translate-x-1/2- -univer-translate-y-1/2 univer-animate-spin univer-text-violet-500- "- />- </div>- );-}-function RenderSheetEmbedTabHost(props: { workbook: Workbook; worksheet: Worksheet }) {const { workbook, worksheet } = props;const injector = useDependency(Injector);diff --git a/packages/ui/src/views/components/dialog-part/DialogPart.tsx b/packages/ui/src/views/components/dialog-part/DialogPart.tsxindex c5877eeb97..ef5cd4a1ab 100644--- a/packages/ui/src/views/components/dialog-part/DialogPart.tsx+++ b/packages/ui/src/views/components/dialog-part/DialogPart.tsx@@ -36,7 +36,9 @@ export function DialogPart() {const props = options[k] as any;if (props) {- (dialogProps as any)[k] = <CustomLabel {...props} />;+ const { key: itemKey, ...customLabelProps } = props;++ (dialogProps as any)[k] = <CustomLabel key={itemKey} {...customLabelProps} />;}}diff --git a/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsx b/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsxindex 3bc1ffe5d0..5c24a716a2 100644--- a/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsx+++ b/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsx@@ -18,7 +18,7 @@ import type { ReactElement } from 'react';import type { IDialogPartMethodOptions } from '../interface';import { act, cleanup, render, screen, waitFor } from '@testing-library/react';import { DesktopLogService, ILogService, Injector, LocaleService } from '@univerjs/core';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { ComponentManager, IconManager } from '../../../../common';import { DesktopDialogService } from '../../../../services/dialog/desktop-dialog.service';import { IDialogService } from '../../../../services/dialog/dialog.service';@@ -55,6 +55,7 @@ function renderWithDependencies(element: ReactElement) {describe('DialogPart', () => {afterEach(() => {+ vi.restoreAllMocks();cleanup();});@@ -89,6 +90,30 @@ describe('DialogPart', () => {rendered.dispose();});+ it('passes custom label keys without spreading them into JSX', async () => {+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const rendered = renderWithDependencies(<DialogPart />);+ const dialogService = rendered.injector.get(IDialogService);+ const children = {+ key: 'pivot-filter',+ title: <span>Keyed dialog content</span>,+ };++ act(() => {+ dialogService.open({+ id: 'keyed-dialog',+ children,+ });+ });++ expect(await screen.findByText('Keyed dialog content')).toBeTruthy();+ expect(consoleErrorSpy.mock.calls.some(([message]) =>+ typeof message === 'string' && message.includes('A props object containing a "key" prop is being spread into JSX')+ )).toBe(false);++ rendered.dispose();+ });+it('keeps excepted dialogs visible when service closes the rest', async () => {const rendered = renderWithDependencies(<DialogPart />);const dialogService = rendered.injector.get(IDialogService);diff --git a/packages/ui/src/views/components/popup/RectPopup.tsx b/packages/ui/src/views/components/popup/RectPopup.tsxindex 77628e223d..68e2936a1d 100644--- a/packages/ui/src/views/components/popup/RectPopup.tsx+++ b/packages/ui/src/views/components/popup/RectPopup.tsx@@ -89,9 +89,10 @@ export interface IRectPopupProps {autoRelayout?: boolean;boundaryElement?: Element;+ boundaryInsets?: { left?: number; top?: number };}-export interface IPopupLayoutInfo extends Pick<IRectPopupProps, 'direction'> {+export interface IPopupLayoutInfo extends Pick<IRectPopupProps, 'boundaryInsets' | 'direction'> {position: IAbsolutePosition;width: number;height: number;@@ -107,9 +108,9 @@ const PUSHING_MINIMUM_GAP = 8;function resolvePopupDirection(layout: IPopupLayoutInfo): RectPopupDirection {const direction = layout.direction ?? 'vertical';- const containerTop = layout.containerTop ?? 0;+ const containerTop = (layout.containerTop ?? 0) + (layout.boundaryInsets?.top ?? 0);const availableTop = layout.position.top - containerTop;- const availableBottom = containerTop + layout.containerHeight - layout.position.bottom;+ const availableBottom = (layout.containerTop ?? 0) + layout.containerHeight - layout.position.bottom;const placeAbove = availableTop >= availableBottom;switch (direction) {@@ -128,10 +129,12 @@ function calcPopupPosition(layout: IPopupLayoutInfo): { top: number; left: numbeconst { position, width, height, containerHeight, containerWidth, noPushMinimumGap = false } = layout;const direction = resolvePopupDirection(layout);- const containerLeft = layout.containerLeft ?? 0;- const containerTop = layout.containerTop ?? 0;- const containerRight = containerLeft + containerWidth;- const containerBottom = containerTop + containerHeight;+ const boundaryLeft = layout.containerLeft ?? 0;+ const boundaryTop = layout.containerTop ?? 0;+ const containerLeft = boundaryLeft + (layout.boundaryInsets?.left ?? 0);+ const containerTop = boundaryTop + (layout.boundaryInsets?.top ?? 0);+ const containerRight = boundaryLeft + containerWidth;+ const containerBottom = boundaryTop + containerHeight;const minTop = noPushMinimumGap ? -Infinity : containerTop + PUSHING_MINIMUM_GAP;const maxTop = noPushMinimumGap ? Infinity : containerBottom - height - PUSHING_MINIMUM_GAP;const minLeft = noPushMinimumGap ? -Infinity : containerLeft + PUSHING_MINIMUM_GAP;@@ -228,6 +231,7 @@ function RectPopup(props: IRectPopupProps) {noPushMinimumGap,autoRelayout = true,boundaryElement,+ boundaryInsets,} = props;const nodeRef = useRef<HTMLElement>(null);const clickOtherFn = useEvent(onClickOutside ?? (() => { /* empty */ }));@@ -274,6 +278,7 @@ function RectPopup(props: IRectPopupProps) {containerTop,containerWidth,containerHeight,+ boundaryInsets,direction,noPushMinimumGap,};diff --git a/packages/ui/src/views/components/popup/__tests__/RectPopup.spec.ts b/packages/ui/src/views/components/popup/__tests__/RectPopup.spec.tsindex e1b28b30b9..5f5bd7a55d 100644--- a/packages/ui/src/views/components/popup/__tests__/RectPopup.spec.ts+++ b/packages/ui/src/views/components/popup/__tests__/RectPopup.spec.ts@@ -31,6 +31,22 @@ describe('RectPopup adaptive vertical placement', () => {})).toEqual({ left: 668, top: 160 });});+ it('keeps a left-side popup outside the container boundary insets', () => {+ const layout = {+ position: { left: 40, right: 90, top: 29, bottom: 398 },+ width: 60,+ height: 40,+ containerLeft: 100,+ containerTop: 200,+ containerWidth: 400,+ containerHeight: 300,+ boundaryInsets: { left: 50, top: 30 },+ direction: 'left' as const,+ };++ expect(RectPopup.calcPopupPosition(layout)).toEqual({ left: 158, top: 238 });+ });+it('keeps a horizontal popup inside the bottom and right container edges', () => {expect(RectPopup.calcPopupPosition({position: { left: 450, right: 550, top: 480, bottom: 600 },