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): add opt-in canvas bounds for popups (#7443)
Univerfc73e5179505
diff --git a/packages/sheets-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.ts b/packages/sheets-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.tsindex 1ba843f9a4..2d947cf7ab 100644--- a/packages/sheets-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.ts+++ b/packages/sheets-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.ts@@ -33,7 +33,10 @@ import { describe, expect, it, vi } from 'vitest';import { DrawingPopupMenuController } from '../drawing-popup-menu.controller';describe('DrawingPopupMenuController', () => {- it('places the image popup on the left in RTL', () => {+ it.each([+ { drawingType: DrawingTypeEnum.DRAWING_IMAGE, label: 'image' },+ { drawingType: DrawingTypeEnum.DRAWING_DOM, label: 'Float DOM' },+ ])('constrains the $label popup to the canvas and places it on the left in RTL', ({ drawingType }) => {const injector = new Injector();const createControl$ = new Subject<void>();const clearControl$ = new Subject<void>();@@ -55,7 +58,7 @@ describe('DrawingPopupMenuController', () => {unitId: 'unit-1',subUnitId: 'sheet-1',drawingId: 'image-1',- drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ drawingType,}),} as never,}]);@@ -105,7 +108,10 @@ describe('DrawingPopupMenuController', () => {expect(attachPopupToObject).toHaveBeenCalledWith(imageObject,- expect.objectContaining({ direction: 'left' })+ expect.objectContaining({+ constrainToCanvas: true,+ direction: 'left',+ }));controller.dispose();diff --git a/packages/sheets-drawing-ui/src/menu/drawing-popup-menu.controller.ts b/packages/sheets-drawing-ui/src/menu/drawing-popup-menu.controller.tsindex 655517ad70..bf1aeb159a 100644--- a/packages/sheets-drawing-ui/src/menu/drawing-popup-menu.controller.ts+++ b/packages/sheets-drawing-ui/src/menu/drawing-popup-menu.controller.ts@@ -172,6 +172,7 @@ export class DrawingPopupMenuController extends RxDisposable {const menus = this._canvasPopManagerService.getFeatureMenu(unitId, subUnitId, drawingId, drawingType);singletonPopupDisposer = this.disposeWithMe(this._canvasPopManagerService.attachPopupToObject(object, {componentKey: COMPONENT_IMAGE_POPUP_MENU,+ constrainToCanvas: true,direction: this._localeService.getDirection() === 'rtl' ? 'left' : 'horizontal',offset: [2, 0],extraProps: {diff --git a/packages/ui/src/services/popup/canvas-popup.service.ts b/packages/ui/src/services/popup/canvas-popup.service.tsindex 4f2d61ef4e..7ce8df7be3 100644--- a/packages/ui/src/services/popup/canvas-popup.service.ts+++ b/packages/ui/src/services/popup/canvas-popup.service.ts@@ -34,6 +34,8 @@ export interface IPopup<T = Record<string, unknown>> extends Omit<IRectPopupPropoffset?: [number, number];canvasElement: HTMLCanvasElement;+ /** Clamp popup placement to the visible canvas boundary instead of the viewport. */+ constrainToCanvas?: boolean;hideOnInvisible?: boolean;hiddenType?: 'hide' | 'destroy';hiddenRects$?: Observable<IBoundRectNoAngle[]>;diff --git a/packages/ui/src/views/components/popup/CanvasPopup.tsx b/packages/ui/src/views/components/popup/CanvasPopup.tsxindex 814772c246..8640b88c47 100644--- a/packages/ui/src/views/components/popup/CanvasPopup.tsx+++ b/packages/ui/src/views/components/popup/CanvasPopup.tsx@@ -45,7 +45,7 @@ export const SingleCanvasPopup = ({ popup, children }: ISingleCanvasPopupProps)const hiddenRects$ = useMemo(() => popup.hiddenRects$?.pipe(throttleTime(0, animationFrameScheduler)) ?? of([]), [popup.hiddenRects$]);const excludeRects$ = useMemo(() => popup.excludeRects$?.pipe(throttleTime(0, animationFrameScheduler)), [popup.excludeRects$]);const excludeRectsRef = useObservableRef(excludeRects$, popup.excludeRects);- const { canvasElement, hideOnInvisible = true, hiddenType = 'destroy' } = popup;+ const { canvasElement, constrainToCanvas = false, hideOnInvisible = true, hiddenType = 'destroy' } = popup;const hidden = useObservable(hideOnInvisible@@ -82,6 +82,7 @@ export const SingleCanvasPopup = ({ popup, children }: ISingleCanvasPopupProps){...popup}hidden={hidden}anchorRect$={anchorRect$}+ boundaryElement={constrainToCanvas ? canvasElement : popup.boundaryElement}direction={popup.direction}onClickOutside={popup.onClickOutside}excludeOutside={popup.excludeOutside}diff --git a/packages/ui/src/views/components/popup/RectPopup.tsx b/packages/ui/src/views/components/popup/RectPopup.tsxindex b6b680b145..77628e223d 100644--- a/packages/ui/src/views/components/popup/RectPopup.tsx+++ b/packages/ui/src/views/components/popup/RectPopup.tsx@@ -88,12 +88,15 @@ export interface IRectPopupProps {noPushMinimumGap?: boolean;autoRelayout?: boolean;+ boundaryElement?: Element;}export interface IPopupLayoutInfo extends Pick<IRectPopupProps, 'direction'> {position: IAbsolutePosition;width: number;height: number;+ containerLeft?: number;+ containerTop?: number;containerWidth: number;containerHeight: number;noPushMinimumGap?: boolean;@@ -104,8 +107,9 @@ const PUSHING_MINIMUM_GAP = 8;function resolvePopupDirection(layout: IPopupLayoutInfo): RectPopupDirection {const direction = layout.direction ?? 'vertical';- const availableTop = layout.position.top;- const availableBottom = layout.containerHeight - layout.position.bottom;+ const containerTop = layout.containerTop ?? 0;+ const availableTop = layout.position.top - containerTop;+ const availableBottom = containerTop + layout.containerHeight - layout.position.bottom;const placeAbove = availableTop >= availableBottom;switch (direction) {@@ -124,10 +128,14 @@ function calcPopupPosition(layout: IPopupLayoutInfo): { top: number; left: numbeconst { position, width, height, containerHeight, containerWidth, noPushMinimumGap = false } = layout;const direction = resolvePopupDirection(layout);- const minTop = noPushMinimumGap ? -Infinity : PUSHING_MINIMUM_GAP;- const maxTop = noPushMinimumGap ? Infinity : containerHeight - height - PUSHING_MINIMUM_GAP;- const minLeft = noPushMinimumGap ? -Infinity : PUSHING_MINIMUM_GAP;- const maxLeft = noPushMinimumGap ? Infinity : containerWidth - width - PUSHING_MINIMUM_GAP;+ const containerLeft = layout.containerLeft ?? 0;+ const containerTop = layout.containerTop ?? 0;+ const containerRight = containerLeft + containerWidth;+ const containerBottom = containerTop + 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;+ const maxLeft = noPushMinimumGap ? Infinity : containerRight - width - PUSHING_MINIMUM_GAP;// In y-axisif (direction === 'vertical' || direction.indexOf('top') === 0 || direction.indexOf('bottom') === 0) {@@ -144,7 +152,7 @@ function calcPopupPosition(layout: IPopupLayoutInfo): { top: number; left: numbeconst rectWidth = endX - startX;const offsetX = (rectWidth - width) / 2;- horizontalStyle = (Math.max(startX + offsetX, minLeft) + width) > containerWidth+ horizontalStyle = (Math.max(startX + offsetX, minLeft) + width) > containerRight? { left: Math.max(Math.min(maxLeft, endX - width - offsetX), minLeft) }: { left: Math.max(minLeft, Math.min(startX + offsetX, maxLeft)) };} else if (direction.includes('right')) {@@ -153,7 +161,7 @@ function calcPopupPosition(layout: IPopupLayoutInfo): { top: number; left: numbehorizontalStyle = { left: Math.max(Math.min(startX, maxLeft), minLeft) };} else {// If the popup element exceed the visible area. We should "push" it back.- horizontalStyle = (startX + width) > containerWidth+ horizontalStyle = (startX + width) > containerRight? Math.max(endX - width, minLeft) < PUSHING_MINIMUM_GAP? { left: Math.max(Math.min(startX, maxLeft), minLeft) }: { left: Math.max(Math.min(endX - width, maxLeft), minLeft) } // on left@@ -176,7 +184,7 @@ function calcPopupPosition(layout: IPopupLayoutInfo): { top: number; left: numbeconst rectHeight = endY - startY;const offsetY = (rectHeight - height) / 2;- verticalStyle = (Math.max(startY + offsetY, minTop) + height) > containerHeight+ verticalStyle = (Math.max(startY + offsetY, minTop) + height) > containerBottom? { top: Math.max(Math.min(maxTop, endY - height - offsetY), minTop) }: { top: Math.max(minTop, Math.min(startY + offsetY, maxTop)) };} else if (direction.includes('top')) {@@ -189,7 +197,7 @@ function calcPopupPosition(layout: IPopupLayoutInfo): { top: number; left: numbe};} else {// If the popup element exceed the visible area. We should "push" it back.- verticalStyle = ((startY + height) > containerHeight)+ verticalStyle = ((startY + height) > containerBottom)? Math.max(endY - height, minTop) < PUSHING_MINIMUM_GAP? { top: Math.max(Math.min(startY, maxTop), minTop) }: { top: Math.max(Math.min(endY - height, maxTop), minTop) } // on top@@ -219,6 +227,7 @@ function RectPopup(props: IRectPopupProps) {onMaskClick,noPushMinimumGap,autoRelayout = true,+ boundaryElement,} = props;const nodeRef = useRef<HTMLElement>(null);const clickOtherFn = useEvent(onClickOutside ?? (() => { /* empty */ }));@@ -239,15 +248,32 @@ function RectPopup(props: IRectPopupProps) {if (!nodeRef.current) return;const { clientWidth, clientHeight } = nodeRef.current;- const innerWidth = window.innerWidth;- const innerHeight = window.innerHeight;+ const boundaryRect = boundaryElement?.getBoundingClientRect();+ const containerLeft = Math.max(boundaryRect?.left ?? 0, 0);+ const containerTop = Math.max(boundaryRect?.top ?? 0, 0);+ const containerRight = Math.min(boundaryRect?.right ?? window.innerWidth, window.innerWidth);+ const containerBottom = Math.min(boundaryRect?.bottom ?? window.innerHeight, window.innerHeight);+ const containerWidth = Math.max(containerRight - containerLeft, 0);+ const containerHeight = Math.max(containerBottom - containerTop, 0);+ const minimumGap = noPushMinimumGap ? 0 : PUSHING_MINIMUM_GAP * 2;+ const cannotFitBoundary = boundaryElement != null && (+ containerWidth <= 0 ||+ containerHeight <= 0 ||+ containerWidth < clientWidth + minimumGap ||+ containerHeight < clientHeight + minimumGap+ );++ nodeRef.current.style.visibility = cannotFitBoundary ? 'hidden' : '';+ if (cannotFitBoundary) return;const layout = {position,width: clientWidth,height: clientHeight,- containerWidth: innerWidth,- containerHeight: innerHeight,+ containerLeft,+ containerTop,+ containerWidth,+ containerHeight,direction,noPushMinimumGap,};diff --git a/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsx b/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsxindex 6bc79a0961..8d39e83507 100644--- a/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsx+++ b/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsx@@ -101,7 +101,7 @@ describe('CanvasPopup', () => {}});- it('positions service popups from canvas anchors and tracks hover ownership', async () => {+ it('uses viewport placement by default and tracks hover ownership', async () => {const rendered = renderWithDependencies(<CanvasPopup />);const popupService = rendered.injector.get(ICanvasPopupService);const anchorRect$ = new BehaviorSubject({ left: 40, top: 50, right: 90, bottom: 70 });@@ -113,9 +113,10 @@ describe('CanvasPopup', () => {subUnitId: 'sheet-1',componentKey: 'test-popup',anchorRect$,- canvasElement: createCanvasElement(new DOMRect(0, 0, 400, 300)),+ canvasElement: createCanvasElement(new DOMRect(0, 100, 400, 300)),direction: 'bottom-left',offset: [4, 6],+ hideOnInvisible: false,extraProps: { label: 'Cell comment' },});});@@ -144,4 +145,64 @@ describe('CanvasPopup', () => {rendered.dispose();});++ it('keeps a partially visible drawing popup inside the canvas', async () => {+ const rendered = renderWithDependencies(<CanvasPopup />);+ const popupService = rendered.injector.get(ICanvasPopupService);++ act(() => {+ popupService.addPopup({+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ componentKey: 'test-popup',+ anchorRect$: new BehaviorSubject({ left: 200, top: 29, right: 668, bottom: 398 }),+ canvasElement: createCanvasElement(new DOMRect(0, 152, 1580, 891)),+ constrainToCanvas: true,+ direction: 'horizontal',+ extraProps: { label: 'Drawing menu' },+ });+ });++ expect(await screen.findByRole('button', { name: 'Drawing menu' })).toBeTruthy();++ const popupElement = document.querySelector<HTMLElement>('[data-u-comp="rect-popup"]');+ if (!popupElement) {+ throw new Error('RectPopup was not rendered');+ }+ await waitFor(() => {+ expect(popupElement.style.top).toBe('160px');+ });++ rendered.dispose();+ });++ it('hides a drawing popup when the canvas boundary is outside the viewport', async () => {+ const rendered = renderWithDependencies(<CanvasPopup />);+ const popupService = rendered.injector.get(ICanvasPopupService);++ act(() => {+ popupService.addPopup({+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ componentKey: 'test-popup',+ anchorRect$: new BehaviorSubject({ left: 40, top: -180, right: 90, bottom: -160 }),+ canvasElement: createCanvasElement(new DOMRect(0, -200, 400, 100)),+ constrainToCanvas: true,+ direction: 'horizontal',+ extraProps: { label: 'Offscreen drawing menu' },+ });+ });++ expect(await screen.findByText('Offscreen drawing menu')).toBeTruthy();++ const popupElement = document.querySelector<HTMLElement>('[data-u-comp="rect-popup"]');+ if (!popupElement) {+ throw new Error('RectPopup was not rendered');+ }+ await waitFor(() => {+ expect(popupElement.style.visibility).toBe('hidden');+ });++ rendered.dispose();+ });});diff --git a/packages/ui/src/views/components/popup/__tests__/RectPopup.spec.ts b/packages/ui/src/views/components/popup/__tests__/RectPopup.spec.tsindex 9e1bed1fd3..e1b28b30b9 100644--- a/packages/ui/src/views/components/popup/__tests__/RectPopup.spec.ts+++ b/packages/ui/src/views/components/popup/__tests__/RectPopup.spec.ts@@ -18,6 +18,45 @@ import { describe, expect, it } from 'vitest';import { RectPopup } from '../RectPopup';describe('RectPopup adaptive vertical placement', () => {+ it('keeps a horizontal popup inside an offset container', () => {+ expect(RectPopup.calcPopupPosition({+ position: { left: 200, right: 668, top: 29, bottom: 398 },+ width: 26,+ height: 26,+ containerLeft: 0,+ containerTop: 152,+ containerWidth: 1580,+ containerHeight: 891,+ direction: 'horizontal',+ })).toEqual({ left: 668, top: 160 });+ });++ it('keeps a horizontal popup inside the bottom and right container edges', () => {+ expect(RectPopup.calcPopupPosition({+ position: { left: 450, right: 550, top: 480, bottom: 600 },+ width: 60,+ height: 40,+ containerLeft: 100,+ containerTop: 200,+ containerWidth: 400,+ containerHeight: 300,+ direction: 'horizontal',+ })).toEqual({ left: 432, top: 452 });+ });++ it('uses offset container space when choosing the vertical side', () => {+ expect(RectPopup.calcPopupPosition({+ position: { left: 200, right: 300, top: 550, bottom: 600 },+ width: 50,+ height: 40,+ containerLeft: 100,+ containerTop: 500,+ containerWidth: 400,+ containerHeight: 400,+ direction: 'vertical-center',+ })).toEqual({ left: 225, top: 600 });+ });+it('uses the bottom side when the anchor has more space below', () => {expect(RectPopup.calcPopupPosition({position: { left: 100, right: 300, top: 100, bottom: 200 },