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-quick-insert-ui): enhance placeholder rendering with dynamic styles (#6673)

白熱27b363fcd037
diff --git a/packages/docs-quick-insert-ui/src/commands/commands/__tests__/doc-quick-insert.command.spec.ts b/packages/docs-quick-insert-ui/src/commands/commands/__tests__/doc-quick-insert.command.spec.ts
new file mode 100644
index 0000000000..ce3a8e96e3
--- /dev/null
+++ b/packages/docs-quick-insert-ui/src/commands/commands/__tests__/doc-quick-insert.command.spec.ts
@@ -0,0 +1,57 @@
+/**
+ * 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 { ICommandService, Injector, RANGE_DIRECTION } from '@univerjs/core';
+import { CutContentCommand } from '@univerjs/docs-ui';
+import { describe, expect, it, vi } from 'vitest';
+import { DeleteSearchKeyCommand } from '../doc-quick-insert.command';
+
+function createAccessor(bindings: Array<[unknown, unknown]>) {
+ const injector = new Injector();
+
+ bindings.forEach(([token, value]) => {
+ injector.add([token as never, { useValue: value }]);
+ });
+
+ return injector as never;
+}
+
+describe('DeleteSearchKeyCommand', () => {
+ it('cuts the slash-triggered keyword range from the document', () => {
+ const syncExecuteCommand = vi.fn(() => true);
+ const accessor = createAccessor([
+ [ICommandService, { syncExecuteCommand }],
+ ]);
+
+ const result = DeleteSearchKeyCommand.handler(accessor, { start: 4, end: 9 });
+
+ expect(result).toBe(true);
+ expect(syncExecuteCommand).toHaveBeenCalledWith(CutContentCommand.id, {
+ segmentId: '',
+ textRanges: [{
+ startOffset: 4,
+ endOffset: 4,
+ collapsed: true,
+ }],
+ selections: [{
+ startOffset: 4,
+ endOffset: 9,
+ collapsed: false,
+ direction: RANGE_DIRECTION.FORWARD,
+ }],
+ });
+ });
+});
diff --git a/packages/docs-quick-insert-ui/src/commands/operations/__tests__/quick-insert-popup.operation.spec.ts b/packages/docs-quick-insert-ui/src/commands/operations/__tests__/quick-insert-popup.operation.spec.ts
new file mode 100644
index 0000000000..49b6fa763a
--- /dev/null
+++ b/packages/docs-quick-insert-ui/src/commands/operations/__tests__/quick-insert-popup.operation.spec.ts
@@ -0,0 +1,61 @@
+/**
+ * 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 { Injector } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { DocQuickInsertPopupService } from '../../../services/doc-quick-insert-popup.service';
+import { CloseQuickInsertPopupOperation, ShowQuickInsertPopupOperation } from '../quick-insert-popup.operation';
+
+function createAccessor(bindings: Array<[unknown, unknown]>) {
+ const injector = new Injector();
+
+ bindings.forEach(([token, value]) => {
+ injector.add([token as never, { useValue: value }]);
+ });
+
+ return injector as never;
+}
+
+describe('quick insert popup operations', () => {
+ it('shows a popup only when parameters are provided', () => {
+ const showPopup = vi.fn();
+ const accessor = createAccessor([
+ [DocQuickInsertPopupService, { showPopup }],
+ ]);
+ const params = {
+ unitId: 'doc-1',
+ index: 3,
+ popup: {
+ keyword: '/',
+ menus$: { subscribe: vi.fn() },
+ },
+ } as never;
+
+ expect(ShowQuickInsertPopupOperation.handler(accessor, undefined)).toBe(false);
+ expect(ShowQuickInsertPopupOperation.handler(accessor, params)).toBe(true);
+ expect(showPopup).toHaveBeenCalledWith(params);
+ });
+
+ it('closes the active popup session', () => {
+ const closePopup = vi.fn();
+ const accessor = createAccessor([
+ [DocQuickInsertPopupService, { closePopup }],
+ ]);
+
+ expect(CloseQuickInsertPopupOperation.handler(accessor)).toBe(true);
+ expect(closePopup).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/docs-quick-insert-ui/src/controllers/__tests__/doc-quick-insert-trigger.controller.spec.ts b/packages/docs-quick-insert-ui/src/controllers/__tests__/doc-quick-insert-trigger.controller.spec.ts
new file mode 100644
index 0000000000..1f235e2eff
--- /dev/null
+++ b/packages/docs-quick-insert-ui/src/controllers/__tests__/doc-quick-insert-trigger.controller.spec.ts
@@ -0,0 +1,212 @@
+/**
+ * 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 { DeleteDirection, Direction } from '@univerjs/core';
+import { RichTextEditingMutation } from '@univerjs/docs';
+import { DeleteCommand, DeleteLeftCommand, IMEInputCommand, InsertCommand, MoveCursorOperation } from '@univerjs/docs-ui';
+import { KeyCode } from '@univerjs/ui';
+import { describe, expect, it, vi } from 'vitest';
+import { CloseQuickInsertPopupOperation, ShowQuickInsertPopupOperation } from '../../commands/operations/quick-insert-popup.operation';
+import { numberedListMenu, textMenu } from '../../menu/built-in-menus';
+import { DocQuickInsertTriggerController } from '../doc-quick-insert-trigger.controller';
+
+function createCommandService() {
+ const listeners = new Set<(commandInfo: { id: string; params?: unknown }) => void>();
+
+ return {
+ executeCommand: vi.fn(() => true),
+ onCommandExecuted: vi.fn((callback: (commandInfo: { id: string; params?: unknown }) => void) => {
+ listeners.add(callback);
+ return {
+ dispose: () => listeners.delete(callback),
+ };
+ }),
+ emit(commandInfo: { id: string; params?: unknown }) {
+ listeners.forEach((listener) => listener(commandInfo));
+ },
+ };
+}
+
+function createPopupService() {
+ let menuSelectedHandler: ((menu: { id: string }) => void) | null = null;
+ let editPopup: { anchor: number } | null = null;
+ let isComposing = false;
+ let inputOffset = { start: 0, end: 0 };
+
+ return {
+ get editPopup() {
+ return editPopup;
+ },
+ setEditPopup(value: { anchor: number } | null) {
+ editPopup = value;
+ },
+ get isComposing() {
+ return isComposing;
+ },
+ get inputOffset() {
+ return inputOffset;
+ },
+ setInputOffset: vi.fn((value: { start: number; end: number }) => {
+ inputOffset = value;
+ }),
+ resolvePopup: vi.fn(),
+ setIsComposing: vi.fn((value: boolean) => {
+ isComposing = value;
+ }),
+ onMenuSelected: vi.fn((handler: (menu: { id: string }) => void) => {
+ menuSelectedHandler = handler;
+ return () => {
+ menuSelectedHandler = null;
+ };
+ }),
+ triggerMenuSelected(menu: { id: string }) {
+ menuSelectedHandler?.(menu);
+ },
+ };
+}
+
+describe('DocQuickInsertTriggerController', () => {
+ it('reacts to insert, edit, cursor, delete and IME events like a real quick-insert session', () => {
+ vi.useFakeTimers();
+
+ const commandService = createCommandService();
+ const popupService = createPopupService();
+ const shortcutService = {
+ registerShortcut: vi.fn(() => ({ dispose: vi.fn() })),
+ };
+ const selectionManagerService = {
+ getActiveTextRange: vi.fn(() => ({ startOffset: 5, endOffset: 5 })),
+ };
+ const popup = {
+ keyword: '/',
+ menus$: { subscribe: vi.fn() },
+ preconditions: vi.fn(() => true),
+ };
+ popupService.resolvePopup.mockReturnValue(popup);
+
+ const controller = new DocQuickInsertTriggerController(
+ commandService as never,
+ selectionManagerService as never,
+ popupService as never,
+ shortcutService as never,
+ {
+ getCurrentUnitOfType: vi.fn(() => ({ getDisabled: () => false })),
+ } as never
+ );
+
+ expect(shortcutService.registerShortcut).toHaveBeenCalledWith(expect.objectContaining({
+ id: CloseQuickInsertPopupOperation.id,
+ binding: KeyCode.ESC,
+ priority: 1000,
+ }));
+
+ commandService.emit({
+ id: InsertCommand.id,
+ params: {
+ body: { dataStream: '/' },
+ range: { endOffset: 5 },
+ unitId: 'doc-1',
+ },
+ });
+
+ expect(popupService.setInputOffset).toHaveBeenCalledWith({ start: 4, end: 5 });
+ expect(commandService.executeCommand).not.toHaveBeenCalledWith(ShowQuickInsertPopupOperation.id, expect.anything());
+
+ vi.advanceTimersByTime(100);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(ShowQuickInsertPopupOperation.id, {
+ index: 4,
+ unitId: 'doc-1',
+ popup,
+ });
+
+ popupService.setEditPopup({ anchor: 4 });
+ commandService.emit({
+ id: InsertCommand.id,
+ params: {
+ body: { dataStream: 'a' },
+ range: { endOffset: 7 },
+ unitId: 'doc-1',
+ },
+ });
+ expect(popupService.setInputOffset).toHaveBeenLastCalledWith({ start: 4, end: 8 });
+
+ commandService.emit({
+ id: IMEInputCommand.id,
+ params: { isCompositionStart: true, isCompositionEnd: false },
+ });
+ commandService.emit({
+ id: IMEInputCommand.id,
+ params: { isCompositionStart: false, isCompositionEnd: true },
+ });
+ expect(popupService.setIsComposing).toHaveBeenNthCalledWith(1, true);
+ expect(popupService.setIsComposing).toHaveBeenNthCalledWith(2, false);
+
+ commandService.emit({
+ id: RichTextEditingMutation.id,
+ params: {
+ isCompositionEnd: true,
+ textRanges: [{ endOffset: 9 }],
+ },
+ });
+ expect(popupService.setInputOffset).toHaveBeenLastCalledWith({ start: 4, end: 9 });
+
+ commandService.emit({
+ id: DeleteCommand.id,
+ params: {
+ direction: DeleteDirection.LEFT,
+ len: 2,
+ range: { endOffset: 10 },
+ },
+ });
+ expect(popupService.setInputOffset).toHaveBeenLastCalledWith({ start: 4, end: 8 });
+
+ commandService.emit({
+ id: MoveCursorOperation.id,
+ params: { direction: Direction.LEFT },
+ });
+ expect(commandService.executeCommand).toHaveBeenCalledWith(CloseQuickInsertPopupOperation.id);
+
+ selectionManagerService.getActiveTextRange.mockReturnValue({ startOffset: 4, endOffset: 4 });
+ commandService.emit({ id: DeleteLeftCommand.id });
+ expect(commandService.executeCommand).toHaveBeenCalledWith(CloseQuickInsertPopupOperation.id);
+
+ controller.dispose();
+ vi.useRealTimers();
+ });
+
+ it('executes built-in menu commands but skips plain text selection', () => {
+ const commandService = createCommandService();
+ const popupService = createPopupService();
+
+ const controller = new DocQuickInsertTriggerController(
+ commandService as never,
+ { getActiveTextRange: vi.fn() } as never,
+ popupService as never,
+ { registerShortcut: vi.fn(() => ({ dispose: vi.fn() })) } as never,
+ {
+ getCurrentUnitOfType: vi.fn(() => ({ getDisabled: () => false })),
+ } as never
+ );
+
+ popupService.triggerMenuSelected(textMenu);
+ popupService.triggerMenuSelected(numberedListMenu);
+
+ expect(commandService.executeCommand).not.toHaveBeenCalledWith(textMenu.id);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(numberedListMenu.id);
+
+ controller.dispose();
+ });
+});
diff --git a/packages/docs-quick-insert-ui/src/controllers/__tests__/doc-quick-insert-ui.controller.spec.ts b/packages/docs-quick-insert-ui/src/controllers/__tests__/doc-quick-insert-ui.controller.spec.ts
new file mode 100644
index 0000000000..5ba54788a2
--- /dev/null
+++ b/packages/docs-quick-insert-ui/src/controllers/__tests__/doc-quick-insert-ui.controller.spec.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 { describe, expect, it, vi } from 'vitest';
+import { QuickInsertButton } from '../../menu';
+import { DocQuickInsertUIController } from '../doc-quick-insert-ui.controller';
+
+describe('DocQuickInsertUIController', () => {
+ it('registers commands, components and the built-in slash popup', () => {
+ const registerCommand = vi.fn(() => ({ dispose: vi.fn() }));
+ const register = vi.fn(() => ({ dispose: vi.fn() }));
+ const unregisterPopup = vi.fn();
+ const registerPopup = vi.fn(() => unregisterPopup);
+
+ const controller = new DocQuickInsertUIController(
+ { registerCommand } as never,
+ { registerPopup } as never,
+ { register } as never
+ );
+
+ expect(registerCommand).toHaveBeenCalledTimes(3);
+ expect(register).toHaveBeenCalledWith(QuickInsertButton.componentKey, QuickInsertButton);
+ expect(registerPopup).toHaveBeenCalledTimes(1);
+
+ const firstRegisterPopupCall = registerPopup.mock.calls[0] as unknown[] | undefined;
+ expect(firstRegisterPopupCall).toBeDefined();
+
+ const slashPopup = firstRegisterPopupCall?.[0] as unknown as {
+ keyword: string;
+ preconditions: (params: { range: { startNodePosition?: { glyph?: number } } }) => boolean;
+ };
+ expect(slashPopup.keyword).toBe('/');
+ expect(slashPopup.preconditions({ range: { startNodePosition: { glyph: 0 } } })).toBe(true);
+ expect(slashPopup.preconditions({ range: { startNodePosition: { glyph: 2 } } })).toBe(false);
+
+ controller.dispose();
+ expect(unregisterPopup).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/docs-quick-insert-ui/src/menu/__tests__/doc-quick-insert-menu.controller.spec.ts b/packages/docs-quick-insert-ui/src/menu/__tests__/doc-quick-insert-menu.controller.spec.ts
new file mode 100644
index 0000000000..d4ab8c497d
--- /dev/null
+++ b/packages/docs-quick-insert-ui/src/menu/__tests__/doc-quick-insert-menu.controller.spec.ts
@@ -0,0 +1,101 @@
+/**
+ * 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 { BehaviorSubject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { DocQuickInsertMenuController } from '../doc-quick-insert-menu.controller';
+
+function createParagraph(startIndex: number, paragraphEnd = startIndex) {
+ return {
+ startIndex,
+ paragraphStart: startIndex,
+ paragraphEnd,
+ firstLine: { left: 1, top: 2, right: 10, bottom: 12 },
+ };
+}
+
+describe('DocQuickInsertMenuController', () => {
+ it('shows the quick insert button for empty paragraphs and hides it when the line is no longer eligible', () => {
+ const hoverParagraphLeftRealTime$ = new BehaviorSubject<ReturnType<typeof createParagraph> | null>(null);
+ const hoverParagraphRealTime$ = new BehaviorSubject<ReturnType<typeof createParagraph> | null>(null);
+ const firstDisposable = { dispose: vi.fn(), canDispose: vi.fn(() => true) };
+ const secondDisposable = { dispose: vi.fn(), canDispose: vi.fn(() => true) };
+ const attachPopupToRect = vi.fn()
+ .mockReturnValueOnce(firstDisposable)
+ .mockReturnValueOnce(secondDisposable);
+
+ const controller = new DocQuickInsertMenuController(
+ {
+ unit: {
+ getDisabled: () => false,
+ getUnitId: () => 'doc-1',
+ },
+ } as never,
+ { hoverParagraphLeftRealTime$, hoverParagraphRealTime$ } as never,
+ { editPopup: null } as never,
+ { attachPopupToRect } as never
+ );
+
+ const emptyParagraph = createParagraph(6);
+ hoverParagraphRealTime$.next(emptyParagraph);
+
+ expect(attachPopupToRect).toHaveBeenCalledTimes(1);
+ expect(controller.popup).toEqual({ startIndex: 6, disposable: firstDisposable });
+
+ hoverParagraphRealTime$.next(emptyParagraph);
+ expect(attachPopupToRect).toHaveBeenCalledTimes(1);
+
+ hoverParagraphRealTime$.next(createParagraph(6, 9));
+ expect(firstDisposable.dispose).toHaveBeenCalledTimes(1);
+ expect(controller.popup).toBeNull();
+
+ hoverParagraphLeftRealTime$.next(createParagraph(8));
+ expect(attachPopupToRect).toHaveBeenCalledTimes(2);
+ expect(controller.popup).toEqual({ startIndex: 8, disposable: secondDisposable });
+
+ controller.dispose();
+ });
+
+ it('keeps the left-side button mounted while the edit popup itself is active', () => {
+ const hoverParagraphLeftRealTime$ = new BehaviorSubject<ReturnType<typeof createParagraph> | null>(createParagraph(3));
+ const hoverParagraphRealTime$ = new BehaviorSubject<ReturnType<typeof createParagraph> | null>(null);
+ const disposable = { dispose: vi.fn(), canDispose: vi.fn(() => true) };
+ const quickInsertPopupService = {
+ editPopup: null as { anchor: number } | null,
+ };
+
+ const controller = new DocQuickInsertMenuController(
+ {
+ unit: {
+ getDisabled: () => false,
+ getUnitId: () => 'doc-1',
+ },
+ } as never,
+ { hoverParagraphLeftRealTime$, hoverParagraphRealTime$ } as never,
+ quickInsertPopupService as never,
+ { attachPopupToRect: vi.fn(() => disposable) } as never
+ );
+
+ quickInsertPopupService.editPopup = { anchor: 3 };
+ hoverParagraphLeftRealTime$.next(null);
+ hoverParagraphRealTime$.next(null);
+
+ expect(disposable.dispose).not.toHaveBeenCalled();
+ expect(controller.popup).toEqual({ startIndex: 3, disposable });
+
+ controller.dispose();
+ });
+});
diff --git a/packages/docs-quick-insert-ui/src/services/__tests__/doc-quick-insert-popup.service.spec.ts b/packages/docs-quick-insert-ui/src/services/__tests__/doc-quick-insert-popup.service.spec.ts
new file mode 100644
index 0000000000..ebf24bea72
--- /dev/null
+++ b/packages/docs-quick-insert-ui/src/services/__tests__/doc-quick-insert-popup.service.spec.ts
@@ -0,0 +1,198 @@
+/**
+ * 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 { of } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { DeleteSearchKeyCommand } from '../../commands/commands/doc-quick-insert.command';
+import { KeywordInputPlaceholder } from '../../views/KeywordInputPlaceholder';
+import { QuickInsertPopup } from '../../views/QuickInsertPopup';
+import { DocQuickInsertPopupService } from '../doc-quick-insert-popup.service';
+
+function createPopupDisposable() {
+ return {
+ dispose: vi.fn(),
+ canDispose: vi.fn(() => true),
+ };
+}
+
+function createServiceTestBed() {
+ let dataStream = '/';
+ const paragraphBound = {
+ firstLine: { left: 0, top: 0, right: 10, bottom: 20 },
+ };
+ const popupEntries: Array<{
+ rect: unknown;
+ popup: { componentKey: string; extraProps?: unknown };
+ disposable: ReturnType<typeof createPopupDisposable>;
+ }> = [];
+ const activeRange = {
+ startOffset: 1,
+ endOffset: 1,
+ segmentId: '',
+ segmentPage: -1,
+ };
+ const glyph = {
+ content: '\r',
+ ts: { fs: 11, ff: 'Arial' },
+ fontStyle: {
+ fontString: '14.6666666667px Arial',
+ fontFamily: 'Arial',
+ },
+ bBox: {
+ ba: 10,
+ bd: 4,
+ },
+ };
+ const docDataModel = {
+ getBody: () => ({
+ dataStream,
+ paragraphs: [{ startIndex: 1 }],
+ }),
+ };
+ const docEventManagerService = {
+ findParagraphBoundByIndex: vi.fn(() => paragraphBound),
+ };
+ const skeleton = {
+ findNodeByCharIndex: vi.fn(() => glyph),
+ findNodePositionByCharIndex: vi.fn(() => undefined),
+ };
+ const currentRender = {
+ with: vi.fn((token: unknown) => {
+ const name = (token as { name?: string })?.name;
+ if (name === 'DocEventManagerService') {
+ return docEventManagerService;
+ }
+ if (name === 'DocSkeletonManagerService') {
+ return { getSkeleton: () => skeleton };
+ }
+ return undefined;
+ }),
+ mainComponent: {
+ getOffsetConfig: () => ({ docsLeft: 0, docsTop: 0 }),
+ },
+ };
+ const docCanvasPopupManagerService = {
+ attachPopupToRect: vi.fn((rect: unknown, popup: { componentKey: string; extraProps?: unknown }) => {
+ const disposable = createPopupDisposable();
+ popupEntries.push({ rect, popup, disposable });
+ return disposable;
+ }),
+ };
+ const commandService = {
+ syncExecuteCommand: vi.fn(() => true),
+ };
+
+ const service = new DocQuickInsertPopupService(
+ docCanvasPopupManagerService as never,
+ {
+ getCurrentUnitOfType: vi.fn(() => docDataModel),
+ getUnit: vi.fn(() => docDataModel),
+ } as never,
+ commandService as never,
+ {
+ getRenderById: vi.fn(() => currentRender),
+ } as never,
+ {
+ getActiveTextRange: vi.fn(() => activeRange),
+ } as never
+ );
+
+ return {
+ service,
+ popupEntries,
+ commandService,
+ paragraphBound,
+ setDataStream: (value: string) => {
+ dataStream = value;
+ },
+ };
+}
+
+describe('DocQuickInsertPopupService', () => {
+ it('registers popups, resolves them by trigger and emits selected menus after deleting the search key', () => {
+ vi.useFakeTimers();
+
+ const { service, commandService } = createServiceTestBed();
+ const popup = {
+ keyword: '/',
+ menus$: of([]),
+ };
+ const menu = {
+ id: 'menu-1',
+ title: 'Text',
+ };
+ const onSelected = vi.fn();
+
+ const unregisterPopup = service.registerPopup(popup);
+ const unregisterHandler = service.onMenuSelected(onSelected);
+
+ expect(service.resolvePopup('/')).toBe(popup);
+
+ service.setInputOffset({ start: 2, end: 4 });
+ service.emitMenuSelected(menu as never);
+
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(DeleteSearchKeyCommand.id, { start: 2, end: 4 });
+ expect(onSelected).not.toHaveBeenCalled();
+
+ vi.runAllTimers();
+ expect(onSelected).toHaveBeenCalledWith(menu);
+
+ unregisterHandler();
+ unregisterPopup();
+ expect(service.resolvePopup('/')).toBeUndefined();
+
+ service.dispose();
+ vi.useRealTimers();
+ });
+
+ it('shows the popup on an empty line and remounts the keyword placeholder as input state changes', () => {
+ const { service, popupEntries, setDataStream } = createServiceTestBed();
+ const popup = {
+ keyword: '/',
+ menus$: of([]),
+ };
+
+ service.showPopup({ popup, index: 0, unitId: 'doc-1' });
+
+ expect(popupEntries).toHaveLength(2);
+ expect(popupEntries[0].popup.componentKey).toBe(KeywordInputPlaceholder.componentKey);
+ expect(popupEntries[1].popup.componentKey).toBe(QuickInsertPopup.componentKey);
+ expect(service.editPopup).toEqual(expect.objectContaining({ popup, anchor: 0, unitId: 'doc-1' }));
+
+ setDataStream('/a');
+ service.setInputOffset({ start: 0, end: 2 });
+ expect(popupEntries[0].disposable.dispose).toHaveBeenCalledTimes(1);
+
+ setDataStream('/');
+ service.setInputOffset({ start: 0, end: 1 });
+ expect(popupEntries).toHaveLength(3);
+ expect(popupEntries[2].popup.componentKey).toBe(KeywordInputPlaceholder.componentKey);
+
+ service.setIsComposing(true);
+ expect(popupEntries[2].disposable.dispose).toHaveBeenCalledTimes(1);
+
+ service.setIsComposing(false);
+ expect(popupEntries).toHaveLength(4);
+ expect(popupEntries[3].popup.componentKey).toBe(KeywordInputPlaceholder.componentKey);
+
+ service.closePopup();
+ expect(popupEntries[1].disposable.dispose).toHaveBeenCalledTimes(1);
+ expect(popupEntries[3].disposable.dispose).toHaveBeenCalledTimes(1);
+ expect(service.editPopup).toBeNull();
+
+ service.dispose();
+ });
+});
diff --git a/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts b/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts
index 774fe3bf64..d6c4ceaf95 100644
--- a/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts
+++ b/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts
@@ -16,10 +16,11 @@
import type { DocumentDataModel, IDisposable, Nullable } from '@univerjs/core';
import type { IInsertCommandParams } from '@univerjs/docs-ui';
+import type { Documents, DocumentSkeleton, IBoundRectNoAngle, IDocumentSkeletonGlyph, ITextRangeWithStyle } from '@univerjs/engine-render';
import type { Observable } from 'rxjs';
import { Disposable, ICommandService, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
-import { DocCanvasPopManagerService, DocEventManagerService } from '@univerjs/docs-ui';
+import { DocCanvasPopManagerService, DocEventManagerService, getAnchorBounding, NodePositionConvertToCursor } from '@univerjs/docs-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
import { BehaviorSubject, combineLatest, distinctUntilChanged, map, tap } from 'rxjs';
import { DeleteSearchKeyCommand } from '../commands/commands/doc-quick-insert.command';
@@ -52,6 +53,17 @@ export interface IDocPopup {
const noopDisposable = {
dispose: () => {},
};
+
+interface IKeywordInputPlaceholderExtraProps {
+ fontSize?: number;
+ fontString?: string;
+ fontFamily?: string;
+ fontStyle?: 'normal' | 'italic';
+ fontWeight?: 'normal' | 'bold';
+ ascent?: number;
+ contentHeight?: number;
+}
+
export class DocQuickInsertPopupService extends Disposable {
private readonly _popups: Set<IDocPopup> = new Set();
get popups() {
@@ -195,49 +207,104 @@ export class DocQuickInsertPopupService extends Disposable {
return renderRoot;
}
- showPopup(options: { popup: IDocPopup; index: number; unitId: string }) {
- const { popup, index, unitId } = options;
- this.closePopup();
+ private _getParagraphBound(unitId: string, index: number) {
const currentDoc = this._univerInstanceService.getUnit<DocumentDataModel>(unitId);
const paragraph = currentDoc?.getBody()?.paragraphs?.find((p) => p.startIndex > index);
if (!paragraph) {
- return;
+ return null;
}
+
const docEventManagerService = this.getDocEventManagerService(unitId);
- const paragraphBound = docEventManagerService?.findParagraphBoundByIndex(paragraph.startIndex);
- if (!paragraphBound) {
- return;
+ return docEventManagerService?.findParagraphBoundByIndex(paragraph.startIndex) ?? null;
+ }
+
+ private _getKeywordPlaceholderAnchorRect(
+ document: Documents,
+ skeleton: DocumentSkeleton,
+ activeRange: ITextRangeWithStyle,
+ fallbackRect: IBoundRectNoAngle
+ ): IBoundRectNoAngle {
+ const startPosition = skeleton.findNodePositionByCharIndex(activeRange.startOffset, true, activeRange.segmentId, activeRange.segmentPage);
+ if (!startPosition) {
+ return fallbackRect;
}
- this._inputPlaceholderRenderRoot = this._createInputPlaceholderRenderRoot(() => {
- const docSkeletonManagerService = this._renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService);
- const activeRange = this._docSelectionManagerService.getActiveTextRange();
- if (!docSkeletonManagerService || !activeRange) {
- return noopDisposable;
- }
-
- const skeleton = docSkeletonManagerService.getSkeleton();
- const curGlyph = skeleton.findNodeByCharIndex(activeRange.startOffset, activeRange.segmentId, activeRange.segmentPage);
- const isEmptyLine = curGlyph?.content === '\r';
- // Only show filter keyword placeholder on empty line
- if (!isEmptyLine) {
- return noopDisposable;
- }
-
- const disposable = this._docCanvasPopupManagerService.attachPopupToRange(
- { startOffset: index + 1, endOffset: index + 1, collapsed: false },
- {
- componentKey: KeywordInputPlaceholder.componentKey,
- onClickOutside: () => {
- disposable.dispose();
- },
- direction: 'horizontal',
+ const documentOffsetConfig = document.getOffsetConfig();
+ const convertor = new NodePositionConvertToCursor(documentOffsetConfig, skeleton);
+ const { contentBoxPointGroup } = convertor.getRangePointData(startPosition, startPosition);
+
+ if (contentBoxPointGroup.length === 0) {
+ return fallbackRect;
+ }
+
+ const anchor = getAnchorBounding(contentBoxPointGroup);
+ const left = anchor.left + documentOffsetConfig.docsLeft;
+ const top = anchor.top + documentOffsetConfig.docsTop;
+
+ return {
+ left,
+ right: left,
+ top,
+ bottom: top + anchor.height,
+ };
+ }
+
+ private _getKeywordPlaceholderExtraProps(curGlyph: IDocumentSkeletonGlyph): IKeywordInputPlaceholderExtraProps {
+ return {
+ fontSize: curGlyph.ts?.fs,
+ fontString: curGlyph.fontStyle?.fontString,
+ fontFamily: curGlyph.fontStyle?.fontFamily ?? curGlyph.ts?.ff ?? undefined,
+ fontStyle: curGlyph.ts?.it ? 'italic' : 'normal',
+ fontWeight: curGlyph.ts?.bl ? 'bold' : 'normal',
+ ascent: curGlyph.bBox?.ba,
+ contentHeight: ((curGlyph.bBox?.ba ?? 0) + (curGlyph.bBox?.bd ?? 0)) || undefined,
+ };
+ }
+
+ private _mountInputPlaceholder(unitId: string, fallbackRect: IBoundRectNoAngle): IDisposable {
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+ const docSkeletonManagerService = currentRender?.with(DocSkeletonManagerService);
+ const activeRange = this._docSelectionManagerService.getActiveTextRange();
+ if (!currentRender || !docSkeletonManagerService || !activeRange) {
+ return noopDisposable;
+ }
+
+ const skeleton = docSkeletonManagerService.getSkeleton();
+ const curGlyph = skeleton.findNodeByCharIndex(activeRange.startOffset, activeRange.segmentId, activeRange.segmentPage);
+ const isEmptyLine = curGlyph?.content === '\r';
+ if (!isEmptyLine || !curGlyph) {
+ return noopDisposable;
+ }
+
+ const document = currentRender.mainComponent as Documents;
+ const placeholderAnchorRect = this._getKeywordPlaceholderAnchorRect(document, skeleton, activeRange, fallbackRect);
+ const extraProps = this._getKeywordPlaceholderExtraProps(curGlyph);
+
+ const disposable = this._docCanvasPopupManagerService.attachPopupToRect(
+ placeholderAnchorRect,
+ {
+ componentKey: KeywordInputPlaceholder.componentKey,
+ extraProps,
+ onClickOutside: () => {
+ disposable.dispose();
},
- unitId
- );
+ direction: 'horizontal',
+ },
+ unitId
+ );
- return disposable;
- });
+ return disposable;
+ }
+
+ showPopup(options: { popup: IDocPopup; index: number; unitId: string }) {
+ const { popup, index, unitId } = options;
+ this.closePopup();
+ const paragraphBound = this._getParagraphBound(unitId, index);
+ if (!paragraphBound) {
+ return;
+ }
+
+ this._inputPlaceholderRenderRoot = this._createInputPlaceholderRenderRoot(() => this._mountInputPlaceholder(unitId, paragraphBound.firstLine));
this._inputPlaceholderRenderRoot.mount();
const disposable = this._docCanvasPopupManagerService.attachPopupToRect(
diff --git a/packages/docs-quick-insert-ui/src/views/KeywordInputPlaceholder.tsx b/packages/docs-quick-insert-ui/src/views/KeywordInputPlaceholder.tsx
index 15cf7dc474..2249432206 100644
--- a/packages/docs-quick-insert-ui/src/views/KeywordInputPlaceholder.tsx
+++ b/packages/docs-quick-insert-ui/src/views/KeywordInputPlaceholder.tsx
@@ -14,17 +14,80 @@
* limitations under the License.
*/
+import type { IPopup } from '@univerjs/ui';
import { LocaleService } from '@univerjs/core';
+import { ptToPixel } from '@univerjs/engine-render';
import { useDependency } from '@univerjs/ui';
+import { useMemo } from 'react';
export const KeywordInputPlaceholderComponentKey = 'docs.quick.insert.keyword-input-placeholder';
-export const KeywordInputPlaceholder = () => {
+const DEFAULT_FONT_SIZE = 11;
+
+interface IKeywordInputPlaceholderExtraProps {
+ fontSize?: number;
+ fontString?: string;
+ fontFamily?: string;
+ fontStyle?: 'normal' | 'italic';
+ fontWeight?: 'normal' | 'bold';
+ ascent?: number;
+ contentHeight?: number;
+}
+
+function measureTextWidth(text: string, font: string) {
+ if (typeof document === 'undefined') {
+ return text.length * DEFAULT_FONT_SIZE;
+ }
+
+ const canvas = document.createElement('canvas');
+ const context = canvas.getContext('2d');
+
+ if (!context) {
+ return text.length * DEFAULT_FONT_SIZE;
+ }
+
+ context.font = font;
+
+ return Math.ceil(context.measureText(text).width);
+}
+
+export const KeywordInputPlaceholder = ({ popup }: { popup: IPopup<IKeywordInputPlaceholderExtraProps> }) => {
const localeService = useDependency(LocaleService);
- // TODO: 需要根据fontSize来计算高度跟偏移
+ const placeholder = localeService.t('docQuickInsert.keywordInputPlaceholder');
+ const fontSize = popup.extraProps?.fontSize ?? DEFAULT_FONT_SIZE;
+ const fontSizePx = ptToPixel(fontSize);
+ const fontString = popup.extraProps?.fontString ?? `${fontSizePx}px sans-serif`;
+ const ascent = popup.extraProps?.ascent ?? fontSizePx;
+ const contentHeight = Math.max(popup.extraProps?.contentHeight ?? fontSizePx, fontSizePx);
+ const textWidth = useMemo(() => measureTextWidth(placeholder, fontString), [fontString, placeholder]);
+
return (
- <div className="univer-translate-y-1.5 univer-text-sm univer-text-gray-500">
- {localeService.t('docQuickInsert.keywordInputPlaceholder')}
+ <div
+ className={`
+ univer-select-none univer-font-normal univer-text-gray-500 univer-transition-colors
+ dark:!univer-text-gray-400
+ `}
+ >
+ <svg
+ width={textWidth}
+ height={contentHeight}
+ viewBox={`0 0 ${textWidth} ${contentHeight}`}
+ style={{ overflow: 'visible', display: 'block' }}
+ >
+ <text
+ x={0}
+ y={ascent}
+ fill="currentColor"
+ style={{
+ font: fontString,
+ fontFamily: popup.extraProps?.fontFamily,
+ fontStyle: popup.extraProps?.fontStyle,
+ fontWeight: popup.extraProps?.fontWeight,
+ }}
+ >
+ {placeholder}
+ </text>
+ </svg>
</div>
);
};