Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(docs): restore zoom and add facade insertion APIs (#6968)

Univer94c2aef0e970
diff --git a/packages/docs-ui/src/components/paragraph-menu/__tests__/paragraph-menu.spec.ts b/packages/docs-ui/src/components/paragraph-menu/__tests__/paragraph-menu.spec.ts
index 41d2930553..cd1c9eb99c 100644
--- a/packages/docs-ui/src/components/paragraph-menu/__tests__/paragraph-menu.spec.ts
+++ b/packages/docs-ui/src/components/paragraph-menu/__tests__/paragraph-menu.spec.ts
@@ -16,8 +16,8 @@
import { NamedStyleType } from '@univerjs/core';
-import { describe, expect, it } from 'vitest';
-import { getParagraphMenuActiveHeadingCommandId, getParagraphMenuCommand, getParagraphMenuHiddenHeadingCommandIds, getParagraphMenuIconSizeClass, getParagraphMenuPopupDirection, getParagraphMenuTargetRange, isEmptyParagraphMenuTarget, shouldShowParagraphSettingMenu, shouldUseInsertBelowRange } from '..';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createParagraphMenuHoverOpenScheduler, getParagraphMenuActiveHeadingCommandId, getParagraphMenuCommand, getParagraphMenuHiddenHeadingCommandIds, getParagraphMenuIconSizeClass, getParagraphMenuPopupDirection, getParagraphMenuTargetRange, isEmptyParagraphMenuTarget, PARAGRAPH_MENU_HOVER_OPEN_DELAY, shouldShowParagraphSettingMenu, shouldUseInsertBelowRange } from '..';
import { HorizontalLineCommand } from '../../../commands/commands/doc-horizontal-line.command';
import { BulletListCommand, InsertBulletListBellowCommand, OrderListCommand } from '../../../commands/commands/list.command';
import { H1HeadingCommand, H3HeadingCommand, H5HeadingCommand, NormalTextHeadingCommand, SetParagraphNamedStyleCommand, SubtitleHeadingCommand, TitleHeadingCommand } from '../../../commands/commands/set-heading.command';
@@ -35,6 +35,10 @@ import {
} from '../../../menu/paragraph-menu';
describe('ParagraphMenu', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
it('uses a smaller icon for normal text paragraph triggers', () => {
expect(getParagraphMenuIconSizeClass('TextTypeIcon')).toBe('univer-size-3');
expect(getParagraphMenuIconSizeClass('TitleTypeIcon')).toBe('univer-size-4');
@@ -65,6 +69,43 @@ describe('ParagraphMenu', () => {
expect(getParagraphMenuPopupDirection(260)).toBe('left');
});
+ it('delays opening the paragraph popup for hover and cancels before the delay elapses', () => {
+ vi.useFakeTimers();
+ const openMenu = vi.fn();
+ const scheduler = createParagraphMenuHoverOpenScheduler(openMenu);
+
+ scheduler.schedule();
+ vi.advanceTimersByTime(PARAGRAPH_MENU_HOVER_OPEN_DELAY - 1);
+
+ expect(openMenu).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(1);
+
+ expect(openMenu).toHaveBeenCalledTimes(1);
+
+ openMenu.mockClear();
+ scheduler.schedule();
+ scheduler.cancel();
+ vi.advanceTimersByTime(PARAGRAPH_MENU_HOVER_OPEN_DELAY);
+
+ expect(openMenu).not.toHaveBeenCalled();
+ });
+
+ it('opens the paragraph popup immediately for click', () => {
+ vi.useFakeTimers();
+ const openMenu = vi.fn();
+ const scheduler = createParagraphMenuHoverOpenScheduler(openMenu);
+
+ scheduler.schedule();
+ scheduler.openNow();
+
+ expect(openMenu).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(PARAGRAPH_MENU_HOVER_OPEN_DELAY);
+
+ expect(openMenu).toHaveBeenCalledTimes(1);
+ });
+
it('shows title and subtitle heading shortcuts only when they are the current paragraph style', () => {
expect(shouldShowParagraphHeadingOption(NamedStyleType.HEADING_5, NamedStyleType.NORMAL_TEXT)).toBe(true);
expect(shouldShowParagraphHeadingOption(NamedStyleType.TITLE, NamedStyleType.NORMAL_TEXT)).toBe(false);
diff --git a/packages/docs-ui/src/components/paragraph-menu/index.tsx b/packages/docs-ui/src/components/paragraph-menu/index.tsx
index ff9e6730bb..59d523b4ce 100644
--- a/packages/docs-ui/src/components/paragraph-menu/index.tsx
+++ b/packages/docs-ui/src/components/paragraph-menu/index.tsx
@@ -47,6 +47,34 @@ export function getParagraphMenuPopupDirection(anchorLeft: number, menuWidth = 2
return anchorLeft - menuWidth < viewportPadding ? 'right' : 'left';
}
+export const PARAGRAPH_MENU_HOVER_OPEN_DELAY = 260;
+
+export function createParagraphMenuHoverOpenScheduler(openMenu: () => void, delay = PARAGRAPH_MENU_HOVER_OPEN_DELAY) {
+ let openTimer: number | null = null;
+
+ const cancel = () => {
+ if (openTimer != null) {
+ window.clearTimeout(openTimer);
+ openTimer = null;
+ }
+ };
+
+ return {
+ schedule() {
+ cancel();
+ openTimer = window.setTimeout(() => {
+ openTimer = null;
+ openMenu();
+ }, delay);
+ },
+ cancel,
+ openNow() {
+ cancel();
+ openMenu();
+ },
+ };
+}
+
export function isEmptyParagraphMenuTarget(dataStream: string, paragraph?: IMutiPageParagraphBound | null | void): boolean {
if (!paragraph) {
return false;
@@ -179,6 +207,8 @@ export const ParagraphMenu = ({ popup }: { popup: IPopup }) => {
const dragTargetOffsetRef = useRef<number | null>(null);
const dragRangeRef = useRef<{ startOffset: number; endOffset: number } | null>(null);
const isDraggingRef = useRef(false);
+ const openMenuRef = useRef<() => void>(() => undefined);
+ const hoverOpenSchedulerRef = useRef(createParagraphMenuHoverOpenScheduler(() => openMenuRef.current()));
const commandService = useDependency(ICommandService);
const docSelectionManagerService = useDependency(DocSelectionManagerService);
const docClipboardService = useDependency(IDocClipboardService);
@@ -271,8 +301,24 @@ export const ParagraphMenu = ({ popup }: { popup: IPopup }) => {
setEmptyMode(isEmptyParagraph);
setVisible(true);
};
+ openMenuRef.current = handleOpenMenu;
- useEffect(() => () => clearHideTimer(), []);
+ const scheduleOpenMenu = () => {
+ clearHideTimer();
+ hoverOpenSchedulerRef.current.schedule();
+ };
+
+ const cancelOpenMenu = () => {
+ hoverOpenSchedulerRef.current.cancel();
+ };
+
+ useEffect(() => () => {
+ if (hideTimerRef.current != null) {
+ window.clearTimeout(hideTimerRef.current);
+ hideTimerRef.current = null;
+ }
+ hoverOpenSchedulerRef.current.cancel();
+ }, []);
return (
<>
@@ -292,17 +338,18 @@ export const ParagraphMenu = ({ popup }: { popup: IPopup }) => {
onMouseEnter={(e) => {
popup.onPointerEnter?.(e);
isMouseOver.current = true;
- handleOpenMenu();
+ scheduleOpenMenu();
}}
onMouseLeave={() => {
isMouseOver.current = false;
+ cancelOpenMenu();
scheduleHideMenu();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
isMouseOver.current = true;
- handleOpenMenu();
+ hoverOpenSchedulerRef.current.openNow();
}}
>
<TargetIcon
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/zoom.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/zoom.render-controller.spec.ts
new file mode 100644
index 0000000000..1ea476c376
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/zoom.render-controller.spec.ts
@@ -0,0 +1,31 @@
+/**
+ * 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 { DocumentFlavor } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { shouldHandleDocWheelZoom } from '../zoom.render-controller';
+
+describe('DocZoomRenderController', () => {
+ it('handles wheel zoom intent for focused modern docs', () => {
+ expect(shouldHandleDocWheelZoom({ ctrlKey: true, metaKey: false }, true, DocumentFlavor.MODERN)).toBe(true);
+ });
+
+ it('handles platform zoom modifier variants only while docs are focused', () => {
+ expect(shouldHandleDocWheelZoom({ ctrlKey: false, metaKey: true }, true, DocumentFlavor.TRADITIONAL)).toBe(true);
+ expect(shouldHandleDocWheelZoom({ ctrlKey: false, metaKey: false }, true, DocumentFlavor.TRADITIONAL)).toBe(false);
+ expect(shouldHandleDocWheelZoom({ ctrlKey: true, metaKey: false }, false, DocumentFlavor.TRADITIONAL)).toBe(false);
+ });
+});
diff --git a/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts
index 9c56dcc249..cf320f6f7e 100644
--- a/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts
@@ -41,6 +41,14 @@ import { SetDocZoomRatioOperation } from '../../commands/operations/set-doc-zoom
import { DocPageLayoutService } from '../../services/doc-page-layout.service';
import { IEditorService } from '../../services/editor/editor-manager.service';
+export function shouldHandleDocWheelZoom(
+ event: Pick<IWheelEvent, 'ctrlKey' | 'metaKey'>,
+ focusingDoc: boolean,
+ _documentFlavor?: DocumentFlavor
+): boolean {
+ return focusingDoc && (event.ctrlKey || event.metaKey);
+}
+
export class DocZoomRenderController extends Disposable implements IRenderModule {
private _isSheetEditor = false;
private _initTimer: number;
@@ -146,19 +154,13 @@ export class DocZoomRenderController extends Disposable implements IRenderModule
this.disposeWithMe(
// hold ctrl & mousewheel ---> zoom
scene.onMouseWheel$.subscribeEvent((e: IWheelEvent) => {
- if (!e.ctrlKey || !this._contextService.getContextValue(FOCUSING_DOC)) {
- return;
- }
-
const documentModel = this._univerInstanceService.getCurrentUniverDocInstance();
if (!documentModel) {
return;
}
const { documentFlavor } = documentModel.getSnapshot().documentStyle;
-
- if (documentFlavor === DocumentFlavor.MODERN) {
- e.preventDefault();
+ if (!shouldHandleDocWheelZoom(e, Boolean(this._contextService.getContextValue(FOCUSING_DOC)), documentFlavor)) {
return;
}
diff --git a/packages/docs-ui/src/facade/__tests__/f-document.spec.ts b/packages/docs-ui/src/facade/__tests__/f-document.spec.ts
index 6456facd5b..de9decda70 100644
--- a/packages/docs-ui/src/facade/__tests__/f-document.spec.ts
+++ b/packages/docs-ui/src/facade/__tests__/f-document.spec.ts
@@ -79,6 +79,51 @@ describe('Test FDocument', () => {
});
});
+ it('inserts text at an explicit document range', async () => {
+ await expect(document.insertText('Docs', {
+ endOffset: 4,
+ segmentId: '',
+ startOffset: 2,
+ })).resolves.toBe(true);
+
+ expect(commandService.executeCommand).toHaveBeenCalledWith(InsertCommand.id, {
+ unitId: 'test',
+ body: {
+ dataStream: 'Docs',
+ },
+ range: {
+ startOffset: 2,
+ endOffset: 4,
+ collapsed: false,
+ segmentId: '',
+ },
+ segmentId: '',
+ });
+ });
+
+ it('inserts paragraphs at an explicit document range', async () => {
+ await expect(document.insertParagraph('Line 1\nLine 2', {
+ endOffset: 6,
+ segmentId: '',
+ startOffset: 6,
+ })).resolves.toBe(true);
+
+ expect(commandService.executeCommand).toHaveBeenCalledWith(InsertCommand.id, {
+ unitId: 'test',
+ body: {
+ dataStream: 'Line 1\r\nLine 2\r\n',
+ },
+ range: {
+ startOffset: 6,
+ endOffset: 6,
+ collapsed: true,
+ segmentId: '',
+ },
+ segmentId: '',
+ cursorOffset: 'Line 1\r\nLine 2\r\n'.length,
+ });
+ });
+
it('throws when appending text to a document without a body', () => {
const emptyDocument = new FDocument(
{
diff --git a/packages/docs-ui/src/facade/f-document.ts b/packages/docs-ui/src/facade/f-document.ts
index b8d218cb50..a3f9d1fb04 100644
--- a/packages/docs-ui/src/facade/f-document.ts
+++ b/packages/docs-ui/src/facade/f-document.ts
@@ -29,6 +29,13 @@ import {
import { DocSelectionRenderService, InsertCommand } from '@univerjs/docs-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
+export interface IDocumentInsertTextFacadeOptions {
+ startOffset?: number;
+ endOffset?: number;
+ segmentId?: string;
+ cursorOffset?: number;
+}
+
/**
* @hideconstructor
*/
@@ -76,8 +83,6 @@ export class FDocument {
* @param text - The text to be added to the end of this text region.
*/
appendText(text: string): Promise<boolean> {
- const unitId = this.id;
-
const { body } = this.getSnapshot();
if (!body) {
@@ -86,14 +91,35 @@ export class FDocument {
const lastPosition = body.dataStream.length - 2;
- const activeRange = {
+ return this.insertText(text, {
startOffset: lastPosition,
endOffset: lastPosition,
- collapsed: true,
segmentId: '',
- };
+ });
+ }
+
+ /**
+ * Inserts text at the provided document range. Defaults to appending before the final section break.
+ * @param text - The text to insert.
+ * @param options - Optional target range, segment id, and cursor offset.
+ */
+ insertText(text: string, options: IDocumentInsertTextFacadeOptions = {}): Promise<boolean> {
+ const unitId = this.id;
+ const { body } = this.getSnapshot();
- const { segmentId } = activeRange;
+ if (!body) {
+ throw new Error('The document body is empty');
+ }
+
+ const startOffset = options.startOffset ?? Math.max(0, body.dataStream.length - 2);
+ const endOffset = options.endOffset ?? startOffset;
+ const segmentId = options.segmentId ?? '';
+ const activeRange = {
+ startOffset,
+ endOffset,
+ collapsed: startOffset === endOffset,
+ segmentId,
+ };
return this._commandService.executeCommand(InsertCommand.id, {
unitId,
@@ -102,6 +128,21 @@ export class FDocument {
},
range: activeRange,
segmentId,
+ ...(options.cursorOffset == null ? {} : { cursorOffset: options.cursorOffset }),
+ });
+ }
+
+ /**
+ * Inserts one or more plain-text paragraphs at the provided document range.
+ * @param text - Paragraph text. Newlines are normalized to document paragraph separators.
+ * @param options - Optional target range, segment id, and cursor offset.
+ */
+ insertParagraph(text = '', options: IDocumentInsertTextFacadeOptions = {}): Promise<boolean> {
+ const dataStream = `${text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n').join('\r\n')}\r\n`;
+
+ return this.insertText(dataStream, {
+ ...options,
+ cursorOffset: options.cursorOffset ?? dataStream.length,
});
}