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.

feat(sheet): copy paste supports style,merge cell,row and col (#300)

Dushusirc1d153006853
diff --git a/packages/base-sheets/src/commands/commands/clear-selection-format.command.ts b/packages/base-sheets/src/commands/commands/clear-selection-format.command.ts
index e0b55e8077..9b8bf006e9 100644
--- a/packages/base-sheets/src/commands/commands/clear-selection-format.command.ts
+++ b/packages/base-sheets/src/commands/commands/clear-selection-format.command.ts
@@ -127,7 +127,7 @@ export const ClearSelectionFormatCommand: ICommand = {
};
// Generate cellValue from range and set s to null
-function generateNullCellValue(range: IRange[]): ObjectMatrixPrimitiveType<ICellData> {
+export function generateNullCellValue(range: IRange[]): ObjectMatrixPrimitiveType<ICellData> {
const cellValue = new ObjectMatrix<ICellData>();
range.forEach((range: IRange) => {
const { startRow, startColumn, endRow, endColumn } = range;
diff --git a/packages/base-sheets/src/commands/commands/insert-row-col.command.ts b/packages/base-sheets/src/commands/commands/insert-row-col.command.ts
index 62fcb5139f..a697bc4d69 100644
--- a/packages/base-sheets/src/commands/commands/insert-row-col.command.ts
+++ b/packages/base-sheets/src/commands/commands/insert-row-col.command.ts
@@ -381,7 +381,7 @@ export const InsertColCommand: ICommand<IInsertColCommandParams> = {
const count = endColumn - startColumn + 1;
if (startColumn > merge.endColumn) {
continue;
- } else if (endColumn <= merge.startColumn) {
+ } else if (startColumn <= merge.startColumn) {
merge.startColumn += count;
merge.endColumn += count;
} else {
diff --git a/packages/base-sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts b/packages/base-sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts
index b9431333e1..1476b6b674 100644
--- a/packages/base-sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts
@@ -65,7 +65,7 @@ export const SetWorksheetColWidthMutation: IMutation<ISetWorksheetColWidthMutati
if (typeof params.colWidth === 'number') {
column.w = params.colWidth;
} else {
- column.w = params.colWidth.get(j) ?? defaultColumnWidth;
+ column.w = params.colWidth.get(j - range.startColumn) ?? defaultColumnWidth;
}
}
}
diff --git a/packages/base-sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts b/packages/base-sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts
index 554bf39d86..e0fe99906e 100644
--- a/packages/base-sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts
@@ -104,7 +104,7 @@ export const SetWorksheetRowHeightMutation: IMutation<ISetWorksheetRowHeightMuta
if (typeof params.rowHeight === 'number') {
row.h = params.rowHeight;
} else {
- row.h = params.rowHeight.get(j) ?? defaultRowHeight;
+ row.h = params.rowHeight.get(j - range.startRow) ?? defaultRowHeight;
}
}
}
diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.ts
index 311f3252d0..4ac8677b6e 100644
--- a/packages/base-sheets/src/index.ts
+++ b/packages/base-sheets/src/index.ts
@@ -17,6 +17,10 @@ export { getSheetObject } from './Basics/component-tools';
// #region commands
export { type IInsertColMutationParams, type IInsertRowMutationParams } from './Basics/Interfaces/MutationInterface';
+export {
+ type IAddWorksheetMergeMutationParams,
+ type IRemoveWorksheetMergeMutationParams,
+} from './Basics/Interfaces/MutationInterface';
export {
AddWorksheetMergeAllCommand,
AddWorksheetMergeCommand,
@@ -106,6 +110,7 @@ export { SetWorksheetOrderCommand } from './commands/commands/set-worksheet-orde
export { SetRowHeightCommand as SetWorksheetRowHeightCommand } from './commands/commands/set-worksheet-row-height.command';
export { SetWorksheetShowCommand } from './commands/commands/set-worksheet-show.command';
export { ChangeZoomRatioCommand, SetZoomRatioCommand } from './commands/commands/set-zoom-ratio.command';
+export { getPrimaryForRange } from './commands/commands/utils/selection-util';
export { AddWorksheetMergeMutation } from './commands/mutations/add-worksheet-merge.mutation';
export {
InsertColMutation,
@@ -118,6 +123,7 @@ export { MoveRowsMutation } from './commands/mutations/move-rows-cols.mutation';
export { RemoveColMutation, RemoveRowMutation } from './commands/mutations/remove-row-col.mutation';
export { RemoveSheetMutation, RemoveSheetUndoMutationFactory } from './commands/mutations/remove-sheet.mutation';
export { RemoveWorksheetMergeMutation } from './commands/mutations/remove-worksheet-merge.mutation';
+export { RemoveMergeUndoMutationFactory } from './commands/mutations/remove-worksheet-merge.mutation';
export { SetBorderStylesMutation } from './commands/mutations/set-border-styles.mutation';
export { SetColHiddenMutation, SetColVisibleMutation } from './commands/mutations/set-col-visible.mutation';
export { SetFrozenMutation } from './commands/mutations/set-frozen.mutation';
@@ -125,6 +131,7 @@ export type { ISetRangeStyleMutationParams } from './commands/mutations/set-rang
export { SetRangeStyleMutation } from './commands/mutations/set-range-styles.mutation';
export type { ISetRangeValuesMutationParams } from './commands/mutations/set-range-values.mutation';
export { SetRangeValuesMutation } from './commands/mutations/set-range-values.mutation';
+export { SetRangeValuesUndoMutationFactory } from './commands/mutations/set-range-values.mutation';
export { SetRowHiddenMutation, SetRowVisibleMutation } from './commands/mutations/set-row-visible.mutation';
export { SetTabColorMutation } from './commands/mutations/set-tab-color.mutation';
export { SetWorksheetActivateMutation } from './commands/mutations/set-worksheet-activate.mutation';
@@ -146,6 +153,7 @@ export {
} from './commands/mutations/set-worksheet-row-height.mutation';
export { SetScrollOperation } from './commands/operations/scroll.operation';
export { SetSelectionsOperation } from './commands/operations/selection.operation';
+export { type ISetSelectionsOperationParams } from './commands/operations/selection.operation';
export { SetZoomRatioOperation } from './commands/operations/set-zoom-ratio.operation';
export * from './Locale';
export { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';
diff --git a/packages/base-ui/src/Helpers/Cell.ts b/packages/base-ui/src/Helpers/Cell.ts
index 43864329ac..ba6d25cb7b 100644
--- a/packages/base-ui/src/Helpers/Cell.ts
+++ b/packages/base-ui/src/Helpers/Cell.ts
@@ -117,13 +117,12 @@ export function handleDomToJson($dom: HTMLElement): IDocumentData | string {
* @param $dom
* @returns
*/
-export function handleStringToStyle($dom: HTMLElement, cssStyle: string = '') {
- let cssText = $dom.style.cssText ?? '';
+export function handleStringToStyle($dom?: HTMLElement, cssStyle: string = '') {
+ let cssText = $dom?.style?.cssText ?? '';
cssText += cssStyle;
- if (cssText == null || cssText.length === 0) {
+ if (cssText.length === 0) {
return {};
}
- cssText += cssStyle;
const cssTextArray = cssText.split(';');
const styleList: IStyleData = {};
@@ -171,7 +170,7 @@ export function handleStringToStyle($dom: HTMLElement, cssStyle: string = '') {
fs *= 2;
}
- // px to pt
+ // px to pt TODO@Dushusir: px or pt?
if (value.indexOf('px') !== -1) {
fs = pxToPt(parseInt(value));
}
@@ -307,7 +306,7 @@ export function handleStringToStyle($dom: HTMLElement, cssStyle: string = '') {
angle = +match[0];
}
// 竖排文字
- if ($dom.dataset.vertical) {
+ if ($dom?.dataset.vertical) {
ver = +$dom.dataset.vertical;
}
styleList.tr = {
@@ -331,10 +330,19 @@ export function handleStringToStyle($dom: HTMLElement, cssStyle: string = '') {
}
}
- if (key === 'overflow-wrap' || key === 'overflowWrap') {
+ // wrap text
+ if (key === 'overflow-wrap' || key === 'word-wrap') {
if (value === 'break-word') {
styleList.tb = 3;
}
+ } else if (key === 'text-overflow') {
+ if (value === 'clip') {
+ styleList.tb = 2;
+ }
+ } else if (key === 'text-break') {
+ if (value === 'overflow') {
+ styleList.tb = 1;
+ }
}
if (key === 'border-color') {
diff --git a/packages/core/src/Shared/Common.ts b/packages/core/src/Shared/Common.ts
index 1ccb334083..cd1c5520b1 100644
--- a/packages/core/src/Shared/Common.ts
+++ b/packages/core/src/Shared/Common.ts
@@ -228,8 +228,6 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
() => {
if (style.it) {
str += `font-style: italic; `;
- } else {
- str += `font-style: normal; `;
}
},
],
@@ -238,8 +236,6 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
() => {
if (style.bl) {
str += `font-weight: bold; `;
- } else {
- str += `font-weight: normal; `;
}
},
],
@@ -301,7 +297,9 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
[
'bg',
() => {
- str += `background: ${getColorStyle(style.bg)}; `;
+ if (style.bg) {
+ str += `background: ${getColorStyle(style.bg)}; `;
+ }
},
],
[
@@ -324,17 +322,17 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
[
'cl',
() => {
- str += `color: ${getColorStyle(style.cl)}; `;
+ if (style.cl) {
+ str += `color: ${getColorStyle(style.cl)}; `;
+ }
},
],
[
'va',
() => {
- if (style.va === BaselineOffset.NORMAL) {
- str += `vertical-align: baseline; `;
- } else if (style.va === BaselineOffset.SUBSCRIPT) {
+ if (style.va === BaselineOffset.SUBSCRIPT) {
str += `vertical-align: sub; `;
- } else {
+ } else if (style.va === BaselineOffset.SUPERSCRIPT) {
str += `vertical-align: super; `;
}
},
@@ -342,11 +340,9 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
[
'td',
() => {
- if (style.td === TextDirection.UNSPECIFIED) {
- str += `direction: inherit; `;
- } else if (style.td === TextDirection.LEFT_TO_RIGHT) {
+ if (style.td === TextDirection.LEFT_TO_RIGHT) {
str += `direction: ltr; `;
- } else {
+ } else if (style.td === TextDirection.RIGHT_TO_LEFT) {
str += `direction: rtl; `;
}
},
@@ -354,21 +350,21 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
[
'tr',
() => {
- str += `data-rotate: (${style.tr?.a}deg${style.tr?.v ? ` ,${style.tr?.v}` : ''});`;
+ if (style.tr) {
+ str += `data-rotate: (${style.tr?.a}deg${style.tr?.v ? ` ,${style.tr?.v}` : ''});`;
+ }
},
],
[
'ht',
() => {
- if (style.ht === HorizontalAlign.UNSPECIFIED) {
- str += `text-align: inherit; `;
- } else if (style.ht === HorizontalAlign.LEFT) {
+ if (style.ht === HorizontalAlign.LEFT) {
str += `text-align: left; `;
} else if (style.ht === HorizontalAlign.RIGHT) {
str += `text-align: right; `;
} else if (style.ht === HorizontalAlign.CENTER) {
str += `text-align: center; `;
- } else {
+ } else if (style.ht === HorizontalAlign.JUSTIFIED) {
str += `text-align: justify; `;
}
},
@@ -376,13 +372,11 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
[
'vt',
() => {
- if (style.vt === VerticalAlign.UNSPECIFIED) {
- str += `vertical-align: inherit; `;
- } else if (style.vt === VerticalAlign.BOTTOM) {
+ if (style.vt === VerticalAlign.BOTTOM) {
str += `vertical-align: bottom; `;
} else if (style.vt === VerticalAlign.TOP) {
str += `vertical-align: top; `;
- } else {
+ } else if (style.vt === VerticalAlign.MIDDLE) {
str += `vertical-align: middle; `;
}
},
@@ -395,7 +389,7 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
} else if (style.tb === WrapStrategy.OVERFLOW) {
str += `text-break: overflow; `;
} else if (style.tb === WrapStrategy.WRAP) {
- str += `word-wrap: break-word; word-break: normal; `;
+ str += `word-wrap: break-word;`;
}
},
],
diff --git a/packages/ui-plugin-sheets/src/controller/clipboard/clipboard.controller.ts b/packages/ui-plugin-sheets/src/controller/clipboard/clipboard.controller.ts
index 27b914285e..db0add5467 100644
--- a/packages/ui-plugin-sheets/src/controller/clipboard/clipboard.controller.ts
+++ b/packages/ui-plugin-sheets/src/controller/clipboard/clipboard.controller.ts
@@ -1,32 +1,47 @@
import {
+ AddWorksheetMergeMutation,
+ getPrimaryForRange,
+ IAddWorksheetMergeMutationParams,
IInsertColMutationParams,
IInsertRowMutationParams,
InsertColMutation,
InsertRowMutation,
+ IRemoveWorksheetMergeMutationParams,
ISetRangeValuesMutationParams,
+ ISetSelectionsOperationParams,
ISetWorksheetColWidthMutationParams,
ISetWorksheetRowHeightMutationParams,
+ NORMAL_SELECTION_PLUGIN_NAME,
+ RemoveMergeUndoMutationFactory,
+ RemoveWorksheetMergeMutation,
SetRangeValuesMutation,
+ SetRangeValuesUndoMutationFactory,
+ SetSelectionsOperation,
SetWorksheetColWidthMutation,
SetWorksheetRowHeightMutation,
} from '@univerjs/base-sheets';
-import { IMessageService, MessageType } from '@univerjs/base-ui';
+import { AddMergeUndoMutationFactory } from '@univerjs/base-sheets/commands/mutations/add-worksheet-merge.mutation.js';
+import { handleStringToStyle, IMessageService, MessageType, textTrim } from '@univerjs/base-ui';
import {
BooleanNumber,
+ DEFAULT_WORKSHEET_COLUMN_WIDTH,
+ DEFAULT_WORKSHEET_ROW_HEIGHT,
Disposable,
+ handleStyleToString,
ICellData,
ICommandInfo,
ICommandService,
IConfigService,
IRange,
+ IRowData,
IUniverInstanceService,
LifecycleStages,
LocaleService,
ObjectArray,
ObjectMatrix,
OnLifecycle,
+ Rectangle,
Worksheet,
- WrapStrategy,
} from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
@@ -38,9 +53,6 @@ import {
ISheetClipboardService,
} from '../../services/clipboard/clipboard.service';
-// TODO: default row height from config?
-const DEFAULT_HEIGHT = 20;
-
/**
* 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.
@@ -99,36 +111,40 @@ export class SheetClipboardController extends Disposable {
// use worksheet.getStyle()
const range = currentSheet!.getRange(row, col);
const textStyle = range.getTextStyle();
- const color = range.getFontColor();
- const backgroundColor = range.getBackground();
+ // const color = range.getFontColor();
+ // const backgroundColor = range.getBackground();
let style = '';
- if (color) {
- style += `color: ${color};`;
- }
- if (backgroundColor) {
- style += `background-color: ${backgroundColor};`;
- }
- if (textStyle?.bl) {
- style += 'font-weight: bold;';
- }
- if (textStyle?.fs) {
- style += `font-size: ${textStyle.fs}px;`;
- }
- if (textStyle?.tb === WrapStrategy.WRAP) {
- style += 'word-wrap: break-word;';
- }
- if (textStyle?.it) {
- style += 'font-style: italic;';
- }
- if (textStyle?.ff) {
- style += `font-family: ${textStyle.ff};`;
- }
- if (textStyle?.st) {
- style += 'text-decoration: line-through;';
- }
- if (textStyle?.ul) {
- style += 'text-decoration: underline';
+ // if (color) {
+ // style += `color: ${color};`;
+ // }
+ // if (backgroundColor) {
+ // style += `background-color: ${backgroundColor};`;
+ // }
+ // if (textStyle?.bl) {
+ // style += 'font-weight: bold;';
+ // }
+ // if (textStyle?.fs) {
+ // style += `font-size: ${textStyle.fs}px;`;
+ // }
+ // if (textStyle?.tb === WrapStrategy.WRAP) {
+ // style += 'word-wrap: break-word;';
+ // }
+ // if (textStyle?.it) {
+ // style += 'font-style: italic;';
+ // }
+ // if (textStyle?.ff) {
+ // style += `font-family: ${textStyle.ff};`;
+ // }
+ // if (textStyle?.st) {
+ // style += 'text-decoration: line-through;';
+ // }
+ // if (textStyle?.ul) {
+ // style += 'text-decoration: underline';
+ // }
+
+ if (textStyle) {
+ style = handleStyleToString(textStyle);
}
if (style) {
@@ -194,16 +210,34 @@ export class SheetClipboardController extends Disposable {
const addingRowsCount = range.endRow - maxRow;
const existingRowsCount = rowProperties.length - addingRowsCount;
if (addingRowsCount > 0) {
+ const rowInfo = new ObjectArray<IRowData>();
+ rowProperties.slice(existingRowsCount).forEach((property, index) => {
+ const style = property.style;
+ const cssTextArray = style.split(';');
+ let height = DEFAULT_WORKSHEET_ROW_HEIGHT;
+
+ cssTextArray.find((css) => {
+ css = css.toLowerCase();
+ const key = textTrim(css.substr(0, css.indexOf(':')));
+ const value = textTrim(css.substr(css.indexOf(':') + 1));
+ if (key === 'height') {
+ height = parseFloat(value);
+ return true;
+ }
+ return false;
+ });
+
+ rowInfo.set(index, {
+ h: height,
+ hd: BooleanNumber.FALSE,
+ });
+ });
+
const addRowMutation: IInsertRowMutationParams = {
workbookId: workbookId!,
worksheetId: worksheetId!,
ranges: [{ ...range, startRow: maxRow }],
- rowInfo: new ObjectArray(
- rowProperties.slice(existingRowsCount).map((property) => ({
- h: property.height ? +property.height : DEFAULT_HEIGHT,
- hd: BooleanNumber.FALSE,
- }))
- ),
+ rowInfo,
};
redoMutations.push({
id: InsertRowMutation.id,
@@ -211,16 +245,34 @@ export class SheetClipboardController extends Disposable {
});
}
+ // get row height of existing rows
+ // TODO When Excel pasted, there was no width height, Do we still need to set the height?
+ const rowHeight = new ObjectArray<number>();
+ rowProperties.slice(0, existingRowsCount).forEach((property, index) => {
+ const style = property.style;
+ const cssTextArray = style.split(';');
+ let height = DEFAULT_WORKSHEET_ROW_HEIGHT;
+
+ cssTextArray.find((css) => {
+ css = css.toLowerCase();
+ const key = textTrim(css.substr(0, css.indexOf(':')));
+ const value = textTrim(css.substr(css.indexOf(':') + 1));
+ if (key === 'height') {
+ height = parseFloat(value);
+ return true;
+ }
+ return false;
+ });
+
+ rowHeight.set(index, height);
+ });
+
// apply row properties to the existing rows
const setRowPropertyMutation: ISetWorksheetRowHeightMutationParams = {
workbookId: workbookId!,
worksheetId: worksheetId!,
ranges: [{ ...range, endRow: Math.min(range.endRow, maxRow) }],
- rowHeight: new ObjectArray(
- rowProperties
- .slice(0, existingRowsCount)
- .map((property) => (property.height ? +property.height : DEFAULT_HEIGHT))
- ),
+ rowHeight,
};
redoMutations.push({
id: SetWorksheetRowHeightMutation.id,
@@ -230,7 +282,7 @@ export class SheetClipboardController extends Disposable {
// TODO: add undo mutations but we cannot do it now because underlying mechanism is not ready
return {
- redos: [] || redoMutations,
+ redos: redoMutations,
undos: [] || undoMutations,
};
},
@@ -250,7 +302,7 @@ export class SheetClipboardController extends Disposable {
ranges: [{ ...range, startColumn: maxColumn }],
colInfo: new ObjectArray(
colProperties.slice(existingColsCount).map((property) => ({
- w: property.width ? +property.width : DEFAULT_HEIGHT,
+ w: property.width ? +property.width : DEFAULT_WORKSHEET_COLUMN_WIDTH,
hd: BooleanNumber.FALSE,
}))
),
@@ -260,7 +312,6 @@ export class SheetClipboardController extends Disposable {
params: addColMutation,
});
}
-
// apply row properties to the existing rows
const setRowPropertyMutation: ISetWorksheetColWidthMutationParams = {
workbookId: workbookId!,
@@ -269,7 +320,7 @@ export class SheetClipboardController extends Disposable {
colWidth: new ObjectArray(
colProperties
.slice(0, existingColsCount)
- .map((property) => (property.width ? +property.width : DEFAULT_HEIGHT))
+ .map((property) => (property.width ? +property.width : DEFAULT_WORKSHEET_COLUMN_WIDTH))
),
};
redoMutations.push({
@@ -280,7 +331,7 @@ export class SheetClipboardController extends Disposable {
// TODO: add undo mutations but we cannot do it now because underlying mechanism is not ready
return {
- redos: [] || redoMutations,
+ redos: redoMutations,
undos: [] || undoMutations,
};
},
@@ -305,22 +356,89 @@ export class SheetClipboardController extends Disposable {
undos: ICommandInfo[];
} {
// insert cell style, insert cell content and insert merged cell info
- // 1. merged cell (TODO)
+ // 1. merged cell
// 2. raw content
- // 3. cell style (TODO)
+ // 3. cell style
- const { startColumn, startRow } = range;
+ const { startColumn, startRow, endColumn, endRow } = range;
const valueMatrix = new ObjectMatrix<ICellData>();
+ const clearStyleMatrix = new ObjectMatrix<ICellData>();
+ const mergeRangeData: IRange[] = [];
const redoMutationsInfo: ICommandInfo[] = [];
const undoMutationsInfo: ICommandInfo[] = [];
+ let hasMerge = false;
matrix.forValue((row, col, value) => {
+ // TODO@Dushusir Temporarily use handleStringToStyle. After all replication and paste function is completed, fix the handleStringToStyle method
+ const style = handleStringToStyle(undefined, value.properties.style);
+
+ // NOTE: When pasting, the original cell may contain a default style that is not explicitly carried, resulting in the failure to overwrite the style of the target cell.
+ // If the original cell has a style (lack of other default styles) or is undefined (all default styles), we need to clear the existing styles in the target area
+ // If the original cell style is "", it is to handle the situation where the target area contains merged cells. The style is not overwritten, only the value is overwritten. There is no need to clear the existing style of the target area.
+ if (value.properties.style !== '') {
+ clearStyleMatrix.setValue(row + startRow, col + startColumn, { s: null });
+ }
+
valueMatrix.setValue(row + startRow, col + startColumn, {
v: value.content,
+ s: style,
});
+
+ // rowspan and colspan to merge data
+ if (value.rowSpan) {
+ const colSpan = value.colSpan || 1;
+ const mergeRange = {
+ startRow: startRow + row,
+ endRow: startRow + row + value.rowSpan - 1,
+ startColumn: startColumn + col,
+ endColumn: startColumn + col + colSpan - 1,
+ };
+ mergeRangeData.push(mergeRange);
+ hasMerge = true;
+ } else if (value.colSpan) {
+ const rowSpan = value.rowSpan || 1;
+ const mergeRange = {
+ startRow: startRow + row,
+ endRow: startRow + row + rowSpan - 1,
+ startColumn: startColumn + col,
+ endColumn: startColumn + col + value.colSpan - 1,
+ };
+ mergeRangeData.push(mergeRange);
+ hasMerge = true;
+ }
});
- const setContentMutation: ISetRangeValuesMutationParams = {
+ const accessor = {
+ get: this._injector.get.bind(this._injector),
+ };
+
+ // clear style
+ if (clearStyleMatrix.getLength() > 0) {
+ const clearMutation: ISetRangeValuesMutationParams = {
+ range: [range],
+ worksheetId,
+ workbookId,
+ cellValue: clearStyleMatrix.getData(),
+ };
+ redoMutationsInfo.push({
+ id: SetRangeValuesMutation.id,
+ params: clearMutation,
+ });
+
+ // undo
+ const undoClearMutation: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(
+ accessor,
+ clearMutation
+ );
+
+ undoMutationsInfo.push({
+ id: SetRangeValuesMutation.id,
+ params: undoClearMutation,
+ });
+ }
+
+ // set cell value and style
+ const setValuesMutation: ISetRangeValuesMutationParams = {
workbookId,
worksheetId,
range: [range],
@@ -329,7 +447,119 @@ export class SheetClipboardController extends Disposable {
redoMutationsInfo.push({
id: SetRangeValuesMutation.id,
- params: setContentMutation,
+ params: setValuesMutation,
+ });
+
+ // undo
+ const undoSetValuesMutation: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(
+ accessor,
+ setValuesMutation
+ );
+
+ undoMutationsInfo.push({
+ id: SetRangeValuesMutation.id,
+ params: undoSetValuesMutation,
+ });
+
+ // remove current range's all merged Cell
+ if (hasMerge) {
+ // get all merged cells
+ const mergeData = this._getWorksheet(workbookId, worksheetId).getMergeData();
+ const mergedCellsInRange = mergeData.filter((rect) =>
+ Rectangle.intersects({ startRow, startColumn, endRow, endColumn }, rect)
+ );
+
+ const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {
+ workbookId,
+ worksheetId,
+ ranges: mergedCellsInRange,
+ };
+ redoMutationsInfo.push({
+ id: RemoveWorksheetMergeMutation.id,
+ params: removeMergeMutationParams,
+ });
+
+ const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveMergeUndoMutationFactory(
+ accessor,
+ removeMergeMutationParams
+ );
+
+ undoMutationsInfo.push({
+ id: AddWorksheetMergeMutation.id,
+ params: undoRemoveMergeMutationParams,
+ });
+ }
+
+ // set merged cell info
+ const addMergeMutationParams: IAddWorksheetMergeMutationParams = {
+ workbookId,
+ worksheetId,
+ ranges: mergeRangeData,
+ };
+ redoMutationsInfo.push({
+ id: AddWorksheetMergeMutation.id,
+ params: addMergeMutationParams,
+ });
+
+ // undo
+ const undoAddMergeMutation: IRemoveWorksheetMergeMutationParams = AddMergeUndoMutationFactory(
+ accessor,
+ addMergeMutationParams
+ );
+
+ undoMutationsInfo.push({
+ id: RemoveWorksheetMergeMutation.id,
+ params: undoAddMergeMutation,
+ });
+
+ // set selection
+ const worksheet = this._getWorksheet(workbookId, worksheetId);
+ // const destinationRange = {
+ // startRow,
+ // endRow: range.endRow - 1,
+ // startColumn,
+ // endColumn: range.endColumn - 1,
+ // };
+ const primaryCell = {
+ startRow,
+ endRow: startRow,
+ startColumn,
+ endColumn: startColumn,
+ };
+
+ const primary = getPrimaryForRange(primaryCell, worksheet);
+
+ const mainCell = matrix.getValue(0, 0);
+ const rowSpan = mainCell?.rowSpan || 1;
+ const colSpan = mainCell?.colSpan || 1;
+
+ if (rowSpan > 1 || colSpan > 1) {
+ const mergeRange = {
+ startRow,
+ endRow: startRow + rowSpan - 1,
+ startColumn,
+ endColumn: startColumn + colSpan - 1,
+ };
+
+ primary.startRow = mergeRange.startRow;
+ primary.endRow = mergeRange.endRow;
+ primary.startColumn = mergeRange.startColumn;
+ primary.endColumn = mergeRange.endColumn;
+
+ primary.isMerged = true;
+ primary.isMergedMainCell = true;
+ }
+
+ // selection does not require undo
+ const setSelectionsParam: ISetSelectionsOperationParams = {
+ workbookId,
+ worksheetId,
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ selections: [{ range, primary, style: null }],
+ };
+ redoMutationsInfo.push({
+ id: SetSelectionsOperation.id,
+ params: setSelectionsParam,
});
return {
diff --git a/packages/ui-plugin-sheets/src/services/clipboard/__test__/clipboard-service.spec.ts b/packages/ui-plugin-sheets/src/services/clipboard/__test__/clipboard-service.spec.ts
new file mode 100644
index 0000000000..0d3df40274
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/services/clipboard/__test__/clipboard-service.spec.ts
@@ -0,0 +1,869 @@
+import {
+ AddWorksheetMergeMutation,
+ NORMAL_SELECTION_PLUGIN_NAME,
+ RemoveWorksheetMergeMutation,
+ SelectionManagerService,
+ SetRangeValuesMutation,
+ SetSelectionsOperation,
+ SetWorksheetColWidthMutation,
+ SetWorksheetRowHeightMutation,
+} from '@univerjs/base-sheets';
+import {
+ ICellData,
+ ICommandService,
+ IRange,
+ IStyleData,
+ IUniverInstanceService,
+ Nullable,
+ RANGE_TYPE,
+ Rectangle,
+ Univer,
+} from '@univerjs/core';
+import { Injector } from '@wendellhu/redi';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ISheetClipboardService } from '../clipboard.service';
+import { clipboardTestBed } from './clipboard-test-bed';
+import { IClipboardItem, MockClipboard } from './mock-clipboard';
+
+describe('Test clipboard', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let sheetClipboardService: ISheetClipboardService;
+ let clipboardItem: IClipboardItem;
+ let getValues: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ) => Array<Array<Nullable<ICellData>>> | undefined;
+ let getMergedCells: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ) => IRange[] | undefined;
+
+ let getStyles: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ) => Array<Array<Nullable<IStyleData>>> | undefined;
+
+ beforeEach(async () => {
+ const testBed = clipboardTestBed();
+ univer = testBed.univer;
+ get = testBed.get;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(SetRangeValuesMutation);
+ commandService.registerCommand(SetWorksheetRowHeightMutation);
+ commandService.registerCommand(SetWorksheetColWidthMutation);
+ commandService.registerCommand(AddWorksheetMergeMutation);
+ commandService.registerCommand(RemoveWorksheetMergeMutation);
+ commandService.registerCommand(SetSelectionsOperation);
+
+ sheetClipboardService = get(ISheetClipboardService);
+
+ getValues = (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ): Array<Array<Nullable<ICellData>>> | undefined =>
+ get(IUniverInstanceService)
+ .getUniverSheetInstance('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(startRow, startColumn, endRow, endColumn)
+ .getValues();
+
+ getMergedCells = (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ): IRange[] | undefined =>
+ get(IUniverInstanceService)
+ .getUniverSheetInstance('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getMergeData()
+ .filter((rect) => Rectangle.intersects({ startRow, startColumn, endRow, endColumn }, rect));
+
+ getStyles = (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ): Array<Array<Nullable<IStyleData>>> | undefined => {
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = get(IUniverInstanceService).getUniverSheetInstance('test')?.getStyles();
+ if (values && styles) {
+ return values.map((row) => row.map((cell) => styles.getStyleByCell(cell)));
+ }
+ };
+ // read use mock
+ const clipbordData = {
+ '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>\n<tbody>
+ <tr style="height: 81px;">
+ <td rowspan="1" colspan="2"
+ style="background: rgb(255,0,0); text-align: center; vertical-align: middle;">row1col2</td>
+ </tr>
+ </tbody>
+ </table>
+ </google-sheets-html-origin>`,
+ };
+ const mockClipboard = new MockClipboard(clipbordData);
+ const clipboardItems = await mockClipboard.read();
+
+ if (clipboardItems.length !== 0) {
+ clipboardItem = clipboardItems[0];
+ }
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ describe('Test paste, the original data is a merged cell of 1 row and 2 columns, the current selection consists only of ordinary cells', () => {
+ it('The current selection is a single cell in 1 row and 1 column', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to A1
+ const startRow = 0;
+ const startColumn = 0;
+ const endRow = 0;
+ const endColumn = 0;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await sheetClipboardService.paste(clipboardItem);
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+ expect(values && values[0][0]?.v).toBe('row1col2');
+ expect(styles && styles[0][0]).toStrictEqual({
+ bg: { rgb: 'rgb(255,0,0)' },
+ ht: 2,
+ vt: 2,
+ });
+ expect(mergedCells && mergedCells[0]).toStrictEqual({
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 1,
+ });
+ });
+ it('The current selection is a single cell in 1 row and 2 columns', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to A2:B2
+ const startRow = 1;
+ const startColumn = 0;
+ const endRow = 1;
+ const endColumn = 1;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await sheetClipboardService.paste(clipboardItem);
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+ expect(values && values[0][0]?.v).toBe('row1col2');
+ expect(styles && styles[0][0]).toStrictEqual({
+ bg: { rgb: 'rgb(255,0,0)' },
+ ht: 2,
+ vt: 2,
+ });
+ expect(mergedCells && mergedCells[0]).toStrictEqual({
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ });
+ });
+ it('The current selection is a single cell in 1 row and 3 columns', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to A3:C3
+ const startRow = 2;
+ const startColumn = 0;
+ const endRow = 2;
+ const endColumn = 2;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await sheetClipboardService.paste(clipboardItem);
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+ expect(values && values[0][0]?.v).toBe('row1col2');
+ expect(styles && styles[0][0]).toStrictEqual({
+ bg: { rgb: 'rgb(255,0,0)' },
+ ht: 2,
+ vt: 2,
+ });
+ expect(mergedCells && mergedCells[0]).toStrictEqual({
+ startRow: 2,
+ startColumn: 0,
+ endRow: 2,
+ endColumn: 1,
+ });
+ });
+ it('The current selection is a single cell in 2 rows and 2 columns', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to A4:B5
+ const startRow = 3;
+ const startColumn = 0;
+ const endRow = 4;
+ const endColumn = 1;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await sheetClipboardService.paste(clipboardItem);
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+ expect(values && values[0][0]?.v).toBe('row1col2');
+ expect(values && values[1][0]?.v).toBe('row1col2');
+
+ expect(styles && styles[0][0]).toStrictEqual({
+ bg: { rgb: 'rgb(255,0,0)' },
+ ht: 2,
+ vt: 2,
+ });
+ expect(styles && styles[1][0]).toStrictEqual({
+ bg: { rgb: 'rgb(255,0,0)' },
+ ht: 2,
+ vt: 2,
+ });
+ expect(mergedCells).toStrictEqual([
+ {
+ startRow: 3,
+ startColumn: 0,
+ endRow: 3,
+ endColumn: 1,
+ },
+ {
+ startRow: 4,
+ startColumn: 0,
+ endRow: 4,
+ endColumn: 1,
+ },
+ ]);
+ });
+ it('The current selection is a single cell in 4 rows and 4 columns', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to A6:D9
+ const startRow = 5;
+ const startColumn = 0;
+ const endRow = 8;
+ const endColumn = 3;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await sheetClipboardService.paste(clipboardItem);
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+
+ for (let i = 0; i < 4; i++) {
+ expect(values && values[i][0]?.v).toBe('row1col2');
+ expect(values && values[i][2]?.v).toBe('row1col2');
+
+ expect(styles && styles[i][0]).toStrictEqual({
+ bg: { rgb: 'rgb(255,0,0)' },
+ ht: 2,
+ vt: 2,
+ });
+ expect(styles && styles[i][2]).toStrictEqual({
+ bg: { rgb: 'rgb(255,0,0)' },
+ ht: 2,
+ vt: 2,
+ });
+ }
+ expect(mergedCells).toStrictEqual([
+ {
+ startRow: 5,
+ startColumn: 0,
+ endRow: 5,
+ endColumn: 1,
+ },
+ {
+ startRow: 5,
+ startColumn: 2,
+ endRow: 5,
+ endColumn: 3,
+ },
+ {
+ startRow: 6,
+ startColumn: 0,
+ endRow: 6,
+ endColumn: 1,
+ },
+ {
+ startRow: 6,
+ startColumn: 2,
+ endRow: 6,
+ endColumn: 3,
+ },
+ {
+ startRow: 7,
+ startColumn: 0,
+ endRow: 7,
+ endColumn: 1,
+ },
+ {
+ startRow: 7,
+ startColumn: 2,
+ endRow: 7,
+ endColumn: 3,
+ },
+ {
+ startRow: 8,
+ startColumn: 0,
+ endRow: 8,
+ endColumn: 1,
+ },
+ {
+ startRow: 8,
+ startColumn: 2,
+ endRow: 8,
+ endColumn: 3,
+ },
+ ]);
+ });
+ });
+
+ describe('Test paste, the original data is a merged cell of 1 row and 2 columns, the current selection contains merged cells and no content', () => {
+ it('The current selection is a merged cell of 1 row and 2 columns.', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to F1:G2
+ const startRow = 0;
+ const startColumn = 5;
+ const endRow = 0;
+ const endColumn = 6;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await sheetClipboardService.paste(clipboardItem);
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+
+ expect(values && values[0][0]?.v).toBe('row1col2');
+ expect(styles && styles[0][0]).toStrictEqual({
+ bg: { rgb: 'rgb(255,0,0)' },
+ ht: 2,
+ vt: 2,
+ });
+ expect(mergedCells && mergedCells[0]).toStrictEqual({
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ });
+ });
+
+ it('The current selection is a merged cell of 1 row and 3 columns.', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to F3:H3
+ const startRow = 2;
+ const startColumn = 5;
+ const endRow = 2;
+ const endColumn = 7;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await sheetClipboardService.paste(clipboardItem);
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+
+ expect(values && values[0][0]?.v).toBe('row1col2');
+ expect(styles && styles[0][0]).toBe(undefined);
+ expect(mergedCells && mergedCells[0]).toStrictEqual({
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ });
+ });
+
+ it('The current selection is a merged cell of 1 row and 4 columns.', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to F5:I5
+ const startRow = 4;
+ const startColumn = 5;
+ const endRow = 4;
+ const endColumn = 8;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await sheetClipboardService.paste(clipboardItem);
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+
+ expect(values && values[0][0]?.v).toBe('row1col2');
+ expect(styles && styles[0][0]).toBe(undefined);
+ expect(mergedCells && mergedCells[0]).toStrictEqual({
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ });
+ });
+
+ it('The current selection is a merged cell of 2 rows and 2 columns.', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to F7:G8
+ const startRow = 6;
+ const startColumn = 5;
+ const endRow = 7;
+ const endColumn = 6;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await sheetClipboardService.paste(clipboardItem);
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+
+ expect(values && values[0][0]?.v).toBe('row1col2');
+ expect(styles && styles[0][0]).toBe(undefined);
+ expect(mergedCells && mergedCells[0]).toStrictEqual({
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ });
+ });
+
+ it('The current selection is a merged cell of 1 row and 2 columns, with 1 ordinary cell', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to F10:H10
+ const startRow = 9;
+ const startColumn = 5;
+ const endRow = 9;
+ const endColumn = 7;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await sheetClipboardService.paste(clipboardItem);
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+
+ expect(values && values[0][0]?.v).toBe('row1col2');
+ expect(styles && styles[0][0]).toStrictEqual({ bg: { rgb: 'rgb(255,0,0)' }, ht: 2, vt: 2 });
+ expect(mergedCells && mergedCells[0]).toStrictEqual({
+ startRow: 9,
+ startColumn: 5,
+ endRow: 9,
+ endColumn: 6,
+ });
+ });
+
+ it('The current selection is a merged cell of 2 rows and 2 columns, with a merged cell of 2 rows and 1 column', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to F12:H13
+ const startRow = 11;
+ const startColumn = 5;
+ const endRow = 12;
+ const endColumn = 7;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ // TODO@Dushusir remove after Dialog replacement
+ let alert = false;
+ vi.spyOn(window, 'alert').mockImplementation(() => {
+ alert = true;
+ });
+
+ await sheetClipboardService.paste(clipboardItem);
+ expect(alert).toBe(true);
+
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+
+ expect(values && values[0][0]?.v).toBe(undefined);
+ expect(styles && styles[0][0]).toBe(undefined);
+ expect(mergedCells).toStrictEqual([
+ {
+ startRow: 11,
+ startColumn: 5,
+ endRow: 12,
+ endColumn: 6,
+ },
+ {
+ startRow: 11,
+ startColumn: 7,
+ endRow: 12,
+ endColumn: 7,
+ },
+ ]);
+ });
+ });
+
+ describe('Test paste, the original data is a merged cell of 1 row and 2 columns, the current selection contains merged cells with content and style', () => {
+ it('The current selection is a merged cell of 1 row and 3 columns', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to K4:M4
+ const startRow = 3;
+ const startColumn = 10;
+ const endRow = 3;
+ const endColumn = 12;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await sheetClipboardService.paste(clipboardItem);
+
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+
+ expect(values && values[0][0]?.v).toBe('row1col2');
+ expect(styles && styles[0][0]).toStrictEqual({
+ bg: {
+ rgb: '#ccc',
+ },
+ });
+ expect(mergedCells && mergedCells[0]).toStrictEqual({
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ });
+ });
+ it('The current selection is a merged cell of 1 row and 2 columns, with a merged cell of 2 rows and 2 columns', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to K7:M10
+ const startRow = 6;
+ const startColumn = 10;
+ const endRow = 9;
+ const endColumn = 12;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await sheetClipboardService.paste(clipboardItem);
+
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+
+ // first merged cells changed
+ expect(values && values[0][0]?.v).toBe('row1col2');
+ expect(styles && styles[0][0]).toStrictEqual({ bg: { rgb: 'rgb(255,0,0)' }, ht: 2, vt: 2 });
+
+ // second merged cells not changed
+ expect(values && values[2][1]?.v).toBe('456');
+ expect(styles && styles[2][1]).toStrictEqual({ bg: { rgb: '#ccc' }, ht: 2, vt: 2 });
+
+ expect(mergedCells).toStrictEqual([
+ {
+ startRow: 8,
+ startColumn: 11,
+ endRow: 9,
+ endColumn: 12,
+ },
+ {
+ startRow: 6,
+ startColumn: 10,
+ endRow: 6,
+ endColumn: 11,
+ },
+ ]);
+ });
+ it('The current selection is a merged cell of 1 row and 3 columns, with a merged cell of 2 rows and 2 columns', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to K12:M15
+ const startRow = 11;
+ const startColumn = 10;
+ const endRow = 14;
+ const endColumn = 12;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ let alert = false;
+ vi.spyOn(window, 'alert').mockImplementation(() => {
+ alert = true;
+ });
+
+ await sheetClipboardService.paste(clipboardItem);
+ expect(alert).toBe(true);
+
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+
+ // first merged cells not changed
+ expect(values && values[0][0]?.v).toBe('456');
+ expect(styles && styles[0][0]).toStrictEqual({ bg: { rgb: '#ccc' }, ht: 3 });
+
+ // second merged cells not changed
+ expect(values && values[2][1]?.v).toBe('456');
+ expect(styles && styles[2][1]).toStrictEqual({ bg: { rgb: '#ccc' } });
+
+ expect(mergedCells).toStrictEqual([
+ {
+ startRow: 11,
+ startColumn: 10,
+ endRow: 11,
+ endColumn: 12,
+ },
+ {
+ startRow: 13,
+ startColumn: 11,
+ endRow: 14,
+ endColumn: 12,
+ },
+ ]);
+ });
+ it('The current selection is a merged cell of 2 rows and 2 columns, with a merged cell of 1 row and 2 columns', async () => {
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // set selection to K22:M24
+ const startRow = 21;
+ const startColumn = 10;
+ const endRow = 23;
+ const endColumn = 12;
+
+ selectionManager.add([
+ {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ let alert = false;
+ vi.spyOn(window, 'alert').mockImplementation(() => {
+ alert = true;
+ });
+
+ await sheetClipboardService.paste(clipboardItem);
+ expect(alert).toBe(true);
+
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = getStyles(startRow, startColumn, endRow, endColumn);
+ const mergedCells = getMergedCells(startRow, startColumn, endRow, endColumn);
+
+ // first merged cells not changed
+ expect(values && values[0][0]?.v).toBe('456');
+ expect(styles && styles[0][0]).toStrictEqual({ bg: { rgb: '#ccc' } });
+
+ // second merged cells not changed
+ expect(values && values[2][1]?.v).toBe('456');
+ expect(styles && styles[2][1]).toStrictEqual({ bg: { rgb: '#ccc' } });
+
+ expect(mergedCells).toStrictEqual([
+ {
+ startRow: 21,
+ startColumn: 10,
+ endRow: 22,
+ endColumn: 11,
+ },
+ {
+ startRow: 23,
+ startColumn: 11,
+ endRow: 23,
+ endColumn: 12,
+ },
+ ]);
+ });
+ });
+});
diff --git a/packages/ui-plugin-sheets/src/services/clipboard/__test__/clipboard-test-bed.ts b/packages/ui-plugin-sheets/src/services/clipboard/__test__/clipboard-test-bed.ts
new file mode 100644
index 0000000000..b3851de52d
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/services/clipboard/__test__/clipboard-test-bed.ts
@@ -0,0 +1,557 @@
+import { SelectionManagerService } from '@univerjs/base-sheets';
+import {
+ BrowserClipboardService,
+ DesktopMessageService,
+ IClipboardInterfaceService,
+ IMessageService,
+} from '@univerjs/base-ui';
+import {
+ ILogService,
+ IUniverInstanceService,
+ IWorkbookConfig,
+ LocaleType,
+ Plugin,
+ PluginType,
+ Univer,
+} from '@univerjs/core';
+import { Dependency, Inject, Injector } from '@wendellhu/redi';
+
+import { SheetClipboardController } from '../../../controller/clipboard/clipboard.controller';
+import { ISheetClipboardService, SheetClipboardService } from '../clipboard.service';
+
+const cellData = {
+ '0': {
+ '7': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '8': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '10': {
+ v: '456',
+ m: '456',
+ s: '3UpAbI',
+ },
+ '11': {
+ s: '3UpAbI',
+ },
+ },
+ '1': {
+ '5': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '6': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '7': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '8': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ },
+ '2': {
+ '8': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ },
+ '3': {
+ '5': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '6': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '7': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '8': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '10': {
+ s: '3UpAbI',
+ v: '456',
+ m: '456',
+ },
+ '11': {
+ s: '3UpAbI',
+ },
+ '12': {
+ s: '3UpAbI',
+ },
+ },
+ '5': {
+ '5': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '6': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '7': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '8': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ },
+ '6': {
+ '7': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '8': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '10': {
+ v: '456',
+ m: '456',
+ s: 'hw-erj',
+ },
+ '11': {
+ s: 'hw-erj',
+ },
+ },
+ '7': {
+ '7': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '8': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ },
+ '8': {
+ '5': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '6': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '7': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '8': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '11': {
+ v: '456',
+ m: '456',
+ s: '_aRLOe',
+ },
+ '12': {
+ s: '_aRLOe',
+ },
+ },
+ '9': {
+ '7': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '8': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '11': {
+ s: '_aRLOe',
+ },
+ '12': {
+ s: '_aRLOe',
+ },
+ },
+ '10': {
+ '5': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '6': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '7': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '8': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ },
+ '11': {
+ '8': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ '10': {
+ v: '456',
+ m: '456',
+ s: 'Mtn4vb',
+ },
+ '11': {
+ s: 'Mtn4vb',
+ },
+ '12': {
+ s: 'Mtn4vb',
+ },
+ },
+ '12': {
+ '8': {
+ v: ' ',
+ m: ' ',
+ s: 'u5otPe',
+ },
+ },
+ '13': {
+ '11': {
+ v: '456',
+ m: '456',
+ s: '3UpAbI',
+ },
+ '12': {
+ s: '3UpAbI',
+ },
+ },
+ '14': {
+ '11': {
+ s: '3UpAbI',
+ },
+ '12': {
+ s: '3UpAbI',
+ },
+ },
+ '16': {
+ '10': {
+ v: '456',
+ m: '456',
+ s: '3UpAbI',
+ },
+ '11': {
+ s: '3UpAbI',
+ },
+ },
+ '17': {
+ '11': {
+ v: '456',
+ m: '456',
+ s: '3UpAbI',
+ },
+ '12': {
+ s: '3UpAbI',
+ },
+ },
+ '18': {
+ '11': {
+ s: '3UpAbI',
+ },
+ '12': {
+ s: '3UpAbI',
+ },
+ },
+ '21': {
+ '10': {
+ v: '456',
+ m: '456',
+ s: '3UpAbI',
+ },
+ '11': {
+ s: '3UpAbI',
+ },
+ },
+ '22': {
+ '10': {
+ s: '3UpAbI',
+ },
+ '11': {
+ s: '3UpAbI',
+ },
+ },
+ '23': {
+ '11': {
+ v: '456',
+ m: '456',
+ s: '3UpAbI',
+ },
+ '12': {
+ s: '3UpAbI',
+ },
+ },
+};
+
+const styles = {
+ u5otPe: {
+ bd: {},
+ },
+ '3UpAbI': {
+ bg: {
+ rgb: '#ccc',
+ },
+ },
+ 'hw-erj': {
+ bg: {
+ rgb: '#ccc',
+ },
+ ht: 2,
+ },
+ _aRLOe: {
+ bg: {
+ rgb: '#ccc',
+ },
+ ht: 2,
+ vt: 2,
+ },
+ Mtn4vb: {
+ bg: {
+ rgb: '#ccc',
+ },
+ ht: 3,
+ },
+};
+
+const mergeData = [
+ {
+ startRow: 16,
+ endRow: 16,
+ startColumn: 10,
+ endColumn: 11,
+ },
+ {
+ startRow: 21,
+ endRow: 22,
+ startColumn: 10,
+ endColumn: 11,
+ },
+ // check
+ {
+ startRow: 0,
+ startColumn: 5,
+ endRow: 0,
+ endColumn: 6,
+ },
+ // check
+ {
+ startRow: 2,
+ startColumn: 5,
+ endRow: 2,
+ endColumn: 7,
+ },
+ // check
+ {
+ startRow: 4,
+ startColumn: 5,
+ endRow: 4,
+ endColumn: 8,
+ },
+ // check
+ {
+ startRow: 6,
+ startColumn: 5,
+ endRow: 7,
+ endColumn: 6,
+ },
+ // check
+ {
+ startRow: 9,
+ startColumn: 5,
+ endRow: 9,
+ endColumn: 6,
+ },
+ // check
+ {
+ startRow: 11,
+ startColumn: 5,
+ endRow: 12,
+ endColumn: 6,
+ },
+ // check
+ {
+ startRow: 11,
+ startColumn: 7,
+ endRow: 12,
+ endColumn: 7,
+ },
+ // check
+ {
+ startRow: 0,
+ startColumn: 10,
+ endRow: 0,
+ endColumn: 11,
+ },
+ // check
+ {
+ startRow: 3,
+ startColumn: 10,
+ endRow: 3,
+ endColumn: 12,
+ },
+ // check
+ {
+ startRow: 6,
+ startColumn: 10,
+ endRow: 6,
+ endColumn: 11,
+ },
+ // check
+ {
+ startRow: 8,
+ startColumn: 11,
+ endRow: 9,
+ endColumn: 12,
+ },
+ // check
+ {
+ startRow: 11,
+ startColumn: 10,
+ endRow: 11,
+ endColumn: 12,
+ },
+ // check
+ {
+ startRow: 13,
+ startColumn: 11,
+ endRow: 14,
+ endColumn: 12,
+ },
+ {
+ startRow: 17,
+ startColumn: 11,
+ endRow: 18,
+ endColumn: 12,
+ },
+ {
+ startRow: 23,
+ startColumn: 11,
+ endRow: 23,
+ endColumn: 12,
+ },
+];
+
+const TEST_WORKBOOK_DATA_DEMO: IWorkbookConfig = {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData,
+ mergeData,
+ },
+ },
+ createdTime: '',
+ creator: '',
+ extensions: [],
+ lastModifiedBy: '',
+ locale: LocaleType.EN,
+ modifiedTime: '',
+ name: '',
+ sheetOrder: [],
+ styles,
+ timeZone: '',
+};
+
+export function clipboardTestBed(workbookConfig?: IWorkbookConfig, dependencies?: Dependency[]) {
+ const univer = new Univer();
+
+ let get: Injector['get'] | undefined;
+
+ /**
+ * This plugin hooks into Sheet's DI system to expose API to test scripts
+ */
+ class TestSpyPlugin extends Plugin {
+ static override type = PluginType.Sheet;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super('test-plugin');
+
+ this._injector = _injector;
+ get = this._injector.get.bind(this._injector);
+ }
+
+ override onStarting(injector: Injector): void {
+ injector.add([SelectionManagerService]);
+ injector.add([IClipboardInterfaceService, { useClass: BrowserClipboardService, lazy: true }]);
+ injector.add([ISheetClipboardService, { useClass: SheetClipboardService }]);
+ injector.add([IMessageService, { useClass: DesktopMessageService, lazy: true }]);
+
+ // Because SheetClipboardController is initialized in the rendered life cycle, here we need to initialize it manually
+ const sheetClipboardController = injector.createInstance(SheetClipboardController);
+ injector.add([SheetClipboardController, { useValue: sheetClipboardController }]);
+
+ dependencies?.forEach((d) => injector.add(d));
+ }
+
+ override onDestroy(): void {
+ get = undefined;
+ }
+ }
+
+ univer.registerPlugin(TestSpyPlugin);
+ const sheet = univer.createUniverSheet(workbookConfig || TEST_WORKBOOK_DATA_DEMO);
+
+ if (get === undefined) {
+ throw new Error('[TestPlugin]: not hooked on!');
+ }
+
+ const univerInstanceService = get(IUniverInstanceService);
+ univerInstanceService.focusUniverInstance('test');
+
+ const logService = get(ILogService);
+ logService.toggleLogEnabled(false); // change this to `true` to debug tests via logs
+
+ return {
+ univer,
+ get,
+ sheet,
+ };
+}
diff --git a/packages/ui-plugin-sheets/src/services/clipboard/__test__/mock-clipboard.ts b/packages/ui-plugin-sheets/src/services/clipboard/__test__/mock-clipboard.ts
new file mode 100644
index 0000000000..539038c127
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/services/clipboard/__test__/mock-clipboard.ts
@@ -0,0 +1,42 @@
+export interface IClipboardItem {
+ readonly types: readonly string[];
+ getType(type: string): Promise<Blob>;
+}
+
+export class MockClipboardItem implements IClipboardItem {
+ private readonly itemTypes: readonly string[];
+ constructor(private props: IMockClipboardProps) {
+ this.itemTypes = Object.keys(props);
+ }
+
+ get types(): readonly string[] {
+ return this.itemTypes;
+ }
+
+ getType(type: string): Promise<Blob> {
+ // Here the corresponding mock Blob object is returned according to the type
+ if (this.itemTypes.includes(type)) {
+ // Mock returns a fake HTML/Text/Image content
+ const blob = new Blob([this.props[type as keyof IMockClipboardProps] || ''], { type });
+ return Promise.resolve(blob);
+ }
+
+ // Can return an false Promise if the types do not match
+ return Promise.reject(new Error('Unsupported type'));
+ }
+}
+
+interface IMockClipboardProps {
+ 'text/plain'?: string;
+ 'text/html'?: string;
+ 'image/png'?: string;
+}
+
+export class MockClipboard {
+ constructor(private props: IMockClipboardProps) {}
+ read(): Promise<IClipboardItem[]> {
+ // Here you can return the simulated IClipboardItem array
+ const clipboardItems: IClipboardItem[] = [new MockClipboardItem(this.props)];
+ return Promise.resolve(clipboardItems);
+ }
+}
diff --git a/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts b/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts
index e4f61bdd4e..fea352fd8d 100644
--- a/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts
+++ b/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts
@@ -15,7 +15,9 @@ import {
IUniverInstanceService,
ObjectMatrix,
ObjectMatrixPrimitiveType,
+ Rectangle,
toDisposable,
+ Worksheet,
} from '@univerjs/core';
import { createIdentifier, IDisposable, Inject } from '@wendellhu/redi';
@@ -188,8 +190,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
rowContents.push(getRowContent(row, cols, hooks, matrix));
});
- const html = `<google-sheets-html-origin><style type="text/css"><!--td {border: 1px solid #cccccc;}br {mso-data-placement:same-cell;}--></style>
-<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">${colStyles}
+ const 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">${colStyles}
<tbody>${rowContents.join('')}</tbody></table>`;
// TODO: plain text copying is not implemented yet
@@ -211,11 +212,11 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
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.text())
+ ? 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.text())
+ ? await item.getType(HTML_CLIPBOARD_MIME_TYPE).then((blob) => blob && blob.text())
: '';
if (html && isLegalSpreadsheetHTMLContent(html)) {
@@ -228,6 +229,8 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
return this._pastePlainText(text);
}
+ this._logService.error('[SheetClipboardService]', 'No valid data on clipboard');
+
return false;
}
@@ -307,9 +310,16 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
// 3. call hooks with cell position and properties and get mutations (both do mutations and undo mutations)
// we also handle 'copy value only' or 'copy style only' as this step
- const pastedRange = { ...selection.range };
- pastedRange.endColumn = pastedRange.startColumn + colCount;
- pastedRange.endRow = pastedRange.startRow + rowCount;
+ const pastedRange = this._transformPastedData(rowCount, colCount, cellMatrix, selection.range);
+
+ // pastedRange.endColumn = pastedRange.startColumn + colCount;
+ // pastedRange.endRow = pastedRange.startRow + rowCount;
+
+ // If PastedRange is null, it means that the paste fails
+ if (!pastedRange) {
+ return false;
+ }
+
const hooks = this._clipboardHooks;
const enabledHooks: ISheetClipboardHook[] = [];
const disableCopying = hooks.some(
@@ -375,6 +385,180 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
selection,
};
}
+
+ /**
+ * Handles copying one range to another range, obtained by the following rules
+ *
+ * [Content to be assigned] => [Target range]
+ *
+ * I. There are no merged cells in the upper left corner of the pasted area
+ *
+ * 1. 1 -> 1: 1 => 1
+ * 2. N -> 1: N => N
+ * 3. 1 -> N: N => N
+ * 4. N1 -> N2:
+ * 1) N1 <N2: If N2 is a multiple of N1 (X), N1 * X => N2; If not, N1 => N1 (refer to office excel, different from google sheet)
+ * 2) N1> N2: N1 => N1
+ *
+ * The above four cases can be combined and processed as
+ *
+ * Case 1, 1/2/4-2 merged into N1 => N1
+ * Case 2, 3/4-1 merge into N1 * X => N2 or Case 1
+ *
+ * In the end we only need to judge whether N2 is a multiple of N1
+ *
+ * II. The pasted area contains merged cells
+ *
+ * 1. If N2 is a multiple of N1,
+ * 1) If N2 === N1, paste this area directly and the range remains unchanged.
+ * 2) Otherwise, determine whether other cells are included
+ * 1] If included, tile, the range remains unchanged
+ * 2] If not included, determine whether the source data is a combined cell
+ * 1} If yes, tile, the range remains unchanged
+ * 2} If not, only the content will be pasted, the original style will be discarded, and the scope will remain unchanged.
+ *
+ * 2. If N2 is not a multiple of N1, determine whether the upper left corner cell (merged or non-merged or combined) is consistent with the size of the original data.
+ * 1) If consistent, only paste this area;
+ * 2) If inconsistent, then determine whether the pasted area contains other cells.
+ * 1] If yes, pasting is not allowed and an error will pop up;
+ * 2] If not, only the content will be pasted and the original style will be discarded.
+ *
+ * @param rowCount
+ * @param colCount
+ * @param cellMatrix
+ * @param range
+ */
+ private _transformPastedData(
+ rowCount: number,
+ colCount: number,
+ cellMatrix: ObjectMatrix<IParsedCellValue>,
+ range: IRange
+ ): IRange | null {
+ const { startRow, startColumn, endRow, endColumn } = range;
+ const destinationRows = endRow - startRow + 1;
+ const destinationColumns = endColumn - startColumn + 1;
+
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+ const worksheet = workbook.getActiveSheet();
+ // const mergedRange = worksheet.getMergedCell(startRow, startColumn);
+ const mergeData = worksheet.getMergeData();
+ // get all merged cells
+ const mergedCellsInRange = mergeData.filter((rect) =>
+ Rectangle.intersects({ startRow, startColumn, endRow, endColumn }, rect)
+ );
+ const mergedRange = mergedCellsInRange[0];
+
+ let mergedRangeStartRow = 0;
+ let mergedRangeStartColumn = 0;
+ let mergedRangeEndRow = 0;
+ let mergedRangeEndColumn = 0;
+ if (mergedRange) {
+ mergedRangeStartRow = mergedRange.startRow;
+ mergedRangeStartColumn = mergedRange.startColumn;
+ mergedRangeEndRow = mergedRange.endRow;
+ mergedRangeEndColumn = mergedRange.endColumn;
+ }
+
+ // judge whether N2 is a multiple of N1
+ if (destinationRows % rowCount === 0 && destinationColumns % colCount === 0) {
+ // N2 !== N1
+ if (mergedCellsInRange.length > 0 && (destinationRows !== rowCount || destinationColumns !== colCount)) {
+ // Only merged cells, not other cells
+ if (
+ mergedRangeStartRow === startRow &&
+ mergedRangeStartColumn === startColumn &&
+ mergedRangeEndRow === endRow &&
+ mergedRangeEndColumn === endColumn
+ ) {
+ const isMultiple = isMultipleCells(cellMatrix);
+ if (isMultiple) {
+ for (let r = 0; r < destinationRows; r++) {
+ for (let c = 0; c < destinationColumns; c++) {
+ const cell = cellMatrix.getValue(r % rowCount, c % colCount);
+ cell && cellMatrix.setValue(r, c, cell);
+ }
+ }
+ } else {
+ cellMatrix.forValue((row, col, cell) => {
+ cell.properties.style = '';
+ delete cell.colSpan;
+ delete cell.rowSpan;
+ });
+ }
+ } else {
+ for (let r = 0; r < destinationRows; r++) {
+ for (let c = 0; c < destinationColumns; c++) {
+ const cell = cellMatrix.getValue(r % rowCount, c % colCount);
+ cell && cellMatrix.setValue(r, c, cell);
+ }
+ }
+ }
+ } else {
+ /**
+ * Expand cellMatrix content according to the destination size
+ * A1,B1 => A1,B1,C1,D1
+ * A2,B2 A2,B2,C2,D2
+ * A3,B3,C3,D3
+ * A4,B4,C4,D4
+ */
+ for (let r = 0; r < destinationRows; r++) {
+ for (let c = 0; c < destinationColumns; c++) {
+ const cell = cellMatrix.getValue(r % rowCount, c % colCount);
+ cell && cellMatrix.setValue(r, c, cell);
+ }
+ }
+ }
+ } else if (mergedCellsInRange.length > 0) {
+ const isMatch = this._topLeftCellsMatch(rowCount, colCount, range);
+ if (isMatch) {
+ // Expand or shrink the destination to the same size as the original range
+ range.endRow = startRow + rowCount - 1;
+ range.endColumn = startColumn + colCount - 1;
+ } else if (endRow > mergedRange.endRow || endColumn > mergedRange.endColumn) {
+ // TODO@Dushusir: use dialog component
+ alert("We can't do that to a merged cell ");
+ return null;
+ } else {
+ cellMatrix.forValue((row, col, cell) => {
+ cell.properties.style = '';
+ delete cell.colSpan;
+ delete cell.rowSpan;
+ });
+ }
+ } else {
+ // Expand or shrink the destination to the same size as the original range
+ range.endRow = startRow + rowCount - 1;
+ range.endColumn = startColumn + colCount - 1;
+ }
+
+ return range;
+ }
+
+ /**
+ * Determine whether the cells starting from the upper left corner of the range (merged or non-merged or combined) are consistent with the size of the original data
+ * @param cellMatrix
+ * @param range
+ */
+ private _topLeftCellsMatch(rowCount: number, colCount: number, range: IRange): boolean {
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+ const worksheet = workbook.getActiveSheet();
+ const { startRow, startColumn, endRow, endColumn } = range;
+
+ const isRowAcross = rowAcrossMergedCell(
+ startRow + rowCount - 1,
+ startColumn,
+ startColumn + rowCount - 1,
+ worksheet
+ );
+ const isColAcross = columnAcrossMergedCell(
+ startColumn + colCount - 1,
+ startRow,
+ startRow + rowCount - 1,
+ worksheet
+ );
+
+ return !isRowAcross && !isColAcross;
+ }
}
// #region paste parsing
@@ -457,7 +641,7 @@ function parseTableCells(tdStrings: string[]) {
Array.from(cellMatches).forEach((cellMatch) => {
const cellProperties = parseProperties(cellMatch[1]);
- const content = cellMatch[2];
+ const content = cellMatch[2].replace(/&nbsp;/g, ' '); // paste from excel
const rowSpan = cellProperties.rowspan ? +cellProperties.rowspan : 1;
const colSpan = cellProperties.colspan ? +cellProperties.colspan : 1;
@@ -628,4 +812,46 @@ function isLegalSpreadsheetHTMLContent(html: string): boolean {
return html.indexOf('<table') !== -1; // NOTE: This is just a temporary implementation. Definitely would be changed later.
}
+function rowAcrossMergedCell(row: number, startColumn: number, endColumn: number, worksheet: Worksheet): boolean {
+ return worksheet
+ .getMergeData()
+ .some(
+ (mergedCell) =>
+ mergedCell.startRow <= row &&
+ row < mergedCell.endRow &&
+ startColumn <= mergedCell.startColumn &&
+ mergedCell.startColumn <= endColumn
+ );
+}
+
+function columnAcrossMergedCell(col: number, startRow: number, endRow: number, worksheet: Worksheet): boolean {
+ return worksheet
+ .getMergeData()
+ .some(
+ (mergedCell) =>
+ mergedCell.startColumn <= col &&
+ col < mergedCell.endColumn &&
+ startRow <= mergedCell.startRow &&
+ mergedCell.startRow <= endRow
+ );
+}
+
+/**
+ * Determine whether CellMatrix consists of multiple cells, it must consist of 2 or more cells. It can be an ordinary cell or merge cell
+ * @param cellMatrix
+ */
+function isMultipleCells(cellMatrix: ObjectMatrix<IParsedCellValue>): boolean {
+ let count = 0;
+ cellMatrix.forValue((row, col, cell) => {
+ if (cell) {
+ count++;
+ }
+
+ if (count > 1) {
+ return false;
+ }
+ });
+ return count > 1;
+}
+
// #endregion