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
refactor(clipboard): always use native event for pasting (#1417)
Wenzhao Hu271574a0f98f
diff --git a/packages/docs-ui/src/controllers/clipboard.controller.ts b/packages/docs-ui/src/controllers/clipboard.controller.tsindex c009e3d197..81a3372afe 100644--- a/packages/docs-ui/src/controllers/clipboard.controller.ts+++ b/packages/docs-ui/src/controllers/clipboard.controller.ts@@ -51,18 +51,16 @@ export class DocClipboardController extends RxDisposable {}private _initLegacyPasteCommand(): void {- if (!this._clipboardInterfaceService.supportClipboard) {- this._textSelectionRenderManager?.onPaste$.pipe(takeUntil(this.dispose$)).subscribe((config) => {- if (!whenDocOrEditor(this._contextService)) {- return;- }+ this._textSelectionRenderManager?.onPaste$.pipe(takeUntil(this.dispose$)).subscribe((config) => {+ if (!whenDocOrEditor(this._contextService)) {+ return;+ }- config!.event.preventDefault();- const clipboardEvent = config!.event as ClipboardEvent;- const htmlContent = clipboardEvent.clipboardData?.getData('text/html');- const textContent = clipboardEvent.clipboardData?.getData('text/plain');- this._docClipboardService.legacyPaste(htmlContent, textContent);- });- }+ config!.event.preventDefault();+ const clipboardEvent = config!.event as ClipboardEvent;+ const htmlContent = clipboardEvent.clipboardData?.getData('text/html');+ const textContent = clipboardEvent.clipboardData?.getData('text/plain');+ this._docClipboardService.legacyPaste(htmlContent, textContent);+ });}}diff --git a/packages/sheets-ui/src/commands/commands/clipboard.command.ts b/packages/sheets-ui/src/commands/commands/clipboard.command.tsindex 5a04c4245d..3c43b92fd4 100644--- a/packages/sheets-ui/src/commands/commands/clipboard.command.ts+++ b/packages/sheets-ui/src/commands/commands/clipboard.command.ts@@ -15,7 +15,7 @@*/import type { ICommand, IMultiCommand } from '@univerjs/core';-import { CommandType, ICommandService, ILogService } from '@univerjs/core';+import { CommandType, ICommandService } from '@univerjs/core';import { CopyCommand, CutCommand, IClipboardInterfaceService, PasteCommand } from '@univerjs/ui';import type { IAccessor } from '@wendellhu/redi';@@ -62,31 +62,17 @@ export const SheetPasteCommand: IMultiCommand = {priority: SHEET_CLIPBOARD_PRIORITY,preconditions: whenSheetFocused,handler: async (accessor: IAccessor, params: ISheetPasteParams) => {- const logService = accessor.get(ILogService);+ // const messageService = accessor.get(IMessageService);- // use cell editor to get ClipboardData first- // if that doesn't work, use the browser's clipboard API- // this clipboard API would ask user for permission, so we may need to notify user (and retry perhaps)- logService.debug('[SheetPasteCommand]', 'the focusing element is', document.activeElement);+ // TODO: @yuhongz: check if there is excel content in the clipboard, if so+ // ask users to use shortcuts instead.- const result = document.execCommand('paste');- if (!result) {- logService.debug(- '[SheetPasteCommand]',- 'failed to execute paste command on the activeElement, trying to use clipboard API.'- );-- const clipboardInterfaceService = accessor.get(IClipboardInterfaceService);- const clipboardItems = await clipboardInterfaceService.read();- const sheetClipboardService = accessor.get(ISheetClipboardService);-- // logService.debug('[SheetPasteCommand]: clipboard data is', clipboardItems);-- if (clipboardItems.length !== 0) {- return sheetClipboardService.paste(clipboardItems[0], params?.value);- }+ const clipboardInterfaceService = accessor.get(IClipboardInterfaceService);+ const clipboardItems = await clipboardInterfaceService.read();+ const sheetClipboardService = accessor.get(ISheetClipboardService);- return false;+ if (clipboardItems.length !== 0) {+ return sheetClipboardService.paste(clipboardItems[0], params?.value);}return false;diff --git a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.tsindex 4d3ab58be3..8f205499ec 100644--- a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts+++ b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts@@ -114,21 +114,19 @@ export class SheetClipboardController extends RxDisposable {this._init();- if (!this._clipboardInterfaceService.supportClipboard) {- this._textSelectionRenderManager?.onPaste$.pipe(takeUntil(this.dispose$)).subscribe((config) => {- if (!whenSheetEditorFocused(this._contextService)) {- return;- }+ this._textSelectionRenderManager?.onPaste$.pipe(takeUntil(this.dispose$)).subscribe((config) => {+ if (!whenSheetEditorFocused(this._contextService)) {+ return;+ }- // editor's value should not change and avoid triggering input event- config!.event.preventDefault();+ // editor's value should not change and avoid triggering input event+ config!.event.preventDefault();- const clipboardEvent = config!.event as ClipboardEvent;- const htmlContent = clipboardEvent.clipboardData?.getData('text/html');- const textContent = clipboardEvent.clipboardData?.getData('text/plain');- this._sheetClipboardService.legacyPaste(htmlContent, textContent);- });- }+ const clipboardEvent = config!.event as ClipboardEvent;+ const htmlContent = clipboardEvent.clipboardData?.getData('text/html');+ const textContent = clipboardEvent.clipboardData?.getData('text/plain');+ this._sheetClipboardService.legacyPaste(htmlContent, textContent);+ });}private _init() {diff --git a/packages/sheets-ui/src/locale/en-US.ts b/packages/sheets-ui/src/locale/en-US.tsindex ba25e20e4e..476096aae5 100644--- a/packages/sheets-ui/src/locale/en-US.ts+++ b/packages/sheets-ui/src/locale/en-US.ts@@ -429,6 +429,10 @@ const locale: typeof zhCN = {paste: {exceedMaxCells: 'The number of cells pasted exceeds the maximum number of cells',},+ shortCutNotify: {+ title: 'Kindly paste using keyboard shortcuts.',+ useShortCutInstead: 'Detected Excel content. Use keyboard shortcut to paste.',+ },},statusbar: {sum: 'Sum',diff --git a/packages/sheets-ui/src/locale/zh-CN.ts b/packages/sheets-ui/src/locale/zh-CN.tsindex 235803a9de..fbc7e44369 100644--- a/packages/sheets-ui/src/locale/zh-CN.ts+++ b/packages/sheets-ui/src/locale/zh-CN.ts@@ -427,6 +427,10 @@ const locale = {paste: {exceedMaxCells: '粘贴区域超出最大单元格数',},+ shortCutNotify: {+ title: '请使用快捷键粘贴',+ useShortCutInstead: '检测到 Excel 内容,请使用快捷键粘贴',+ },},statusbar: {sum: '求和',diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.tsindex 87a58f1cf8..add6df68fe 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts@@ -23,8 +23,10 @@ import {DesktopMessageService,IClipboardInterfaceService,IMessageService,+ INotificationService,+ IPlatformService,} from '@univerjs/ui';-import type { Dependency } from '@wendellhu/redi';+import type { Dependency, IDisposable } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';import { SheetClipboardController } from '../../../controllers/clipboard/clipboard.controller';@@ -494,6 +496,20 @@ export class testMarkSelectionService {}}+export class testNotificationService {+ show(): IDisposable {+ return {+ dispose: () => {},+ };+ }+}++export class testPlatformService {+ isWindows: false;+ isMac: true;+ isLinux: false;+}+export function clipboardTestBed(workbookConfig?: IWorkbookData, dependencies?: Dependency[]) {const univer = new Univer();@@ -529,6 +545,8 @@ export function clipboardTestBed(workbookConfig?: IWorkbookData, dependencies?:]);injector.add([IRenderManagerService, { useClass: RenderManagerService }]);injector.add([ISelectionRenderService, { useClass: SelectionRenderService }]);+ injector.add([INotificationService, { useClass: testNotificationService }]); ;+ injector.add([IPlatformService, { useClass: testPlatformService }]);// Because SheetClipboardController is initialized in the rendered life cycle, here we need to initialize it manuallyconst sheetClipboardController = injector.createInstance(SheetClipboardController);injector.add([SheetClipboardController, { useValue: sheetClipboardController }]);diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.tsindex d0c0a30241..e71bd70a46 100644--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts@@ -21,6 +21,7 @@ import {ILogService,IUndoRedoService,IUniverInstanceService,+ LocaleService,ObjectMatrix,Rectangle,toDisposable,@@ -33,7 +34,7 @@ import {SelectionManagerService,SetSelectionsOperation,} from '@univerjs/sheets';-import { HTML_CLIPBOARD_MIME_TYPE, IClipboardInterfaceService, PLAIN_TEXT_CLIPBOARD_MIME_TYPE } from '@univerjs/ui';+import { HTML_CLIPBOARD_MIME_TYPE, IClipboardInterfaceService, INotificationService, IPlatformService, PLAIN_TEXT_CLIPBOARD_MIME_TYPE } from '@univerjs/ui';import type { IDisposable } from '@wendellhu/redi';import { createIdentifier, Inject } from '@wendellhu/redi';import { BehaviorSubject } from 'rxjs';@@ -53,6 +54,7 @@ import type {} from './type';import { COPY_TYPE } from './type';import { USMToHtmlService } from './usm-to-html/convertor';+import { clipboardItemIsFromExcel } from './utils';export const PREDEFINED_HOOK_NAME = {DEFAULT_COPY: 'default-copy',@@ -102,7 +104,10 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard@IUndoRedoService private readonly _undoRedoService: IUndoRedoService,@ICommandService private readonly _commandService: ICommandService,@IMarkSelectionService private readonly _markSelectionService: IMarkSelectionService,- @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,+ @INotificationService private readonly _notificationService: INotificationService,+ @IPlatformService private readonly _platformService: IPlatformService,+ @Inject(LocaleService) private readonly _localeService: LocaleService) {super();this._htmlToUSM = new HtmlToUSMService({@@ -177,8 +182,16 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard: '';if (html) {- // Firstly see if the html content is in good format.- // In another word, if it is copied from any spreadsheet apps (including Univer itself).+ // Firstly see if the html content is from Excel+ if (this._platformService.isWindows && (await clipboardItemIsFromExcel(html))) {+ this._notificationService.show({+ type: 'warning',+ title: this._localeService.t('clipboard.shortCutNotify.title'),+ content: this._localeService.t('clipboard.shortCutNotify.useShortCutInstead'),+ });+ return false;+ }+return this._pasteHTML(html, pasteType);}diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.tsindex 1c56e7f254..fcf5bb7ef1 100644--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts@@ -81,13 +81,24 @@ export class HtmlToUSMService {private afterProcessRules: IAfterProcessRule[] = [];+ private htmlElement: HTMLIFrameElement;+private getCurrentSkeleton: () => Nullable<ISheetSkeletonManagerParam>;constructor(props: IHtmlToUSMServiceProps) {this.getCurrentSkeleton = props.getCurrentSkeleton;+ this.htmlElement = document.createElement('iframe');+ document.body.appendChild(this.htmlElement);}convert(html: string): IUniverSheetCopyDataModel {+ if (this.htmlElement.contentDocument) {+ this.htmlElement.contentDocument.open();+ this.htmlElement.contentDocument.write(html);+ this.htmlElement.contentDocument.close();+ }+ html = html.replace(/<!--[\s\S]*?-->/g, '');+const pastePlugin = HtmlToUSMService.pluginList.find((plugin) => plugin.checkPasteType(html));if (pastePlugin) {this.styleRules = [...pastePlugin.stylesRules];@@ -221,8 +232,43 @@ export class HtmlToUSMService {const { rowProperties, rowCount, cellMatrix: parsedCellMatrix } = parseTableRows(html);parsedCellMatrix &&parsedCellMatrix.forValue((row, col, value) => {+ let styleString = value.properties?.style;// TODO@Dushusir Temporarily use handleStringToStyle. After all replication and paste function is completed, fix the handleStringToStyle method- const style = handleStringToStyle(undefined, value.properties?.style);++ const className = value.properties?.class;+ if (className) {+ const dom = this.htmlElement.contentDocument?.getElementsByClassName(className)?.[0];+ if (dom) {+ const computedStyle = window.getComputedStyle(dom!, null);++ const { fontSize, fontFamily, border, borderLeft, borderRight, borderTop, borderBottom, verticalAlign } = computedStyle;+ if (fontSize) {+ styleString += `;font-size: ${Number.parseInt(fontSize) * 0.75}pt`;+ }+ if (fontFamily) {+ styleString += `;font-family: ${fontFamily}`;+ }+ if (border) {+ styleString += `;border: ${border}`;+ }+ if (borderLeft) {+ styleString += `;border-left: ${borderLeft}`;+ }+ if (borderRight) {+ styleString += `;border-right: ${borderRight}`;+ }+ if (borderTop) {+ styleString += `;border-top: ${borderTop}`;+ }+ if (borderBottom) {+ styleString += `;border-bottom: ${borderBottom}`;+ }+ if (verticalAlign) {+ styleString += `;vertical-align: ${verticalAlign}`;+ }+ }+ }+ const style = handleStringToStyle(undefined, styleString);if (/\r|\n/.test(value.content)) {const body = generateBody(value.content);@@ -436,13 +482,16 @@ function parseProperties(propertyStr: string): IClipboardPropertyItem {return {};}- const PROPERTY_REGEX = /([\w-]+)="([^"]*)"/gi;- const propertyMatches = propertyStr.matchAll(PROPERTY_REGEX);const property: IClipboardPropertyItem = {};- Array.from(propertyMatches).forEach((m) => {- const [_, key, val] = m;- property[key] = val;- });+ const PROPERTY_REGEX = /([\w-]+)\s*=\s*(?:(['"])([^'"]*)\2|(\S+))/g;++ let match;++ while ((match = PROPERTY_REGEX.exec(propertyStr)) !== null) {+ const [, attributeName, , attributeValue1, attributeValue2] = match;+ const attributeValue = attributeValue1 !== undefined ? attributeValue1 : attributeValue2;+ property[attributeName] = attributeValue;+ }return property;}diff --git a/packages/sheets-ui/src/services/clipboard/utils.ts b/packages/sheets-ui/src/services/clipboard/utils.tsindex d245ca5fd3..0d10e5627c 100644--- a/packages/sheets-ui/src/services/clipboard/utils.ts+++ b/packages/sheets-ui/src/services/clipboard/utils.ts@@ -90,3 +90,12 @@ export const getRepeatRange = (sourceRange: IRange, targetRang: IRange, isStrict}return repeatList;};++export async function clipboardItemIsFromExcel(html: string): Promise<boolean> {+ if (html) {+ const regex = /<td[^>]*class=".*?xl.*?"[^>]*>.*?<\/td>/;+ return regex.test(html);+ }++ return false;+}diff --git a/packages/ui/src/controllers/shared-shortcut.controller.ts b/packages/ui/src/controllers/shared-shortcut.controller.tsindex a5f89a19e2..7dab503684 100644--- a/packages/ui/src/controllers/shared-shortcut.controller.ts+++ b/packages/ui/src/controllers/shared-shortcut.controller.ts@@ -23,7 +23,6 @@ import { KeyCode, MetaKeys } from '../services/shortcut/keycode';import type { IShortcutItem } from '../services/shortcut/shortcut.service';import { IShortcutService } from '../services/shortcut/shortcut.service';import { IClipboardInterfaceService } from '../services/clipboard/clipboard-interface.service';-import { supportClipboardAPI } from '../services/clipboard/clipboard-utils';import { SetEditorResizeOperation } from '../commands/operations/editor/set-editor-resize.operation';import { RedoMenuItemFactory, UndoMenuItemFactory } from './menus/menus';@@ -36,7 +35,6 @@ export const CopyShortcutItem: IShortcutItem = {description: 'shortcut.copy',group: '1_common-edit',binding: KeyCode.C | MetaKeys.CTRL_COMMAND,- // preconditions: supportClipboardAPI,};export const CutShortcutItem: IShortcutItem = {@@ -44,17 +42,29 @@ export const CutShortcutItem: IShortcutItem = {description: 'shortcut.cut',group: '1_common-edit',binding: KeyCode.X | MetaKeys.CTRL_COMMAND,- // preconditions: supportClipboardAPI,};-export const PasteShortcutItem: IShortcutItem = {+/**+ * This shortcut item is just for displaying shortcut info, do not use it.+ */+export const OnlyDisplayPasteShortcutItem: IShortcutItem = {id: PasteCommand.id,description: 'shortcut.paste',group: '1_common-edit',binding: KeyCode.V | MetaKeys.CTRL_COMMAND,- preconditions: supportClipboardAPI,+ preconditions: () => false,};+// For compatibility issues, paste from the shortcut should always go with the native paste event,+// see #1404.+// export const PasteShortcutItem: IShortcutItem = {+// id: PasteCommand.id,+// description: 'shortcut.paste',+// group: '1_common-edit',+// binding: KeyCode.V | MetaKeys.CTRL_COMMAND,+// preconditions: supportClipboardAPI,+// };+export const UndoShortcutItem: IShortcutItem = {id: UndoCommand.id,description: 'shortcut.undo',@@ -106,7 +116,7 @@ export class SharedController extends Disposable {private _registerShortcuts(): void {const shortcutItems = [UndoShortcutItem, RedoShortcutItem];- shortcutItems.push(CutShortcutItem, CopyShortcutItem, PasteShortcutItem);+ shortcutItems.push(CutShortcutItem, CopyShortcutItem, OnlyDisplayPasteShortcutItem);shortcutItems.forEach((shortcut) => this.disposeWithMe(this._shortcutService.registerShortcut(shortcut)));}diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex 50e758614c..6be7537f86 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -22,7 +22,6 @@ export { useObservable } from './components/hooks/observable';export {CopyShortcutItem,CutShortcutItem,- PasteShortcutItem,RedoShortcutItem,SharedController,UndoShortcutItem,