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.

fix(docs): stabilize paragraph menus and zoom scrollbars (#7941)

Univer8652a07849b7
diff --git a/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.ts
index e1daae2af9..43ffbae4b9 100644
--- a/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.ts
@@ -14,12 +14,23 @@
* limitations under the License.
*/
-import type { DocumentDataModel } from '@univerjs/core';
-import type { IRenderContext, ISceneTransformState } from '@univerjs/engine-render';
+import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
+import type { IRenderContext, ISceneTransformState, RenderUnit } from '@univerjs/engine-render';
+import { ICommandService, Injector, Univer, UniverInstanceType } from '@univerjs/core';
+import {
+ CanvasColorService,
+ DocBackground,
+ Documents,
+ ICanvasColorService,
+ IRenderManagerService,
+ RenderManagerService,
+ ScrollBar,
+ Viewport,
+} from '@univerjs/engine-render';
+import { beforeEach, describe, expect, it, onTestFinished } from 'vitest';
import type { IDocFitToWidthOptions } from '../../config/config';
-import { Injector } from '@univerjs/core';
-import { beforeEach, describe, expect, it } from 'vitest';
import { DOCS_VIEW_KEY, VIEWPORT_KEY } from '../../basics/docs-view-key';
+import { SetDocZoomRatioOperation } from '../../commands/operations/set-doc-zoom-ratio.operation';
import { DocPageLayoutService } from '../doc-page-layout.service';
import { DocViewScaleService } from '../doc-view-scale';
@@ -154,11 +165,88 @@ function createLayoutService(params: {
};
}
+function createScrollableLayout(documentHeight: number) {
+ const univer = new Univer();
+ onTestFinished(() => univer.dispose());
+ const injector = univer.__getInjector();
+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ const commandService = injector.get(ICommandService);
+ commandService.registerCommand(SetDocZoomRatioOperation);
+ const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: 'zoom-scroll-layout',
+ body: { dataStream: '\r\n' },
+ documentStyle: { pageSize: { width: 600, height: documentHeight } },
+ settings: { zoomRatio: 1 },
+ });
+ const render = injector.get(IRenderManagerService).createRender(model.getUnitId()) as RenderUnit;
+ render.deactivate();
+ render.engine.resizeBySize(1000, 800);
+ const documents = new Documents(DOCS_VIEW_KEY.MAIN, undefined, { pageMarginLeft: 40, pageMarginTop: 20 });
+ documents.resize(600, documentHeight);
+ const background = new DocBackground(DOCS_VIEW_KEY.BACKGROUND);
+ render.mainComponent = documents;
+ render.components.set(DOCS_VIEW_KEY.BACKGROUND, background);
+ render.scene.addObjects([documents, background]);
+ const viewport = new Viewport(VIEWPORT_KEY.VIEW_MAIN, render.scene, { left: 0, top: 0, right: 0, bottom: 0 });
+ const scrollBar = new ScrollBar(viewport);
+ render.addRenderDependencies([[DocViewScaleService], [DocPageLayoutService]]);
+ const service = render.with(DocPageLayoutService);
+ return {
+ scrollBar,
+ viewport,
+ zoom(ratio: number) {
+ commandService.syncExecuteCommand(SetDocZoomRatioOperation.id, { unitId: model.getUnitId(), zoomRatio: ratio });
+ service.calculatePagePosition();
+ },
+ };
+}
+
describe('DocPageLayoutService', () => {
beforeEach(() => {
TestDocViewScaleService.reset();
});
+ it.each([600, 780])('creates a scrollable range when zooming a fitting %ipx document past the viewport', (documentHeight) => {
+ const { scrollBar, viewport, zoom } = createScrollableLayout(documentHeight);
+ zoom(0.75);
+ expect(scrollBar.hasVerticalThumb()).toBe(false);
+
+ zoom(1.5);
+
+ expect(scrollBar.hasVerticalThumb()).toBe(true);
+ viewport.scrollToViewportPos({ viewportScrollY: documentHeight + 40 });
+ expect(viewport.viewportScrollY).toBeGreaterThan(0);
+ expect(viewport.calcViewportInfo().viewBound.bottom).toBeGreaterThanOrEqual(documentHeight + 20);
+
+ zoom(0.75);
+
+ expect(scrollBar.hasVerticalThumb()).toBe(false);
+ expect(viewport.viewportScrollY).toBe(0);
+ });
+
+ it('includes page margins when zooming into the overflow boundary', () => {
+ const { scrollBar, zoom } = createScrollableLayout(600);
+ zoom(1);
+ expect(scrollBar.hasVerticalThumb()).toBe(false);
+
+ zoom(1.26);
+
+ expect(scrollBar.hasVerticalThumb()).toBe(true);
+ });
+
+ it('updates an existing scrollable range on zoom', () => {
+ const { scrollBar, zoom } = createScrollableLayout(1200);
+ zoom(1);
+ expect(scrollBar.hasVerticalThumb()).toBe(true);
+ const initialThumbHeight = scrollBar.verticalThumbSize;
+
+ zoom(2);
+
+ expect(scrollBar.hasVerticalThumb()).toBe(true);
+ expect(scrollBar.verticalThumbSize).toBeLessThan(initialThumbHeight);
+ });
+
it('centers the document page when the viewport is wider than the page', () => {
const { docBackground, documentComponent, scene, service } = createLayoutService({
documentWidth: 600,
diff --git a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
index 09db077eed..a55c87be85 100644
--- a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
@@ -16,7 +16,6 @@
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
import type { RenderUnit } from '@univerjs/engine-render';
-import type { IMutiPageParagraphBound, ITableBound } from '../doc-event-manager.service';
import {
BlockType,
DataStreamTreeTokenType,
@@ -33,6 +32,7 @@ import {
} from '@univerjs/core';
import {
createDocumentPermissionPoint,
+ DocSelectionManagerService,
DocSkeletonManagerService,
getDocumentParagraphPermissionObjectId,
setDocumentPermissionValue,
@@ -44,6 +44,7 @@ import {
Documents,
ICanvasColorService,
IRenderManagerService,
+ NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
RenderManagerService,
Viewport,
} from '@univerjs/engine-render';
@@ -58,13 +59,11 @@ import {
} from '@univerjs/ui';
import { BehaviorSubject, Subject } from 'rxjs';
import { describe, expect, it, onTestFinished, vi } from 'vitest';
+import type { IMutiPageParagraphBound, ITableBound } from '../doc-event-manager.service';
import { buildMoveDocBlockActions } from '../../commands/commands/doc-block-move.command';
import { genTableSource } from '../../commands/commands/table/table';
import enUS from '../../locale/en-US';
-import {
- DOC_PARAGRAPH_MENU_COMPONENT_KEY,
- DOC_TABLE_BLOCK_MENU_COMPONENT_KEY,
-} from '../../views/paragraph-menu/component-keys';
+import { DOC_PARAGRAPH_MENU_COMPONENT_KEY } from '../../views/paragraph-menu/component-keys';
import {
DocEventManagerService,
getPreferredParagraphBoundsInRange,
@@ -142,7 +141,10 @@ describe('focused table menus with real render services', () => {
]);
const service = render.with(DocParagraphMenuService);
const bound = render.with(DocEventManagerService).tableBounds.get(table.tableId)!;
- return { injector, service, bound, render, model };
+ const events = render.with(DocEventManagerService);
+ const hoverParagraph$ = Reflect.get(events, '_hoverParagraph$') as BehaviorSubject<IMutiPageParagraphBound | null>;
+ const hoverTable$ = Reflect.get(events, '_hoverTable$') as Subject<ITableBound | null>;
+ return { injector, service, bound, render, model, hoverParagraph$, hoverTable$ };
}
it('keeps a focused table trigger independent of paragraph hover and closes each popup independently', () => {
@@ -197,6 +199,210 @@ describe('focused table menus with real render services', () => {
service.dispose();
expect(popups.popups).toHaveLength(0);
});
+
+ it('keeps the hover trigger mounted across short gaps and switches its paragraph anchor', () => {
+ vi.useFakeTimers();
+ onTestFinished(() => {
+ vi.useRealTimers();
+ });
+ const { injector, service, model, hoverParagraph$, hoverTable$ } = createFocusedMenuTestBed();
+ const popups = injector.get(ICanvasPopupService);
+ const paragraph = createParagraphBound({ paragraphStart: 3, paragraphEnd: 7, startIndex: 7 });
+ hoverTable$.next(null);
+ hoverParagraph$.next(paragraph);
+ vi.advanceTimersByTime(32);
+ const popupId = popups.popups[0][0];
+ const anchors: unknown[] = [];
+ const anchorSubscription = popups.popups[0][1].anchorRect$.subscribe((anchor) => anchors.push(anchor));
+ onTestFinished(() => anchorSubscription.unsubscribe());
+ const targets: Array<string | null> = [];
+ const subscription = service.activeTarget$.subscribe((target) => targets.push(target?.key ?? null));
+ onTestFinished(() => subscription.unsubscribe());
+
+ hoverParagraph$.next(null);
+ vi.advanceTimersByTime(199);
+ expect(popups.popups[0]?.[0]).toBe(popupId);
+
+ const startOffset = model.getBody()!.dataStream.indexOf('Body');
+ const nextParagraph = createParagraphBound({
+ paragraphStart: startOffset,
+ paragraphEnd: startOffset + 4,
+ startIndex: startOffset + 4,
+ });
+ hoverParagraph$.next(nextParagraph);
+ vi.advanceTimersByTime(200);
+
+ expect(popups.popups).toHaveLength(1);
+ expect(popups.popups[0][0]).toBe(popupId);
+ expect(service.activeTarget?.key).toBe(`paragraph:${nextParagraph.startIndex}`);
+ expect(targets).not.toContain(null);
+ expect(anchors[anchors.length - 1]).not.toEqual(anchors[0]);
+ });
+
+ it('hides 200ms after hover loss without extending the deadline on repeated empty hover events', () => {
+ vi.useFakeTimers();
+ onTestFinished(() => {
+ vi.useRealTimers();
+ });
+ const { injector, service, hoverParagraph$, hoverTable$ } = createFocusedMenuTestBed();
+ const popups = injector.get(ICanvasPopupService);
+ hoverTable$.next(null);
+ hoverParagraph$.next(createParagraphBound({ paragraphStart: 3, paragraphEnd: 7, startIndex: 7 }));
+ vi.advanceTimersByTime(32);
+ hoverParagraph$.next(null);
+ vi.advanceTimersByTime(100);
+ hoverParagraph$.next(null);
+ vi.advanceTimersByTime(99);
+ expect(popups.popups).toHaveLength(1);
+ vi.advanceTimersByTime(1);
+ expect(popups.popups).toHaveLength(0);
+ expect(service.activeTarget).toBeNull();
+ });
+
+ it('cancels a pending hover dismissal when the trigger becomes active or the same paragraph returns', () => {
+ vi.useFakeTimers();
+ onTestFinished(() => {
+ vi.useRealTimers();
+ });
+ const { injector, service, hoverParagraph$, hoverTable$ } = createFocusedMenuTestBed();
+ const popups = injector.get(ICanvasPopupService);
+ const paragraph = createParagraphBound({ paragraphStart: 3, paragraphEnd: 7, startIndex: 7 });
+ hoverTable$.next(null);
+ hoverParagraph$.next(paragraph);
+ vi.advanceTimersByTime(32);
+ const popupId = popups.popups[0][0];
+ hoverParagraph$.next(null);
+ vi.advanceTimersByTime(150);
+ hoverParagraph$.next(paragraph);
+ vi.advanceTimersByTime(200);
+ expect(popups.popups[0]?.[0]).toBe(popupId);
+
+ hoverParagraph$.next(null);
+ vi.advanceTimersByTime(150);
+ service.setParagraphMenuActive(true);
+ vi.advanceTimersByTime(200);
+ expect(popups.popups[0]?.[0]).toBe(popupId);
+ });
+
+ it('cancels pending hover dismissal on disposal and still closes immediately on permission loss', () => {
+ vi.useFakeTimers();
+ onTestFinished(() => {
+ vi.useRealTimers();
+ });
+ const { injector, service, hoverParagraph$, hoverTable$ } = createFocusedMenuTestBed();
+ const popups = injector.get(ICanvasPopupService);
+ const paragraph = createParagraphBound({ paragraphStart: 3, paragraphEnd: 7, startIndex: 7 });
+ hoverTable$.next(null);
+ hoverParagraph$.next(paragraph);
+ vi.advanceTimersByTime(32);
+ hoverParagraph$.next(null);
+ vi.advanceTimersByTime(50);
+ setDocumentPermissionValue(injector.get(IPermissionService), 'focused-table-doc', 'focused-table-doc', UnitAction.Edit, false);
+ expect(popups.popups).toHaveLength(0);
+ setDocumentPermissionValue(injector.get(IPermissionService), 'focused-table-doc', 'focused-table-doc', UnitAction.Edit, true);
+ service.showParagraphMenu(paragraph);
+ hoverParagraph$.next(null);
+ vi.advanceTimersByTime(32);
+ const hideMenu = vi.spyOn(service, 'hideParagraphMenu');
+ service.dispose();
+ hideMenu.mockClear();
+ vi.advanceTimersByTime(200);
+ expect(hideMenu).not.toHaveBeenCalled();
+ expect(popups.popups).toHaveLength(0);
+ });
+
+ it.each([DocumentBlockType.PARAGRAPH, DocumentBlockType.TABLE])(
+ 'keeps the passive %s trigger mounted on pointerdown and dismisses it on selection movement',
+ (kind) => {
+ vi.useFakeTimers();
+ onTestFinished(() => {
+ vi.useRealTimers();
+ });
+ const { injector, service, render, bound, model, hoverParagraph$, hoverTable$ } = createFocusedMenuTestBed();
+ const popups = injector.get(ICanvasPopupService);
+ if (kind === DocumentBlockType.TABLE) {
+ service.showTableMenu(bound);
+ } else {
+ service.showParagraphMenu(createParagraphBound({ paragraphStart: 3, paragraphEnd: 7, startIndex: 7 }));
+ }
+ const popupId = popups.popups[0][0];
+ const selectionRender = render.with(DocSelectionRenderService);
+ const selectionStart$ = Reflect.get(selectionRender, '_onSelectionStart$') as Subject<unknown>;
+ hoverTable$.next(null);
+ vi.advanceTimersByTime(32);
+ Reflect.set(selectionRender, '_onPointerEvent', true);
+ selectionStart$.next(null);
+ vi.advanceTimersByTime(220);
+ expect(popups.popups[0]?.[0]).toBe(popupId);
+
+ popups.popups[0][1].onClickOutside?.(new MouseEvent('pointerdown'));
+ const selections = injector.get(DocSelectionManagerService);
+ const offset = model.getBody()!.dataStream.indexOf('Body');
+ const selectionInfo = {
+ textRanges: [{ startOffset: offset, endOffset: offset, collapsed: true }],
+ rectRanges: [],
+ segmentId: '',
+ segmentPage: -1,
+ isEditing: true,
+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ };
+ selections.replaceSelectionInfoWithoutRefresh(selectionInfo);
+ const textSelection$ = Reflect.get(selections, '_textSelection$') as Subject<unknown>;
+ textSelection$.next(selectionInfo);
+ expect(popups.popups[0]?.[0]).toBe(popupId);
+
+ hoverTable$.next(null);
+ hoverParagraph$.next(null);
+ vi.advanceTimersByTime(32);
+ expect(popups.popups[0]?.[0]).toBe(popupId);
+
+ render.scene.onPointerMove$.emitEvent(new PointerEvent('pointermove', { buttons: 1 }) as never);
+ expect(popups.popups[0]?.[0]).toBe(popupId);
+ const movingSelection$ = Reflect.get(selectionRender, '_movingSelection$') as Subject<unknown>;
+ movingSelection$.next(selectionInfo);
+ expect(popups.popups).toHaveLength(0);
+ Reflect.set(selectionRender, '_onPointerEvent', false);
+ }
+ );
+
+ it('keeps the trigger when navigation and modifier keys do not expand the selection', () => {
+ const { injector, service, render } = createFocusedMenuTestBed();
+ const popups = injector.get(ICanvasPopupService);
+ service.showParagraphMenu(createParagraphBound({ paragraphStart: 3, paragraphEnd: 7, startIndex: 7 }));
+ const popupId = popups.popups[0][0];
+ const keydown$ = Reflect.get(render.with(DocSelectionRenderService), '_onKeydown$') as Subject<unknown>;
+
+ for (const key of ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown', 'Shift', 'Control', 'Alt', 'Meta']) {
+ keydown$.next({ event: new KeyboardEvent('keydown', { key }) });
+ expect(popups.popups[0]?.[0], key).toBe(popupId);
+ }
+ });
+
+ it('reuses the hover popup and publishes target changes when switching between tables and paragraphs', () => {
+ const { injector, service, bound, model } = createFocusedMenuTestBed();
+ const popups = injector.get(ICanvasPopupService);
+ service.showTableMenu(bound);
+ const [popupId, popup] = popups.popups[0];
+ const targetKinds: Array<DocumentBlockType | undefined> = [];
+ const subscription = service.activeTarget$.subscribe((target) => targetKinds.push(target?.kind));
+ onTestFinished(() => subscription.unsubscribe());
+
+ service.showParagraphMenu(createParagraphBound({ paragraphStart: 3, paragraphEnd: 7, startIndex: 7 }));
+ expect(popups.popups[0][0]).toBe(popupId);
+ expect(popups.popups[0][1].componentKey).toBe(popup.componentKey);
+ expect(targetKinds[targetKinds.length - 1]).toBe(DocumentBlockType.PARAGRAPH);
+
+ const startOffset = model.getBody()!.dataStream.indexOf('Body');
+ service.showParagraphMenu(createParagraphBound({
+ paragraphStart: startOffset,
+ paragraphEnd: startOffset + 4,
+ startIndex: startOffset + 4,
+ }));
+ service.showTableMenu(bound);
+ expect(popups.popups).toHaveLength(1);
+ expect(popups.popups[0][0]).toBe(popupId);
+ expect(targetKinds[targetKinds.length - 1]).toBe(DocumentBlockType.TABLE);
+ });
});
describe('DocParagraphMenuService', () => {
@@ -394,8 +600,7 @@ describe('DocParagraphMenuService', () => {
tableId: 'table-1',
});
- const [anchor, options] = attachPopupToRect.mock.calls[0] as unknown as [() => { bottom: number; left: number; right: number; top: number }, { componentKey: string; direction: string }];
- expect(options.componentKey).toBe(DOC_TABLE_BLOCK_MENU_COMPONENT_KEY);
+ const [anchor, options] = attachPopupToRect.mock.calls[0] as unknown as [() => { bottom: number; left: number; right: number; top: number }, { direction: string }];
expect(options.direction).toBe('top-right');
expect(anchor()).toEqual({
bottom: 76,
@@ -429,11 +634,8 @@ describe('DocParagraphMenuService', () => {
});
it('does not let the same table hover target steal back a cell paragraph menu', () => {
- const disposeTableMenu = vi.fn();
- const disposeCellMenu = vi.fn();
- const attachPopupToRect = vi.fn()
- .mockReturnValueOnce({ canDispose: () => true, dispose: disposeTableMenu })
- .mockReturnValueOnce({ canDispose: () => true, dispose: disposeCellMenu });
+ const dispose = vi.fn();
+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose }));
const service = createService({
attachPopupToRect,
dataStream: `${DataStreamTreeTokenType.TABLE_START}${DataStreamTreeTokenType.TABLE_ROW_START}${DataStreamTreeTokenType.TABLE_CELL_START}Cell\r${DataStreamTreeTokenType.TABLE_CELL_END}${DataStreamTreeTokenType.TABLE_ROW_END}${DataStreamTreeTokenType.TABLE_END}`,
@@ -460,8 +662,8 @@ describe('DocParagraphMenuService', () => {
expect(service.activeTarget?.kind).toBe(DocumentBlockType.PARAGRAPH);
expect(service.activeTarget?.key).toBe(`${DocumentBlockType.PARAGRAPH}:7`);
- expect(disposeCellMenu).not.toHaveBeenCalled();
- expect(attachPopupToRect).toHaveBeenCalledTimes(2);
+ expect(dispose).not.toHaveBeenCalled();
+ expect(attachPopupToRect).toHaveBeenCalledTimes(1);
});
it('anchors first-column table-cell paragraph menus to the left of the row header lane', () => {
@@ -1256,7 +1458,7 @@ describe('DocParagraphMenuService', () => {
expect(service.activeTarget?.key).toBe('paragraph:5');
});
- it('hides the visible paragraph menu after a custom range click and after scrolling', () => {
+ it('keeps a passive trigger during scrolling but closes an active menu or a custom range click', () => {
const dispose = vi.fn();
const clickCustomRanges$ = new Subject();
const scrollAfter = createScrollAfterEvent();
@@ -1285,6 +1487,10 @@ describe('DocParagraphMenuService', () => {
}));
scrollAfter.emit({ scrollY: 20 });
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(service.activeTarget).not.toBeNull();
+ service.setParagraphMenuActive(true);
+ scrollAfter.emit({ scrollY: 40 });
expect(dispose).toHaveBeenCalledTimes(2);
expect(service.activeTarget).toBeNull();
});
@@ -1316,6 +1522,8 @@ describe('DocParagraphMenuService', () => {
hoverParagraphRealTime$.next(null);
hoverParagraphLeft$.next(null);
await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(dispose).not.toHaveBeenCalled();
+ await new Promise((resolve) => setTimeout(resolve, 200));
expect(dispose).toHaveBeenCalledTimes(1);
expect(service.activeTarget).toBeNull();
@@ -1355,28 +1563,6 @@ describe('DocParagraphMenuService', () => {
expect(attachPopupToRect).not.toHaveBeenCalled();
});
- it('hides a visible table menu as soon as text selection starts', () => {
- const dispose = vi.fn();
- const selectionStart$ = new Subject<unknown>();
- const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose }));
- const service = createService({
- attachPopupToRect,
- dataStream: '',
- selectionStart$,
- tables: [{ tableId: 'table-1', startIndex: 10, endIndex: 30 }],
- });
-
- service.showTableMenu({
- pageIndex: 0,
- rect: { bottom: 170, left: 100, right: 400, top: 80 },
- tableId: 'table-1',
- });
- selectionStart$.next(null);
-
- expect(dispose).toHaveBeenCalledTimes(1);
- expect(service.activeTarget).toBeNull();
- });
-
it('does not show table menus from hover events while pointer text selection is active', async () => {
const hoverTableRealTime$ = new BehaviorSubject<ITableBound | null>(null);
const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));
@@ -1515,7 +1701,6 @@ function createService(options: {
mobile?: boolean;
replaceDocRanges?: ReturnType<typeof vi.fn>;
scrollAfter$?: { subscribeEvent: (callback: (event: { scrollY: number }) => void) => { dispose: () => void } };
- selectionStart$?: Subject<unknown>;
textSelection$?: Subject<unknown>;
tableCellBounds?: Map<string, Array<{ colIndex: number; pageIndex: number; rect: { bottom: number; left: number; right: number; top: number }; rowIndex: number; tableId: string }>>;
tables?: Array<{ endIndex: number; startIndex: number; tableId: string }>;
@@ -1590,7 +1775,8 @@ function createService(options: {
{
onInputBefore$: options.inputBefore$ ?? new Subject(),
onKeydown$: options.keydown$ ?? new Subject(),
- onSelectionStart$: options.selectionStart$ ?? new Subject(),
+ onSelectionStart$: new Subject(),
+ movingSelection$: new Subject(),
isOnPointerEvent: options.isOnPointerEvent ?? false,
} as never,
{
diff --git a/packages/docs-ui/src/services/doc-page-layout.service.ts b/packages/docs-ui/src/services/doc-page-layout.service.ts
index e700d44f3e..81cb8e912f 100644
--- a/packages/docs-ui/src/services/doc-page-layout.service.ts
+++ b/packages/docs-ui/src/services/doc-page-layout.service.ts
@@ -88,7 +88,7 @@ export class DocPageLayoutService extends Disposable implements IRenderModule {
scrollToX = 0;
}
- if (engineHeight > docsHeight) {
+ if (engineHeight > (docsHeight + pageMarginTop * 2) * viewScale) {
sceneHeight = (engineHeight - pageMarginTop * 2) / viewScale;
} else {
sceneHeight = docsHeight + pageMarginTop * 2;
diff --git a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
index 8c36882509..089aeadda1 100644
--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
@@ -45,7 +45,7 @@ import {
getDocumentEditTargetObjectIds,
} from '@univerjs/docs';
import { DocumentEditArea } from '@univerjs/engine-render';
-import { BehaviorSubject, combineLatest, first, Subject, throttleTime } from 'rxjs';
+import { BehaviorSubject, combineLatest, Subject, throttleTime } from 'rxjs';
import type { IMutiPageParagraphBound, ITableBound, ITableParagraphBound } from './doc-event-manager.service';
import type { IEditorInputConfig } from './selection/doc-selection-render.service';
import { VIEWPORT_KEY } from '../basics/docs-view-key';
@@ -139,6 +139,21 @@ interface IDocExpandedSelectionState {
hasRectRange: boolean;
}
+const PASSIVE_PARAGRAPH_MENU_KEYS = new Set([
+ 'ArrowLeft',
+ 'ArrowRight',
+ 'ArrowUp',
+ 'ArrowDown',
+ 'Home',
+ 'End',
+ 'PageUp',
+ 'PageDown',
+ 'Shift',
+ 'Control',
+ 'Alt',
+ 'Meta',
+]);
+
export class DocParagraphMenuService extends Disposable implements IRenderModule {
private _paragraphMenu: {
paragraph: IMutiPageParagraphBound;
@@ -146,8 +161,11 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
blockRange?: IDocumentBlockRange;
disposable: INeedCheckDisposable;
active: boolean;
+ getAnchor: () => IBoundRectNoAngle;
} | null = null;
+ private _paragraphMenuHideTimer: ReturnType<typeof setTimeout> | null = null;
+
private readonly _activeTarget$ = new BehaviorSubject<IDocBlockMenuTarget | null>(null);
readonly activeTarget$ = this._activeTarget$.asObservable();
private _focusedTableMenu: {
@@ -184,6 +202,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
setBlockMenuDragging(isDragging: boolean) {
this._isBlockMenuDragging = isDragging;
if (isDragging) {
+ this._cancelParagraphMenuHide();
this._dragInteraction ??= this._docLayoutInteractionService.beginInteraction();
} else {
this._dragInteraction?.dispose();
@@ -226,27 +245,6 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
}));
}
- private _isCursorInActiveParagraph() {
- if (!this._paragraphMenu) {
- return false;
- }
-
- const activeTextRange = this._docSelectionManagerService.getActiveTextRange();
- if (!activeTextRange?.collapsed) {
- return false;
- }
-
- if (
- !activeTextRange?.collapsed ||
- activeTextRange.startOffset < this._paragraphMenu.paragraph.paragraphStart ||
- activeTextRange.startOffset > this._paragraphMenu.paragraph.paragraphEnd
- ) {
- return false;
- }
-
- return true;
- }
-
private _getExpandedSelectionState(ranges: readonly ITextRangeWithStyle[]): IDocExpandedSelectionState {
return ranges.reduce<IDocExpandedSelectionState>((state, range) => {
if (range.rangeType === DOC_RANGE_TYPE.RECT) {
@@ -287,6 +285,9 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
}
setParagraphMenuActive(active: boolean, focusedTable = false) {
+ if (active && !focusedTable) {
+ this._cancelParagraphMenuHide();
+ }
const menu = focusedTable ? this._focusedTableMenu : this._paragraphMenu;
if (menu) {
menu.active = active;
@@ -309,7 +310,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
}
if (this._docSelectionRenderService.isOnPointerEvent) {
- this.hideParagraphMenu(true);
+ // Queued hover updates must not dismiss the trigger after a stationary pointerdown.
return;
}
@@ -353,6 +354,9 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
this.showTableMenu(tableBound);
return;
}
+
+ this._scheduleParagraphMenuHide();
+ return;
}
this.hideParagraphMenu(true);
@@ -372,6 +376,10 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
);
this.disposeWithMe(this._docSelectionRenderService.onSelectionStart$.subscribe(() => {
+ this._cancelParagraphMenuHide();
+ }));
+
+ this.disposeWithMe(this._docSelectionRenderService.movingSelection$.subscribe(() => {
this.hideParagraphMenu(true);
}));
@@ -396,7 +404,9 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
if (this._isBlockMenuDragging) {
return;
}
- this.hideParagraphMenu(true);
+ if (this._paragraphMenu?.active) {
+ this.hideParagraphMenu(true);
+ }
}));
this.disposeWithMe(this._docEventManagerService.clickCustomRanges$.subscribe(() => {
@@ -416,6 +426,9 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
}
this._focusedTableMenuDismiss$.next();
+ if (PASSIVE_PARAGRAPH_MENU_KEYS.has((config.event as KeyboardEvent).key)) {
+ return;
+ }
this.hideParagraphMenu(true);
}));
@@ -558,11 +571,11 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
return;
}
+ this._cancelParagraphMenuHide();
if (this._paragraphMenu?.target.key === target.key) {
return;
}
- this.hideParagraphMenu(true);
const targetParagraph = target.paragraph ?? paragraph;
const blockRange = target.blockRange;
@@ -582,42 +595,13 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
return getTableCellParagraphAnchorRect(this._docEventManagerService, latestParagraphBound, menuAnchor);
};
- const disposable = this._docPopupManagerService.attachPopupToRect(
- getFirstLine,
- {
- componentKey: DOC_PARAGRAPH_MENU_COMPONENT_KEY,
- constrainToCanvas: true,
- // Hovering is passive; opened menus and drags hold their own interaction lease.
- requiresStableLayout: false,
- direction: 'left-center',
- onClickOutside: () => {
- if (this._isSlashMenuActive) {
- this.hideParagraphMenu(true);
- return;
- }
-
- this._docSelectionManagerService.textSelection$.pipe(first()).subscribe(() => {
- if (!this._isCursorInActiveParagraph()) {
- this.hideParagraphMenu(true);
- }
- });
- },
- zIndex: 101,
- },
- this._context.unitId
- );
-
- this._paragraphMenu = {
- paragraph: targetParagraph,
- target,
- blockRange,
- disposable,
- active: false,
- };
- this._activeTarget$.next(target);
+ this._showHoverMenu(targetParagraph, target, getFirstLine);
}
showTableMenu(tableBound: ITableBound, focused = false) {
+ if (!focused) {
+ this._cancelParagraphMenuHide();
+ }
if (!focused && this._focusedTableMenu?.target.table?.tableId === tableBound.tableId) {
return;
}
@@ -687,25 +671,42 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
return;
}
- this._showHoverTableMenu(tableBound, target, paragraph);
+ const getFirstLine = () => getTableAnchorRect(this._docEventManagerService.tableBounds.get(tableBound.tableId) ?? tableBound);
+ this._showHoverMenu(paragraph, target, getFirstLine);
}
- private _showHoverTableMenu(
- tableBound: ITableBound,
+ private _showHoverMenu(
+ paragraph: IMutiPageParagraphBound,
target: IDocBlockMenuTarget,
- paragraph: IMutiPageParagraphBound
+ getAnchor: () => IBoundRectNoAngle
): void {
- this.hideParagraphMenu(true);
- const getFirstLine = () => getTableAnchorRect(this._docEventManagerService.tableBounds.get(tableBound.tableId) ?? tableBound);
+ const menu = this._paragraphMenu;
+ if (menu?.active && (menu.target.kind === DocumentBlockType.TABLE) !== (target.kind === DocumentBlockType.TABLE)) {
+ this.hideParagraphMenu(true);
+ }
+ if (this._paragraphMenu) {
+ this._paragraphMenu.paragraph = paragraph;
+ this._paragraphMenu.target = target;
+ this._paragraphMenu.blockRange = target.blockRange;
+ this._paragraphMenu.getAnchor = getAnchor;
+ this._activeTarget$.next(target);
+ return;
+ }
+
const disposable = this._docPopupManagerService.attachPopupToRect(
- getFirstLine,
+ () => this._paragraphMenu?.getAnchor() ?? getAnchor(),
{
- componentKey: DOC_TABLE_BLOCK_MENU_COMPONENT_KEY,
+ direction: target.kind === DocumentBlockType.TABLE ? 'top-right' : 'left-center',
+ offset: target.kind === DocumentBlockType.TABLE ? [0, 0] : [8, 0],
+ componentKey: DOC_PARAGRAPH_MENU_COMPONENT_KEY,
+ positionChanges$: this.activeTarget$,
constrainToCanvas: true,
+ // Hovering is passive; opened menus and drags hold their own interaction lease.
requiresStableLayout: false,
- direction: 'top-right',
onClickOutside: () => {
- this.hideParagraphMenu(true);
+ if (this._isSlashMenuActive) {
+ this.hideParagraphMenu(true);
+ }
},
zIndex: 101,
},
@@ -715,8 +716,10 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
this._paragraphMenu = {
paragraph,
target,
+ blockRange: target.blockRange,
disposable,
active: false,
+ getAnchor,
};
this._activeTarget$.next(target);
}
@@ -805,7 +808,26 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
};
}
+ private _cancelParagraphMenuHide() {
+ if (this._paragraphMenuHideTimer != null) {
+ clearTimeout(this._paragraphMenuHideTimer);
+ this._paragraphMenuHideTimer = null;
+ }
+ }
+
+ private _scheduleParagraphMenuHide() {
+ if (!this._paragraphMenu || this._paragraphMenu.active || this._paragraphMenuHideTimer != null) {
+ return;
+ }
+
+ this._paragraphMenuHideTimer = setTimeout(() => {
+ this._paragraphMenuHideTimer = null;
+ this.hideParagraphMenu();
+ }, 200);
+ }
+
hideParagraphMenu(force = false) {
+ this._cancelParagraphMenuHide();
if (this._isBlockMenuDragging) {
return;
}
@@ -842,6 +864,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
this._isBlockMenuDragging = false;
this.hideFocusedTableMenu();
this.hideParagraphMenu(true);
+ this._activeTarget$.complete();
this._focusedTableTarget$.complete();
this._focusedTableMenuDismiss$.complete();
this._menuInteraction?.dispose();
diff --git a/packages/docs-ui/src/views/ParagraphMenu.tsx b/packages/docs-ui/src/views/ParagraphMenu.tsx
index f8eaae2fa9..784c5b5988 100644
--- a/packages/docs-ui/src/views/ParagraphMenu.tsx
+++ b/packages/docs-ui/src/views/ParagraphMenu.tsx
@@ -60,7 +60,7 @@ import {
useObservable,
} from '@univerjs/ui';
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
-import { BehaviorSubject } from 'rxjs';
+import { BehaviorSubject, skip } from 'rxjs';
import type { LocaleKey } from '../locale/types';
import type { IMutiPageParagraphBound } from '../services/doc-event-manager.service';
import type { IDocBlockMenuTarget } from '../services/doc-paragraph-menu.service';
@@ -113,6 +113,8 @@ import {
import { IDocClipboardService } from '../services/clipboard/clipboard.service';
import { DocEventManagerService } from '../services/doc-event-manager.service';
import { DocParagraphMenuService } from '../services/doc-paragraph-menu.service';
+import { DocSelectionRenderService } from '../services/selection/doc-selection-render.service';
+import { observeParagraphMenuPosition } from './paragraph-menu/paragraph-menu-position';
export function getParagraphMenuPopupDirection(
anchorLeft: number,
@@ -905,6 +907,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
const doc = univerInstanceService.getUnit<DocumentDataModel>(popup.unitId, UniverInstanceType.UNIVER_DOC);
const docParagraphMenuService = renderUnit?.with(DocParagraphMenuService);
const docEventManagerService = renderUnit?.with(DocEventManagerService);
+ const docSelectionRenderService = renderUnit?.with(DocSelectionRenderService);
const isFocusedTableMenu = popup.extraProps?.focusedTableMenu === true;
const activeTarget = useObservable(isFocusedTableMenu
? docParagraphMenuService?.focusedTableTarget$
@@ -922,7 +925,8 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
docParagraphMenuService?.setParagraphMenuActive(active, isFocusedTableMenu);
};
const rawActiveTarget = getActiveTarget();
- const currentActiveTarget = (rawActiveTarget?.kind === 'table') === tableBlockOnly ? rawActiveTarget : null;
+ const isTableMenu = tableBlockOnly || rawActiveTarget?.kind === 'table';
+ const currentActiveTarget = (rawActiveTarget?.kind === 'table') === isTableMenu ? rawActiveTarget : null;
const activeParagraphBound = currentActiveTarget?.paragraph ?? docParagraphMenuService?.activeParagraph ?? paragraph ?? paragraphLeft;
const startIndex = activeParagraphBound?.startIndex;
const dataStream = doc?.getBody()?.dataStream ?? '';
@@ -931,7 +935,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
const namedStyleType = paragraphObj?.paragraphStyle?.namedStyleType;
const isModernHeading = doc?.getDocumentStyle().documentFlavor === DocumentFlavor.MODERN &&
startIndex != null && renderUnit?.with(DocSkeletonManagerService).getViewModel().getHeadingSections().some((heading) => heading.paragraphIndex === startIndex && heading.startOffset < heading.endOffset);
- const targetIconKey = currentActiveTarget?.icon ?? getParagraphMenuTriggerIconKey(namedStyleType);
+ const targetIconKey = isEmptyParagraph ? 'IncreaseIcon' : currentActiveTarget?.icon ?? getParagraphMenuTriggerIconKey(namedStyleType);
const TargetIcon = iconManager.get(targetIconKey);
const paragraphMenuType = useMemo(
() => getParagraphMenuType(currentActiveTarget, isEmptyParagraph),
@@ -991,6 +995,17 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
// Service-driven dismissal (for example scrolling) can unmount the entire popup.
useLayoutEffect(() => restoreMenuFocus, [restoreMenuFocus]);
+ useLayoutEffect(() => {
+ if (isFocusedTableMenu || !docParagraphMenuService) {
+ return;
+ }
+ const popupElement = anchorRef.current?.closest<HTMLElement>('[data-u-comp="rect-popup"]');
+ if (!popupElement) {
+ return;
+ }
+ return observeParagraphMenuPosition(popupElement, popup, docParagraphMenuService.activeTarget$);
+ }, [docParagraphMenuService, isFocusedTableMenu, popup]);
+
const handleHideMenu = useCallback(() => {
hoverOpenSchedulerRef.current.cancel();
restoreMenuFocus();
@@ -1000,6 +1015,15 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
docParagraphMenuService?.setParagraphMenuActive(false, isFocusedTableMenu);
}, [docParagraphMenuService, isFocusedTableMenu, restoreMenuFocus]);
+ useEffect(() => {
+ if (!visible || isFocusedTableMenu || !docSelectionRenderService) {
+ return;
+ }
+ // Selection-start replays its last value; dismiss only for a new canvas interaction.
+ const subscription = docSelectionRenderService.onSelectionStart$.pipe(skip(1)).subscribe(handleHideMenu);
+ return () => subscription.unsubscribe();
+ }, [docSelectionRenderService, handleHideMenu, isFocusedTableMenu, visible]);
+
useEffect(() => {
if (!isFocusedTableMenu || !docParagraphMenuService) {
return;
@@ -1323,7 +1347,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
}, [docParagraphMenuService, isFocusedTableMenu]);
useEffect(() => {
- if (tableBlockOnly || !slashMenuRequest || handledSlashRequestNonceRef.current >= slashMenuRequest.nonce) {
+ if (isTableMenu || !slashMenuRequest || handledSlashRequestNonceRef.current >= slashMenuRequest.nonce) {
return;
}
@@ -1332,7 +1356,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
clearHideTimer();
isMouseOver.current = false;
handleOpenSlashMenu(slashMenuRequest);
- }, [slashMenuRequest, tableBlockOnly]);
+ }, [slashMenuRequest, isTableMenu]);
if (!currentActiveTarget) {
return null;
@@ -1342,7 +1366,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
<>
<div
data-u-comp="paragraph-menu"
- data-u-table-menu={tableBlockOnly ? 'true' : undefined}
+ data-u-table-menu={isTableMenu ? 'true' : undefined}
data-u-focused-table-menu={isFocusedTableMenu ? 'true' : undefined}
ref={anchorRef}
className={clsx(`
@@ -1384,7 +1408,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
`
)}
/>
- {currentActiveTarget?.draggable && (
+ {!isEmptyParagraph && currentActiveTarget?.draggable && (
<button
type="button"
className={`
diff --git a/packages/docs-ui/src/views/paragraph-menu/__tests__/paragraph-menu-position.spec.ts b/packages/docs-ui/src/views/paragraph-menu/__tests__/paragraph-menu-position.spec.ts
new file mode 100644
index 0000000000..054f481508
--- /dev/null
+++ b/packages/docs-ui/src/views/paragraph-menu/__tests__/paragraph-menu-position.spec.ts
@@ -0,0 +1,133 @@
+/**
+ * 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 { IPopup } from '@univerjs/ui';
+import { DocumentBlockType } from '@univerjs/core';
+import { BehaviorSubject } from 'rxjs';
+import { describe, expect, it, onTestFinished, vi } from 'vitest';
+import { observeParagraphMenuPosition } from '../paragraph-menu-position';
+
+function createPopup(kind = DocumentBlockType.PARAGRAPH) {
+ const resizeCallbacks: Array<() => void> = [];
+ const disconnect = vi.fn();
+ vi.stubGlobal('ResizeObserver', class {
+ constructor(callback: () => void) {
+ resizeCallbacks.push(callback);
+ }
+
+ observe() {}
+ disconnect = disconnect;
+ });
+ vi.stubGlobal('innerWidth', 1000);
+ vi.stubGlobal('innerHeight', 1000);
+ const element = document.createElement('section');
+ element.style.top = '-9999px';
+ element.style.left = '-9999px';
+ element.appendChild(document.createElement('button'));
+ document.body.appendChild(element);
+ Object.defineProperties(element, {
+ clientWidth: { configurable: true, value: 40 },
+ clientHeight: { configurable: true, value: 28 },
+ });
+ const canvasElement = document.createElement('canvas');
+ const getBoundary = vi.spyOn(canvasElement, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 1000, 1000));
+ const anchorRect$ = new BehaviorSubject({ left: 400, right: 400, top: 400, bottom: 440 });
+ const targets$ = new BehaviorSubject({ kind });
+ const popup: IPopup = { unitId: 'doc', subUnitId: 'body', componentKey: 'paragraph-menu', canvasElement, anchorRect$ };
+ const dispose = observeParagraphMenuPosition(element, popup, targets$);
+ onTestFinished(() => {
+ dispose();
+ element.remove();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+ return { element, anchorRect$, targets$, resizeCallbacks, disconnect, getBoundary, dispose };
+}
+
+describe('Docs paragraph menu positioning', () => {
+ it.each([DocumentBlockType.PARAGRAPH, DocumentBlockType.TABLE])('places the initial %s trigger without animation', (kind) => {
+ const { element } = createPopup(kind);
+ expect(element.style.transition).toBe('');
+ expect(element.style.left).toBe(kind === DocumentBlockType.TABLE ? '360px' : '352px');
+ expect(element.style.top).toBe(kind === DocumentBlockType.TABLE ? '372px' : '406px');
+ });
+
+ it('moves the same trigger and corrects shared popup writes after table/paragraph switches', async () => {
+ const { element, anchorRect$, targets$ } = createPopup();
+ const trigger = element.firstChild;
+ anchorRect$.next({ left: 500, right: 500, top: 500, bottom: 540 });
+ expect(element.style.left).toBe('452px');
+ expect(element.style.top).toBe('506px');
+ expect(element.style.transition).toBe('top 100ms ease-out, left 100ms ease-out');
+
+ targets$.next({ kind: DocumentBlockType.TABLE });
+ expect(element.style.left).toBe('460px');
+ expect(element.style.top).toBe('472px');
+ element.style.left = '452px';
+ element.style.top = '506px';
+ await Promise.resolve();
+ expect(element.style.left).toBe('460px');
+ expect(element.style.top).toBe('472px');
+
+ targets$.next({ kind: DocumentBlockType.PARAGRAPH });
+ expect(element.style.left).toBe('452px');
+ expect(element.style.top).toBe('506px');
+ expect(element.firstChild).toBe(trigger);
+ });
+
+ it('keeps the trigger inside a resized canvas and releases its observers on disposal', async () => {
+ const { element, anchorRect$, resizeCallbacks, disconnect, getBoundary, dispose } = createPopup();
+ getBoundary.mockReturnValue(new DOMRect(100, 450, 400, 100));
+ resizeCallbacks.forEach((callback) => callback());
+ expect(element.style.top).toBe('458px');
+ expect(element.style.left).toBe('352px');
+
+ dispose();
+ dispose();
+ anchorRect$.next({ left: 600, right: 600, top: 600, bottom: 640 });
+ element.style.left = '123px';
+ resizeCallbacks.forEach((callback) => callback());
+ await Promise.resolve();
+ expect(element.style.left).toBe('123px');
+ expect(element.style.transition).toBe('');
+ expect(disconnect).toHaveBeenCalled();
+ expect(anchorRect$.observed).toBe(false);
+ });
+
+ it('respects reduced motion when the anchor moves', () => {
+ vi.stubGlobal('matchMedia', () => ({ matches: true }));
+ const { element, anchorRect$ } = createPopup();
+ anchorRect$.next({ left: 500, right: 500, top: 500, bottom: 540 });
+ expect(element.style.left).toBe('452px');
+ expect(element.style.top).toBe('506px');
+ expect(element.style.transition).toBe('');
+ });
+
+ it('settles fractional positions after the browser normalizes CSS numbers', async () => {
+ const { element, anchorRect$ } = createPopup();
+ const topSetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(element.style), 'top')!.set!;
+ const writeTop = vi.spyOn(element.style, 'top', 'set').mockImplementation((value) => {
+ topSetter.call(element.style, `${Number.parseFloat(value).toFixed(3)}px`);
+ });
+
+ anchorRect$.next({ left: 500, right: 500, top: 500.6666666666667, bottom: 540.6666666666667 });
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(element.style.top).toBe('506.667px');
+ expect(writeTop).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/docs-ui/src/views/paragraph-menu/paragraph-menu-position.ts b/packages/docs-ui/src/views/paragraph-menu/paragraph-menu-position.ts
new file mode 100644
index 0000000000..d9749fe1b0
--- /dev/null
+++ b/packages/docs-ui/src/views/paragraph-menu/paragraph-menu-position.ts
@@ -0,0 +1,92 @@
+/**
+ * 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 { IBoundRectNoAngle } from '@univerjs/engine-render';
+import type { IPopup } from '@univerjs/ui';
+import type { Observable } from 'rxjs';
+import { DocumentBlockType } from '@univerjs/core';
+import { RectPopup } from '@univerjs/ui';
+import { Subscription } from 'rxjs';
+
+export function observeParagraphMenuPosition(
+ element: HTMLElement,
+ popup: IPopup,
+ targets$: Observable<{ kind: DocumentBlockType } | null>
+): () => void {
+ let anchor: IBoundRectNoAngle | undefined;
+ let table = false;
+ let previousPosition: { top: number; left: number; styleTop: string; styleLeft: string } | undefined;
+ let disposed = false;
+ const previousTransition = element.style.transition;
+ const updatePosition = () => {
+ if (disposed || !anchor || element.style.visibility === 'hidden') {
+ return;
+ }
+ const gap = table ? 0 : 8;
+ const boundary = popup.canvasElement.getBoundingClientRect();
+ const containerLeft = Math.max(boundary.left, 0);
+ const containerTop = Math.max(boundary.top, 0);
+ const position = RectPopup.calcPopupPosition({
+ position: { ...anchor, left: anchor.left - gap, right: anchor.right + gap },
+ width: element.clientWidth,
+ height: element.clientHeight,
+ direction: table ? 'top-right' : 'left-center',
+ containerLeft,
+ containerTop,
+ containerWidth: Math.max(0, Math.min(boundary.right, window.innerWidth) - containerLeft),
+ containerHeight: Math.max(0, Math.min(boundary.bottom, window.innerHeight) - containerTop),
+ boundaryInsets: popup.boundaryInsets,
+ noPushMinimumGap: popup.noPushMinimumGap,
+ });
+ if (previousPosition?.top === position.top && previousPosition.left === position.left &&
+ element.style.top === previousPosition.styleTop && element.style.left === previousPosition.styleLeft) {
+ return;
+ }
+ element.style.transition = previousPosition && !window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
+ ? 'top 100ms ease-out, left 100ms ease-out'
+ : '';
+ element.style.top = `${position.top}px`;
+ element.style.left = `${position.left}px`;
+ // Compare the browser's serialized CSS values on the next mutation, including fractional coordinates.
+ previousPosition = { ...position, styleTop: element.style.top, styleLeft: element.style.left };
+ };
+ // Reapply Docs placement after RectPopup updates its own positioning styles, before the next paint.
+ const mutationObserver = new MutationObserver(updatePosition);
+ mutationObserver.observe(element, { attributes: true, attributeFilter: ['style'] });
+ const resizeObserver = new ResizeObserver(updatePosition);
+ resizeObserver.observe(element);
+ resizeObserver.observe(popup.canvasElement);
+ const subscription = new Subscription();
+ subscription.add(targets$.subscribe((target) => {
+ table = target?.kind === DocumentBlockType.TABLE;
+ updatePosition();
+ }));
+ subscription.add(popup.anchorRect$.subscribe((rect) => {
+ anchor = rect;
+ updatePosition();
+ }));
+
+ return () => {
+ if (disposed) {
+ return;
+ }
+ disposed = true;
+ subscription.unsubscribe();
+ mutationObserver.disconnect();
+ resizeObserver.disconnect();
+ element.style.transition = previousTransition;
+ };
+}