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
chore: add clipboard event & merge example (#4420)
ybzkyd477e5c17f36
diff --git a/packages/core/src/facade/f-univer.ts b/packages/core/src/facade/f-univer.tsindex 404b71297a..ad6e26e098 100644--- a/packages/core/src/facade/f-univer.ts+++ b/packages/core/src/facade/f-univer.ts@@ -222,7 +222,7 @@ export class FUniver extends FBaseInitialable {/*** Fire an event, used in internal only.* @param event {string} key of event- * @param params {any} parmas of event+ * @param params {any} params of event* @returns {boolean} should cancel* @example* ```ts@@ -237,6 +237,15 @@ export class FUniver extends FBaseInitialable {return params.cancel;}+ /**+ * Get the callback map corresponding to the event+ * @returns {number} The number of callbacks+ */+ protected hasEventCallback(event: keyof IEventParamConfig): boolean {+ const eventCallbackLens = this._eventRegistry.get(event)?.getData().length ?? 0;+ return eventCallbackLens > 0;+ }+getUserManager(): FUserManager {return this._injector.createInstance(FUserManager);}diff --git a/packages/sheets-ui/src/facade/f-event.ts b/packages/sheets-ui/src/facade/f-event.tsnew file mode 100644index 0000000000..989de2fe75--- /dev/null+++ b/packages/sheets-ui/src/facade/f-event.ts@@ -0,0 +1,158 @@+/**+ * 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.+ */++import type { IEventBase } from '@univerjs/core';+import type { FRange, FWorkbook, FWorksheet } from '@univerjs/sheets/facade';+import { FEventName } from '@univerjs/core';++interface IFSheetsUIEventNameMixin {+ /**+ * Trigger this event before the clipboard content changes.+ * Type of the event parameter is {@link IBeforeClipboardChangeParam}+ * @example+ * ```ts+ * univerAPI.addEvent(univerAPI.Event.BeforeClipboardChange, (param) => {+ * const {text, html} = param;+ * console.log('debugger', text, html); // {text: '...', html: '...'}+ * // if want to cancel the clipboard change+ * param.cancel = true;+ * })+ * ```+ */+ readonly BeforeClipboardChange: 'BeforeClipboardChange';++ /**+ * Trigger this event after the clipboard content changes.+ * Type of the event parameter is {@link IClipboardChangedParam}+ * @example+ * ```ts+ * univerAPI.addEvent(univerAPI.Event.ClipboardChanged, (param) => {+ * const {text, html} = param;+ * console.log('debugger', text, html); // {text: '...', html: '...'}+ * })+ * ```+ */+ readonly ClipboardChanged: 'ClipboardChanged';+ /**+ * Trigger this event before pasting.+ * Type of the event parameter is {@link IBeforeClipboardPasteParam}+ * @example+ * ```ts+ * univerAPI.addEvent(univerAPI.Event.BeforeClipboardPaste, (param) => {+ * const {text, html} = param;+ * console.log('debugger', text, html);+ * // if want to cancel the clipboard paste+ * param.cancel = true;+ * })+ * ```+ */+ readonly BeforeClipboardPaste: 'BeforeClipboardPaste';+ /**+ * Trigger this event after pasting.+ * Type of the event parameter is {@link IClipboardPastedParam}+ * @example+ * ```ts+ * univerAPI.addEvent(univerAPI.Event.ClipboardPasted, (param) => {+ * const {text, html} = param;+ * console.log('debugger', text, html); // {text: '...', html: '...'}+ * })+ * ```+ */+ readonly ClipboardPasted: 'ClipboardPasted';+}++export class FSheetsUIEventName extends FEventName implements IFSheetsUIEventNameMixin {+ override get BeforeClipboardChange(): 'BeforeClipboardChange' {+ return 'BeforeClipboardChange' as const;+ }++ override get ClipboardChanged(): 'ClipboardChanged' {+ return 'ClipboardChanged' as const;+ }++ override get BeforeClipboardPaste(): 'BeforeClipboardPaste' {+ return 'BeforeClipboardPaste' as const;+ }++ override get ClipboardPasted(): 'ClipboardPasted' {+ return 'ClipboardPasted' as const;+ }+}++export interface IBeforeClipboardChangeParam extends IEventBase {+ /**+ * The workbook instance currently being operated on. {@link FWorkbook}+ */+ workbook: FWorkbook;+ /**+ * The worksheet instance currently being operated on. {@link FWorksheet}+ */+ worksheet: FWorksheet;+ /**+ * Clipboard Text String+ */+ text: string;+ /**+ * Clipboard HTML String+ */+ html: string;+ /**+ * The sheet containing the content that was (copied/cut)+ */+ fromSheet: FWorksheet;+ /**+ * The range containing the content that was (copied/cut)+ */+ fromRange: FRange;+}++export type IClipboardChangedParam = IBeforeClipboardChangeParam;++export interface IBeforeClipboardPasteParam extends IEventBase {+ /**+ * The workbook instance currently being operated on. {@link FWorkbook}+ */+ workbook: FWorkbook;+ /**+ * The worksheet instance currently being operated on. {@link FWorkbook}+ */+ worksheet: FWorksheet;+ /**+ * Clipboard Text String+ */+ text?: string;+ /**+ * Clipboard HTML String+ */+ html?: string;+}++export type IClipboardPastedParam = IBeforeClipboardPasteParam;++interface IFSheetsUIEventParamConfig {+ BeforeClipboardChange: IBeforeClipboardChangeParam;+ ClipboardChanged: IClipboardChangedParam;+ BeforeClipboardPaste: IBeforeClipboardPasteParam;+ ClipboardPasted: IClipboardPastedParam;+}++FEventName.extend(FSheetsUIEventName);+declare module '@univerjs/core' {+ // eslint-disable-next-line ts/naming-convention+ interface FEventName extends IFSheetsUIEventNameMixin { }+ interface IEventParamConfig extends IFSheetsUIEventParamConfig { }+}+diff --git a/packages/sheets-ui/src/facade/f-univer.ts b/packages/sheets-ui/src/facade/f-univer.tsindex 2a83464511..cfe3439eb0 100644--- a/packages/sheets-ui/src/facade/f-univer.ts+++ b/packages/sheets-ui/src/facade/f-univer.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { IDisposable, Nullable } from '@univerjs/core';+import type { IDisposable, Injector, Nullable } from '@univerjs/core';import type {IColumnsHeaderCfgParam,IRowsHeaderCfgParam,@@ -24,10 +24,13 @@ import type {SpreadsheetColumnHeader,SpreadsheetRowHeader,} from '@univerjs/engine-render';-import { FUniver, toDisposable } from '@univerjs/core';+import type { ISheetPasteByShortKeyParams } from '@univerjs/sheets-ui';+import type { IBeforeClipboardChangeParam, IBeforeClipboardPasteParam } from './f-event';+import { FUniver, ICommandService, ILogService, toDisposable } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';-import { SHEET_VIEW_KEY } from '@univerjs/sheets-ui';+import { ISheetClipboardService, SHEET_VIEW_KEY, SheetPasteShortKeyCommand } from '@univerjs/sheets-ui';import { FSheetHooks } from '@univerjs/sheets/facade';+import { CopyCommand, CutCommand, HTML_CLIPBOARD_MIME_TYPE, IClipboardInterfaceService, PasteCommand, PLAIN_TEXT_CLIPBOARD_MIME_TYPE, supportClipboardAPI } from '@univerjs/ui';export interface IFUniverSheetsUIMixin {/**@@ -86,6 +89,201 @@ export interface IFUniverSheetsUIMixin {}export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMixin {+ override _initialize(injector: Injector): void {+ const commandService = injector.get(ICommandService);+ this.disposeWithMe(commandService.beforeCommandExecuted((commandInfo) => {+ switch (commandInfo.id) {+ case CopyCommand.id:+ case CutCommand.id:+ this._beforeClipboardChange();+ break;+ case SheetPasteShortKeyCommand.id:+ this._beforeClipboardPaste(commandInfo.params);+ break;+ }+ }));+ this.disposeWithMe(commandService.onCommandExecuted((commandInfo) => {+ switch (commandInfo.id) {+ case CopyCommand.id:+ case CutCommand.id:+ this._clipboardChanged();+ break;+ case SheetPasteShortKeyCommand.id:+ this._clipboardPaste();+ break;+ case PasteCommand.id:+ this._clipboardPasteAsync();+ break;+ }+ }));+ // async listeners+ this.disposeWithMe(commandService.beforeCommandExecuted(async (commandInfo) => {+ switch (commandInfo.id) {+ case PasteCommand.id:+ await this._beforeClipboardPasteAsync();+ break;+ }+ }));+ }++ private _generateClipboardCopyParam(): IBeforeClipboardChangeParam | undefined {+ const workbook = this.getActiveUniverSheet();+ const worksheet = workbook?.getActiveSheet();+ const range = workbook?.getActiveRange();+ if (!workbook || !worksheet || !range) {+ return;+ }++ const clipboardService = this._injector.get(ISheetClipboardService);+ const content = clipboardService.generateCopyContent(workbook.getId(), worksheet.getSheetId(), range.getRange());+ if (!content) {+ return;+ }+ const { html, plain } = content;+ const eventParams: IBeforeClipboardChangeParam = {+ workbook,+ worksheet,+ text: plain,+ html,+ fromSheet: worksheet,+ fromRange: range,+ };+ return eventParams;+ }++ private _beforeClipboardChange(): void {+ if (!this.hasEventCallback(this.Event.BeforeClipboardChange)) {+ return;+ }+ const eventParams = this._generateClipboardCopyParam();+ if (!eventParams) return;++ this.fireEvent(this.Event.BeforeClipboardChange, eventParams);+ if (eventParams.cancel) {+ throw new Error('Before clipboard change is canceled');+ }+ }++ private _clipboardChanged(): void {+ if (!this.hasEventCallback(this.Event.ClipboardChanged)) {+ return;+ }+ const eventParams = this._generateClipboardCopyParam();+ if (!eventParams) return;++ this.fireEvent(this.Event.ClipboardChanged, eventParams);+ if (eventParams.cancel) {+ throw new Error('Clipboard changed is canceled');+ }+ }++ private _generateClipboardPasteParam(params?: ISheetPasteByShortKeyParams): IBeforeClipboardPasteParam | undefined {+ if (!params) {+ return;+ }+ const { htmlContent, textContent } = params as ISheetPasteByShortKeyParams;+ const workbook = this.getActiveUniverSheet();+ const worksheet = workbook?.getActiveSheet();+ if (!workbook || !worksheet) {+ return;+ }+ const eventParams: IBeforeClipboardPasteParam = {+ workbook,+ worksheet,+ text: textContent,+ html: htmlContent,+ };+ return eventParams;+ }++ private async _generateClipboardPasteParamAsync(): Promise<IBeforeClipboardPasteParam | undefined> {+ const workbook = this.getActiveUniverSheet();+ const worksheet = workbook?.getActiveSheet();+ if (!workbook || !worksheet) {+ return;+ }+ const clipboardInterfaceService = this._injector.get(IClipboardInterfaceService);+ const clipboardItems = await clipboardInterfaceService.read();+ const item = clipboardItems[0];+ let eventParams;+ if (item) {+ const types = item.types;+ const text =+ types.indexOf(PLAIN_TEXT_CLIPBOARD_MIME_TYPE) !== -1+ ? await item.getType(PLAIN_TEXT_CLIPBOARD_MIME_TYPE).then((blob) => blob && blob.text())+ : '';+ const html =+ types.indexOf(HTML_CLIPBOARD_MIME_TYPE) !== -1+ ? await item.getType(HTML_CLIPBOARD_MIME_TYPE).then((blob) => blob && blob.text())+ : '';+ eventParams = {+ workbook,+ worksheet,+ text,+ html,+ };+ }+ return eventParams;+ }++ private _beforeClipboardPaste(params?: ISheetPasteByShortKeyParams): void {+ if (!this.hasEventCallback(this.Event.BeforeClipboardPaste)) {+ return;+ }+ const eventParams = this._generateClipboardPasteParam(params);+ if (!eventParams) return;+ this.fireEvent(this.Event.BeforeClipboardPaste, eventParams);+ if (eventParams.cancel) {+ throw new Error('Before clipboard paste is canceled');+ }+ }++ private _clipboardPaste(params?: ISheetPasteByShortKeyParams): void {+ if (!this.hasEventCallback(this.Event.BeforeClipboardPaste)) {+ return;+ }+ const eventParams = this._generateClipboardPasteParam(params);+ if (!eventParams) return;+ this.fireEvent(this.Event.BeforeClipboardPaste, eventParams);+ if (eventParams.cancel) {+ throw new Error('Clipboard pasted is canceled');+ }+ }++ private async _beforeClipboardPasteAsync(): Promise<void> {+ if (!this.hasEventCallback(this.Event.BeforeClipboardPaste)) {+ return;+ }+ if (!supportClipboardAPI()) {+ const logService = this._injector.get(ILogService);+ logService.warn('[Facade]: The navigator object only supports the browser environment');+ return;+ }+ const eventParams = await this._generateClipboardPasteParamAsync();+ if (!eventParams) return;+ this.fireEvent(this.Event.BeforeClipboardPaste, eventParams);+ if (eventParams.cancel) {+ throw new Error('Before clipboard paste is canceled');+ }+ }++ private async _clipboardPasteAsync(): Promise<void> {+ if (!this.hasEventCallback(this.Event.ClipboardPasted)) {+ return;+ }+ if (!supportClipboardAPI()) {+ const logService = this._injector.get(ILogService);+ logService.warn('[Facade]: The navigator object only supports the browser environment');+ return;+ }+ const eventParams = await this._generateClipboardPasteParamAsync();+ if (!eventParams) return;+ this.fireEvent(this.Event.ClipboardPasted, eventParams);+ if (eventParams.cancel) {+ throw new Error('Clipboard pasted is canceled');+ }+ }+override customizeColumnHeader(cfg: IColumnsHeaderCfgParam): void {const wb = this.getActiveWorkbook();if (!wb) {diff --git a/packages/sheets-ui/src/facade/index.ts b/packages/sheets-ui/src/facade/index.tsindex 714b0c8c7f..04356ee417 100644--- a/packages/sheets-ui/src/facade/index.ts+++ b/packages/sheets-ui/src/facade/index.ts@@ -19,6 +19,7 @@ import './f-workbook';import './f-worksheet';import './f-permission';import './f-sheet-hooks';+import './f-event';export { type IFComponentKey, transformComponentKey } from './f-range';diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.tsindex ccfd0fe7a0..0c9ce39c52 100644--- a/packages/sheets-ui/src/index.ts+++ b/packages/sheets-ui/src/index.ts@@ -114,6 +114,7 @@ export { type IBaseSheetBarProps } from './views/sheet-bar/sheet-bar-tabs/SheetB// #region - all commandsexport { AutoClearContentCommand, AutoFillCommand } from './commands/commands/auto-fill.command';export {+ type ISheetPasteByShortKeyParams,type ISheetPasteParams,SheetCopyCommand,SheetCutCommand,diff --git a/packages/sheets/src/commands/commands/add-worksheet-merge.command.ts b/packages/sheets/src/commands/commands/add-worksheet-merge.command.tsindex b8ea1db23c..96ea7dac4d 100644--- a/packages/sheets/src/commands/commands/add-worksheet-merge.command.ts+++ b/packages/sheets/src/commands/commands/add-worksheet-merge.command.ts@@ -281,7 +281,7 @@ export function addMergeCellsUtil(injector: Injector, unitId: string, subUnitId:throw new Error('The ranges to be merged overlap with the existing merged cells');}const commandService = injector.get(ICommandService);- commandService.syncExecuteCommand(AddWorksheetMergeCommand.id, {+ commandService.executeCommand(AddWorksheetMergeCommand.id, {unitId,subUnitId,selections: ranges,diff --git a/packages/sheets/src/facade/f-permission.ts b/packages/sheets/src/facade/f-permission.tsindex 9157fc2242..8fe26731d7 100644--- a/packages/sheets/src/facade/f-permission.ts+++ b/packages/sheets/src/facade/f-permission.ts@@ -314,13 +314,4 @@ export class FPermission extends FBase {});}}-- /**- * Set visibility of unauthorized pop-up window- *- * @param {boolean} visible- */- setPermissionDialogVisible(visible: boolean): void {- this._permissionService.setShowComponents(visible);- }}diff --git a/packages/sheets/src/facade/f-range.ts b/packages/sheets/src/facade/f-range.tsindex 776e50911d..8620e4e2f2 100644--- a/packages/sheets/src/facade/f-range.ts+++ b/packages/sheets/src/facade/f-range.ts@@ -563,10 +563,17 @@ export class FRange extends FBaseInitialable {/*** Merge cells in a range into one merged cell- ** @param [defaultMerge] - If true, only the value in the upper left cell is retained.- ** @returns This range, for chaining+ * @example+ * ```ts+ * const workbook = univerAPI.getActiveWorkbook();+ * const worksheet = workbook.getActiveSheet();+ * const range = worksheet.getRange(0, 0, 2, 2);+ * const merge = range.merge();+ * const isMerged = merge.isMerged();+ * console.log('debugger', isMerged);+ * ```*/merge(defaultMerge: boolean = true): FRange {const unitId = this._workbook.getUnitId();@@ -579,10 +586,17 @@ export class FRange extends FBaseInitialable {/*** Merges cells in a range horizontally.- ** @param [defaultMerge] - If true, only the value in the upper left cell is retained.- ** @returns This range, for chaining+ * @example+ * ```ts+ * const workbook = univerAPI.getActiveWorkbook();+ * const worksheet = workbook.getActiveSheet();+ * const range = worksheet.getRange(2, 2, 2, 2);+ * const merge = range.mergeAcross();+ * const allMerge = worksheet.getMergeData();+ * console.log(allMerge.length); // There will be two merged cells.+ * ```*/mergeAcross(defaultMerge: boolean = true): FRange {const ranges = getAddMergeMutationRangeByType([this._range], Dimension.ROWS);@@ -596,10 +610,17 @@ export class FRange extends FBaseInitialable {/*** Merges cells in a range vertically.- ** @param [defaultMerge] - If true, only the value in the upper left cell is retained.- ** @returns This range, for chaining+ * @example+ * ```ts+ * const workbook = univerAPI.getActiveWorkbook();+ * const worksheet = workbook.getActiveSheet();+ * const range = worksheet.getRange(4, 4, 2, 2);+ * const merge = range.mergeVertically();+ * const allMerge = worksheet.getMergeData();+ * console.log(allMerge.length); // There will be two merged cells.+ * ```*/mergeVertically(defaultMerge: boolean = true): FRange {const ranges = getAddMergeMutationRangeByType([this._range], Dimension.COLUMNS);@@ -614,6 +635,16 @@ export class FRange extends FBaseInitialable {/*** Returns true if cells in the current range overlap a merged cell.* @returns {boolean} is overlap with a merged cell+ * @example+ * ```ts+ * const workbook = univerAPI.getActiveWorkbook();+ * const worksheet = workbook.getActiveSheet();+ * const range = worksheet.getRange(0,0,2,2);+ * const merge = range.merge();+ * const anchor = worksheet.getRange(0,0);+ * const isPartOfMerge = anchor.isPartOfMerge();+ * console.log('debugger, isPartOfMerge) // true+ * ```*/isPartOfMerge(): boolean {const { startRow, startColumn, endRow, endColumn } = this._range;@@ -623,6 +654,19 @@ export class FRange extends FBaseInitialable {/*** Break all horizontally- or vertically-merged cells contained within the range list into individual cells again.* @returns This range, for chaining+ * @example+ * ```ts+ * const workbook = univerAPI.getActiveWorkbook();+ * const worksheet = workbook.getActiveSheet();+ * const range = worksheet.getRange(0,0,2,2);+ * const merge = range.merge();+ * const anchor = worksheet.getRange(0,0);+ * const isPartOfMergeFirst = anchor.isPartOfMerge();+ * console.log('debugger' isPartOfMergeFirst) // true+ * range.breakApart();+ * const isPartOfMergeSecond = anchor.isPartOfMerge();+ * console.log('debugger' isPartOfMergeSecond) // false+ * ```*/breakApart(): FRange {this._commandService.executeCommand(RemoveWorksheetMergeCommand.id, { ranges: [this._range] });diff --git a/packages/sheets/src/facade/f-worksheet.ts b/packages/sheets/src/facade/f-worksheet.tsindex e29616a7b7..2968afda9d 100644--- a/packages/sheets/src/facade/f-worksheet.ts+++ b/packages/sheets/src/facade/f-worksheet.ts@@ -1709,19 +1709,38 @@ export class FWorksheet extends FBaseInitialable {this._fWorkbook.insertDefinedNameBuilder(param);}- /**- * Get all the defined names in the worksheet.- * @returns {FDefinedName[]} All the defined names in the worksheet- * @example- * ```ts- * // The code below gets all the defined names in the worksheet- * const activeSpreadsheet = univerAPI.getActiveWorkbook();- * const sheet1 = activeSpreadsheet.getSheetByName('Sheet1');- * const definedNames = sheet1.getDefinedNames();- * ```- */+ /**+ * Get all the defined names in the worksheet.+ * @returns {FDefinedName[]} All the defined names in the worksheet+ * @example+ * ```ts+ * // The code below gets all the defined names in the worksheet+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();+ * const sheet1 = activeSpreadsheet.getSheetByName('Sheet1');+ * const definedNames = sheet1.getDefinedNames();+ * ```+ */getDefinedNames(): FDefinedName[] {const names = this._fWorkbook.getDefinedNames();return names.filter((name) => name.getLocalSheetId() === this.getSheetId());}++ /**+ * Get all merged cells in the current worksheet+ * @returns {FRange[]} All the merged cells in the worksheet+ * @example+ * ```ts+ * const workbook = univerAPI.getActiveWorkbook();+ * const worksheet = workbook.getActiveSheet();+ * const rangeFirst = worksheet.getRange(0, 0, 2, 2);+ * const mergeFirst = rangeFirst.merge();+ * const rangeSecond = worksheet.getRange(5, 0, 2, 2);+ * const mergeSecond = rangeSecond.merge();+ * const mergeData = worksheet.getMergeData();+ * console.log('debugger', mergeData);+ * ```+ */+ getMergeData(): FRange[] {+ return this._worksheet.getMergeData().map((merge) => this._injector.createInstance(FRange, this._workbook, this._worksheet, merge));+ }}diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex 47d938da86..c8cf188940 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -45,6 +45,7 @@ export { DesktopUIController } from './controllers/ui/ui-desktop.controller';export { UniverMobileUIPlugin } from './mobile-ui-plugin';export { DesktopBeforeCloseService, IBeforeCloseService } from './services/before-close/before-close.service';export { CopyCommand, CutCommand, PasteCommand, SheetPasteShortKeyCommandName } from './services/clipboard/clipboard.command';+export { supportClipboardAPI } from './services/clipboard/clipboard-utils';export {BrowserClipboardService,FILE__BMP_CLIPBOARD_MIME_TYPE,