Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(sheets-ui): handle floating object clipboard copy (#7598)

wpxp1234565f5a7797e112
diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts
index aeec159a70..f841f5e41c 100644
--- a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts
+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts
@@ -14,10 +14,17 @@
* limitations under the License.
*/
-import { DrawingTypeEnum, ImageSourceType } from '@univerjs/core';
+import type { IRange } from '@univerjs/core';
+import type { ISheetClipboardHook } from '@univerjs/sheets-ui';
+import { DrawingTypeEnum, ICommandService, ImageSourceType, Injector, ObjectMatrix } from '@univerjs/core';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { SheetSkeletonService } from '@univerjs/sheets';
import { RemoveSheetDrawingCommand, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
-import { COPY_TYPE, PREDEFINED_HOOK_NAME_PASTE } from '@univerjs/sheets-ui';
+import { COPY_TYPE, ISheetClipboardService, PREDEFINED_HOOK_NAME_PASTE } from '@univerjs/sheets-ui';
+import { IClipboardInterfaceService } from '@univerjs/ui';
import { describe, expect, it, vi } from 'vitest';
+import { InsertFloatImageCommand } from '../../commands/commands/insert-image.command';
import { SheetsDrawingCopyPasteController } from '../sheet-drawing-copy-paste.controller';
function createSkeleton() {
@@ -63,35 +70,56 @@ function createImageDrawing(overrides: Record<string, unknown> = {}) {
};
}
-function createController(options?: { focusedDrawings?: any[]; drawingData?: Record<string, any> }) {
- let hook: any;
+type IImageDrawing = ReturnType<typeof createImageDrawing>;
+
+interface IPrivateControllerAccess {
+ _copyInfo: {
+ unitId: string;
+ subUnitId: string;
+ copyRange?: IRange;
+ drawings: IImageDrawing[];
+ } | null;
+}
+
+interface ITestClipboardHook extends ISheetClipboardHook {
+ onBeforeCopy: NonNullable<ISheetClipboardHook['onBeforeCopy']>;
+ onBeforeCopyFocusedObject?: (unitId: string, subUnitId: string, copyType: COPY_TYPE) => boolean;
+ onPasteCells: NonNullable<ISheetClipboardHook['onPasteCells']>;
+ onPasteFiles: NonNullable<ISheetClipboardHook['onPasteFiles']>;
+ onPasteUnrecognized: NonNullable<ISheetClipboardHook['onPasteUnrecognized']>;
+}
+
+function createController(options?: { focusedDrawings?: IImageDrawing[]; drawingData?: Record<string, object> }) {
+ let hook: ISheetClipboardHook | undefined;
const skeleton = createSkeleton();
const drawingService = {
getFocusDrawings: vi.fn(() => options?.focusedDrawings ?? []),
getDrawingData: vi.fn(() => options?.drawingData ?? {}),
- getBatchAddOp: vi.fn((drawings) => ({ undo: 'add-undo', redo: 'add-redo', objects: drawings })),
- getBatchUpdateOp: vi.fn((drawings) => ({ undo: 'update-undo', redo: 'update-redo', objects: drawings })),
+ getBatchAddOp: vi.fn((drawings: IImageDrawing[]) => ({ undo: 'add-undo', redo: 'add-redo', objects: drawings })),
+ getBatchUpdateOp: vi.fn((drawings: IImageDrawing[]) => ({ undo: 'update-undo', redo: 'update-redo', objects: drawings })),
};
const commandService = {
executeCommand: vi.fn(),
};
const sheetClipboardService = {
- addClipboardHook: vi.fn((config) => {
+ addClipboardHook: vi.fn((config: ISheetClipboardHook) => {
hook = config;
return { dispose: vi.fn() };
}),
};
- const controller = new SheetsDrawingCopyPasteController(
- sheetClipboardService as never,
- {} as never,
- { getSkeleton: vi.fn(() => skeleton) } as never,
- drawingService as never,
- { writeText: vi.fn() } as never,
- commandService as never
- );
+ const injector = new Injector([
+ [ISheetClipboardService, { useValue: sheetClipboardService }],
+ [IRenderManagerService, { useValue: {} }],
+ [SheetSkeletonService, { useValue: { getSkeleton: vi.fn(() => skeleton) } }],
+ [IDrawingManagerService, { useValue: drawingService }],
+ [IClipboardInterfaceService, { useValue: { writeText: vi.fn() } }],
+ [ICommandService, { useValue: commandService }],
+ [SheetsDrawingCopyPasteController],
+ ]);
+ const controller = injector.get(SheetsDrawingCopyPasteController);
- return { controller, hook, skeleton, drawingService, commandService };
+ return { controller, hook: hook as ITestClipboardHook, skeleton, drawingService, commandService };
}
describe('SheetsDrawingCopyPasteController', () => {
@@ -106,6 +134,7 @@ describe('SheetsDrawingCopyPasteController', () => {
anchorType: SheetDrawingAnchorType.Position,
});
const { controller, hook, drawingService } = createController({
+ focusedDrawings: [outsideDrawing],
drawingData: {
[containedDrawing.drawingId]: containedDrawing,
[outsideDrawing.drawingId]: outsideDrawing,
@@ -120,7 +149,6 @@ describe('SheetsDrawingCopyPasteController', () => {
startColumn: 0,
endColumn: 1,
}, COPY_TYPE.COPY);
-
const mutations = hook.onPasteCells(
{
unitId: 'unit-1',
@@ -132,8 +160,8 @@ describe('SheetsDrawingCopyPasteController', () => {
subUnitId: 'sheet-2',
range: { rows: [2, 3], cols: [3, 4] },
},
- null,
- { copyType: COPY_TYPE.COPY, pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }
+ new ObjectMatrix(),
+ { copyId: 'range-copy', copyType: COPY_TYPE.COPY, pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }
);
expect(drawingService.getBatchAddOp).toHaveBeenCalledTimes(1);
@@ -161,27 +189,26 @@ describe('SheetsDrawingCopyPasteController', () => {
focusedDrawings: [focusedDrawing],
});
- hook.onBeforeCopy('unit-1', 'sheet-1', {
- startRow: 0,
- endRow: 0,
- startColumn: 0,
- endColumn: 0,
- }, COPY_TYPE.CUT);
-
+ expect(hook.onBeforeCopyFocusedObject).toBeTypeOf('function');
+ expect(hook.onBeforeCopyFocusedObject?.('unit-1', 'sheet-1', COPY_TYPE.CUT)).toBe(true);
expect(commandService.executeCommand).toHaveBeenCalledWith(RemoveSheetDrawingCommand.id, {
unitId: 'unit-1',
drawings: [focusedDrawing],
});
const mutations = hook.onPasteCells(
- undefined,
+ {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { rows: [0], cols: [0] },
+ },
{
unitId: 'unit-1',
subUnitId: 'sheet-1',
range: { rows: [3], cols: [4] },
},
- null,
- { copyType: COPY_TYPE.CUT, pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }
+ new ObjectMatrix(),
+ { copyId: 'image-cut', copyType: COPY_TYPE.CUT, pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }
);
expect(drawingService.getBatchAddOp).toHaveBeenCalledTimes(1);
@@ -198,4 +225,166 @@ describe('SheetsDrawingCopyPasteController', () => {
controller.dispose();
});
+
+ it('copies all focused image drawings', () => {
+ const firstDrawing = createImageDrawing({ drawingId: 'first-image' });
+ const secondDrawing = createImageDrawing({
+ drawingId: 'second-image',
+ transform: { left: 30, top: 40, width: 10, height: 20 },
+ });
+ const { controller, hook, drawingService } = createController({
+ focusedDrawings: [firstDrawing, secondDrawing],
+ });
+
+ expect(hook.onBeforeCopyFocusedObject?.('unit-1', 'sheet-1', COPY_TYPE.COPY)).toBe(true);
+
+ const mutations = hook.onPasteFiles(
+ {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { rows: [3], cols: [4] },
+ },
+ [new File(['clipboard'], 'clipboard-image.png', { type: 'image/png' })],
+ { pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }
+ );
+
+ expect(drawingService.getBatchAddOp).toHaveBeenCalledTimes(2);
+ expect(drawingService.getBatchAddOp.mock.calls.map(([drawings]) => drawings[0].transform)).toEqual([
+ expect.objectContaining({ left: 40, top: 60 }),
+ expect.objectContaining({ left: 65, top: 95 }),
+ ]);
+ expect(mutations.redos).toHaveLength(2);
+
+ controller.dispose();
+ });
+
+ it('pastes external image files instead of the previous copied drawing', () => {
+ const focusedDrawing = createImageDrawing({ drawingId: 'focused-image' });
+ const { controller, hook } = createController({
+ focusedDrawings: [focusedDrawing],
+ });
+ const internalImage = new File(['internal'], 'clipboard-image.png', { type: 'image/png' });
+ const externalImage = new File(['external'], 'external.png', { type: 'image/png' });
+
+ (controller as unknown as IPrivateControllerAccess)._copyInfo = {
+ unitId: focusedDrawing.unitId,
+ subUnitId: focusedDrawing.subUnitId,
+ drawings: [focusedDrawing],
+ };
+
+ hook.onPasteFiles(
+ {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { rows: [0], cols: [0] },
+ },
+ [internalImage],
+ { pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }
+ );
+
+ const mutations = hook.onPasteFiles(
+ {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { rows: [0], cols: [0] },
+ },
+ [externalImage],
+ { pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }
+ );
+
+ expect(mutations).toEqual({
+ undos: [],
+ redos: [{
+ id: InsertFloatImageCommand.id,
+ params: { files: [externalImage] },
+ }],
+ });
+
+ controller.dispose();
+ });
+
+ it('clears a copied image after pasting external cell content', () => {
+ const focusedDrawing = createImageDrawing({ drawingId: 'focused-image' });
+ const { controller, hook } = createController({
+ focusedDrawings: [focusedDrawing],
+ });
+
+ (controller as unknown as IPrivateControllerAccess)._copyInfo = {
+ unitId: focusedDrawing.unitId,
+ subUnitId: focusedDrawing.subUnitId,
+ drawings: [focusedDrawing],
+ };
+
+ const mutations = hook.onPasteCells(
+ null,
+ {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { rows: [0], cols: [0] },
+ },
+ new ObjectMatrix(),
+ { copyType: COPY_TYPE.COPY, pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }
+ );
+
+ expect(mutations).toEqual({ undos: [], redos: [] });
+
+ const externalImage = new File(['external'], 'external.png', { type: 'image/png' });
+ expect(hook.onPasteFiles(
+ {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { rows: [0], cols: [0] },
+ },
+ [externalImage],
+ { pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }
+ ).redos).toEqual([{
+ id: InsertFloatImageCommand.id,
+ params: { files: [externalImage] },
+ }]);
+
+ expect(hook.onPasteUnrecognized({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { rows: [0], cols: [0] },
+ })).toEqual({ undos: [], redos: [] });
+
+ controller.dispose();
+ });
+
+ it('clears a copied image after an unrecognized internal paste', () => {
+ const focusedDrawing = createImageDrawing({ drawingId: 'focused-image' });
+ const { controller, hook } = createController({
+ focusedDrawings: [focusedDrawing],
+ });
+ const externalImage = new File(['external'], 'external.png', { type: 'image/png' });
+
+ (controller as unknown as IPrivateControllerAccess)._copyInfo = {
+ unitId: focusedDrawing.unitId,
+ subUnitId: focusedDrawing.subUnitId,
+ drawings: [focusedDrawing],
+ };
+
+ hook.onPasteUnrecognized({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { rows: [0], cols: [0] },
+ });
+
+ const mutations = hook.onPasteFiles(
+ {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { rows: [0], cols: [0] },
+ },
+ [externalImage],
+ { pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }
+ );
+
+ expect(mutations.redos).toEqual([{
+ id: InsertFloatImageCommand.id,
+ params: { files: [externalImage] },
+ }]);
+
+ controller.dispose();
+ });
});
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
index 0b35ea96ef..5c486f7fe2 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
@@ -116,60 +116,61 @@ export class SheetsDrawingCopyPasteController extends Disposable {
this._sheetClipboardService.addClipboardHook({
id: 'SHEET_IMAGE_UI_PLUGIN',
- onBeforeCopy: (unitId, subUnitId, range, copyType) => {
+ onBeforeCopyFocusedObject: (unitId, _subUnitId, copyType) => {
this._copyInfo = null;
- const focusDrawings = this._focusedDrawings;
- if (focusDrawings.length > 0) {
- // handle single drawing copy
- const [drawing] = focusDrawings;
+ const drawings = this._focusedDrawings.filter((drawing) => drawing.drawingType === DrawingTypeEnum.DRAWING_IMAGE);
+ if (drawings.length === 0) {
+ return false;
+ }
- if (drawing.drawingType !== DrawingTypeEnum.DRAWING_IMAGE) {
- return;
- }
+ const [drawing] = drawings;
+
+ if (copyType === COPY_TYPE.CUT) {
+ const params: IRemoveSheetDrawingCommandParams = {
+ unitId,
+ drawings,
+ };
+ // Delete the drawing when it is cut
+ this._commandService.executeCommand<IRemoveSheetDrawingCommandParams>(RemoveSheetDrawingCommand.id, params);
+ }
- if (copyType === COPY_TYPE.CUT) {
- const params: IRemoveSheetDrawingCommandParams = {
- unitId,
- drawings: [drawing],
- };
- // Delete the drawing when it is cut
- this._commandService.executeCommand<IRemoveSheetDrawingCommandParams>(RemoveSheetDrawingCommand.id, params);
+ setTimeout(() => {
+ // Rewrite the clipboard content to prevent the default copy behavior, prevent to call the 'onPasteCells'
+ const dispose = focusDocument();
+ if (drawing.drawingType === DrawingTypeEnum.DRAWING_IMAGE
+ && (drawing as ISheetImage).imageSourceType === ImageSourceType.BASE64) {
+ copyBase64ToClipboard((drawing as ISheetImage).source);
+ } else {
+ this._clipboardInterfaceService.writeText('');
}
+ dispose();
+ }, 200);
- setTimeout(() => {
- // Rewrite the clipboard content to prevent the default copy behavior, prevent to call the 'onPasteCells'
- const dispose = focusDocument();
- if (drawing.drawingType === DrawingTypeEnum.DRAWING_IMAGE
- && (drawing as ISheetImage).imageSourceType === ImageSourceType.BASE64) {
- copyBase64ToClipboard((drawing as ISheetImage).source);
- } else {
- this._clipboardInterfaceService.writeText('');
- }
- dispose();
- }, 200);
-
- const newCopyInfo = {
- unitId: drawing.unitId,
- subUnitId: drawing.subUnitId,
- drawings: [drawing],
- };
+ this._copyInfo = {
+ unitId: drawing.unitId,
+ subUnitId: drawing.subUnitId,
+ drawings,
+ };
+ return true;
+ },
- this._copyInfo = newCopyInfo;
- } else {
- // handle copy range that contained drawings
- const newCopyInfo = this._createDrawingsCopyInfoByRange(unitId, subUnitId, range);
- this._copyInfo = newCopyInfo;
- }
+ onBeforeCopy: (unitId, subUnitId, range) => {
+ this._copyInfo = this._createDrawingsCopyInfoByRange(unitId, subUnitId, range);
},
- onPasteCells: (pasteFrom, pasteTo, data, payload) => {
- if (!this._copyInfo) {
+ onPasteCells: (pasteFrom, pasteTo, _data, payload) => {
+ if (!payload.copyId) {
+ this._copyInfo = null;
+ return { redos: [], undos: [] };
+ }
+
+ if (!pasteFrom || !this._copyInfo) {
return { redos: [], undos: [] };
}
const { copyType = COPY_TYPE.COPY, pasteType } = payload;
- const { range: copyRange, unitId: fromUnitId, subUnitId: fromSubUnitId } = pasteFrom || {};
+ const { range: copyRange, unitId: fromUnitId, subUnitId: fromSubUnitId } = pasteFrom;
const { range: pasteRange, unitId: toUnitId, subUnitId: toSubUnitId } = pasteTo;
const mutations = this._copyInfo.copyRange
@@ -182,35 +183,40 @@ export class SheetsDrawingCopyPasteController extends Disposable {
return mutations;
},
- onPastePlainText: (pasteTo: ISheetDiscreteRangeLocation, clipText: string) => {
+ onPastePlainText: (_pasteTo: ISheetDiscreteRangeLocation, _clipText: string) => {
+ this._copyInfo = null;
return { undos: [], redos: [] };
},
onPasteUnrecognized: (pasteTo: ISheetDiscreteRangeLocation) => {
- if (this._copyInfo) {
- return this._generateSingleDrawingPasteMutations({ pasteTo, pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }, COPY_TYPE.COPY);
- } else {
+ if (!this._copyInfo || this._copyInfo.copyRange) {
return { undos: [], redos: [] };
}
+
+ const mutations = this._generateSingleDrawingPasteMutations({ pasteTo, pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }, COPY_TYPE.COPY);
+ this._copyInfo = null;
+ return mutations;
},
onPasteFiles: (pasteTo: ISheetDiscreteRangeLocation, files) => {
- if (this._copyInfo) {
- return this._generateSingleDrawingPasteMutations({ pasteTo, pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }, COPY_TYPE.COPY);
- } else {
- // Paste image from external
- const images = files.filter((file) => file.type.includes('image'));
- if (images.length) {
- return {
- undos: [],
- redos: [
- {
- id: InsertFloatImageCommand.id,
- params: { files: images },
- },
- ],
- };
- }
+ if (this._copyInfo && !this._copyInfo.copyRange) {
+ const mutations = this._generateSingleDrawingPasteMutations({ pasteTo, pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }, COPY_TYPE.COPY);
+ this._copyInfo = null;
+ return mutations;
+ }
+
+ const images = files.filter((file) => file.type.includes('image'));
+ if (images.length) {
+ this._copyInfo = null;
+ return {
+ undos: [],
+ redos: [
+ {
+ id: InsertFloatImageCommand.id,
+ params: { files: images },
+ },
+ ],
+ };
}
return { undos: [], redos: [] };
@@ -228,7 +234,7 @@ export class SheetsDrawingCopyPasteController extends Disposable {
const { startX, endX, startY, endY } = selectionRect;
const drawings = this._drawingService.getDrawingData(unitId, subUnitId);
- const containedDrawings: ISheetDrawing[] = this._focusedDrawings.slice();
+ const containedDrawings: ISheetDrawing[] = [];
Object.keys(drawings).forEach((drawingId) => {
const drawing = drawings[drawingId];
@@ -284,6 +290,17 @@ export class SheetsDrawingCopyPasteController extends Disposable {
const copyInfo = this._copyInfo!;
const { drawings } = copyInfo;
const pasteRange = discreteRangeToRange(range);
+ let drawingAnchor: { left: number; top: number } | undefined;
+ if (drawings.length > 1) {
+ let anchorLeft = Infinity;
+ let anchorTop = Infinity;
+ for (const drawing of drawings) {
+ const { left = 0, top = 0 } = drawing.transform ?? {};
+ anchorLeft = Math.min(anchorLeft, left);
+ anchorTop = Math.min(anchorTop, top);
+ }
+ drawingAnchor = { left: anchorLeft, top: anchorTop };
+ }
return this._generateMutations(drawings, {
unitId,
@@ -299,8 +316,12 @@ export class SheetsDrawingCopyPasteController extends Disposable {
const newTransform = {
...transform,
- left: pasteRect?.startX,
- top: pasteRect?.startY,
+ left: drawingAnchor && pasteRect
+ ? pasteRect.startX + (transform?.left ?? 0) - drawingAnchor.left
+ : pasteRect?.startX,
+ top: drawingAnchor && pasteRect
+ ? pasteRect.startY + (transform?.top ?? 0) - drawingAnchor.top
+ : pasteRect?.startY,
};
return {
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-group-copy-paste.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-group-copy-paste.controller.ts
index e3be33381a..3f95c610c0 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-group-copy-paste.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-group-copy-paste.controller.ts
@@ -78,43 +78,39 @@ export class SheetsDrawingGroupCopyPasteController extends Disposable {
this._sheetClipboardService.addClipboardHook({
id: 'SHEET_DRAWING_GROUP',
- onBeforeCopy: (_unitId, _subUnitId) => {
+ onBeforeCopyFocusedObject: (_unitId, _subUnitId) => {
this._copyInfo = null;
const focusDrawings = this._focusedDrawings;
- if (focusDrawings.length === 0) return;
+ if (focusDrawings.length === 0) return false;
// Only handle the first focused group drawing.
const groupDrawing = focusDrawings.find((d) => d.drawingType === DrawingTypeEnum.DRAWING_GROUP);
- if (!groupDrawing) return;
+ if (!groupDrawing) return false;
const groupNestedParam = this._drawingManagerService.getDrawingsByGroupNested({
unitId: groupDrawing.unitId,
subUnitId: groupDrawing.subUnitId,
drawingId: groupDrawing.drawingId,
});
- if (!groupNestedParam) return;
+ if (!groupNestedParam) return false;
this._copyInfo = {
unitId: groupDrawing.unitId,
subUnitId: groupDrawing.subUnitId,
groupNestedParam,
};
+ return true;
},
- onPasteCells: (_pasteFrom, pasteTo, _data, payload) => {
- if (!this._copyInfo) return { redos: [], undos: [] };
+ onPasteCells: (pasteFrom, pasteTo, _data, payload) => {
+ if (!payload.copyId || !pasteFrom || !this._copyInfo) return { redos: [], undos: [] };
const { pasteType } = payload;
if (specialPastes.includes(pasteType)) return { redos: [], undos: [] };
return this._generateGroupPasteMutations(pasteTo);
},
-
- onPasteUnrecognized: (pasteTo) => {
- if (!this._copyInfo) return { redos: [], undos: [] };
- return this._generateGroupPasteMutations(pasteTo);
- },
});
}
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts
index 3dfd2f693c..281b281543 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts
@@ -107,7 +107,15 @@ interface IPrivateClipboardServiceAccess {
_pasteUSM(
data: { cellMatrix: ObjectMatrix<ITestCell>; rowProperties: unknown[]; colProperties: unknown[] },
target: { unitId: string; subUnitId: string; pastedRange: ITestDiscreteRange },
- pasteType: string
+ pasteType: string,
+ source?: {
+ unitId: string;
+ subUnitId: string;
+ range: ITestDiscreteRange;
+ copyId: string;
+ copyType: COPY_TYPE;
+ skipCellCopy?: boolean;
+ }
): boolean;
_transformPastedData(
rowCount: number,
@@ -539,6 +547,92 @@ describe('SheetClipboardService', () => {
expect(lifecycle).toEqual(['before', 'after']);
});
+ it('does not copy or mark cell data when a copy hook handles a focused object', async () => {
+ const { injector, service } = createTestContext();
+ selectCell(injector);
+ const workbook = injector.get(IUniverInstanceService).getUnit<Workbook>('unit-1');
+ const worksheet = workbook!.getSheetBySheetId('sheet-1')!;
+ const getMatrixWithMergedCells = vi.spyOn(worksheet, 'getMatrixWithMergedCells');
+ const addCopyMark = vi.spyOn(injector.get(IMarkSelectionService), 'addShape');
+ const cellBeforeCopy = vi.fn();
+
+ service.addClipboardHook({
+ id: 'focused-object-copy',
+ onBeforeCopyFocusedObject() {
+ return true;
+ },
+ } as never);
+ service.addClipboardHook({ id: 'cell-feature-copy', onBeforeCopy: cellBeforeCopy } as never);
+
+ expect(await service.copy()).toBe(true);
+
+ const clipboard = injector.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;
+ const copied = clipboard.writes[0];
+ const copyId = copied.html.match(/data-copy-id="([^"]+)"/)?.[1];
+ const cachedCopy = copyId ? service.copyContentCache().get(copyId) : undefined;
+
+ expect(getMatrixWithMergedCells).not.toHaveBeenCalled();
+ expect(cellBeforeCopy).not.toHaveBeenCalled();
+ expect(addCopyMark).not.toHaveBeenCalled();
+ expect(copied.text).toBe('');
+ expect(copied.html).not.toContain('Quarterly revenue');
+ expect(cachedCopy?.matrix?.getValue(0, 0)?.v).toBeNull();
+ expect(cachedCopy?.skipCellCopy).toBe(true);
+ });
+
+ it('keeps explicit range content generation independent from focused objects', () => {
+ const service = createService();
+ const focusedObjectBeforeCopy = vi.fn(() => true);
+ const rangeBeforeCopy = vi.fn();
+ service.addClipboardHook({
+ id: 'focused-object-copy',
+ onBeforeCopyFocusedObject: focusedObjectBeforeCopy,
+ onBeforeCopy: rangeBeforeCopy,
+ } as never);
+
+ const copyContent = service.generateCopyContent('unit-1', 'sheet-1', {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 0,
+ });
+
+ expect(copyContent?.plain).toBe('Quarterly revenue');
+ expect(focusedObjectBeforeCopy).not.toHaveBeenCalled();
+ expect(rangeBeforeCopy).toHaveBeenCalledOnce();
+ });
+
+ it('runs only the focused object hook when pasting an object-only copy', () => {
+ const service = createService();
+ const objectPaste = vi.fn(() => ({ redos: [], undos: [] }));
+ const cellPaste = vi.fn(() => ({ redos: [], undos: [] }));
+ const matrix = new ObjectMatrix<ITestCell>({ 0: { 0: {} } });
+
+ service.addClipboardHook({
+ id: 'focused-object-copy',
+ onBeforeCopyFocusedObject: () => false,
+ onPasteCells: objectPaste,
+ } as never);
+ service.addClipboardHook({ id: 'cell-feature-copy', onPasteCells: cellPaste } as never);
+
+ (service as unknown as IPrivateClipboardServiceAccess)._pasteUSM(
+ { cellMatrix: matrix, rowProperties: [], colProperties: [] },
+ { unitId: 'unit-1', subUnitId: 'sheet-1', pastedRange: { rows: [0], cols: [0] } },
+ PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE,
+ {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { rows: [0], cols: [0] },
+ copyId: 'object-copy',
+ copyType: COPY_TYPE.COPY,
+ skipCellCopy: true,
+ }
+ );
+
+ expect(objectPaste).toHaveBeenCalledOnce();
+ expect(cellPaste).not.toHaveBeenCalled();
+ });
+
it('stops paste execution when a hook blocks the target range', async () => {
const { injector, service } = createTestContext();
selectCell(injector);
diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
index 4f62aadfc7..d07f261ed3 100644
--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
@@ -323,7 +323,15 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
const worksheetId = worksheet.getSheetId();
const { copyType = COPY_TYPE.COPY, copyHookType = PREDEFINED_HOOK_NAME_COPY.DEFAULT_COPY } = options || {};
- const copyContent = this.generateCopyContent(workbookId, worksheetId, selection.range, { copyType, copyHookType });
+ const focusedObjectHooks = copyHookType === PREDEFINED_HOOK_NAME_COPY.SPECIAL_COPY_FORMULA_ONLY
+ ? []
+ : this._clipboardHooks.filter((hook) => hook.onBeforeCopyFocusedObject);
+ const focusedObjectCopied = focusedObjectHooks
+ .map((hook) => hook.onBeforeCopyFocusedObject?.(workbookId, worksheetId, copyType))
+ .some(Boolean);
+ const copyContent = focusedObjectCopied
+ ? this._generateObjectCopyContent(workbookId, worksheetId, selection.range)
+ : this.generateCopyContent(workbookId, worksheetId, selection.range, { copyType, copyHookType });
if (!copyContent) {
return false;
@@ -339,6 +347,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
range: discreteRange,
matrix: matrixFragment,
copyType,
+ skipCellCopy: focusedObjectCopied,
});
// 4. write html and get plain text info the clipboard interface
@@ -350,9 +359,12 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
// 5. mark the copy range
this._markSelectionService.removeAllShapes();
-
- const style = createCopyPasteSelectionStyle(this._themeService);
- this._copyMarkId = this._markSelectionService.addShape({ ...selection, style });
+ if (focusedObjectCopied) {
+ this._copyMarkId = null;
+ } else {
+ const style = createCopyPasteSelectionStyle(this._themeService);
+ this._copyMarkId = this._markSelectionService.addShape({ ...selection, style });
+ }
return true;
}
@@ -506,6 +518,30 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
return this._clipboardHooks;
}
+ private _generateObjectCopyContent(unitId: string, subUnitId: string, range: IRange): Nullable<ICopyContent> {
+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ const worksheet = workbook?.getSheetBySheetId(subUnitId);
+ if (!worksheet) {
+ return null;
+ }
+
+ const copyId = generateRandomId(6);
+ const matrixFragment = new ObjectMatrix<ICellDataWithSpanAndDisplay>();
+ matrixFragment.setValue(0, 0, getEmptyCell());
+ const discreteRange: IDiscreteRange = {
+ rows: [range.startRow],
+ cols: [range.startColumn],
+ };
+
+ return {
+ copyId,
+ plain: '',
+ html: this._usmToHtml.convert(matrixFragment, discreteRange, [], copyId),
+ matrixFragment,
+ discreteRange,
+ };
+ }
+
private _generateCopyContent(unitId: string, subUnitId: string, range: IRange, hooks: ISheetClipboardHook[], copyHookType: ICopyHookValueType = PREDEFINED_HOOK_NAME_COPY.DEFAULT_COPY): Nullable<ICopyContent> {
const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
const worksheet = workbook?.getSheetBySheetId(subUnitId);
@@ -868,7 +904,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
// const target = this._getPastingTarget();
// const { selection, unitId, subUnitId } = target;
const cachedData = this._copyContentCache.get(copyId);
- const { range, matrix: cachedMatrix, unitId: copyUnitId, subUnitId: copySubUnitId } = cachedData || {};
+ const { range, matrix: cachedMatrix, unitId: copyUnitId, subUnitId: copySubUnitId, skipCellCopy } = cachedData || {};
if (!cachedMatrix || !cachedData || !range || !copyUnitId || !copySubUnitId) {
return false;
}
@@ -965,6 +1001,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
subUnitId: cachedData.subUnitId,
copyType: cachedData.copyType,
copyId,
+ skipCellCopy,
}
);
@@ -982,7 +1019,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
data: IUniverSheetCopyDataModel,
target: IPasteTarget,
pasteType: IPasteHookValueType,
- source?: ISheetDiscreteRangeLocation & { copyId: string; copyType: COPY_TYPE }
+ source?: ISheetDiscreteRangeLocation & { copyId: string; copyType: COPY_TYPE; skipCellCopy?: boolean }
): boolean {
const { rowProperties, colProperties, cellMatrix } = data;
const { unitId, subUnitId, pastedRange } = target;
@@ -1016,7 +1053,10 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
// if hooks are not special or default, it will be executed in any case.
// other hooks will be executed only when the paste type is the same as the hook name, including the default one
- const filteredHooks: ISheetClipboardHook[] = enabledHooks.filter(
+ const pasteHooks = source?.skipCellCopy
+ ? enabledHooks.filter((hook) => hook.onBeforeCopyFocusedObject)
+ : enabledHooks;
+ const filteredHooks: ISheetClipboardHook[] = pasteHooks.filter(
(h) => (!h.specialPasteInfo && h.id !== PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE) || pasteType === h.id
);
filteredHooks.forEach((h) => {
diff --git a/packages/sheets-ui/src/services/clipboard/copy-content-cache.ts b/packages/sheets-ui/src/services/clipboard/copy-content-cache.ts
index 218424a541..3f002ee596 100644
--- a/packages/sheets-ui/src/services/clipboard/copy-content-cache.ts
+++ b/packages/sheets-ui/src/services/clipboard/copy-content-cache.ts
@@ -28,6 +28,7 @@ export interface ICopyContentCacheData {
range: IDiscreteRange;
copyType: COPY_TYPE;
matrix: Nullable<ObjectMatrix<ICellDataWithSpanInfo>>;
+ skipCellCopy?: boolean;
}
export function extractId(html: string) {
diff --git a/packages/sheets-ui/src/services/clipboard/type.ts b/packages/sheets-ui/src/services/clipboard/type.ts
index f7f23e4cf2..b1570fb754 100644
--- a/packages/sheets-ui/src/services/clipboard/type.ts
+++ b/packages/sheets-ui/src/services/clipboard/type.ts
@@ -102,6 +102,11 @@ export interface ISheetClipboardHook {
* The priority of the hook. The higher the priority, the earlier the hook would be called.
*/
priority?: number;
+ /**
+ * Handles a copy initiated from a focused floating object.
+ * @returns Whether the focused object has taken over the copy.
+ */
+ onBeforeCopyFocusedObject?(unitId: string, subUnitId: string, copyType: COPY_TYPE): boolean;
/**
* The callback would be called after the clipboard service has decided what region need to be copied.
* Features could use this hook to build copying cache or any other pre-copy jobs.