Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(docs-ui): add paste special and post-paste formatting (#7709)
Univer13e30364c01e
diff --git a/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.tsindex 9d28cefac3..e4ee4873d6 100644--- a/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts@@ -14,9 +14,8 @@* limitations under the License.*/-import type { ICommand, ICommandInfo, IDisposable, IDocumentData, Injector, IStyleBase, JSONXActions, Univer } from '@univerjs/core';+import type { ICommand, ICommandInfo, IDocumentData, Injector, IStyleBase, JSONXActions, Univer } from '@univerjs/core';import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';-import type { IDocClipboardHook } from '../../../services/clipboard/clipboard.service';import type { IInnerCutCommandParams, IInnerPasteCommandParams } from '../clipboard.inner.command';import {BooleanNumber,@@ -32,19 +31,33 @@ import {ICommandService,IContextService,IUniverInstanceService,+ LocaleService,+ LocaleType,ObjectRelativeFromH,ObjectRelativeFromV,PositionedObjectLayoutType,RedoCommand,- SliceBodyType,Tools,UndoCommand,UniverInstanceType,} from '@univerjs/core';import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';-import { IClipboardInterfaceService } from '@univerjs/ui';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { IDocClipboardService } from '../../../services/clipboard/clipboard.service';+import {+ IClipboardInterfaceService,+ IMessageService,+ IPlatformService,+ IShortcutService,+ IUIRuntimeScopeService,+ KeyCode,+ MetaKeys,+ MOBILE_UI_MODE,+ PasteCommand,+ ShortcutService,+ UIRuntimeScopeService,+} from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import zhCN from '../../../locale/zh-CN';+import { DocClipboardService, IDocClipboardService } from '../../../services/clipboard/clipboard.service';import {DocCopyCommand,DocCopyCurrentParagraphCommand,@@ -58,44 +71,9 @@ import { CutContentCommand, InnerPasteCommand } from '../clipboard.inner.commandimport { genEmptyTable, genTableSource } from '../table/table';import { createCommandTestBed } from './create-command-test-bed';-class TestDocClipboardService {- readonly copies: Array<{ sliceType?: SliceBodyType; ranges?: ITextRangeWithStyle[] }> = [];- readonly cuts: Array<{ ranges?: ITextRangeWithStyle[] }> = [];- readonly pastes: ClipboardItem[][] = [];- memoryPasteResult = false;- memoryPastes = 0;-- async copy(sliceType?: SliceBodyType, ranges?: ITextRangeWithStyle[]): Promise<boolean> {- this.copies.push({ sliceType, ranges });- return true;- }-- async cut(ranges?: ITextRangeWithStyle[]): Promise<boolean> {- this.cuts.push({ ranges });- return true;- }-- async paste(items?: ClipboardItem[]): Promise<boolean> {- if (!items?.length) {- this.memoryPastes++;- return this.memoryPasteResult;- }-- this.pastes.push(items);- return true;- }-- async legacyPaste(): Promise<boolean> {- return false;- }-- addClipboardHook(_hook: IDocClipboardHook): IDisposable {- return { dispose() {} };- }-}-class TestClipboardInterfaceService {- items: ClipboardItem[] = [{ types: ['text/plain'] } as unknown as ClipboardItem];+ items: ClipboardItem[] = [];+ readonly writes: Array<{ text: string; html: string }> = [];supported = true;reads = 0;@@ -104,7 +82,10 @@ class TestClipboardInterfaceService {}async writeText(): Promise<void> {}- async write(): Promise<void> {}+ async write(text: string, html: string): Promise<void> {+ this.writes.push({ text, html });+ }+async readText(): Promise<string> { return ''; }async read(): Promise<ClipboardItem[]> {this.reads++;@@ -1299,8 +1280,13 @@ describe('test cases in clipboard', () => {});describe('Test public doc clipboard commands', () => {+ function selectRanges(textRanges: ITextRangeWithStyle[]) {+ const selection = get(DocSelectionManagerService);+ selection.replaceSelectionInfoWithoutRefresh({ ...selection.getSelectionInfo()!, textRanges, rectRanges: [] });+ }+beforeEach(() => {- injector.add([IDocClipboardService, { useClass: TestDocClipboardService }]);+ injector.add([IDocClipboardService, { useClass: DocClipboardService }]);injector.add([IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }]);commandService.registerMultipleCommand(DocCopyCommand);@@ -1327,69 +1313,98 @@ describe('test cases in clipboard', () => {expect(whenFocusEditor(contextService)).toBe(true);});- it('Should route document copy and cut commands to the docs clipboard service', async () => {- const docClipboardService = get(IDocClipboardService) as unknown as TestDocClipboardService;-- await commandService.executeCommand(DocCopyCommand.id);- await commandService.executeCommand(DocCutCommand.id);-- expect(docClipboardService.copies).toEqual([{ sliceType: undefined, ranges: undefined }]);- expect(docClipboardService.cuts).toEqual([{ ranges: undefined }]);+ it('copies selected text and cuts it through the public commands', async () => {+ selectRanges([{+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ isActive: true,+ segmentId: '',+ }]);+ const clipboard = get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;+ expect(await commandService.executeCommand(DocCopyCommand.id)).toBe(true);+ expect(clipboard.writes[0].text).toBe('What’');+ const before = getDocumentSnapshot()?.body?.dataStream ?? '';+ expect(await commandService.executeCommand(DocCutCommand.id)).toBe(true);+ expect(getDocumentSnapshot()?.body?.dataStream).toBe(before.slice(5));});- it('Should route current paragraph copy and cut with paragraph document ranges', async () => {- const selectionManager = get(DocSelectionManagerService);- selectionManager.__TEST_ONLY_add([{+ it('copies and cuts the paragraph containing the cursor', async () => {+ selectRanges([{startOffset: 3,endOffset: 3,collapsed: true,isActive: true,segmentId: '',- style: null as never,}]);- const docClipboardService = get(IDocClipboardService) as unknown as TestDocClipboardService;-- await commandService.executeCommand(DocCopyCurrentParagraphCommand.id);- await commandService.executeCommand(DocCutCurrentParagraphCommand.id);-- expect(docClipboardService.copies[0].sliceType).toBe(SliceBodyType.copy);- expect(docClipboardService.copies[0].ranges?.[0]).toMatchObject({- startOffset: 0,- endOffset: 23,- collapsed: false,- });- expect(docClipboardService.cuts[0].ranges?.[0]).toMatchObject({- startOffset: 0,- endOffset: 23,- collapsed: false,- rangeType: DOC_RANGE_TYPE.TEXT,- });+ const clipboard = get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;+ expect(await commandService.executeCommand(DocCopyCurrentParagraphCommand.id)).toBe(true);+ expect(clipboard.writes[0].text).toContain('What’s New in the 2022');+ expect(await commandService.executeCommand(DocCutCurrentParagraphCommand.id)).toBe(true);+ expect(getDocumentSnapshot()?.body?.dataStream).not.toContain('What’s New in the 2022');});- it('Should read browser clipboard items before pasting into the document', async () => {- const docClipboardService = get(IDocClipboardService) as unknown as TestDocClipboardService;- const clipboardInterfaceService = get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;-- clipboardInterfaceService.items = [];- const emptyResult = await commandService.executeCommand(DocPasteCommand.id);- expect(emptyResult).toBe(false);- expect(docClipboardService.pastes).toHaveLength(0);-- clipboardInterfaceService.items = [{ types: ['text/html'] } as unknown as ClipboardItem];- await commandService.executeCommand(DocPasteCommand.id);-- expect(docClipboardService.pastes).toEqual([clipboardInterfaceService.items]);+ it('reads browser clipboard items and pastes their content', async () => {+ const clipboard = get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;+ expect(await commandService.executeCommand(DocPasteCommand.id)).toBe(false);+ clipboard.items = [{+ types: ['text/html', 'text/plain'],+ presentationStyle: 'unspecified',+ getType: async (type: string) => ({ text: async () => type === 'text/html' ? '<b>External</b>' : 'External' }) as Blob,+ } as ClipboardItem];+ expect(await commandService.executeCommand(DocPasteCommand.id)).toBe(true);+ expect(clipboard.reads).toBe(2);+ expect(getDocumentSnapshot()?.body?.dataStream).toContain('External');});- it('Should paste the internal copy when browser clipboard reads are unsupported', async () => {- const docClipboardService = get(IDocClipboardService) as unknown as TestDocClipboardService;- const clipboardInterfaceService = get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;- docClipboardService.memoryPasteResult = true;- clipboardInterfaceService.supported = false;+ it.each([+ { mobile: true, isMac: false, binding: MetaKeys.CTRL_COMMAND | KeyCode.V, shortcut: 'Ctrl+V' },+ { mobile: false, isMac: false, binding: MetaKeys.CTRL_COMMAND | KeyCode.V, shortcut: 'Ctrl+V' },+ { mobile: false, isMac: true, binding: MetaKeys.CTRL_COMMAND | KeyCode.V, shortcut: '⌘+V' },+ { mobile: false, isMac: false, binding: MetaKeys.ALT | KeyCode.P, shortcut: 'Alt+P' },+ { mobile: false, isMac: false, binding: null, shortcut: null },+ ])('preserves the document and shows configured paste guidance (mobile: $mobile, shortcut: $shortcut)', async ({ mobile, isMac, binding, shortcut }) => {+ const show = vi.fn<IMessageService['show']>(() => ({ dispose: () => {} }));+ injector.add([IMessageService, { useValue: { show, remove: vi.fn(), removeAll: vi.fn() } }]);+ injector.add([IPlatformService, { useValue: { isMac, isWindows: !isMac, isLinux: false } }]);+ injector.add([IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }]);+ injector.add([IShortcutService, { useClass: ShortcutService }]);+ const shortcutService = get(IShortcutService);+ if (binding !== null) {+ shortcutService.registerShortcut({ id: PasteCommand.id, binding });+ }+ const localeService = get(LocaleService);+ localeService.load({ [LocaleType.ZH_CN]: zhCN });+ localeService.setLocale(LocaleType.ZH_CN);+ localeService.setDirection('ltr');+ get(IContextService).setContextValue(MOBILE_UI_MODE, mobile);+ const clipboard = get(IClipboardInterfaceService);+ vi.spyOn(clipboard, 'read').mockRejectedValue(new DOMException('Permission denied', 'NotAllowedError'));+ const before = Tools.deepClone(getRequiredDocumentSnapshot());++ expect(await commandService.executeCommand(DocPasteCommand.id)).toBe(false);+ expect(getRequiredDocumentSnapshot()).toEqual(before);+ expect(show).toHaveBeenCalledOnce();+ const message = show.mock.calls[0][0].content;+ expect(message).not.toContain('docs-ui.');+ if (mobile || !shortcut) {+ expect(message).toContain('设备或键盘');+ expect(message).not.toMatch(/Ctrl|Cmd/);+ } else {+ expect(message).toContain(shortcut);+ expect(message).not.toContain('{0}');+ }+ });+ it('pastes an internal copy when browser reads are unsupported', async () => {+ selectRanges([{ startOffset: 0, endOffset: 5, collapsed: false, isActive: true, segmentId: '' }]);+ expect(await commandService.executeCommand(DocCopyCommand.id)).toBe(true);+ selectRanges([{ startOffset: 0, endOffset: 0, collapsed: true, isActive: true, segmentId: '' }]);+ const clipboard = get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;+ clipboard.supported = false;expect(await commandService.executeCommand(DocPasteCommand.id)).toBe(true);- expect(docClipboardService.memoryPastes).toBe(1);- expect(clipboardInterfaceService.reads).toBe(0);+ expect(clipboard.reads).toBe(0);+ expect(getDocumentSnapshot()?.body?.dataStream).toMatch(/^What’What’s/);});});});diff --git a/packages/docs-ui/src/commands/commands/clipboard.command.ts b/packages/docs-ui/src/commands/commands/clipboard.command.tsindex d5791accf2..c1b496ed2a 100644--- a/packages/docs-ui/src/commands/commands/clipboard.command.ts+++ b/packages/docs-ui/src/commands/commands/clipboard.command.ts@@ -14,9 +14,20 @@* limitations under the License.*/-import type { IAccessor, IContextService, IMultiCommand } from '@univerjs/core';-import { CommandType, DOC_RANGE_TYPE, EDITOR_ACTIVATED, FOCUSING_DOC, SliceBodyType } from '@univerjs/core';-import { CopyCommand, CutCommand, IClipboardInterfaceService, PasteCommand } from '@univerjs/ui';+import type { IAccessor, ICommand, IMultiCommand } from '@univerjs/core';+import type { LocaleKey } from '../../locale/types';+import type { DocPasteMode } from '../../services/clipboard/paste-options';+import {+ CommandType,+ DOC_RANGE_TYPE,+ EDITOR_ACTIVATED,+ FOCUSING_DOC,+ IContextService,+ LocaleService,+ SliceBodyType,+} from '@univerjs/core';+import { MessageType } from '@univerjs/design';+import { CopyCommand, CutCommand, IMessageService, IShortcutService, MOBILE_UI_MODE, PasteCommand } from '@univerjs/ui';import { IDocClipboardService } from '../../services/clipboard/clipboard.service';import { getCurrentParagraph } from './util';@@ -101,6 +112,32 @@ export const DocCutCurrentParagraphCommand = {},};+export const DocPasteSpecialCommand: ICommand<{ value: DocPasteMode }> = {+ id: 'doc.command.paste-special',+ type: CommandType.COMMAND,+ handler: async (accessor, params) => {+ if (!params || !['source', 'destination', 'text'].includes(params.value)) {+ return false;+ }+ const service = accessor.get(IDocClipboardService);+ try {+ return await service.pasteFromClipboard(params.value);+ } catch {+ const localeService = accessor.get(LocaleService);+ const pasteShortcut = accessor.get(IContextService).getContextValue(MOBILE_UI_MODE)+ ? null+ : accessor.get(IShortcutService).getShortcutDisplayOfCommand(PasteCommand.id);+ accessor.get(IMessageService).show({+ type: MessageType.Info,+ content: pasteShortcut+ ? localeService.t<LocaleKey>('docs-ui.pasteOptions.useKeyboard', pasteShortcut)+ : localeService.t<LocaleKey>('docs-ui.pasteOptions.useSystemPaste'),+ });+ return false;+ }+ },+};+export const DocPasteCommand: IMultiCommand = {id: PasteCommand.id,name: 'doc.command.paste',@@ -108,13 +145,26 @@ export const DocPasteCommand: IMultiCommand = {multi: true,priority: DOC_CLIPBOARD_PRIORITY,preconditions: whenDocOrEditor,- handler: async (accessor: IAccessor) => {- const docClipboardService = accessor.get(IDocClipboardService);- const clipboardInterfaceService = accessor.get(IClipboardInterfaceService);- const clipboardItems = clipboardInterfaceService.supportClipboard- ? await clipboardInterfaceService.read()- : [];+ handler: (accessor: IAccessor) => DocPasteSpecialCommand.handler(accessor, { value: 'source' }),+};- return docClipboardService.paste(clipboardItems);+export const DocChangePasteModeCommand: ICommand<{ value: DocPasteMode }> = {+ id: 'doc.command.change-paste-mode',+ type: CommandType.COMMAND,+ handler: async (accessor, params) => {+ if (!params || !['source', 'destination', 'text'].includes(params.value)) {+ return false;+ }+ try {+ return await accessor.get(IDocClipboardService).changePasteMode(params.value);+ } catch {+ accessor.get(IDocClipboardService).dismissPasteOptions();+ const localeService = accessor.get(LocaleService);+ accessor.get(IMessageService).show({+ type: MessageType.Error,+ content: localeService.t<LocaleKey>('docs-ui.pasteOptions.failed'),+ });+ return false;+ }},};diff --git a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts b/packages/docs-ui/src/commands/commands/clipboard.inner.command.tsindex 741b9c604d..bbbb82058b 100644--- a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts+++ b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts@@ -14,12 +14,30 @@* limitations under the License.*/-import type { DocumentDataModel, IAccessor, ICommand, ICustomTable, IDisposable, IDocumentBody, IDocumentData, IDrawingParam, IMutationInfo, ITextRange, JSONXActions, Nullable } from '@univerjs/core';+import type {+ DocumentDataModel,+ IAccessor,+ ICommand,+ ICustomTable,+ IDisposable,+ IDocumentBody,+ IDocumentData,+ IDrawingParam,+ IMutationInfo,+ ITextRange,+ JSONXActions,+ Nullable,+} from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';import type { DocumentViewModel, IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';-import type { IDocClipboardPasteBlockRangeMapping, IDocClipboardPasteCustomBlockMapping, IDocClipboardPasteCustomRangeMapping } from '../../services/clipboard/doc-paste-mutation-adapter.service';+import type {+ IDocClipboardPasteBlockRangeMapping,+ IDocClipboardPasteCustomBlockMapping,+ IDocClipboardPasteCustomRangeMapping,+} from '../../services/clipboard/doc-paste-mutation-adapter.service';import {BuildTextUtils,+ cloneBodyWithFreshParagraphIds,CommandType,createParagraphId,DataStreamTreeTokenType,@@ -33,6 +51,7 @@ import {IUniverInstanceService,JSONX,MemoryCursor,+ PRESERVE_INSERTED_PARAGRAPH_IDS,SHEET_EDITOR_UNITS,TextX,TextXActionType,@@ -71,8 +90,7 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {id: 'doc.command.inner-paste',type: CommandType.COMMAND,- // eslint-disable-next-line max-lines-per-function, complexity- handler: async (accessor, params: IInnerPasteCommandParams) => {+ handler: (accessor, params: IInnerPasteCommandParams) => {const {customRangeMappings = [],segmentId,@@ -195,7 +213,10 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {const len = startOffset - memoryCursor.cursor;- const cloneBody = Tools.deepClone(body);+ const cloneBody = cloneBodyWithFreshParagraphIds(body, { unitId, segmentId });+ // Pasted paragraphs own fresh identities. Keep them explicit so undo/redo+ // does not swap the surviving destination paragraph's identity on a split.+ Reflect.set(cloneBody, PRESERVE_INSERTED_PARAGRAPH_IDS, true);const blockRangeMappings: IDocClipboardPasteBlockRangeMapping[] = [];const customBlockMappings: IDocClipboardPasteCustomBlockMapping[] = [];const selectionCustomRangeMappings = (body.customRanges ?? []).map((range) => ({@@ -356,10 +377,10 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {return false;}- const historyId = `doc-paste-resource:${unitId}:${Date.now()}`;+ const historyId = `doc-paste-resource:${unitId}:${generateRandomId()}`;let batchingDisposable: IDisposable | null = null;if (resourceRedoMutations.length > 0 || resourceUndoMutations.length > 0) {- batchingDisposable = undoRedoService.__tempBatchingUndoRedo(unitId);+ batchingDisposable = undoRedoService.beginUndoRedoGroup(unitId, historyId, 'append');undoRedoService.pushUndoRedo({unitID: unitId,redoMutations: resourceRedoMutations,diff --git a/packages/docs-ui/src/controllers/components.controller.ts b/packages/docs-ui/src/controllers/components.controller.tsindex 103634bf76..affbcbe378 100644--- a/packages/docs-ui/src/controllers/components.controller.ts+++ b/packages/docs-ui/src/controllers/components.controller.ts@@ -26,6 +26,7 @@ import {DeleteIcon,DeleteRowDoubleIcon,DeleteTableDoubleIcon,+ DocPasteOptionsIcon,DocSettingIcon,FontColorDoubleIcon,GridIcon,@@ -73,6 +74,7 @@ import {} from '@univerjs/icons';import { ComponentManager, IconManager } from '@univerjs/ui';import { DOC_LAYOUT_RECOVERY_COMPONENT, DocLayoutRecovery } from '../views/DocLayoutRecovery';+import { DOC_PASTE_OPTIONS_COMPONENT, DocPasteOptions } from '../views/DocPasteOptions';import { FLOAT_MENU_COMPONENT_KEY, FloatToolbar } from '../views/float-toolbar/FloatToolbar';import { COMPONENT_DOC_HEADER_FOOTER_PANEL } from '../views/header-footer/panel/component-name';import { DocHeaderFooterPanel } from '../views/header-footer/panel/DocHeaderFooterPanel';@@ -136,6 +138,7 @@ export class ComponentsController extends Disposable {private _registerParts(): void {const componentManager = this._componentManager;+ this.disposeWithMe(componentManager.register(DOC_PASTE_OPTIONS_COMPONENT, DocPasteOptions));this.disposeWithMe(componentManager.register(COMPONENT_DOC_CREATE_TABLE_CONFIRM, DocCreateTableConfirm));}@@ -177,6 +180,7 @@ export class ComponentsController extends Disposable {PaintBucketDoubleIcon,ParagraphSettingIcon,PasteSpecialDoubleIcon,+ DocPasteOptionsIcon,ReduceDoubleIcon,ReduceIcon,RightInsertColumnDoubleIcon,diff --git a/packages/docs-ui/src/controllers/mobile/components.controller.ts b/packages/docs-ui/src/controllers/mobile/components.controller.tsindex ad2da0c64f..a92ab695b8 100644--- a/packages/docs-ui/src/controllers/mobile/components.controller.ts+++ b/packages/docs-ui/src/controllers/mobile/components.controller.ts@@ -15,15 +15,107 @@*/import { Disposable, Inject } from '@univerjs/core';-import { AddImageIcon, AlignTextBothIcon, BoldIcon, ColumnIcon, CopyDoubleIcon, CutIcon, DeleteColumnDoubleIcon, DeleteIcon, DeleteRowDoubleIcon, DeleteTableDoubleIcon, DocSettingIcon, FontColorDoubleIcon, GridIcon, H1Icon, H2Icon, H3Icon, H4Icon, H5Icon, HeaderFooterIcon, HorizontallyIcon, InsertDoubleIcon, InsertRowAboveDoubleIcon, InsertRowBelowDoubleIcon, ItalicIcon, KeyboardIcon, LeftInsertColumnDoubleIcon, LeftJustifyingIcon, LineIndentDecreaseIcon, LineIndentIncreaseIcon, MenuIcon, MoreLeftIcon, MoreRightIcon, NoColorDoubleIcon, OrderIcon, PaintBucketDoubleIcon, ParagraphSettingIcon, PasteSpecialDoubleIcon, ReduceDoubleIcon, ReduceIcon, RightInsertColumnDoubleIcon, RightJustifyingIcon, SectionSettingIcon, ShapeIcon, SmileIcon, StrikethroughIcon, SubscriptIcon, SubtitleTypeIcon, SuperscriptIcon, SymbolsIcon, TextTypeIcon, TitleTypeIcon, TodoListDoubleIcon, UnderlineIcon, UnorderIcon } from '@univerjs/icons';+import {+ AddImageIcon,+ AlignTextBothIcon,+ BoldIcon,+ ColumnIcon,+ CopyDoubleIcon,+ CutIcon,+ DeleteColumnDoubleIcon,+ DeleteIcon,+ DeleteRowDoubleIcon,+ DeleteTableDoubleIcon,+ DocPasteOptionsIcon,+ DocSettingIcon,+ FontColorDoubleIcon,+ GridIcon,+ H1Icon,+ H2Icon,+ H3Icon,+ H4Icon,+ H5Icon,+ HeaderFooterIcon,+ HorizontallyIcon,+ InsertDoubleIcon,+ InsertRowAboveDoubleIcon,+ InsertRowBelowDoubleIcon,+ ItalicIcon,+ KeyboardIcon,+ LeftInsertColumnDoubleIcon,+ LeftJustifyingIcon,+ LineIndentDecreaseIcon,+ LineIndentIncreaseIcon,+ MenuIcon,+ MoreLeftIcon,+ MoreRightIcon,+ NoColorDoubleIcon,+ OrderIcon,+ PaintBucketDoubleIcon,+ ParagraphSettingIcon,+ PasteSpecialDoubleIcon,+ ReduceDoubleIcon,+ ReduceIcon,+ RightInsertColumnDoubleIcon,+ RightJustifyingIcon,+ SectionSettingIcon,+ ShapeIcon,+ SmileIcon,+ StrikethroughIcon,+ SubscriptIcon,+ SubtitleTypeIcon,+ SuperscriptIcon,+ SymbolsIcon,+ TextTypeIcon,+ TitleTypeIcon,+ TodoListDoubleIcon,+ UnderlineIcon,+ UnorderIcon,+} from '@univerjs/icons';import { ComponentManager, IconManager } from '@univerjs/ui';import { DOC_LAYOUT_RECOVERY_COMPONENT, DocLayoutRecovery } from '../../views/DocLayoutRecovery';+import { DOC_PASTE_OPTIONS_COMPONENT } from '../../views/DocPasteOptions';import { COMPONENT_DOC_HEADER_FOOTER_PANEL } from '../../views/header-footer/panel/component-name';-import { DefaultTextColorIcon, DocParagraphBackgroundColorSwatchIcon0, DocParagraphBackgroundColorSwatchIcon1, DocParagraphBackgroundColorSwatchIcon10, DocParagraphBackgroundColorSwatchIcon11, DocParagraphBackgroundColorSwatchIcon12, DocParagraphBackgroundColorSwatchIcon13, DocParagraphBackgroundColorSwatchIcon14, DocParagraphBackgroundColorSwatchIcon15, DocParagraphBackgroundColorSwatchIcon2, DocParagraphBackgroundColorSwatchIcon3, DocParagraphBackgroundColorSwatchIcon4, DocParagraphBackgroundColorSwatchIcon5, DocParagraphBackgroundColorSwatchIcon6, DocParagraphBackgroundColorSwatchIcon7, DocParagraphBackgroundColorSwatchIcon8, DocParagraphBackgroundColorSwatchIcon9, DocParagraphTextColorSwatchIcon0, DocParagraphTextColorSwatchIcon1, DocParagraphTextColorSwatchIcon2, DocParagraphTextColorSwatchIcon3, DocParagraphTextColorSwatchIcon4, DocParagraphTextColorSwatchIcon5, DocParagraphTextColorSwatchIcon6, HeaderTextColorIcon } from '../../views/Icon';+import {+ DefaultTextColorIcon,+ DocParagraphBackgroundColorSwatchIcon0,+ DocParagraphBackgroundColorSwatchIcon1,+ DocParagraphBackgroundColorSwatchIcon10,+ DocParagraphBackgroundColorSwatchIcon11,+ DocParagraphBackgroundColorSwatchIcon12,+ DocParagraphBackgroundColorSwatchIcon13,+ DocParagraphBackgroundColorSwatchIcon14,+ DocParagraphBackgroundColorSwatchIcon15,+ DocParagraphBackgroundColorSwatchIcon2,+ DocParagraphBackgroundColorSwatchIcon3,+ DocParagraphBackgroundColorSwatchIcon4,+ DocParagraphBackgroundColorSwatchIcon5,+ DocParagraphBackgroundColorSwatchIcon6,+ DocParagraphBackgroundColorSwatchIcon7,+ DocParagraphBackgroundColorSwatchIcon8,+ DocParagraphBackgroundColorSwatchIcon9,+ DocParagraphTextColorSwatchIcon0,+ DocParagraphTextColorSwatchIcon1,+ DocParagraphTextColorSwatchIcon2,+ DocParagraphTextColorSwatchIcon3,+ DocParagraphTextColorSwatchIcon4,+ DocParagraphTextColorSwatchIcon5,+ DocParagraphTextColorSwatchIcon6,+ HeaderTextColorIcon,+} from '../../views/Icon';import { BULLET_LIST_TYPE_COMPONENT, ORDER_LIST_TYPE_COMPONENT } from '../../views/list-type-picker/index';import { BulletListTypePicker, OrderListTypePicker } from '../../views/list-type-picker/Picker';-import { MOBILE_DOC_ELEMENT_MENU, MobileDocElementMenuPopup } from '../../views/mobile-element-menu/MobileDocElementMenu';-import { MobileHeaderFooterPanel, MobilePageSettings, MobileParagraphSettings, MobileSectionSettings } from '../../views/mobile/MobileDocSettings';+import {+ MOBILE_DOC_ELEMENT_MENU,+ MobileDocElementMenuPopup,+} from '../../views/mobile-element-menu/MobileDocElementMenu';+import { MobileDocPasteOptions } from '../../views/mobile/MobileDocPasteOptions';+import {+ MobileHeaderFooterPanel,+ MobilePageSettings,+ MobileParagraphSettings,+ MobileSectionSettings,+} from '../../views/mobile/MobileDocSettings';import { PAGE_SETTING_COMPONENT_ID } from '../../views/PageSettings';import { DOC_SECTION_SETTING_COMPONENT } from '../../views/section-setting/component-name';import { COMPONENT_DOC_CREATE_TABLE_CONFIRM } from '../../views/table/create/component-name';@@ -44,10 +136,12 @@ export class MobileComponentsController extends Disposable {private _registerParts(): void {const componentManager = this._componentManager;this.disposeWithMe(componentManager.register(COMPONENT_DOC_CREATE_TABLE_CONFIRM, DocCreateTableConfirm));+ this.disposeWithMe(componentManager.register(DOC_PASTE_OPTIONS_COMPONENT, MobileDocPasteOptions));}private _registerIcons(): void {this.disposeWithMe(this._iconManager.register({+ DocPasteOptionsIcon,AlignTextBothIcon,AddImageIcon,BoldIcon,diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-paste-options.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-paste-options.render-controller.tsnew file mode 100644index 0000000000..c7f9a81d99--- /dev/null+++ b/packages/docs-ui/src/controllers/render-controllers/doc-paste-options.render-controller.ts@@ -0,0 +1,82 @@+/**+ * 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 { DocumentDataModel, IDisposable } from '@univerjs/core';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';+import { Disposable, IContextService, Inject, isInternalEditorID } from '@univerjs/core';+import { MOBILE_UI_MODE } from '@univerjs/ui';+import { IDocClipboardService } from '../../services/clipboard/clipboard.service';+import { DocCanvasPopManagerService } from '../../services/doc-popup-manager.service';+import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';+import { DOC_PASTE_OPTIONS_COMPONENT } from '../../views/DocPasteOptions';++export class DocPasteOptionsRenderController extends Disposable implements IRenderModule {+ private _popup: IDisposable | undefined;++ constructor(+ private readonly _context: IRenderContext<DocumentDataModel>,+ @IDocClipboardService private readonly _clipboard: IDocClipboardService,+ @Inject(DocSelectionRenderService) selection: DocSelectionRenderService,+ @Inject(DocCanvasPopManagerService) popupManager: DocCanvasPopManagerService,+ @IContextService contextService: IContextService+ ) {+ super();+ if (isInternalEditorID(_context.unitId)) {+ return;+ }+ const mobile = contextService.getContextValue(MOBILE_UI_MODE) === true;+ this.disposeWithMe(selection.onKeydown$.subscribe(({ event }) => {+ const key = event as KeyboardEvent;+ if ((key.ctrlKey || key.metaKey) && key.shiftKey && key.key.toLowerCase() === 'v') {+ this._clipboard.setNextPasteMode('text');+ } else if (!['Control', 'Meta', 'Shift', 'Alt'].includes(key.key)) {+ this._clipboard.setNextPasteMode('source');+ this._clipboard.dismissPasteOptions();+ }+ }));+ this.disposeWithMe(selection.onInputBefore$.subscribe(() => this._clipboard.dismissPasteOptions()));+ this.disposeWithMe(selection.onPointerDown$.subscribe(() => {+ this._clipboard.setNextPasteMode('source');+ // A mobile pointer-down may start a pan. Actual selection changes+ // already invalidate the session in the clipboard service.+ if (!mobile) {+ this._clipboard.dismissPasteOptions();+ }+ }));+ this.disposeWithMe(selection.onBlur$.subscribe(() => this._clipboard.setNextPasteMode('source')));+ this.disposeWithMe(this._clipboard.pasteOptions$.subscribe((state) => {+ this._popup?.dispose();+ this._popup = undefined;+ if (state?.unitId !== this._context.unitId) {+ return;+ }+ this._popup = popupManager.attachPopupToRange(state.range, {+ componentKey: DOC_PASTE_OPTIONS_COMPONENT,+ direction: 'bottom-left',+ rangeAnchor: 'selection-end',+ requiresStableLayout: false,+ hideOnInvisible: !mobile,+ extraProps: { unitId: state.unitId },+ offset: [0, 6],+ onClickOutside: mobile ? undefined : () => this._clipboard.dismissPasteOptions(),+ }, state.unitId);+ }));+ this.disposeWithMe(() => {+ this._popup?.dispose();+ this._clipboard.dismissPasteOptions();+ });+ }+}diff --git a/packages/docs-ui/src/locale/ar-SA.ts b/packages/docs-ui/src/locale/ar-SA.tsindex 72e4694c8f..418f2c6533 100644--- a/packages/docs-ui/src/locale/ar-SA.ts+++ b/packages/docs-ui/src/locale/ar-SA.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: 'خيارات اللصق',+ source: 'الاحتفاظ بتنسيق المصدر',+ destination: 'مطابقة تنسيق الوجهة',+ text: 'الاحتفاظ بالنص فقط',+ useKeyboard: 'تعذر الوصول إلى الحافظة. استخدم {0} للصق، ثم غيّر التنسيق من خيارات اللصق.',+ useSystemPaste: 'تعذر الوصول إلى الحافظة. استخدم وظيفة اللصق في جهازك أو لوحة المفاتيح، ثم غيّر التنسيق من خيارات اللصق.',+ failed: 'تعذر تغيير تنسيق اللصق.',+ },outline: {title: 'مخطط المستند',},diff --git a/packages/docs-ui/src/locale/ca-ES.ts b/packages/docs-ui/src/locale/ca-ES.tsindex cacc75aa1a..e47a342401 100644--- a/packages/docs-ui/src/locale/ca-ES.ts+++ b/packages/docs-ui/src/locale/ca-ES.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: 'Opcions d’enganxament',+ source: 'Mantén el format d’origen',+ destination: 'Adapta al format de destinació',+ text: 'Mantén només el text',+ useKeyboard: 'No es pot accedir al porta-retalls. Fes servir {0} per enganxar i canvia el format amb les opcions d’enganxament.',+ useSystemPaste: 'No es pot accedir al porta-retalls. Utilitza la funció d’enganxar del dispositiu o teclat i canvia el format amb les opcions d’enganxament.',+ failed: 'No s’ha pogut canviar el format d’enganxament.',+ },outline: {title: 'Esquema del document',},diff --git a/packages/docs-ui/src/locale/de-DE.ts b/packages/docs-ui/src/locale/de-DE.tsindex 4ff4204049..d5af6ea341 100644--- a/packages/docs-ui/src/locale/de-DE.ts+++ b/packages/docs-ui/src/locale/de-DE.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: 'Einfügeoptionen',+ source: 'Ursprüngliche Formatierung beibehalten',+ destination: 'Zielformatierung übernehmen',+ text: 'Nur Text übernehmen',+ useKeyboard: 'Kein Zugriff auf die Zwischenablage. Verwenden Sie {0} zum Einfügen und ändern Sie das Format über die Einfügeoptionen.',+ useSystemPaste: 'Kein Zugriff auf die Zwischenablage. Verwenden Sie die Einfügefunktion Ihres Geräts oder Ihrer Tastatur und ändern Sie das Format über die Einfügeoptionen.',+ failed: 'Das Einfügeformat konnte nicht geändert werden.',+ },outline: {title: 'Dokumentgliederung',},diff --git a/packages/docs-ui/src/locale/en-US.ts b/packages/docs-ui/src/locale/en-US.tsindex befc44215c..cd327b565f 100644--- a/packages/docs-ui/src/locale/en-US.ts+++ b/packages/docs-ui/src/locale/en-US.ts@@ -16,6 +16,15 @@const locale = {'docs-ui': {+ pasteOptions: {+ title: 'Paste options',+ source: 'Keep source formatting',+ destination: 'Match destination formatting',+ text: 'Keep text only',+ useKeyboard: 'Clipboard access is unavailable. Press {0} to paste, then change the format with Paste options.',+ useSystemPaste: 'Clipboard access is unavailable. Use your device or keyboard’s paste action, then change the format with Paste options.',+ failed: 'Could not change the paste format.',+ },outline: {title: 'Outline',},diff --git a/packages/docs-ui/src/locale/es-ES.ts b/packages/docs-ui/src/locale/es-ES.tsindex df7dd4f9ce..918994ab8a 100644--- a/packages/docs-ui/src/locale/es-ES.ts+++ b/packages/docs-ui/src/locale/es-ES.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: 'Opciones de pegado',+ source: 'Mantener formato de origen',+ destination: 'Adaptar al formato de destino',+ text: 'Conservar solo texto',+ useKeyboard: 'No se puede acceder al portapapeles. Usa {0} para pegar y cambia el formato con las opciones de pegado.',+ useSystemPaste: 'No se puede acceder al portapapeles. Usa la función de pegar del dispositivo o teclado y cambia el formato con las opciones de pegado.',+ failed: 'No se pudo cambiar el formato de pegado.',+ },outline: {title: 'Esquema del documento',},diff --git a/packages/docs-ui/src/locale/fa-IR.ts b/packages/docs-ui/src/locale/fa-IR.tsindex 852cfeece3..8118ff449e 100644--- a/packages/docs-ui/src/locale/fa-IR.ts+++ b/packages/docs-ui/src/locale/fa-IR.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: 'گزینههای چسباندن',+ source: 'حفظ قالببندی مبدأ',+ destination: 'تطبیق با قالببندی مقصد',+ text: 'فقط متن',+ useKeyboard: 'دسترسی به کلیپبورد امکانپذیر نیست. از {0} برای چسباندن استفاده کنید، سپس قالب را از گزینههای چسباندن تغییر دهید.',+ useSystemPaste: 'دسترسی به کلیپبورد امکانپذیر نیست. از قابلیت چسباندن دستگاه یا صفحهکلید استفاده کنید، سپس قالب را از گزینههای چسباندن تغییر دهید.',+ failed: 'تغییر قالب چسباندن ممکن نشد.',+ },outline: {title: 'طرح کلی سند',},diff --git a/packages/docs-ui/src/locale/fr-FR.ts b/packages/docs-ui/src/locale/fr-FR.tsindex ecf922bab8..966ff85a8b 100644--- a/packages/docs-ui/src/locale/fr-FR.ts+++ b/packages/docs-ui/src/locale/fr-FR.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: 'Options de collage',+ source: 'Conserver la mise en forme source',+ destination: 'Adapter à la mise en forme de destination',+ text: 'Conserver uniquement le texte',+ useKeyboard: 'Le presse-papiers est inaccessible. Utilisez {0} pour coller, puis les options de collage pour changer le format.',+ useSystemPaste: 'Le presse-papiers est inaccessible. Utilisez la fonction de collage de votre appareil ou clavier, puis les options de collage pour changer le format.',+ failed: 'Impossible de modifier le format de collage.',+ },outline: {title: 'Plan du document',},diff --git a/packages/docs-ui/src/locale/id-ID.ts b/packages/docs-ui/src/locale/id-ID.tsindex 42e3092388..93a741e166 100644--- a/packages/docs-ui/src/locale/id-ID.ts+++ b/packages/docs-ui/src/locale/id-ID.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: 'Opsi tempel',+ source: 'Pertahankan format sumber',+ destination: 'Sesuaikan format tujuan',+ text: 'Simpan teks saja',+ useKeyboard: 'Papan klip tidak dapat diakses. Gunakan {0} untuk menempel, lalu ubah format melalui Opsi tempel.',+ useSystemPaste: 'Papan klip tidak dapat diakses. Gunakan fungsi tempel perangkat atau papan ketik, lalu ubah format melalui Opsi tempel.',+ failed: 'Format tempel tidak dapat diubah.',+ },outline: {title: 'Kerangka dokumen',},diff --git a/packages/docs-ui/src/locale/it-IT.ts b/packages/docs-ui/src/locale/it-IT.tsindex 279d66bb7a..0b6dce5e67 100644--- a/packages/docs-ui/src/locale/it-IT.ts+++ b/packages/docs-ui/src/locale/it-IT.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: 'Opzioni di incolla',+ source: 'Mantieni formattazione originale',+ destination: 'Adatta alla formattazione di destinazione',+ text: 'Mantieni solo testo',+ useKeyboard: 'Impossibile accedere agli appunti. Usa {0} per incollare, poi cambia il formato con le opzioni di incolla.',+ useSystemPaste: 'Impossibile accedere agli appunti. Usa la funzione Incolla del dispositivo o della tastiera, poi cambia il formato con le opzioni di incolla.',+ failed: 'Impossibile modificare il formato di incolla.',+ },outline: {title: 'Struttura del documento',},diff --git a/packages/docs-ui/src/locale/ja-JP.ts b/packages/docs-ui/src/locale/ja-JP.tsindex 7629faa22d..ba6b97105d 100644--- a/packages/docs-ui/src/locale/ja-JP.ts+++ b/packages/docs-ui/src/locale/ja-JP.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: '貼り付けのオプション',+ source: '元の書式を保持',+ destination: '貼り付け先の書式に合わせる',+ text: 'テキストのみ保持',+ useKeyboard: 'クリップボードにアクセスできません。{0} で貼り付けてから、貼り付けのオプションで書式を変更してください。',+ useSystemPaste: 'クリップボードにアクセスできません。端末またはキーボードの貼り付け操作を使用し、貼り付けのオプションで書式を変更してください。',+ failed: '貼り付けの書式を変更できませんでした。',+ },outline: {title: 'ドキュメントのアウトライン',},diff --git a/packages/docs-ui/src/locale/ko-KR.ts b/packages/docs-ui/src/locale/ko-KR.tsindex 5a68a17715..8e80d89a2c 100644--- a/packages/docs-ui/src/locale/ko-KR.ts+++ b/packages/docs-ui/src/locale/ko-KR.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: '붙여넣기 옵션',+ source: '원본 서식 유지',+ destination: '대상 서식에 맞추기',+ text: '텍스트만 유지',+ useKeyboard: '클립보드에 접근할 수 없습니다. {0}로 붙여넣은 후 붙여넣기 옵션에서 서식을 변경하세요.',+ useSystemPaste: '클립보드에 접근할 수 없습니다. 기기 또는 키보드의 붙여넣기를 사용한 후 붙여넣기 옵션에서 서식을 변경하세요.',+ failed: '붙여넣기 서식을 변경할 수 없습니다.',+ },outline: {title: '문서 개요',},diff --git a/packages/docs-ui/src/locale/pl-PL.ts b/packages/docs-ui/src/locale/pl-PL.tsindex c4342b328b..0badd9e2cf 100644--- a/packages/docs-ui/src/locale/pl-PL.ts+++ b/packages/docs-ui/src/locale/pl-PL.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: 'Opcje wklejania',+ source: 'Zachowaj formatowanie źródłowe',+ destination: 'Dopasuj formatowanie docelowe',+ text: 'Zachowaj tylko tekst',+ useKeyboard: 'Brak dostępu do schowka. Użyj {0}, aby wkleić, a następnie zmień format w opcjach wklejania.',+ useSystemPaste: 'Brak dostępu do schowka. Użyj funkcji wklejania urządzenia lub klawiatury, a następnie zmień format w opcjach wklejania.',+ failed: 'Nie udało się zmienić formatu wklejania.',+ },outline: {title: 'Konspekt dokumentu',},diff --git a/packages/docs-ui/src/locale/pt-BR.ts b/packages/docs-ui/src/locale/pt-BR.tsindex 66716e4cc2..856d5f3145 100644--- a/packages/docs-ui/src/locale/pt-BR.ts+++ b/packages/docs-ui/src/locale/pt-BR.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: 'Opções de colagem',+ source: 'Manter formatação original',+ destination: 'Usar formatação de destino',+ text: 'Manter somente texto',+ useKeyboard: 'Não é possível acessar a área de transferência. Use {0} para colar e altere o formato nas opções de colagem.',+ useSystemPaste: 'Não é possível acessar a área de transferência. Use a função de colar do dispositivo ou teclado e altere o formato nas opções de colagem.',+ failed: 'Não foi possível alterar o formato da colagem.',+ },outline: {title: 'Estrutura do documento',},diff --git a/packages/docs-ui/src/locale/ru-RU.ts b/packages/docs-ui/src/locale/ru-RU.tsindex 78a17bd088..537558a7d5 100644--- a/packages/docs-ui/src/locale/ru-RU.ts+++ b/packages/docs-ui/src/locale/ru-RU.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: 'Параметры вставки',+ source: 'Сохранить исходное форматирование',+ destination: 'Использовать форматирование назначения',+ text: 'Сохранить только текст',+ useKeyboard: 'Нет доступа к буферу обмена. Используйте {0} для вставки, затем измените формат через параметры вставки.',+ useSystemPaste: 'Нет доступа к буферу обмена. Используйте функцию вставки устройства или клавиатуры, затем измените формат через параметры вставки.',+ failed: 'Не удалось изменить формат вставки.',+ },outline: {title: 'Структура документа',},diff --git a/packages/docs-ui/src/locale/sk-SK.ts b/packages/docs-ui/src/locale/sk-SK.tsindex ba134c202a..1145a2eb39 100644--- a/packages/docs-ui/src/locale/sk-SK.ts+++ b/packages/docs-ui/src/locale/sk-SK.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: 'Možnosti prilepenia',+ source: 'Zachovať zdrojové formátovanie',+ destination: 'Prispôsobiť cieľovému formátovaniu',+ text: 'Zachovať iba text',+ useKeyboard: 'Schránka nie je dostupná. Použite {0} na prilepenie a potom zmeňte formát v možnostiach prilepenia.',+ useSystemPaste: 'Schránka nie je dostupná. Použite funkciu prilepenia zariadenia alebo klávesnice a potom zmeňte formát v možnostiach prilepenia.',+ failed: 'Formát prilepenia sa nepodarilo zmeniť.',+ },outline: {title: 'Osnova dokumentu',},diff --git a/packages/docs-ui/src/locale/vi-VN.ts b/packages/docs-ui/src/locale/vi-VN.tsindex cbe32d0142..84fd2c35cd 100644--- a/packages/docs-ui/src/locale/vi-VN.ts+++ b/packages/docs-ui/src/locale/vi-VN.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: 'Tùy chọn dán',+ source: 'Giữ định dạng nguồn',+ destination: 'Khớp định dạng đích',+ text: 'Chỉ giữ văn bản',+ useKeyboard: 'Không thể truy cập bảng nhớ tạm. Dùng {0} để dán, rồi đổi định dạng trong Tùy chọn dán.',+ useSystemPaste: 'Không thể truy cập bảng nhớ tạm. Hãy dùng chức năng dán của thiết bị hoặc bàn phím, rồi đổi định dạng trong Tùy chọn dán.',+ failed: 'Không thể thay đổi định dạng dán.',+ },outline: {title: 'Dàn ý tài liệu',},diff --git a/packages/docs-ui/src/locale/zh-CN.ts b/packages/docs-ui/src/locale/zh-CN.tsindex 0db8c055db..f7a7b882fe 100644--- a/packages/docs-ui/src/locale/zh-CN.ts+++ b/packages/docs-ui/src/locale/zh-CN.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: '粘贴选项',+ source: '保留源格式',+ destination: '匹配目标格式',+ text: '仅保留文本',+ useKeyboard: '无法读取剪贴板。请按 {0} 粘贴,再通过“粘贴选项”切换格式。',+ useSystemPaste: '无法访问剪贴板。请使用设备或键盘提供的粘贴操作,再通过“粘贴选项”切换格式。',+ failed: '无法切换粘贴格式。',+ },outline: {title: '文档大纲',},diff --git a/packages/docs-ui/src/locale/zh-HK.ts b/packages/docs-ui/src/locale/zh-HK.tsindex d9543e7b11..b95b439825 100644--- a/packages/docs-ui/src/locale/zh-HK.ts+++ b/packages/docs-ui/src/locale/zh-HK.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: '貼上選項',+ source: '保留來源格式',+ destination: '符合目標格式',+ text: '只保留文字',+ useKeyboard: '無法讀取剪貼簿。請按 {0} 貼上,再透過「貼上選項」切換格式。',+ useSystemPaste: '無法存取剪貼簿。請使用裝置或鍵盤提供的貼上操作,再透過「貼上選項」切換格式。',+ failed: '無法切換貼上格式。',+ },outline: {title: '文件大綱',},diff --git a/packages/docs-ui/src/locale/zh-TW.ts b/packages/docs-ui/src/locale/zh-TW.tsindex f854fc1dd5..ae9474a569 100644--- a/packages/docs-ui/src/locale/zh-TW.ts+++ b/packages/docs-ui/src/locale/zh-TW.ts@@ -18,6 +18,15 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ pasteOptions: {+ title: '貼上選項',+ source: '保留來源格式',+ destination: '符合目的地格式',+ text: '只保留文字',+ useKeyboard: '無法讀取剪貼簿。請按 {0} 貼上,再透過「貼上選項」切換格式。',+ useSystemPaste: '無法存取剪貼簿。請使用裝置或鍵盤提供的貼上操作,再透過「貼上選項」切換格式。',+ failed: '無法切換貼上格式。',+ },outline: {title: '文件大綱',},diff --git a/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts b/packages/docs-ui/src/menu/__tests__/context-menu.spec.tsindex beb447dc6e..c3cc618f84 100644--- a/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts+++ b/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts@@ -20,20 +20,28 @@ import { UnitAction } from '@univerjs/protocol';import { ContextMenuGroup } from '@univerjs/ui';import { firstValueFrom, of } from 'rxjs';import { describe, expect, it } from 'vitest';-import { DocPasteCommand } from '../../commands/commands/clipboard.command';+import { DocPasteCommand, DocPasteSpecialCommand } from '../../commands/commands/clipboard.command';import { DocSelectAllCommand, DocSelectWordCommand } from '../../commands/commands/doc-select-all.command';import { DOC_CARET_MENU_ID } from '../../consts/mobile-context';-import { CopyMenuFactory, ParagraphSettingMenuFactory, PasteMenuFactory, SelectAllMenuFactory, SelectWordMenuFactory } from '../context-menu';+import {+ CopyMenuFactory,+ ParagraphSettingMenuFactory,+ PasteMenuFactory,+ PasteSpecialMenuFactory,+ SelectAllMenuFactory,+ SelectWordMenuFactory,+} from '../context-menu';import { mobileMenuSchema } from '../mobile-schema';describe('settings context menu factories', () => {- it('registers a dedicated three-action mobile caret menu', () => {+ it('registers a mobile caret menu with both paste and format choices', () => {const caretMenu = Object.entries(mobileMenuSchema).find(([position]) => position === DOC_CARET_MENU_ID)?.[1];expect(caretMenu).toEqual({[ContextMenuGroup.QUICK]: {quickLayout: 'tile',[DocPasteCommand.id]: { order: 0, menuItemFactory: PasteMenuFactory },+ [DocPasteSpecialCommand.id]: { order: 0.5, menuItemFactory: PasteSpecialMenuFactory },[DocSelectWordCommand.id]: { order: 1, menuItemFactory: SelectWordMenuFactory },[DocSelectAllCommand.id]: { order: 2, menuItemFactory: SelectAllMenuFactory },},diff --git a/packages/docs-ui/src/menu/context-menu.ts b/packages/docs-ui/src/menu/context-menu.tsindex 8ded3d24b6..3639b96e7c 100644--- a/packages/docs-ui/src/menu/context-menu.ts+++ b/packages/docs-ui/src/menu/context-menu.ts@@ -24,7 +24,12 @@ import { DocSelectionManagerService } from '@univerjs/docs';import { UnitAction } from '@univerjs/protocol';import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';import { combineLatest, map, Observable } from 'rxjs';-import { DocCopyCommand, DocCutCommand, DocPasteCommand } from '../commands/commands/clipboard.command';+import {+ DocCopyCommand,+ DocCutCommand,+ DocPasteCommand,+ DocPasteSpecialCommand,+} from '../commands/commands/clipboard.command';import { DeleteLeftCommand } from '../commands/commands/doc-delete.command';import { DocSelectAllCommand, DocSelectWordCommand } from '../commands/commands/doc-select-all.command';import {@@ -40,6 +45,7 @@ import {} from '../commands/commands/table/doc-table-insert.command';import { DocParagraphSettingPanelOperation } from '../commands/operations/doc-paragraph-setting-panel.operation';import { DocSectionSettingPanelOperation } from '../commands/operations/doc-section-setting-panel.operation';+import { DOC_PASTE_OPTIONS } from '../services/clipboard/paste-options';import { disableMenuWithoutDocumentUnitPermission } from './menu';const getDisableOnCollapsedObservable = (accessor: IAccessor) => {@@ -382,3 +388,16 @@ export function DeleteTableMenuItemFactory(accessor: IAccessor): IMenuButtonItemhidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),};}++export function PasteSpecialMenuFactory(accessor: IAccessor): IMenuSelectorItem<LocaleKey> {+ return {+ id: DocPasteSpecialCommand.id,+ type: MenuItemType.SELECTOR,+ icon: 'DocPasteOptionsIcon',+ title: 'docs-ui.pasteOptions.title',+ tooltip: 'docs-ui.pasteOptions.title',+ selections: DOC_PASTE_OPTIONS.map((option) => ({ ...option })),+ disabled$: disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),+ };+}diff --git a/packages/docs-ui/src/menu/mobile-schema.ts b/packages/docs-ui/src/menu/mobile-schema.tsindex 1e4c8b84e0..af7a234107 100644--- a/packages/docs-ui/src/menu/mobile-schema.ts+++ b/packages/docs-ui/src/menu/mobile-schema.ts@@ -16,10 +16,10 @@import type { MenuSchemaType } from '@univerjs/ui';import { ContextMenuGroup, ContextMenuPosition } from '@univerjs/ui';-import { DocPasteCommand } from '../commands/commands/clipboard.command';+import { DocPasteCommand, DocPasteSpecialCommand } from '../commands/commands/clipboard.command';import { DocSelectAllCommand, DocSelectWordCommand } from '../commands/commands/doc-select-all.command';import { DOC_CARET_MENU_ID } from '../consts/mobile-context';-import { PasteMenuFactory, SelectAllMenuFactory, SelectWordMenuFactory } from './context-menu';+import { PasteMenuFactory, PasteSpecialMenuFactory, SelectAllMenuFactory, SelectWordMenuFactory } from './context-menu';export const mobileMenuSchema: MenuSchemaType = {[ContextMenuPosition.MAIN_AREA]: {@@ -35,6 +35,10 @@ export const mobileMenuSchema: MenuSchemaType = {order: 0,menuItemFactory: PasteMenuFactory,},+ [DocPasteSpecialCommand.id]: {+ order: 0.5,+ menuItemFactory: PasteSpecialMenuFactory,+ },[DocSelectWordCommand.id]: {order: 1,menuItemFactory: SelectWordMenuFactory,diff --git a/packages/docs-ui/src/menu/schema.ts b/packages/docs-ui/src/menu/schema.tsindex c387657494..ea3ad108f7 100644--- a/packages/docs-ui/src/menu/schema.ts+++ b/packages/docs-ui/src/menu/schema.ts@@ -22,6 +22,7 @@ import {DocCutCommand,DocCutCurrentParagraphCommand,DocPasteCommand,+ DocPasteSpecialCommand,} from '../commands/commands/clipboard.command';import { DeleteCurrentParagraphCommand, DeleteLeftCommand } from '../commands/commands/doc-delete.command';import { OpenHeaderFooterPanelCommand } from '../commands/commands/doc-header-footer.command';@@ -94,6 +95,7 @@ import {InsertRowBeforeMenuItemFactory,ParagraphSettingMenuFactory,PasteMenuFactory,+ PasteSpecialMenuFactory,SectionSettingMenuFactory,TABLE_DELETE_MENU_ID,TABLE_INSERT_MENU_ID,@@ -225,6 +227,11 @@ export const floatToolbarMenuSchema: MenuSchemaType = {export const menuSchema: MenuSchemaType = {...floatToolbarMenuSchema,[RibbonStartGroup.OTHERS]: {+ [DocPasteSpecialCommand.id]: {+ order: -1,+ gridLayout: { row: 1, column: 2, rowSpan: 2, showLabel: true },+ menuItemFactory: PasteSpecialMenuFactory,+ },[OpenDocPermissionPanelOperation.id]: {order: 0,gridLayout: { row: 1, column: 1, rowSpan: 2, showLabel: true },@@ -408,6 +415,10 @@ export const menuSchema: MenuSchemaType = {order: 2,menuItemFactory: PasteMenuFactory,},+ [DocPasteSpecialCommand.id]: {+ order: 3,+ menuItemFactory: PasteSpecialMenuFactory,+ },} as MenuSchemaType),[ContextMenuGroup.FORMAT]: {[DeleteLeftCommand.id]: {diff --git a/packages/docs-ui/src/mobile-plugin.ts b/packages/docs-ui/src/mobile-plugin.tsindex 58ccb7bafb..c1e1203cc6 100644--- a/packages/docs-ui/src/mobile-plugin.ts+++ b/packages/docs-ui/src/mobile-plugin.ts@@ -41,11 +41,13 @@ import pkg from '../package.json';import { AfterSpaceCommand, EnterCommand, TabCommand } from './commands/commands/auto-format.command';import { BreakLineCommand } from './commands/commands/break-line.command';import {+ DocChangePasteModeCommand,DocCopyCommand,DocCopyCurrentParagraphCommand,DocCutCommand,DocCutCurrentParagraphCommand,DocPasteCommand,+ DocPasteSpecialCommand,} from './commands/commands/clipboard.command';import { CutContentCommand, InnerPasteCommand } from './commands/commands/clipboard.inner.command';import { MoveDocBlockCommand } from './commands/commands/doc-block-move.command';@@ -142,7 +144,10 @@ import { DocTableTabCommand } from './commands/commands/table/doc-table-tab.commimport { MoveCursorOperation, MoveSelectionOperation } from './commands/operations/doc-cursor.operation';import { DocParagraphSettingPanelOperation } from './commands/operations/doc-paragraph-setting-panel.operation';import { DocSectionSettingPanelOperation } from './commands/operations/doc-section-setting-panel.operation';-import { InsertDocumentColumnBreakOperation, InsertDocumentSectionBreakOperation } from './commands/operations/insert-break.operation';+import {+ InsertDocumentColumnBreakOperation,+ InsertDocumentSectionBreakOperation,+} from './commands/operations/insert-break.operation';import { DocOpenPageSettingCommand } from './commands/operations/open-page-setting.operation';import { SetDocZoomRatioOperation } from './commands/operations/set-doc-zoom-ratio.operation';import { defaultPluginMobileConfig, DOCS_UI_PLUGIN_CONFIG_KEY, DOCS_UI_PLUGIN_NAME } from './config/config';@@ -155,22 +160,33 @@ import { DocTableController } from './controllers/doc-table.controller';import { MobileComponentsController } from './controllers/mobile/components.controller';import { DocMobileUIController } from './controllers/mobile/ui.controller';import { DocBackScrollRenderController } from './controllers/render-controllers/back-scroll.render-controller';-import { DocCanvasPopupLayoutInteractionController } from './controllers/render-controllers/doc-canvas-popup-layout-interaction.controller';+import {+ DocCanvasPopupLayoutInteractionController,+} from './controllers/render-controllers/doc-canvas-popup-layout-interaction.controller';import { DocChecklistRenderController } from './controllers/render-controllers/doc-checklist.render-controller';import { DocClipboardController } from './controllers/render-controllers/doc-clipboard.controller';import { DocContextMenuRenderController } from './controllers/render-controllers/doc-contextmenu.render-controller';import { DocEditorBridgeController } from './controllers/render-controllers/doc-editor-bridge.controller';import { DocIMEInputController } from './controllers/render-controllers/doc-ime-input.controller';import { DocInputController } from './controllers/render-controllers/doc-input.controller';-import { DocLayoutProgressRenderController } from './controllers/render-controllers/doc-layout-progress.render-controller';-import { DocLayoutRecoveryRenderController } from './controllers/render-controllers/doc-layout-recovery.render-controller';+import {+ DocLayoutProgressRenderController,+} from './controllers/render-controllers/doc-layout-progress.render-controller';+import {+ DocLayoutRecoveryRenderController,+} from './controllers/render-controllers/doc-layout-recovery.render-controller';import {DocParagraphPlaceholderRenderController,} from './controllers/render-controllers/doc-paragraph-placeholder.render-controller';+import { DocPasteOptionsRenderController } from './controllers/render-controllers/doc-paste-options.render-controller';import { DocResizeRenderController } from './controllers/render-controllers/doc-resize.render-controller';import { DocRenderController } from './controllers/render-controllers/doc.render-controller';-import { MobileDocBackScrollRenderController } from './controllers/render-controllers/mobile/back-scroll.render-controller';-import { MobileDocSelectionRenderController } from './controllers/render-controllers/mobile/doc-selection-render.controller';+import {+ MobileDocBackScrollRenderController,+} from './controllers/render-controllers/mobile/back-scroll.render-controller';+import {+ MobileDocSelectionRenderController,+} from './controllers/render-controllers/mobile/doc-selection-render.controller';import { MobileDocRenderController } from './controllers/render-controllers/mobile/doc.render-controller';import { MobileDocZoomRenderController } from './controllers/render-controllers/mobile/zoom.render-controller';import { DocZoomRenderController } from './controllers/render-controllers/zoom.render-controller';@@ -333,6 +349,8 @@ export class UniverDocsMobileUIPlugin extends Plugin {InsertSpecialCharacterCommand,SetParagraphNamedStyleCommand,QuickHeadingCommand,+ DocPasteSpecialCommand,+ DocChangePasteModeCommand,DocCopyCurrentParagraphCommand,DocCutCurrentParagraphCommand,H1HeadingCommand,@@ -431,6 +449,7 @@ export class UniverDocsMobileUIPlugin extends Plugin {[DocChecklistRenderController],[DocClipboardController],[DocInputController],+ [DocPasteOptionsRenderController],[DocIMEInputController],[DocLayoutRecoveryRenderController],[DocEditorBridgeController],diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.tsindex d3e8bd4e32..338976399f 100644--- a/packages/docs-ui/src/plugin.ts+++ b/packages/docs-ui/src/plugin.ts@@ -41,11 +41,13 @@ import pkg from '../package.json';import { AfterSpaceCommand, EnterCommand, TabCommand } from './commands/commands/auto-format.command';import { BreakLineCommand } from './commands/commands/break-line.command';import {+ DocChangePasteModeCommand,DocCopyCommand,DocCopyCurrentParagraphCommand,DocCutCommand,DocCutCurrentParagraphCommand,DocPasteCommand,+ DocPasteSpecialCommand,} from './commands/commands/clipboard.command';import { CutContentCommand, InnerPasteCommand } from './commands/commands/clipboard.inner.command';import { MoveDocBlockCommand } from './commands/commands/doc-block-move.command';@@ -142,7 +144,10 @@ import { DocTableTabCommand } from './commands/commands/table/doc-table-tab.commimport { MoveCursorOperation, MoveSelectionOperation } from './commands/operations/doc-cursor.operation';import { DocParagraphSettingPanelOperation } from './commands/operations/doc-paragraph-setting-panel.operation';import { DocSectionSettingPanelOperation } from './commands/operations/doc-section-setting-panel.operation';-import { InsertDocumentColumnBreakOperation, InsertDocumentSectionBreakOperation } from './commands/operations/insert-break.operation';+import {+ InsertDocumentColumnBreakOperation,+ InsertDocumentSectionBreakOperation,+} from './commands/operations/insert-break.operation';import { DocOpenPageSettingCommand } from './commands/operations/open-page-setting.operation';import { SetDocZoomRatioOperation } from './commands/operations/set-doc-zoom-ratio.operation';import { defaultPluginConfig, DOCS_UI_PLUGIN_CONFIG_KEY, DOCS_UI_PLUGIN_NAME } from './config/config';@@ -154,18 +159,25 @@ import { DocParagraphSettingController } from './controllers/doc-paragraph-settiimport { DocSectionSettingController } from './controllers/doc-section-setting.controller';import { DocTableController } from './controllers/doc-table.controller';import { DocBackScrollRenderController } from './controllers/render-controllers/back-scroll.render-controller';-import { DocCanvasPopupLayoutInteractionController } from './controllers/render-controllers/doc-canvas-popup-layout-interaction.controller';+import {+ DocCanvasPopupLayoutInteractionController,+} from './controllers/render-controllers/doc-canvas-popup-layout-interaction.controller';import { DocChecklistRenderController } from './controllers/render-controllers/doc-checklist.render-controller';import { DocClipboardController } from './controllers/render-controllers/doc-clipboard.controller';import { DocContextMenuRenderController } from './controllers/render-controllers/doc-contextmenu.render-controller';import { DocEditorBridgeController } from './controllers/render-controllers/doc-editor-bridge.controller';import { DocIMEInputController } from './controllers/render-controllers/doc-ime-input.controller';import { DocInputController } from './controllers/render-controllers/doc-input.controller';-import { DocLayoutProgressRenderController } from './controllers/render-controllers/doc-layout-progress.render-controller';-import { DocLayoutRecoveryRenderController } from './controllers/render-controllers/doc-layout-recovery.render-controller';+import {+ DocLayoutProgressRenderController,+} from './controllers/render-controllers/doc-layout-progress.render-controller';+import {+ DocLayoutRecoveryRenderController,+} from './controllers/render-controllers/doc-layout-recovery.render-controller';import {DocParagraphPlaceholderRenderController,} from './controllers/render-controllers/doc-paragraph-placeholder.render-controller';+import { DocPasteOptionsRenderController } from './controllers/render-controllers/doc-paste-options.render-controller';import { DocResizeRenderController } from './controllers/render-controllers/doc-resize.render-controller';import { DocSelectionRenderController } from './controllers/render-controllers/doc-selection-render.controller';import { DocRenderController } from './controllers/render-controllers/doc.render-controller';@@ -374,6 +386,8 @@ export class UniverDocsUIPlugin extends Plugin {InsertSpecialCharacterCommand,SetParagraphNamedStyleCommand,QuickHeadingCommand,+ DocPasteSpecialCommand,+ DocChangePasteModeCommand,DocCopyCurrentParagraphCommand,DocCutCurrentParagraphCommand,H1HeadingCommand,@@ -510,6 +524,7 @@ export class UniverDocsUIPlugin extends Plugin {([[DocEventManagerService],[DocFloatMenuService],+ [DocPasteOptionsRenderController],[DocParagraphMenuService],[DocHeaderFooterController],[DocResizeRenderController],diff --git a/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts b/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.tsindex 88059a5cbd..f2bb3981bd 100644--- a/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts+++ b/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { DocumentDataModel, IDocumentBody, IDocumentData } from '@univerjs/core';+import type { IDocumentBody, IDocumentData } from '@univerjs/core';import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';import type { IDocClipboardPasteAdapter } from '../doc-paste-mutation-adapter.service';import {@@ -22,9 +22,11 @@ import {DataStreamTreeTokenType,DOC_RANGE_TYPE,DocumentBlockRangeType,+ DocumentDataModel,ICommandService,ImageSourceType,IPermissionService,+ IUndoRedoService,IUniverInstanceService,RedoCommand,SliceBodyType,@@ -1626,3 +1628,302 @@ describe('DocClipboardService copy text hooks', () => {testBed.univer.dispose();});});++describe('DocClipboardService paste options', () => {+ function setup() {+ const bed = createCommandTestBed({+ id: 'paste-options',+ body: {+ dataStream: 'Before selected after\r\n',+ customBlocks: [],+ customRanges: [],+ customDecorations: [],+ paragraphs: [{ startIndex: 21, paragraphId: 'target', paragraphStyle: { spaceAbove: { v: 6 } } }],+ textRuns: [{ st: 0, ed: 21, ts: { ff: 'Arial', fs: 12 } }],+ },+ documentStyle: {},+ }, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ const commands = bed.get(ICommandService);+ [InnerPasteCommand, RichTextEditingMutation, SetTextSelectionsOperation].forEach((command) => commands.registerCommand(command));+ const selection = bed.get(DocSelectionManagerService);+ selection.__TEST_ONLY_setCurrentSelection({ unitId: 'paste-options', subUnitId: '' });+ selection.__TEST_ONLY_add([{ startOffset: 7, endOffset: 15, collapsed: false, isActive: true, segmentId: '' }]);+ const clipboard = bed.get(IDocClipboardService);+ const source: Partial<IDocumentData> = {+ body: {+ dataStream: 'Rich text',+ textRuns: [{ st: 0, ed: 4, ts: { bl: BooleanNumber.TRUE, ff: 'Courier New', fs: 28 } }],+ },+ };+ const payload = { html: '<b>Rich</b> text', text: 'Rich text', internalJson: createInternalClipboardFragment(source), files: [] };+ return { ...bed, commands, selection, clipboard, payload };+ }++ it('switches formats repeatedly and keeps the whole paste as one undoable edit', async () => {+ const bed = setup();+ try {+ const before = Tools.deepClone(bed.doc.getBody());+ expect(await bed.clipboard.legacyPaste(bed.payload)).toBe(true);+ expect(bed.doc.getBody()?.dataStream).toBe('Before Rich text after\r\n');+ expect(await bed.clipboard.changePasteMode('destination')).toBe(true);+ expect(bed.doc.getBody()?.textRuns).toContainEqual(expect.objectContaining({ ts: expect.objectContaining({ ff: 'Arial', fs: 12, bl: BooleanNumber.TRUE }) }));+ expect(await bed.clipboard.changePasteMode('text')).toBe(true);+ expect(bed.doc.getBody()?.dataStream).toBe('Before Rich text after\r\n');+ expect(bed.doc.getBody()?.textRuns?.some((run) => run.ts?.bl === BooleanNumber.TRUE)).toBe(false);+ expect(await bed.clipboard.changePasteMode('source')).toBe(true);+ const after = Tools.deepClone(bed.doc.getBody());+ expect(bed.get(IUndoRedoService).getUndoRedoStatus('paste-options').undos).toBe(1);+ expect(await bed.commands.executeCommand(UndoCommand.id)).toBe(true);+ expect(bed.doc.getBody()).toEqual(before);+ expect(await bed.commands.executeCommand(RedoCommand.id)).toBe(true);+ expect(bed.doc.getBody()).toEqual(after);+ } finally {+ bed.univer.dispose();+ }+ });++ it('emits mutations that reproduce format switches in a collaborating document', async () => {+ const bed = setup();+ const remote = new DocumentDataModel(Tools.deepClone(bed.doc.getSnapshot()));+ const listener = bed.commands.onMutationExecutedForCollab((command) => {+ if (command.id === RichTextEditingMutation.id) {+ const params = command.params as { actions: Parameters<DocumentDataModel['apply']>[0] };+ remote.apply(params.actions);+ }+ });+ try {+ expect(await bed.clipboard.legacyPaste(bed.payload)).toBe(true);+ expect(await bed.clipboard.changePasteMode('text')).toBe(true);+ expect(remote.getBody()).toEqual(bed.doc.getBody());+ expect(await bed.clipboard.changePasteMode('source')).toBe(true);+ expect(remote.getBody()).toEqual(bed.doc.getBody());+ } finally {+ listener.dispose();+ remote.dispose();+ bed.univer.dispose();+ }+ });++ it.each(['source', 'destination', 'text'] as const)('preserves Unicode and paragraph breaks through every transition starting with %s', async (initialMode) => {+ const bed = setup();+ try {+ const before = Tools.deepClone(bed.doc.getBody());+ const text = '中文🙂 café\n第二段';+ const payload = {+ html: '<p><b>中文🙂 café</b></p><p><i>第二段</i></p>',+ text,+ files: [],+ mode: initialMode,+ };+ expect(await bed.clipboard.legacyPaste(payload)).toBe(true);+ let currentMode = initialMode;+ for (const mode of ['text', 'destination', 'source', 'destination', 'text', 'source'] as const) {+ expect(await bed.clipboard.changePasteMode(mode)).toBe(mode !== currentMode);+ currentMode = mode;+ const body = bed.doc.getBody()!;+ expect(body.dataStream.replace(/\r+/g, '\n')).toContain(text);+ expect(body.dataStream.startsWith('Before ')).toBe(true);+ expect(body.dataStream.endsWith(' after\r\n')).toBe(true);+ expect(body.dataStream.match(/中文🙂 café/g)).toHaveLength(1);+ expect(body.textRuns?.some((run) => run.ts?.bl === BooleanNumber.TRUE)).toBe(mode !== 'text');+ }+ expect(bed.get(IUndoRedoService).getUndoRedoStatus('paste-options').undos).toBe(1);+ const after = Tools.deepClone(bed.doc.getBody());+ expect(await bed.commands.executeCommand(UndoCommand.id)).toBe(true);+ expect(bed.doc.getBody()).toEqual(before);+ expect(await bed.commands.executeCommand(RedoCommand.id)).toBe(true);+ expect(bed.doc.getBody()).toEqual(after);+ } finally {+ bed.univer.dispose();+ }+ });++ it('switches a table to text and restores its cells and resources without duplicating surrounding content', async () => {+ const bed = setup();+ try {+ const before = Tools.deepClone(bed.doc.getSnapshot());+ expect(await bed.clipboard.legacyPaste({+ html: '<table><tr><td><b>A</b></td><td>B</td></tr><tr><td>C</td><td>D</td></tr></table>',+ text: 'A\tB\nC\tD',+ files: [],+ })).toBe(true);+ for (const mode of ['text', 'destination', 'text', 'source'] as const) {+ expect(await bed.clipboard.changePasteMode(mode)).toBe(true);+ const body = bed.doc.getBody()!;+ expect(body.dataStream.match(/Before /g)).toHaveLength(1);+ expect(body.dataStream.match(/ after/g)).toHaveLength(1);+ if (mode === 'text') {+ expect(body.dataStream).toContain('A\tB\rC\tD');+ expect(body.tables ?? []).toHaveLength(0);+ } else {+ expect(body.tables).toHaveLength(1);+ expect(bed.doc.getSnapshot().tableSource?.[body.tables![0].tableId]).toBeDefined();+ }+ }+ expect(bed.get(IUndoRedoService).getUndoRedoStatus('paste-options').undos).toBe(1);+ const after = Tools.deepClone(bed.doc.getSnapshot());+ expect(await bed.commands.executeCommand(UndoCommand.id)).toBe(true);+ expect(bed.doc.getBody()).toEqual({ ...before.body, tables: [], sectionBreaks: [] });+ expect(await bed.commands.executeCommand(RedoCommand.id)).toBe(true);+ expect(bed.doc.getBody()).toEqual(after.body);+ expect(bed.doc.getSnapshot().tableSource).toEqual(after.tableSource);+ } finally {+ bed.univer.dispose();+ }+ });++ it('only changes the latest paste and does not undo a preceding paste', async () => {+ const bed = setup();+ try {+ expect(await bed.clipboard.legacyPaste(bed.payload)).toBe(true);+ const firstPaste = Tools.deepClone(bed.doc.getBody());+ bed.selection.replaceSelectionInfoWithoutRefresh({+ ...bed.selection.getSelectionInfo()!,+ textRanges: [{ startOffset: 16, endOffset: 16, collapsed: true, isActive: true, segmentId: '' }],+ });+ bed.selection.refreshSelection();+ expect(await bed.clipboard.legacyPaste({ html: '<i>Next</i>', text: 'Next', files: [] })).toBe(true);+ expect(await bed.clipboard.changePasteMode('text')).toBe(true);+ expect(bed.doc.getBody()?.dataStream).toBe('Before Rich textNext after\r\n');+ expect(bed.get(IUndoRedoService).getUndoRedoStatus('paste-options').undos).toBe(2);+ expect(await bed.commands.executeCommand(UndoCommand.id)).toBe(true);+ expect(bed.doc.getBody()).toEqual(firstPaste);+ expect(await bed.clipboard.changePasteMode('source')).toBe(false);+ } finally {+ bed.univer.dispose();+ }+ });++ it('serializes competing switches without undoing another replacement', async () => {+ const bed = setup();+ try {+ expect(await bed.clipboard.legacyPaste(bed.payload)).toBe(true);+ expect(await Promise.all([+ bed.clipboard.changePasteMode('text'),+ bed.clipboard.changePasteMode('destination'),+ ])).toEqual([true, false]);+ expect(bed.doc.getBody()?.dataStream).toBe('Before Rich text after\r\n');+ expect(bed.doc.getBody()?.textRuns?.some((run) => run.ts?.bl === BooleanNumber.TRUE)).toBe(false);+ expect(bed.get(IUndoRedoService).getUndoRedoStatus('paste-options').undos).toBe(1);+ } finally {+ bed.univer.dispose();+ }+ });++ it('does not upload images for text-only paste and can restore the original rich content', async () => {+ const bed = setup();+ try {+ const upload = vi.fn(async () => null);+ bed.clipboard.addClipboardHook({ onBeforePasteImage: upload });+ expect(await bed.clipboard.legacyPaste({ ...bed.payload, mode: 'text', html: '<b>Rich</b> text<img src="data:image/png;base64,AA==">' })).toBe(true);+ expect(upload).not.toHaveBeenCalled();+ expect(bed.doc.getBody()?.textRuns?.some((run) => run.ts?.bl === BooleanNumber.TRUE)).toBe(false);+ expect(await bed.clipboard.changePasteMode('source')).toBe(true);+ expect(bed.doc.getBody()?.textRuns?.some((run) => run.ts?.bl === BooleanNumber.TRUE)).toBe(true);+ } finally {+ bed.univer.dispose();+ }+ });++ it('keeps options when layout fills in selection metadata without moving the caret', async () => {+ const bed = setup();+ try {+ expect(await bed.clipboard.legacyPaste(bed.payload)).toBe(true);+ const info = bed.selection.getSelectionInfo()!;+ bed.selection.replaceSelectionInfoWithoutRefresh({+ ...info,+ textRanges: info.textRanges.map((range) => ({+ ...range,+ segmentId: '',+ segmentPage: -1,+ rangeType: DOC_RANGE_TYPE.TEXT,+ })),+ });+ bed.selection.refreshSelection();+ expect(await bed.clipboard.changePasteMode('text')).toBe(true);+ } finally {+ bed.univer.dispose();+ }+ });++ it('rejects a stale switch after moving the selection', async () => {+ const bed = setup();+ try {+ await bed.clipboard.legacyPaste(bed.payload);+ bed.selection.__TEST_ONLY_add([{ startOffset: 0, endOffset: 0, collapsed: true, isActive: true, segmentId: '' }]);+ const snapshot = Tools.deepClone(bed.doc.getBody());+ expect(await bed.clipboard.changePasteMode('text')).toBe(false);+ expect(bed.doc.getBody()).toEqual(snapshot);+ } finally {+ bed.univer.dispose();+ }+ });++ it('invalidates options on a remote mutation without undoing that mutation', async () => {+ const bed = setup();+ try {+ await bed.clipboard.legacyPaste(bed.payload);+ expect(bed.commands.syncExecuteCommand(RichTextEditingMutation.id, {+ unitId: 'paste-options',+ segmentId: '',+ textRanges: null,+ actions: [],+ isSync: true,+ })).toBeTruthy();+ const snapshot = Tools.deepClone(bed.doc.getBody());+ expect(await bed.clipboard.changePasteMode('text')).toBe(false);+ expect(bed.doc.getBody()).toEqual(snapshot);+ } finally {+ bed.univer.dispose();+ }+ });++ it('does not paste at a different selection after waiting for clipboard permission', async () => {+ const bed = setup();+ try {+ let resolveRead: ((items: ClipboardItem[]) => void) | undefined;+ vi.spyOn(bed.get(IClipboardInterfaceService), 'read').mockImplementation(() => new Promise((resolve) => {+ resolveRead = resolve;+ }));+ const pending = bed.clipboard.pasteFromClipboard('text');+ bed.selection.__TEST_ONLY_add([{ startOffset: 0, endOffset: 0, collapsed: true, isActive: true, segmentId: '' }]);+ resolveRead!([]);+ expect(await pending).toBe(false);+ expect(bed.doc.getBody()?.dataStream).toBe('Before selected after\r\n');+ } finally {+ bed.univer.dispose();+ }+ });++ it('does not replace another history entry even if the selection has not changed', async () => {+ const bed = setup();+ try {+ await bed.clipboard.legacyPaste(bed.payload);+ bed.get(IUndoRedoService).pushUndoRedo({ unitID: 'paste-options', undoMutations: [], redoMutations: [] });+ expect(await bed.clipboard.changePasteMode('text')).toBe(false);+ expect(bed.doc.getBody()?.dataStream).toBe('Before Rich text after\r\n');+ } finally {+ bed.univer.dispose();+ }+ });++ it('restores the previous paste if the replacement fails', async () => {+ const bed = setup();+ try {+ await bed.clipboard.legacyPaste(bed.payload);+ const snapshot = Tools.deepClone(bed.doc.getBody());+ bed.clipboard.addClipboardHook({+ onBeforePaste: () => {+ throw new Error('Rejected paste');+ },+ });+ await expect(bed.clipboard.changePasteMode('text')).rejects.toThrow('Rejected paste');+ expect(bed.doc.getBody()).toEqual(snapshot);+ } finally {+ bed.univer.dispose();+ }+ });+});diff --git a/packages/docs-ui/src/services/clipboard/__tests__/paste-options.spec.ts b/packages/docs-ui/src/services/clipboard/__tests__/paste-options.spec.tsnew file mode 100644index 0000000000..9c5686b540--- /dev/null+++ b/packages/docs-ui/src/services/clipboard/__tests__/paste-options.spec.ts@@ -0,0 +1,75 @@+/**+ * 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 { IDocumentData } from '@univerjs/core';+import { BooleanNumber, DataStreamTreeTokenType } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { applyDocPasteMode, getClipboardPlainText } from '../paste-options';++describe('document paste format conversion', () => {+ it('converts table cells to tabs and rows to newlines without carrying table resources', () => {+ const t = DataStreamTreeTokenType;+ const row = (cells: string[]) => t.TABLE_ROW_START + cells.map((text) => `${t.TABLE_CELL_START}${text}\r\n${t.TABLE_CELL_END}`).join('') + t.TABLE_ROW_END;+ const source: Partial<IDocumentData> = {+ body: {+ dataStream: t.TABLE_START + row(['A', 'B']) + row(['C', 'D']) + t.TABLE_END,+ tables: [{ startIndex: 0, endIndex: 30, tableId: 'table' }],+ },+ tableSource: {},+ };+ expect(getClipboardPlainText(source)).toBe('A\tB\nC\tD');+ const converted = applyDocPasteMode(source, 'text', { textStyle: { fs: 12 } }, 'ABCD');+ expect(converted.body?.dataStream).toBe('A\tB\rC\tD');+ expect(converted.body?.tables).toBeUndefined();+ expect(converted.tableSource).toBeUndefined();+ });++ it('keeps structure and emphasis while matching destination fonts and paragraph spacing', () => {+ const source: Partial<IDocumentData> = {+ body: {+ dataStream: 'Bold and italic\r',+ textRuns: [+ { st: 0, ed: 4, ts: { bl: BooleanNumber.TRUE, fs: 30, ff: 'Georgia' } },+ { st: 9, ed: 15, ts: { it: BooleanNumber.TRUE, fs: 30 } },+ ],+ paragraphs: [{ startIndex: 15, paragraphId: 'source', paragraphStyle: { spaceAbove: { v: 40 } } }],+ },+ };+ const converted = applyDocPasteMode(source, 'destination', {+ textStyle: { ff: 'Arial', fs: 12 },+ paragraphStyle: { spaceAbove: { v: 6 }, headingId: 'target-heading' },+ });+ expect(converted.body?.dataStream).toBe(source.body?.dataStream);+ expect(converted.body?.textRuns).toContainEqual({ st: 0, ed: 4, ts: { ff: 'Arial', fs: 12, bl: BooleanNumber.TRUE } });+ expect(converted.body?.textRuns).toContainEqual({ st: 4, ed: 9, ts: { ff: 'Arial', fs: 12 } });+ expect(converted.body?.textRuns).toContainEqual({ st: 9, ed: 15, ts: { ff: 'Arial', fs: 12, it: BooleanNumber.TRUE } });+ expect(converted.body?.paragraphs?.[0].paragraphStyle).toEqual({ spaceAbove: { v: 6 } });+ expect(source.body?.textRuns?.[0].ts?.fs).toBe(30);+ });++ it('removes hyperlinks and images in text-only mode without losing line breaks', () => {+ const source: Partial<IDocumentData> = {+ body: { dataStream: `First\rSecond${DataStreamTreeTokenType.CUSTOM_BLOCK}\r\n`, customBlocks: [{ startIndex: 12, blockId: 'image' }] },+ drawings: {},+ };+ const converted = applyDocPasteMode(source, 'text', { textStyle: {} });+ expect(converted.body?.dataStream).toBe('First\rSecond');+ expect(converted.body?.customBlocks).toBeUndefined();+ expect(converted.drawings).toBeUndefined();+ const link = applyDocPasteMode({ body: { dataStream: 'https://example.com' } }, 'text', { textStyle: {} });+ expect(link.body?.customRanges).toBeUndefined();+ });+});diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.tsindex 57a7abc2d9..9aa2715be7 100644--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts@@ -14,11 +14,14 @@* limitations under the License.*/-import type { DocumentDataModel, IDisposable, IDocumentBody, IDocumentData } from '@univerjs/core';+import type { DocumentDataModel, IDisposable, IDocumentBody, IDocumentData, IUndoRedoItem } from '@univerjs/core';import type { IDocImage } from '@univerjs/docs-drawing';import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';+import type { Observable } from 'rxjs';+import type { DocPasteMode, IDocPasteStyle } from './paste-options';import {BuildTextUtils,+ CommandType,createIdentifier,createParagraphId,createSectionId,@@ -36,20 +39,26 @@ import {ImageSourceType,Inject,IPermissionService,+ isInternalEditorID,+ IUndoRedoService,IUniverInstanceService,+ NAMED_STYLE_MAP,normalizeBody,ObjectRelativeFromH,ObjectRelativeFromV,PositionedObjectLayoutType,+ RedoCommand,SliceBodyType,toDisposable,Tools,+ UndoCommand,UniverInstanceType,validateDocBodyStructure,} from '@univerjs/core';import {canEditDocumentTargets,DocSelectionManagerService,+ DocStateChangeManagerService,getDocumentEditTargetObjectIds,getDocumentPermissionValue,} from '@univerjs/docs';@@ -63,9 +72,12 @@ import {IClipboardInterfaceService,PLAIN_TEXT_CLIPBOARD_MIME_TYPE,} from '@univerjs/ui';+import { BehaviorSubject } from 'rxjs';import { isTopLevelStructuralGap } from '../../basics/paragraph';import { CutContentCommand, InnerPasteCommand } from '../../commands/commands/clipboard.inner.command';import { getCursorWhenDelete } from '../../commands/commands/doc-delete.command';+import { getStyleInTextRange } from '../../commands/commands/inline-format.command';+import { DocMenuStyleService } from '../doc-menu-style.service';import { copyContentCache, extractId } from './copy-content-cache';import { HtmlToUDMService } from './html-to-udm/converter';import LarkPastePlugin from './html-to-udm/paste-plugins/plugin-lark';@@ -82,6 +94,7 @@ import {parseInternalClipboardFragment,wrapClipboardHtml,} from './internal-fragment';+import { applyDocPasteMode, getClipboardPlainText } from './paste-options';import { UDMToHtmlService } from './udm-to-html/convertor';import { DocHtmlExportService } from './udm-to-html/doc-html-export.service';@@ -190,11 +203,39 @@ export interface IDocClipboardHook {onBeforePasteImage?: (file: File) => Promise<{ source: string; imageSourceType: ImageSourceType } | null>;}+export interface IDocClipboardPayload {+ html?: string;+ text?: string;+ internalJson?: string;+ files: File[];+ unitId?: string;+ mode?: DocPasteMode;+}++export interface IDocPasteOptionsState {+ unitId: string;+ mode: DocPasteMode;+ range: ITextRangeWithStyle;+}++interface IDocPasteSession {+ payload: IDocClipboardPayload;+ source?: Partial<IDocumentData>;+ style: IDocPasteStyle;+ history: IUndoRedoItem;+ selectionKey: string;+}+export interface IDocClipboardService {copy(sliceType?: SliceBodyType, ranges?: ITextRangeWithStyle[]): Promise<boolean>;cut(ranges?: ITextRangeWithStyle[]): Promise<boolean>;- paste(items?: ClipboardItem[]): Promise<boolean>;- legacyPaste(options: { html?: string; text?: string; internalJson?: string; files: File[]; unitId?: string }): Promise<boolean>;+ paste(items?: ClipboardItem[], mode?: DocPasteMode): Promise<boolean>;+ pasteFromClipboard(mode?: DocPasteMode): Promise<boolean>;+ legacyPaste(options: IDocClipboardPayload): Promise<boolean>;+ readonly pasteOptions$: Observable<IDocPasteOptionsState | null>;+ setNextPasteMode(mode: DocPasteMode): void;+ dismissPasteOptions(): void;+ changePasteMode(mode: DocPasteMode): Promise<boolean>;addClipboardHook(hook: IDocClipboardHook): IDisposable;}@@ -250,6 +291,14 @@ function getTableCellContentClipboardBodySlice(body: IDocumentBody, start: numbeexport const IDocClipboardService = createIdentifier<IDocClipboardService>('doc.clipboard-service');export class DocClipboardService extends Disposable implements IDocClipboardService {+ private readonly _pasteOptions$ = new BehaviorSubject<IDocPasteOptionsState | null>(null);+ readonly pasteOptions$ = this._pasteOptions$.asObservable();+ private _pasteSession: IDocPasteSession | null = null;+ private _applyingPaste = false;+ private _pasteGeneration = 0;+ private _nextPasteMode: DocPasteMode = 'source';+ private _lastSelectionKey = '';+private _clipboardHooks: IDocClipboardHook[] = [];private _memoryClipboardData: Partial<IDocumentData> | null = null;@@ -264,10 +313,36 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ@IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService,@Inject(ErrorService) private readonly _errorService: ErrorService,@Inject(DocHtmlExportService) docHtmlExportService: DocHtmlExportService,- @Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService+ @Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService,+ @Inject(DocStateChangeManagerService) private readonly _stateChangeManager: DocStateChangeManagerService,+ @Inject(DocMenuStyleService) private readonly _menuStyleService: DocMenuStyleService,+ @IUndoRedoService private readonly _undoRedoService: IUndoRedoService) {super();this._umdToHtml = new UDMToHtmlService(docHtmlExportService);+ this.disposeWithMe(this._commandService.beforeCommandExecuted((command) => {+ if (!this._applyingPaste && command.type === CommandType.MUTATION) {+ this.dismissPasteOptions();+ }+ }));+ const invalidateSelection = () => {+ const key = this._getPasteSelectionKey();+ if (key !== this._lastSelectionKey) {+ this._lastSelectionKey = key;+ if (!this._applyingPaste) {+ this.dismissPasteOptions();+ }+ }+ };+ this.disposeWithMe(this._docSelectionManagerService.textSelection$.subscribe(invalidateSelection));+ this.disposeWithMe(this._docSelectionManagerService.refreshSelection$.subscribe(invalidateSelection));+ this.disposeWithMe(this._univerInstanceService.focused$.subscribe(() => this.dismissPasteOptions()));+ this.disposeWithMe(this._univerInstanceService.unitDisposed$.subscribe(() => this.dismissPasteOptions()));+ this.disposeWithMe(this._permissionService.permissionPointUpdate$.subscribe(() => this.dismissPasteOptions()));+ this.disposeWithMe(() => {+ this.dismissPasteOptions();+ this._pasteOptions$.complete();+ });}async copy(sliceType: SliceBodyType = SliceBodyType.copy, ranges?: ITextRangeWithStyle[]): Promise<boolean> {@@ -312,59 +387,212 @@ export class DocClipboardService extends Disposable implements IDocClipboardServreturn this._cut(ranges);}- async paste(items?: ClipboardItem[]): Promise<boolean> {- const targetUnitId = this._getCurrentDocumentUnitId();- if (!targetUnitId || !this._canEditTargets(targetUnitId)) {+ async pasteFromClipboard(mode: DocPasteMode = 'source'): Promise<boolean> {+ const generation = this._pasteGeneration;+ const selectionKey = this._getPasteSelectionKey();+ if (!this._clipboardInterfaceService.supportClipboard) {+ if (this._memoryClipboardData) {+ return this.paste(undefined, mode);+ }+ throw new Error('Clipboard read unavailable');+ }+ const items = await this._clipboardInterfaceService.read();+ if (generation !== this._pasteGeneration || selectionKey !== this._getPasteSelectionKey()) {return false;}+ return this.paste(items, mode);+ }++ async paste(items?: ClipboardItem[], mode: DocPasteMode = 'source'): Promise<boolean> {if (!items?.length) {- return this._memoryClipboardData ? this._paste(Tools.deepClone(this._memoryClipboardData), targetUnitId) : false;+ return this._memoryClipboardData+ ? this._pasteWithOptions({ files: [], mode }, Tools.deepClone(this._memoryClipboardData))+ : false;}-- const partDocData = await this._genDocDataFromClipboardItems(items);- if (!this._canEditTargets(targetUnitId)) {+ const generation = this._pasteGeneration;+ const payload = await this._readClipboardItems(items);+ if (generation !== this._pasteGeneration) {return false;}+ return this.legacyPaste({ ...payload, mode });+ }++ setNextPasteMode(mode: DocPasteMode): void {+ this._nextPasteMode = mode;+ }++ async legacyPaste(options: IDocClipboardPayload): Promise<boolean> {+ const mode = options.mode ?? this._nextPasteMode;+ this._nextPasteMode = 'source';+ return this._pasteWithOptions({ ...options, mode });+ }- return this._paste(partDocData, targetUnitId);+ dismissPasteOptions(): void {+ this._pasteGeneration++;+ this._pasteSession = null;+ if (this._pasteOptions$.value) {+ this._pasteOptions$.next(null);+ }}- async legacyPaste(options: {- html?: string;- internalJson?: string;- text?: string;- files: File[];- unitId?: string;- }): Promise<boolean> {- const docUnitId = options.unitId ?? this._getCurrentDocumentUnitId() ?? '';- if (!docUnitId || !this._canEditTargets(docUnitId)) {+ async changePasteMode(mode: DocPasteMode): Promise<boolean> {+ const session = this._pasteSession;+ const state = this._pasteOptions$.value;+ if (!session || !state || state.mode === mode) {+ return false;+ }+ const generation = this._pasteGeneration;+ const source = await this._preparePaste(session.payload, mode, session.source);+ // Both history identity and the invalidation generation must still match after asynchronous image loading.+ if (generation !== this._pasteGeneration || session !== this._pasteSession ||+ this._undoRedoService.pitchTopUndoElement() !== session.history ||+ this._getPasteSelectionKey() !== session.selectionKey ||+ this._getCurrentDocumentUnitId() !== state.unitId || !this._canEditTargets(state.unitId)) {+ return false;+ }+ const doc = applyDocPasteMode(source, mode, session.style, session.payload.text);+ if (!doc.body?.dataStream) {return false;}- let { html, internalJson, text, files } = options;- if (!html && !text && files.length) {- html = await this._createImagePasteHtml(files);- } else if (html && files.length) {- html += await this._createImagePasteHtml(files);+ this._applyingPaste = true;+ try {+ // This synchronous transaction can only replace the exact, still-current paste history entry.+ if (!this._commandService.syncExecuteCommand(UndoCommand.id)) {+ this.dismissPasteOptions();+ return false;+ }+ try {+ if (!this._paste(doc, state.unitId)) {+ this._commandService.syncExecuteCommand(RedoCommand.id);+ this.dismissPasteOptions();+ return false;+ }+ } catch (error) {+ this._commandService.syncExecuteCommand(RedoCommand.id);+ this.dismissPasteOptions();+ throw error;+ }+ this._savePasteSession(session.payload, mode === 'text' ? session.source : source, session.style, mode, state.unitId);+ return true;+ } finally {+ this._applyingPaste = false;+ }+ }++ private async _preparePaste(+ payload: IDocClipboardPayload,+ mode: DocPasteMode,+ source?: Partial<IDocumentData>+ ): Promise<Partial<IDocumentData>> {+ if (source) {+ return source;+ }+ if (mode === 'text') {+ const internal = parseInternalClipboardFragment(payload.internalJson) ?? extractInternalClipboardFragmentFromHtml(payload.html);+ if (internal?.body) {+ return internal;+ }+ if (payload.text !== undefined) {+ return { body: BuildTextUtils.transform.fromPlainText(payload.text) };+ }+ return this._genDocDataFromHtmlAndText(payload.html, payload.text, payload.unitId, payload.internalJson);+ }+ let html = payload.html;+ if (payload.files.length && !payload.text && !html) {+ html = await this._createImagePasteHtml(payload.files);+ } else if (html && payload.files.length) {+ html += await this._createImagePasteHtml(payload.files);}html = await this._uploadBase64ImagesInHtml(html);- if (!this._canEditTargets(docUnitId)) {+ return this._genDocDataFromHtmlAndText(html, payload.text, payload.unitId, payload.internalJson);+ }++ private async _pasteWithOptions(payload: IDocClipboardPayload, cachedSource?: Partial<IDocumentData>): Promise<boolean> {+ this.dismissPasteOptions();+ const unitId = payload.unitId ?? this._getCurrentDocumentUnitId();+ if (!unitId || !this._canEditTargets(unitId)) {return false;}- if (!html && !text) {- this._logService.warn('[DocClipboardController] html and text cannot be both empty!');+ if (!cachedSource && !payload.html && !payload.text && !payload.internalJson && !payload.files.length) {return false;}- const partDocData = this._genDocDataFromHtmlAndText(html, text, docUnitId, internalJson);- // Paste in sheet editing mode without paste style, so we give textRuns empty array;- if (docUnitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {- if (text) {- const textDocData = BuildTextUtils.transform.fromPlainText(text);- return this._paste({ body: textDocData }, docUnitId);- } else {- partDocData.body!.textRuns = [];+ const generation = this._pasteGeneration;+ const mode = unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY ? 'text' : payload.mode ?? 'source';+ const style = this._getPasteStyle(unitId);+ const source = await this._preparePaste(payload, mode, cachedSource);+ if (generation !== this._pasteGeneration || !this._canEditTargets(unitId)) {+ return false;+ }+ let doc = applyDocPasteMode(source, mode, style, payload.text);+ if (unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {+ doc = { ...source, body: { ...source.body!, textRuns: [] } };+ if (payload.text) {+ doc = { body: BuildTextUtils.transform.fromPlainText(payload.text) };+ }+ }+ if (!doc.body?.dataStream) {+ return false;+ }+ this._applyingPaste = true;+ try {+ // Keep preceding debounced typing out of the paste's undo entry.+ this._stateChangeManager.flushPendingChanges(unitId);+ const result = this._paste(doc, unitId);+ if (result && !isInternalEditorID(unitId)) {+ this._savePasteSession(payload, mode === 'text' ? cachedSource : source, style, mode, unitId);}+ return result;+ } finally {+ this._applyingPaste = false;+ }+ }++ private _getPasteStyle(unitId: string): IDocPasteStyle {+ const model = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC)!;+ const ranges = this._docSelectionManagerService.getTextRanges(this._getSelectionParams(unitId)) ?? [];+ const range = ranges.find((item) => item.isActive) ?? ranges[0];+ const body = model.getSelfOrHeaderFooterModel(range?.segmentId ?? '')?.getBody();+ const paragraph = body?.paragraphs?.find((item) => item.startIndex >= (range?.startOffset ?? 0));+ const textStyle = body && range ? getStyleInTextRange(body, range, {}) : {};+ Tools.deleteNull(textStyle);+ const namedStyle = paragraph?.paragraphStyle?.namedStyleType;+ const headingStyle = namedStyle ? NAMED_STYLE_MAP[namedStyle] : {};+ return Tools.deepClone({+ textStyle: { ...this._menuStyleService.getDefaultStyle(), ...headingStyle, ...paragraph?.paragraphStyle?.textStyle, ...textStyle, ...this._menuStyleService.getStyleCache() },+ paragraphStyle: paragraph?.paragraphStyle,+ });+ }++ private _getPasteSelectionKey(): string {+ return JSON.stringify(this._docSelectionManagerService.getDocRanges().map((range) => [+ range.startOffset,+ range.endOffset,+ range.segmentId ?? '',+ range.rangeType ?? DOC_RANGE_TYPE.TEXT,+ ]));+ }++ private _savePasteSession(+ payload: IDocClipboardPayload,+ source: Partial<IDocumentData> | undefined,+ style: IDocPasteStyle,+ mode: DocPasteMode,+ unitId: string+ ): void {+ if (!source && !payload.html && !payload.internalJson) {+ this.dismissPasteOptions();+ return;}- return this._paste(partDocData, docUnitId);+ this._stateChangeManager.flushPendingChanges(unitId);+ const history = this._undoRedoService.pitchTopUndoElement();+ const ranges = this._docSelectionManagerService.getTextRanges(this._getSelectionParams(unitId));+ const range = ranges?.find((item) => item.isActive) ?? ranges?.[0];+ if (!history || history.unitID !== unitId || !range) {+ return;+ }+ this._lastSelectionKey = this._getPasteSelectionKey();+ this._pasteSession = { payload: { ...payload, text: payload.text ?? (source ? getClipboardPlainText(source) : undefined) }, source, style, history, selectionKey: this._getPasteSelectionKey() };+ this._pasteOptions$.next({ unitId, mode, range: { ...range, collapsed: true } });}private _getCurrentDocumentUnitId(): string | null {@@ -475,7 +703,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}}- private async _paste(docData: Partial<IDocumentData>, expectedUnitId?: string): Promise<boolean> {+ private _paste(docData: Partial<IDocumentData>, expectedUnitId?: string): boolean {const { body: _body } = docData;if (_body == null) {@@ -567,7 +795,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ},];- return this._commandService.executeCommand(InnerPasteCommand.id, {+ return this._commandService.syncExecuteCommand(InnerPasteCommand.id, {unitId,doc: {...docData,@@ -739,10 +967,10 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ};}- private async _genDocDataFromClipboardItems(items: ClipboardItem[]): Promise<Partial<IDocumentData>> {+ private async _readClipboardItems(items: ClipboardItem[]): Promise<IDocClipboardPayload> {try {let html = '';- let text = '';+ let text: string | undefined;let internalJson = '';const files: File[] = [];for (const clipboardItem of items) {@@ -772,12 +1000,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}}}- if (!html && !text && files.length) {- html = await this._createImagePasteHtml(files);- }- html = await this._uploadBase64ImagesInHtml(html) ?? '';-- return this._genDocDataFromHtmlAndText(html, text, undefined, internalJson);+ return { html, text, internalJson, files };} catch (e) {return Promise.reject(e);}diff --git a/packages/docs-ui/src/services/clipboard/paste-options.ts b/packages/docs-ui/src/services/clipboard/paste-options.tsnew file mode 100644index 0000000000..bb5c061710--- /dev/null+++ b/packages/docs-ui/src/services/clipboard/paste-options.ts@@ -0,0 +1,95 @@+/**+ * 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 { IDocumentData, IParagraphStyle, ITextStyle } from '@univerjs/core';+import { BuildTextUtils, DataStreamTreeTokenType, Tools } from '@univerjs/core';++export type DocPasteMode = 'source' | 'destination' | 'text';++export interface IDocPasteStyle {+ textStyle: ITextStyle;+ paragraphStyle?: IParagraphStyle;+}++export const DOC_PASTE_OPTIONS = [+ { value: 'source', label: 'docs-ui.pasteOptions.source' },+ { value: 'destination', label: 'docs-ui.pasteOptions.destination' },+ { value: 'text', label: 'docs-ui.pasteOptions.text' },+] as const;++export function getClipboardPlainText(doc: Partial<IDocumentData>): string {+ const token = DataStreamTreeTokenType;+ return (doc.body?.dataStream ?? '')+ .split(`${token.TABLE_CELL_END}${token.TABLE_CELL_START}`)+ .join('\t')+ .split(`${token.TABLE_ROW_END}${token.TABLE_ROW_START}`)+ .join('\n')+ .replace(/\r\n/g, '')+ .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, '');+}++export function applyDocPasteMode(+ source: Partial<IDocumentData>,+ mode: DocPasteMode,+ style: IDocPasteStyle,+ text?: string+): Partial<IDocumentData> {+ if (mode === 'source') {+ return Tools.deepClone(source);+ }+ let doc: Partial<IDocumentData>;+ if (mode === 'text') {+ const plainText = source.body?.tables?.length+ ? getClipboardPlainText(source)+ : text ?? getClipboardPlainText(source);+ doc = { body: BuildTextUtils.transform.fromPlainText(plainText) };+ } else {+ doc = Tools.deepClone(source);+ }+ const body = doc.body;+ if (!body) {+ return doc;+ }+ const sourceRuns = [...body.textRuns ?? []].sort((a, b) => a.st - b.st);+ const boundaries = [...new Set([0, body.dataStream.length, ...sourceRuns.flatMap(({ st, ed }) => [st, ed])])]+ .filter((offset) => offset >= 0 && offset <= body.dataStream.length)+ .sort((a, b) => a - b);+ let runIndex = 0;+ body.textRuns = boundaries.slice(0, -1).map((st, index) => {+ const ts = Tools.deepClone(style.textStyle);+ while (runIndex < sourceRuns.length && sourceRuns[runIndex].ed <= st) {+ runIndex++;+ }+ const run = sourceRuns[runIndex];+ const original = run && run.st <= st ? run.ts : undefined;+ if (mode === 'destination' && original) {+ for (const key of ['bl', 'it', 'ul', 'st', 'va'] as const) {+ if (original[key] !== undefined) {+ Object.assign(ts, { [key]: original[key] });+ }+ }+ }+ return { st, ed: boundaries[index + 1], ts };+ });+ body.paragraphs?.forEach((paragraph) => {+ paragraph.paragraphStyle = Tools.deepClone(style.paragraphStyle ?? {});+ delete paragraph.paragraphStyle.headingId;+ });+ if (mode === 'text') {+ delete body.customRanges;+ }+ return doc;+}diff --git a/packages/docs-ui/src/views/DocPasteOptions.tsx b/packages/docs-ui/src/views/DocPasteOptions.tsxnew file mode 100644index 0000000000..2b36ebfe83--- /dev/null+++ b/packages/docs-ui/src/views/DocPasteOptions.tsx@@ -0,0 +1,93 @@+/**+ * 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 { LocaleKey } from '../locale/types';+import type { DocPasteMode } from '../services/clipboard/paste-options';+import { ICommandService, LocaleService } from '@univerjs/core';+import { Button, DropdownMenu } from '@univerjs/design';+import { DocPasteOptionsIcon } from '@univerjs/icons';+import { ILayoutService, useDependency, useObservable } from '@univerjs/ui';+import { useState } from 'react';+import { DocChangePasteModeCommand } from '../commands/commands/clipboard.command';+import { IDocClipboardService } from '../services/clipboard/clipboard.service';+import { DOC_PASTE_OPTIONS } from '../services/clipboard/paste-options';++export const DOC_PASTE_OPTIONS_COMPONENT = 'docs-ui.paste-options';++export function DocPasteOptions() {+ const clipboard = useDependency(IDocClipboardService);+ const commandService = useDependency(ICommandService);+ const localeService = useDependency(LocaleService);+ const layoutService = useDependency(ILayoutService);+ const state = useObservable(clipboard.pasteOptions$, null);+ const [busy, setBusy] = useState(false);+ const [open, setOpen] = useState(false);++ const changeMode = async (value: DocPasteMode) => {+ setBusy(true);+ try {+ await commandService.executeCommand(DocChangePasteModeCommand.id, { value });+ } finally {+ setBusy(false);+ layoutService.focus();+ }+ };++ if (!state) {+ return null;+ }++ return (+ <DropdownMenu+ align="start"+ open={open}+ onOpenChange={setOpen}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ layoutService.focus();+ }}+ onEscapeKeyDown={() => clipboard.dismissPasteOptions()}+ items={DOC_PASTE_OPTIONS.map((option) => ({+ type: 'checkbox',+ value: option.value,+ label: localeService.t<LocaleKey>(option.label),+ checked: state.mode === option.value,+ disabled: busy,+ onSelect: () => changeMode(option.value),+ }))}+ >+ <Button+ size="small"+ disabled={busy}+ aria-label={localeService.t<LocaleKey>('docs-ui.pasteOptions.title')}+ title={localeService.t<LocaleKey>('docs-ui.pasteOptions.title')}+ onMouseDown={(event) => event.preventDefault()}+ onKeyDown={(event) => {+ if (event.key === 'Escape') {+ clipboard.dismissPasteOptions();+ layoutService.focus();+ }+ }}+ className="univer-shadow-sm"+ >+ <DocPasteOptionsIcon className="!univer-size-5" aria-hidden="true" />+ <svg className="!univer-size-2" width="8" height="8" viewBox="0 0 8 8" aria-hidden="true">+ <path d="m1 2 3 4 3-4Z" fill="currentColor" />+ </svg>+ </Button>+ </DropdownMenu>+ );+}diff --git a/packages/docs-ui/src/views/mobile/MobileDocPasteOptions.tsx b/packages/docs-ui/src/views/mobile/MobileDocPasteOptions.tsxnew file mode 100644index 0000000000..d60533e5f5--- /dev/null+++ b/packages/docs-ui/src/views/mobile/MobileDocPasteOptions.tsx@@ -0,0 +1,142 @@+/**+ * 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 { IPopupWithExtraProps, MobileDrawerSnap } from '@univerjs/ui';+import type { LocaleKey } from '../../locale/types';+import type { DocPasteMode } from '../../services/clipboard/paste-options';+import type { MobileDocSelectionRenderService } from '../../services/mobile/doc-selection-render.service';+import { ICommandService, LocaleService } from '@univerjs/core';+import { Button } from '@univerjs/design';+import { IRenderManagerService } from '@univerjs/engine-render';+import { CheckMarkIcon, DocPasteOptionsIcon } from '@univerjs/icons';+import { MobileDrawer, useDependency, useObservable } from '@univerjs/ui';+import { useState } from 'react';+import { DocChangePasteModeCommand } from '../../commands/commands/clipboard.command';+import { IDocClipboardService } from '../../services/clipboard/clipboard.service';+import { DOC_PASTE_OPTIONS } from '../../services/clipboard/paste-options';+import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';++export function MobileDocPasteOptions({ popup }: { popup: IPopupWithExtraProps<{ unitId: string }> }) {+ const { unitId } = popup.extraProps;+ const clipboard = useDependency(IDocClipboardService);+ const commands = useDependency(ICommandService);+ const localeService = useDependency(LocaleService);+ const renders = useDependency(IRenderManagerService);+ const selection = renders.getRenderUnitById(unitId)?.with(DocSelectionRenderService) as MobileDocSelectionRenderService | undefined;+ const state = useObservable(clipboard.pasteOptions$, null);+ const keyboard = useObservable(selection?.mobileKeyboardState$, { visible: false, inset: 0 });+ useObservable(localeService.currentLocale$);+ const [open, setOpen] = useState(false);+ const [busy, setBusy] = useState(false);+ const [snap, setSnap] = useState<MobileDrawerSnap>('compact');++ const changeMode = async (value: DocPasteMode) => {+ setBusy(true);+ try {+ await commands.executeCommand(DocChangePasteModeCommand.id, { value });+ setOpen(false);+ } finally {+ setBusy(false);+ }+ };++ if (!state || state.unitId !== unitId) {+ return null;+ }++ return (+ <>+ <Button+ aria-label={localeService.t<LocaleKey>('docs-ui.pasteOptions.title')}+ className="+ univer-min-h-11 univer-min-w-11 univer-shadow-sm+ [&_svg]:!univer-size-6+ "+ style={keyboard.visible+ ? {+ position: 'fixed',+ bottom: keyboard.inset + 56,+ insetInlineEnd: 12,+ }+ : undefined}+ onClick={() => {+ selection?.suspendMobileEditingInput();+ setOpen(true);+ }}+ >+ <DocPasteOptionsIcon aria-hidden="true" />+ </Button>+ {open && (+ <div+ className="univer-pointer-events-none univer-fixed univer-inset-x-0 univer-top-0"+ style={{ bottom: keyboard.inset }}+ >+ <MobileDrawer+ componentName="mobile-doc-paste-options"+ panelClassName="univer-max-h-full"+ snap={snap}+ onSnapChange={setSnap}+ onClose={() => setOpen(false)}+ expandLabel={localeService.t<LocaleKey>('docs-ui.mobile.expand')}+ collapseLabel={localeService.t<LocaleKey>('docs-ui.mobile.collapse')}+ ariaLabel={localeService.t<LocaleKey>('docs-ui.pasteOptions.title')}+ header={(+ <div+ className="+ univer-flex univer-w-full univer-items-center univer-justify-between univer-gap-2+ univer-px-4+ "+ >+ <span>{localeService.t<LocaleKey>('docs-ui.pasteOptions.title')}</span>+ <Button variant="text" className="univer-min-h-11" onClick={() => setOpen(false)}>+ {localeService.t<LocaleKey>('docs-ui.mobile.done')}+ </Button>+ </div>+ )}+ >+ <div+ role="menu"+ aria-label={localeService.t<LocaleKey>('docs-ui.pasteOptions.title')}+ className="univer-flex univer-flex-col univer-gap-1 univer-p-3"+ >+ {DOC_PASTE_OPTIONS.map((option) => (+ <Button+ key={option.value}+ role="menuitemradio"+ aria-checked={state.mode === option.value}+ disabled={busy}+ variant="text"+ className="+ !univer-h-auto univer-min-h-11 univer-justify-start univer-whitespace-normal+ univer-py-3 univer-text-start+ "+ onClick={() => changeMode(option.value)}+ >+ <span+ className="univer-inline-flex univer-size-5 univer-shrink-0 univer-items-center"+ >+ {state.mode === option.value && <CheckMarkIcon />}+ </span>+ {localeService.t<LocaleKey>(option.label)}+ </Button>+ ))}+ </div>+ </MobileDrawer>+ </div>+ )}+ </>+ );+}