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(clipboard): support copy paste on firefox (#1300)
Wenzhao Hu694f793735bd
diff --git a/packages/engine-render/src/components/docs/text-selection-render-manager.ts b/packages/engine-render/src/components/docs/text-selection-render-manager.tsindex 3bcb07c736..7a5790aead 100644--- a/packages/engine-render/src/components/docs/text-selection-render-manager.ts+++ b/packages/engine-render/src/components/docs/text-selection-render-manager.ts@@ -18,7 +18,7 @@ import type { Nullable, Observer } from '@univerjs/core';import { DataStreamTreeTokenType, ILogService, RxDisposable } from '@univerjs/core';import { createIdentifier } from '@wendellhu/redi';import type { Observable } from 'rxjs';-import { BehaviorSubject } from 'rxjs';+import { BehaviorSubject, Subject } from 'rxjs';import { CURSOR_TYPE } from '../../basics/const';import type { IDocumentSkeletonSpan } from '../../basics/i-document-skeleton-cached';@@ -181,39 +181,30 @@ export interface IEditorInputConfig {export class TextSelectionRenderManager extends RxDisposable implements ITextSelectionRenderManager {private readonly _onInputBefore$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);-readonly onInputBefore$ = this._onInputBefore$.asObservable();private readonly _onKeydown$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);-readonly onKeydown$ = this._onKeydown$.asObservable();private readonly _onInput$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);-readonly onInput$ = this._onInput$.asObservable();private readonly _onCompositionstart$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);-readonly onCompositionstart$ = this._onCompositionstart$.asObservable();private readonly _onCompositionupdate$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);-readonly onCompositionupdate$ = this._onCompositionupdate$.asObservable();private readonly _onCompositionend$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);-readonly onCompositionend$ = this._onCompositionend$.asObservable();private readonly _onSelectionStart$ = new BehaviorSubject<Nullable<INodePosition>>(null);-readonly onSelectionStart$ = this._onSelectionStart$.asObservable();- private readonly _onPaste$ = new BehaviorSubject<Nullable<IEditorInputConfig>>(null);-+ private readonly _onPaste$ = new Subject<Nullable<IEditorInputConfig>>();readonly onPaste$ = this._onPaste$.asObservable();private readonly _textSelectionInner$ = new BehaviorSubject<Nullable<ITextSelectionInnerParam>>(null);-readonly textSelectionInner$ = this._textSelectionInner$.asObservable();private _container!: HTMLDivElement;@@ -1002,6 +993,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel});}+ // FIXME: listeners here are not correctly disposedprivate _initInputEvents() {this._input.addEventListener('keydown', (e) => {if (this._isIMEInputApply) {diff --git a/packages/sheets-formula/src/controllers/menu.ts b/packages/sheets-formula/src/controllers/menu.tsindex c1180e2ff5..73a030ff8e 100644--- a/packages/sheets-formula/src/controllers/menu.ts+++ b/packages/sheets-formula/src/controllers/menu.ts@@ -18,8 +18,9 @@ import { UniverInstanceType } from '@univerjs/core';import { getCurrentSheetDisabled$ } from '@univerjs/sheets';import { PASTE_SPECIAL_MENU_ID } from '@univerjs/sheets-ui';import type { IMenuItem } from '@univerjs/ui';-import { getMenuHiddenObservable, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';+import { getMenuHiddenObservable, IClipboardInterfaceService, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';import type { IAccessor } from '@wendellhu/redi';+import { Observable } from 'rxjs';import { SheetOnlyPasteFormulaCommand } from '../commands/commands/formula-clipboard.command';import { InsertFunctionOperation } from '../commands/operations/insert-function.operation';@@ -65,7 +66,7 @@ export function InsertFunctionMenuItemFactory(accessor: IAccessor): IMenuItem {};}-export function MoreFunctionsMenuItemFactory(accessor: IAccessor): IMenuItem {+export function MoreFunctionsMenuItemFactory(): IMenuItem {return {id: MoreFunctionsOperation.id,title: 'formula.insert.more',@@ -74,11 +75,16 @@ export function MoreFunctionsMenuItemFactory(accessor: IAccessor): IMenuItem {};}+function menuClipboardDisabledObservable(injector: IAccessor): Observable<boolean> {+ return new Observable((subscriber) => subscriber.next(!injector.get(IClipboardInterfaceService).supportClipboard));+}+export function PasteFormulaMenuItemFactory(accessor: IAccessor): IMenuItem {return {id: SheetOnlyPasteFormulaCommand.id,type: MenuItemType.BUTTON,title: 'formula.operation.pasteFormula',positions: [PASTE_SPECIAL_MENU_ID],+ disabled$: menuClipboardDisabledObservable(accessor),};}diff --git a/packages/sheets-ui/src/commands/commands/clipboard.command.ts b/packages/sheets-ui/src/commands/commands/clipboard.command.tsindex 655226131e..6bd2332c54 100644--- a/packages/sheets-ui/src/commands/commands/clipboard.command.ts+++ b/packages/sheets-ui/src/commands/commands/clipboard.command.ts@@ -19,7 +19,7 @@ import { CommandType, ICommandService, ILogService } from '@univerjs/core';import { CopyCommand, CutCommand, IClipboardInterfaceService, PasteCommand } from '@univerjs/ui';import type { IAccessor } from '@wendellhu/redi';-import { whenSheetFocused } from '../../controllers/shortcuts/utils';+import { whenSheetEditorFocused, whenSheetFocused } from '../../controllers/shortcuts/utils';import { ISheetClipboardService, PREDEFINED_HOOK_NAME } from '../../services/clipboard/clipboard.service';export const SheetCopyCommand: IMultiCommand = {@@ -41,7 +41,7 @@ export const SheetCutCommand: IMultiCommand = {type: CommandType.COMMAND,multi: true,priority: 1000,- preconditions: whenSheetFocused,+ preconditions: whenSheetEditorFocused,handler: async (accessor) => {const sheetClipboardService = accessor.get(ISheetClipboardService);return sheetClipboardService.cut();@@ -58,19 +58,19 @@ export const SheetPasteCommand: IMultiCommand = {multi: true,name: 'sheet.command.paste',priority: 998,- preconditions: whenSheetFocused,+ preconditions: whenSheetEditorFocused,handler: async (accessor: IAccessor, params: ISheetPasteParams) => {const logService = accessor.get(ILogService);// 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.log('[SheetPasteCommand]', 'the focusing element is', document.activeElement);+ logService.debug('[SheetPasteCommand]', 'the focusing element is', document.activeElement);const result = document.execCommand('paste');if (!result) {- logService.log(+ logService.debug('[SheetPasteCommand]','failed to execute paste command on the activeElement, trying to use clipboard API.');diff --git a/packages/sheets-ui/src/commands/operations/activate-cell-edit.operation.ts b/packages/sheets-ui/src/commands/operations/activate-cell-edit.operation.tsindex 28b84b96d1..64b44bb03d 100644--- a/packages/sheets-ui/src/commands/operations/activate-cell-edit.operation.ts+++ b/packages/sheets-ui/src/commands/operations/activate-cell-edit.operation.ts@@ -25,9 +25,7 @@ export const SetActivateCellEditOperation: IOperation<ICurrentEditCellParam> = {type: CommandType.OPERATION,handler: (accessor, params) => {const editorBridgeService = accessor.get(IEditorBridgeService);-editorBridgeService.setEditCell(params);-return true;},};diff --git a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.tsindex 445785c0e3..eb992a67bc 100644--- a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts+++ b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts@@ -29,15 +29,16 @@ import {BooleanNumber,DEFAULT_WORKSHEET_COLUMN_WIDTH,DEFAULT_WORKSHEET_ROW_HEIGHT,- Disposable,handleStyleToString,ICommandService,IConfigService,+ IContextService,IUniverInstanceService,LifecycleStages,LocaleService,ObjectMatrix,OnLifecycle,+ RxDisposable,} from '@univerjs/core';import { MessageType } from '@univerjs/design';import type {@@ -56,9 +57,11 @@ import {SetWorksheetColWidthMutation,SetWorksheetRowHeightMutation,} from '@univerjs/sheets';-import { IMessageService, textTrim } from '@univerjs/ui';-import { Inject, Injector } from '@wendellhu/redi';+import { IClipboardInterfaceService, IMessageService, textTrim } from '@univerjs/ui';+import { Inject, Injector, Optional } from '@wendellhu/redi';+import { ITextSelectionRenderManager } from '@univerjs/engine-render';+import { takeUntil } from 'rxjs';import {SheetCopyCommand,SheetCutCommand,@@ -77,6 +80,7 @@ import type {ISheetRangeLocation,} from '../../services/clipboard/type';import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';+import { whenSheetEditorFocused } from '../shortcuts/utils';import {generateBody,getClearAndSetMergeMutations,@@ -90,21 +94,40 @@ import {* This controller add basic clipboard logic for basic features such as text color / BISU / row widths to the clipboard* service. You can create a similar clipboard controller to add logic for your own features.*/-@OnLifecycle(LifecycleStages.Ready, SheetClipboardController)-export class SheetClipboardController extends Disposable {+@OnLifecycle(LifecycleStages.Steady, SheetClipboardController)+export class SheetClipboardController extends RxDisposable {constructor(+ @Inject(Injector) private readonly _injector: Injector,@IUniverInstanceService private readonly _currentUniverSheet: IUniverInstanceService,@ICommandService private readonly _commandService: ICommandService,+ @IContextService private readonly _contextService: IContextService,@IConfigService private readonly _configService: IConfigService,@ISheetClipboardService private readonly _sheetClipboardService: ISheetClipboardService,+ @IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService,@IMessageService private readonly _messageService: IMessageService,@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,- @Inject(Injector) private readonly _injector: Injector,- @Inject(LocaleService) private readonly _localService: LocaleService+ @Inject(LocaleService) private readonly _localService: LocaleService,+ @Optional(ITextSelectionRenderManager) private readonly _textSelectionRenderManager?: ITextSelectionRenderManager) {super();- // this._commandExecutedListener();+this._init();++ if (!this._clipboardInterfaceService.supportClipboard) {+ this._textSelectionRenderManager?.onPaste$.pipe(takeUntil(this.dispose$)).subscribe((config) => {+ if (whenSheetEditorFocused(this._contextService) === false) {+ return;+ }++ // 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);+ });+ }}private _init() {@@ -119,6 +142,7 @@ export class SheetClipboardController extends Disposable {SheetPasteColWidthCommand,SheetPasteBesidesBorderCommand,].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));+// register basic sheet clipboard hooksthis.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._initCopyingHooks()));this.disposeWithMe(this._sheetClipboardService.addClipboardHook(this._initPastingHook()));diff --git a/packages/sheets-ui/src/controllers/menu/menu.ts b/packages/sheets-ui/src/controllers/menu/menu.tsindex febc0beb69..d8cc5f103c 100644--- a/packages/sheets-ui/src/controllers/menu/menu.ts+++ b/packages/sheets-ui/src/controllers/menu/menu.ts@@ -61,6 +61,7 @@ import {FONT_FAMILY_LIST,FONT_SIZE_LIST,getMenuHiddenObservable,+ IClipboardInterfaceService,MenuGroup,MenuItemType,MenuPosition,@@ -811,7 +812,11 @@ export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuSelectorIte}// #region - copy cut paste-// TODO@wzhudev: maybe we should move these menu factory to base-ui+// TODO@wzhudev: maybe we should move these menu factory to @univerjs/ui++function menuClipboardDisabledObservable(injector: IAccessor): Observable<boolean> {+ return new Observable((subscriber) => subscriber.next(!injector.get(IClipboardInterfaceService).supportClipboard));+}export function CopyMenuItemFactory(): IMenuButtonItem {return {@@ -842,13 +847,14 @@ export function CutMenuItemFactory(): IMenuButtonItem {};}-export function PasteMenuItemFactory(): IMenuButtonItem {+export function PasteMenuItemFactory(accessor: IAccessor): IMenuButtonItem {return {id: PasteCommand.id,group: MenuGroup.CONTEXT_MENU_FORMAT,type: MenuItemType.BUTTON,title: 'rightClick.paste',icon: 'PasteSpecial',+ disabled$: menuClipboardDisabledObservable(accessor),positions: [MenuPosition.CONTEXT_MENU,SheetMenuPosition.COL_HEADER_CONTEXT_MENU,@@ -858,13 +864,14 @@ export function PasteMenuItemFactory(): IMenuButtonItem {}export const PASTE_SPECIAL_MENU_ID = 'sheet.menu.paste-special';-export function PasteSpacialMenuItemFactory(): IMenuSelectorItem {+export function PasteSpacialMenuItemFactory(accessor: IAccessor): IMenuSelectorItem {return {id: PASTE_SPECIAL_MENU_ID,group: MenuGroup.CONTEXT_MENU_FORMAT,type: MenuItemType.SUBITEMS,icon: 'PasteSpecial',title: 'rightClick.pasteSpecial',+ disabled$: menuClipboardDisabledObservable(accessor),positions: [MenuPosition.CONTEXT_MENU,SheetMenuPosition.COL_HEADER_CONTEXT_MENU,@@ -873,39 +880,43 @@ export function PasteSpacialMenuItemFactory(): IMenuSelectorItem {};}-export function PasteValueMenuItemFactory(): IMenuButtonItem<string> {+export function PasteValueMenuItemFactory(accessor: IAccessor): IMenuButtonItem<string> {return {id: SheetPasteValueCommand.id,type: MenuItemType.BUTTON,title: 'rightClick.pasteValue',positions: [PASTE_SPECIAL_MENU_ID],+ disabled$: menuClipboardDisabledObservable(accessor),};}-export function PasteFormatMenuItemFactory(): IMenuButtonItem<string> {+export function PasteFormatMenuItemFactory(accessor: IAccessor): IMenuButtonItem<string> {return {id: SheetPasteFormatCommand.id,type: MenuItemType.BUTTON,title: 'rightClick.pasteFormat',positions: [PASTE_SPECIAL_MENU_ID],+ disabled$: menuClipboardDisabledObservable(accessor),};}-export function PasteColWidthMenuItemFactory(): IMenuButtonItem<string> {+export function PasteColWidthMenuItemFactory(accessor: IAccessor): IMenuButtonItem<string> {return {id: SheetPasteColWidthCommand.id,type: MenuItemType.BUTTON,title: 'rightClick.pasteColWidth',positions: [PASTE_SPECIAL_MENU_ID],+ disabled$: menuClipboardDisabledObservable(accessor),};}-export function PasteBesidesBorderMenuItemFactory(): IMenuButtonItem<string> {+export function PasteBesidesBorderMenuItemFactory(accessor: IAccessor): IMenuButtonItem<string> {return {id: SheetPasteBesidesBorderCommand.id,type: MenuItemType.BUTTON,title: 'rightClick.pasteBesidesBorder',positions: [PASTE_SPECIAL_MENU_ID],+ disabled$: menuClipboardDisabledObservable(accessor),};}diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.tsindex 10b2137e2e..21837a3504 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts@@ -114,7 +114,7 @@ describe('Test clipboard', () => {};// read use mockconst clipboardData = {- 'text/html': `<google-sheets-html-origin><table xmlns="http://www.w3.org/1999/xhtml" cellspacing="0" cellpadding="0" dir="ltr" border="1" style="table-layout:fixed;font-size:10pt;font-family:Arial;width:0px;border-collapse:collapse;border:none"><colgroup><col width="73"><col width="73"></colgroup><tbody><tr style="height: 81px;"><td rowspan="1" colspan="2" style="background: rgb(255,0,0); text-align: center; vertical-align: middle; text-decoration:none;">row1col2</td></tr></tbody></table></google-sheets-html-origin>`,+ 'text/html': '<google-sheets-html-origin><table xmlns="http://www.w3.org/1999/xhtml" cellspacing="0" cellpadding="0" dir="ltr" border="1" style="table-layout:fixed;font-size:10pt;font-family:Arial;width:0px;border-collapse:collapse;border:none"><colgroup><col width="73"><col width="73"></colgroup><tbody><tr style="height: 81px;"><td rowspan="1" colspan="2" style="background: rgb(255,0,0); text-align: center; vertical-align: middle; text-decoration:none;">row1col2</td></tr></tbody></table></google-sheets-html-origin>',};const mockClipboard = new MockClipboard(clipboardData);const clipboardItems = await mockClipboard.read();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 67bc902028..16420694d0 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@@ -34,267 +34,267 @@ import { SheetSkeletonManagerService } from '../../sheet-skeleton-manager.servicimport { ISheetClipboardService, SheetClipboardService } from '../clipboard.service';const cellData = {- '0': {- '7': {+ 0: {+ 7: {v: ' ',s: 'u5otPe',},- '8': {+ 8: {v: ' ',s: 'u5otPe',},- '10': {+ 10: {v: '456',s: '3UpAbI',},- '11': {+ 11: {s: '3UpAbI',},},- '1': {- '5': {+ 1: {+ 5: {v: ' ',s: 'u5otPe',},- '6': {+ 6: {v: ' ',s: 'u5otPe',},- '7': {+ 7: {v: ' ',s: 'u5otPe',},- '8': {+ 8: {v: ' ',s: 'u5otPe',},},- '2': {- '8': {+ 2: {+ 8: {v: ' ',s: 'u5otPe',},},- '3': {- '5': {+ 3: {+ 5: {v: ' ',s: 'u5otPe',},- '6': {+ 6: {v: ' ',s: 'u5otPe',},- '7': {+ 7: {v: ' ',s: 'u5otPe',},- '8': {+ 8: {v: ' ',s: 'u5otPe',},- '10': {+ 10: {s: '3UpAbI',v: '456',},- '11': {+ 11: {s: '3UpAbI',},- '12': {+ 12: {s: '3UpAbI',},},- '5': {- '5': {+ 5: {+ 5: {v: ' ',s: 'u5otPe',},- '6': {+ 6: {v: ' ',s: 'u5otPe',},- '7': {+ 7: {v: ' ',s: 'u5otPe',},- '8': {+ 8: {v: ' ',s: 'u5otPe',},},- '6': {- '7': {+ 6: {+ 7: {v: ' ',s: 'u5otPe',},- '8': {+ 8: {v: ' ',s: 'u5otPe',},- '10': {+ 10: {v: '456',s: 'hw-erj',},- '11': {+ 11: {s: 'hw-erj',},},- '7': {- '7': {+ 7: {+ 7: {v: ' ',s: 'u5otPe',},- '8': {+ 8: {v: ' ',s: 'u5otPe',},},- '8': {- '5': {+ 8: {+ 5: {v: ' ',s: 'u5otPe',},- '6': {+ 6: {v: ' ',s: 'u5otPe',},- '7': {+ 7: {v: ' ',s: 'u5otPe',},- '8': {+ 8: {v: ' ',s: 'u5otPe',},- '11': {+ 11: {v: '456',s: '_aRLOe',},- '12': {+ 12: {s: '_aRLOe',},},- '9': {- '7': {+ 9: {+ 7: {v: ' ',s: 'u5otPe',},- '8': {+ 8: {v: ' ',s: 'u5otPe',},- '11': {+ 11: {s: '_aRLOe',},- '12': {+ 12: {s: '_aRLOe',},},- '10': {- '5': {+ 10: {+ 5: {v: ' ',s: 'u5otPe',},- '6': {+ 6: {v: ' ',s: 'u5otPe',},- '7': {+ 7: {v: ' ',s: 'u5otPe',},- '8': {+ 8: {v: ' ',s: 'u5otPe',},},- '11': {- '8': {+ 11: {+ 8: {v: ' ',s: 'u5otPe',},- '10': {+ 10: {v: '456',s: 'Mtn4vb',},- '11': {+ 11: {s: 'Mtn4vb',},- '12': {+ 12: {s: 'Mtn4vb',},},- '12': {- '8': {+ 12: {+ 8: {v: ' ',s: 'u5otPe',},},- '13': {- '11': {+ 13: {+ 11: {v: '456',s: '3UpAbI',},- '12': {+ 12: {s: '3UpAbI',},},- '14': {- '11': {+ 14: {+ 11: {s: '3UpAbI',},- '12': {+ 12: {s: '3UpAbI',},},- '16': {- '10': {+ 16: {+ 10: {v: '456',s: '3UpAbI',},- '11': {+ 11: {s: '3UpAbI',},},- '17': {- '11': {+ 17: {+ 11: {v: '456',s: '3UpAbI',},- '12': {+ 12: {s: '3UpAbI',},},- '18': {- '11': {+ 18: {+ 11: {s: '3UpAbI',},- '12': {+ 12: {s: '3UpAbI',},},- '21': {- '10': {+ 21: {+ 10: {v: '456',s: '3UpAbI',},- '11': {+ 11: {s: '3UpAbI',},},- '22': {- '10': {+ 22: {+ 10: {s: '3UpAbI',},- '11': {+ 11: {s: '3UpAbI',},},- '23': {- '11': {+ 23: {+ 11: {v: '456',s: '3UpAbI',},- '12': {+ 12: {s: '3UpAbI',},},diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.tsindex a704c5a6c0..aec5b4db19 100644--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts@@ -73,6 +73,7 @@ export interface ISheetClipboardService {copy(): Promise<boolean>;cut(): Promise<boolean>;paste(item: ClipboardItem, pasteType?: string): Promise<boolean>;+ legacyPaste(html?: string, text?: string): Promise<boolean>;addClipboardHook(hook: ISheetClipboardHook): IDisposable;getClipboardHooks(): ISheetClipboardHook[];@@ -210,6 +211,16 @@ export class SheetClipboardService extends Disposable implements ISheetClipboardreturn false;}+ legacyPaste(html?: string, text?: string): Promise<boolean> {+ if (html) {+ return this._pasteHTML(html, PREDEFINED_HOOK_NAME.DEFAULT_PASTE);+ } else if (text) {+ return this._pastePlainText(text, PREDEFINED_HOOK_NAME.DEFAULT_PASTE);+ }++ return Promise.resolve(false);+ }+addClipboardHook(hook: ISheetClipboardHook): IDisposable {if (this._clipboardHooks.findIndex((h) => h.id === hook.id) !== -1) {this._logService.error('[SheetClipboardService]', 'hook already exists', hook.id);diff --git a/packages/ui/src/controllers/shared-shortcut.controller.ts b/packages/ui/src/controllers/shared-shortcut.controller.tsindex 0892a6b379..e12f2786c0 100644--- a/packages/ui/src/controllers/shared-shortcut.controller.ts+++ b/packages/ui/src/controllers/shared-shortcut.controller.ts@@ -22,13 +22,20 @@ import { IMenuService } from '../services/menu/menu.service';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 { RedoMenuItemFactory, UndoMenuItemFactory } from './menus/menus';+// Not that the clipboard shortcut items would only be invoked when the browser fully supports clipboard API.+// If not, the corresponding shortcut would not be triggered and we will perform clipboard operations+// through clipboard events (editorElement.addEventListener('paste')).+export const CopyShortcutItem: IShortcutItem = {id: CopyCommand.id,description: 'shortcut.copy',group: '1_common-edit',binding: KeyCode.C | MetaKeys.CTRL_COMMAND,+ // preconditions: supportClipboardAPI,};export const CutShortcutItem: IShortcutItem = {@@ -36,6 +43,7 @@ export const CutShortcutItem: IShortcutItem = {description: 'shortcut.cut',group: '1_common-edit',binding: KeyCode.X | MetaKeys.CTRL_COMMAND,+ // preconditions: supportClipboardAPI,};export const PasteShortcutItem: IShortcutItem = {@@ -43,6 +51,7 @@ export const PasteShortcutItem: IShortcutItem = {description: 'shortcut.paste',group: '1_common-edit',binding: KeyCode.V | MetaKeys.CTRL_COMMAND,+ preconditions: supportClipboardAPI,};export const UndoShortcutItem: IShortcutItem = {@@ -60,7 +69,7 @@ export const RedoShortcutItem: IShortcutItem = {};/**- * Define shared UI behavior across Univer business.+ * Define shared UI behavior across Univer business. Including undo / redo and clipboard operations.*/@OnLifecycle(LifecycleStages.Ready, SharedController)export class SharedController extends Disposable {@@ -68,7 +77,8 @@ export class SharedController extends Disposable {@Inject(Injector) private readonly _injector: Injector,@IMenuService private readonly _menuService: IMenuService,@IShortcutService private readonly _shortcutService: IShortcutService,- @ICommandService private readonly _commandService: ICommandService+ @ICommandService private readonly _commandService: ICommandService,+ @IClipboardInterfaceService private readonly _interfaceService: IClipboardInterfaceService) {super();@@ -94,8 +104,9 @@ export class SharedController extends Disposable {}private _registerShortcuts(): void {- [UndoShortcutItem, RedoShortcutItem, CutShortcutItem, CopyShortcutItem, PasteShortcutItem].forEach((shortcut) =>- this.disposeWithMe(this._shortcutService.registerShortcut(shortcut))- );+ const shortcutItems = [UndoShortcutItem, RedoShortcutItem];+ shortcutItems.push(CutShortcutItem, CopyShortcutItem, PasteShortcutItem);++ shortcutItems.forEach((shortcut) => this.disposeWithMe(this._shortcutService.registerShortcut(shortcut)));}}diff --git a/packages/ui/src/locale/en-US.ts b/packages/ui/src/locale/en-US.tsindex af5f12d3c0..730caa1d4a 100644--- a/packages/ui/src/locale/en-US.ts+++ b/packages/ui/src/locale/en-US.ts@@ -53,4 +53,10 @@ export default {},'common-edit': 'Common Editing Shortcuts','toggle-shortcut-panel': 'Toggle Shortcut Panel',+ clipboard: {+ authentication: {+ title: 'Permission Denied',+ content: 'Please allow Univer to access your clipboard.',+ },+ },};diff --git a/packages/ui/src/locale/zh-CN.ts b/packages/ui/src/locale/zh-CN.tsindex 4a4deff95d..f37510d0d7 100644--- a/packages/ui/src/locale/zh-CN.ts+++ b/packages/ui/src/locale/zh-CN.ts@@ -53,4 +53,10 @@ export default {},'common-edit': '常用编辑','toggle-shortcut-panel': '打开收起快捷键面板',+ clipboard: {+ authentication: {+ title: '无法访问剪贴板',+ content: '请允许 Univer 访问您的剪贴板。',+ },+ },};diff --git a/packages/ui/src/services/clipboard/clipboard-interface.service.ts b/packages/ui/src/services/clipboard/clipboard-interface.service.tsindex 1f62b0a2e1..3da9f76df5 100644--- a/packages/ui/src/services/clipboard/clipboard-interface.service.ts+++ b/packages/ui/src/services/clipboard/clipboard-interface.service.ts@@ -14,8 +14,10 @@* limitations under the License.*/-import { Disposable } from '@univerjs/core';-import { createIdentifier } from '@wendellhu/redi';+import { Disposable, ILogService, LocaleService } from '@univerjs/core';+import { createIdentifier, Inject, Optional } from '@wendellhu/redi';++import { INotificationService } from '../notification/notification.service';export const PLAIN_TEXT_CLIPBOARD_MIME_TYPE = 'text/plain';export const HTML_CLIPBOARD_MIME_TYPE = 'text/html';@@ -29,6 +31,7 @@ export interface IClipboardInterfaceService {* @param text*/writeText(text: string): Promise<void>;+/*** Write both plain text and html into clipboard.* @param text@@ -41,12 +44,16 @@ export interface IClipboardInterfaceService {* @returns plain text*/readText(): Promise<string>;+/*** Read `ClipboardItem[]` from clipboard.*/read(): Promise<ClipboardItem[]>;- // NOTE: maybe we should add an interface to support image copy+ /**+ * This property tells if the platform supports reading data directly from the clipboard.+ */+ readonly supportClipboard: boolean;}export const IClipboardInterfaceService = createIdentifier<IClipboardInterfaceService>(@@ -54,7 +61,23 @@ export const IClipboardInterfaceService = createIdentifier<IClipboardInterfaceSe);export class BrowserClipboardService extends Disposable implements IClipboardInterfaceService {+ get supportClipboard(): boolean {+ return typeof window.navigator.clipboard.readText === 'function';+ }++ constructor(+ @Inject(LocaleService) private readonly _localeService: LocaleService,+ @ILogService private readonly _logService: ILogService,+ @Optional(INotificationService) private readonly _notificationService?: INotificationService+ ) {+ super();+ }+async write(text: string, html: string): Promise<void> {+ if (!this.supportClipboard) {+ return this._legacyCopyHtml(html);+ }+try {// write both pure text content and html content to the clipboardreturn await navigator.clipboard.write([@@ -64,54 +87,151 @@ export class BrowserClipboardService extends Disposable implements IClipboardInt}),]);} catch (error) {- console.error(error);+ this._logService.error('[BrowserClipboardService]', error);+ this._showClipboardAuthenticationNotification();}}async writeText(text: string): Promise<void> {+ if (!this.supportClipboard) {+ return this._legacyCopyText(text);+ }+// use new Clipboard API firsttry {return await navigator.clipboard.writeText(text);} catch (error) {- console.error(error);- }-- // fallback to traditional way- const activeElement = document.activeElement;- const container = createCopyPasteContainer();- container.value = text;- container.focus();- container.select();- document.body.appendChild(container);-- document.execCommand('copy');-- if (activeElement instanceof HTMLElement) {- activeElement.focus();+ this._logService.error('[BrowserClipboardService]', error);+ this._showClipboardAuthenticationNotification();}-- document.removeChild(container);}async read(): Promise<ClipboardItem[]> {- return navigator.clipboard.read();+ if (!this.supportClipboard) {+ throw new Error('[BrowserClipboardService] read() is not supported on this platform.');+ }++ try {+ return navigator.clipboard.read();+ } catch (e) {+ this._logService.error('[BrowserClipboardService]', e);+ this._showClipboardAuthenticationNotification();+ return [];+ }}async readText(): Promise<string> {+ if (!this.supportClipboard) {+ throw new Error('[BrowserClipboardService] read() is not supported on this platform.');+ }+try {return await navigator.clipboard.readText();} catch (e) {- console.error(e);-+ this._logService.error('[BrowserClipboardService]', e);+ this._showClipboardAuthenticationNotification();return '';}}++ private _legacyCopyHtml(html: string): void {+ const activeElement = document.activeElement;+ const container = createCopyHtmlContainer();+ document.body.appendChild(container);+ container.innerHTML = html; // TODO: wzhudev: sanitize html++ try {+ select(container);+ document.execCommand('copy');+ } finally {+ if (activeElement instanceof HTMLElement) {+ activeElement.focus();+ }++ document.body.removeChild(container);+ }+ }++ private _legacyCopyText(text: string): void {+ const activeElement = document.activeElement;+ const container = createCopyTextContainer();+ document.body.appendChild(container);+ container.value = text;++ try {+ select(container);+ document.execCommand('copy');+ } finally {+ // reset previous elements focus state+ if (activeElement instanceof HTMLElement) {+ activeElement.focus();+ }++ document.body.removeChild(container);+ }+ }++ private _showClipboardAuthenticationNotification(): void {+ this._notificationService?.show({+ type: 'warning',+ title: this._localeService.t('clipboard.authentication.title'),+ content: this._localeService.t('clipboard.authentication.content'),+ });+ }}-function createCopyPasteContainer() {+function createCopyTextContainer() {const textArea = document.createElement('textarea');textArea.style.position = 'absolute';textArea.style.height = '1px';textArea.style.width = '1px';+ textArea.style.opacity = '0';+ textArea.readOnly = true;return textArea;}++function createCopyHtmlContainer() {+ const div = document.createElement('div');+ div.contentEditable = 'true';+ div.style.position = 'absolute';+ div.style.opacity = '0';+ div.style.height = '1px';+ div.style.width = '1px';+ return div;+}++function select(element: HTMLTextAreaElement | HTMLDivElement): string {+ if (element instanceof HTMLTextAreaElement) {+ const isReadOnly = element.hasAttribute('readonly');++ if (!isReadOnly) {+ element.setAttribute('readonly', '');+ }++ element.select();+ element.setSelectionRange(0, element.value.length);++ if (!isReadOnly) {+ element.removeAttribute('readonly');+ }++ return element.value;+ }++ if (element.hasAttribute('contenteditable')) {+ element.focus();+ }++ const range = document.createRange();+ range.selectNodeContents(element);+ const selection = window.getSelection();++ if (!selection) {+ throw new Error();+ }++ selection.removeAllRanges();+ selection.addRange(range);++ return selection.toString();+}diff --git a/packages/ui/src/services/clipboard/clipboard-utils.ts b/packages/ui/src/services/clipboard/clipboard-utils.tsnew file mode 100644index 0000000000..19a7971fac--- /dev/null+++ b/packages/ui/src/services/clipboard/clipboard-utils.ts@@ -0,0 +1,25 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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.+ */++/**+ * This function is used to check if the system supports full clipboard API,+ * especially for the clipboard.readText() API.+ *+ * @returns if the system supports clipboard API+ */+export function supportClipboardAPI(): boolean {+ return typeof navigator.clipboard.readText !== 'undefined';+}diff --git a/packages/ui/src/services/shortcut/shortcut.service.ts b/packages/ui/src/services/shortcut/shortcut.service.tsindex 5803a17647..062c246d6b 100644--- a/packages/ui/src/services/shortcut/shortcut.service.ts+++ b/packages/ui/src/services/shortcut/shortcut.service.ts@@ -154,7 +154,7 @@ export class DesktopShortcutService extends Disposable implements IShortcutServiconst altKey = binding & MetaKeys.ALT;const macCtrl = binding & MetaKeys.MAC_CTRL;- const body = KeyCodeToChar[binding & 0xff] ?? '<->';+ const body = KeyCodeToChar[binding & 0xFF] ?? '<->';if (this._platformService.isMac) {return `${ctrlKey ? '⌘' : ''}${shiftKey ? '⇧' : ''}${altKey ? '⌥' : ''}${macCtrl ? '⌃' : ''}${body}`;