Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
perf(sheets-ui): optimize pasting large external data into Univer (#7105)
wpxp123456aa5972aab707
diff --git a/packages/core/src/sheets/typedef.ts b/packages/core/src/sheets/typedef.tsindex 46921d18a6..6f1ddf6b55 100644--- a/packages/core/src/sheets/typedef.ts+++ b/packages/core/src/sheets/typedef.ts@@ -593,34 +593,6 @@ export interface IRangeCellData {*/export type IRangeType = IRange | IRangeStringData | IRangeArrayData | IRangeCellData;-/**- * Whether to clear only the contents. Whether to clear only the format; note that clearing format also clears data validation rules.- */-export interface IOptionData {- /**- * 1. designates that only the format should be copied- *- * 2. Whether to clear only the format; note that clearing format also clears data validation rules.- *- * 3. worksheet Whether to clear the format.- */- formatOnly?: boolean;- /**- * 1. designates that only the content should be copied- *- * 2. Whether to clear only the contents.- *- * 3. worksheet Whether to clear the content.- *- */- contentsOnly?: boolean;-}--/**- * Option of copyTo function- */-export interface ICopyToOptionsData extends IOptionData { }-export interface IRectLTRB {left: number;top: number;diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.tsindex 9b1cb6f2df..01297a3266 100644--- a/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts@@ -691,7 +691,6 @@ describe('Test paste with formula', () => {},},},- options: {},},},],@@ -1062,7 +1061,6 @@ describe('Test paste with formula', () => {},},},- options: {},},},],diff --git a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.tsindex e0a9b961d8..f9e73b9ab0 100644--- a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts+++ b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts@@ -101,7 +101,6 @@ import { RemovePasteMenuCommands } from './const';import {generateBody,getClearAndSetMergeMutations,- getClearCellStyleMutations,getDefaultOnPasteCellMutations,getSetCellStyleMutations,getSetCellValueMutations,@@ -607,7 +606,11 @@ export class SheetClipboardController extends RxDisposable {},onPasteCells: (pasteFrom, pasteTo, data) => {return this._injector.invoke((accessor) => {- return getSetCellValueMutations(pasteTo, pasteFrom, data, accessor);+ const { redo, undo } = getSetCellValueMutations(pasteTo, pasteFrom, data, accessor);+ return {+ redos: [redo],+ undos: [undo],+ };});},};@@ -620,12 +623,17 @@ export class SheetClipboardController extends RxDisposable {const redoMutationsInfo: IMutationInfo[] = [];const undoMutationsInfo: IMutationInfo[] = [];- // clear cell style- const { undos: styleUndos, redos: styleRedos } = this._injector.invoke((accessor) => {- return getClearCellStyleMutations(pasteTo, matrix, accessor);+ // Set cell style+ const { redo, undo } = this._injector.invoke((accessor) => {+ return getSetCellStyleMutations(+ pasteTo,+ pasteFrom,+ matrix,+ accessor+ );});- redoMutationsInfo.push(...styleRedos);- undoMutationsInfo.push(...styleUndos);+ redoMutationsInfo.push(redo);+ undoMutationsInfo.push(undo);// clear and set mergeconst { undos: mergeUndos, redos: mergeRedos } = this._injector.invoke((accessor) => {@@ -638,18 +646,6 @@ export class SheetClipboardController extends RxDisposable {redoMutationsInfo.push(...mergeRedos);undoMutationsInfo.push(...mergeUndos);- const { undos: setStyleUndos, redos: setStyleRedos } = this._injector.invoke((accessor) => {- return getSetCellStyleMutations(- pasteTo,- pasteFrom,- matrix,- accessor- );- });-- redoMutationsInfo.push(...setStyleRedos);- undoMutationsInfo.push(...setStyleUndos);-return {undos: undoMutationsInfo,redos: redoMutationsInfo,diff --git a/packages/sheets-ui/src/controllers/clipboard/utils.ts b/packages/sheets-ui/src/controllers/clipboard/utils.tsindex 05274a929d..8c3a2705e3 100644--- a/packages/sheets-ui/src/controllers/clipboard/utils.ts+++ b/packages/sheets-ui/src/controllers/clipboard/utils.ts@@ -16,7 +16,7 @@/* eslint-disable max-lines-per-function */-import type { IAccessor, IBorderData, ICellData, ICustomRange, IDocumentBody, IMutationInfo, IParagraph, IRange, IStyleData, Nullable } from '@univerjs/core';+import type { IAccessor, ICellData, ICustomRange, IDocumentBody, IMutationInfo, IParagraph, IRange, IStyleData, Nullable } from '@univerjs/core';import type {IAddWorksheetMergeMutationParams,IDiscreteRange,@@ -26,12 +26,9 @@ import type {import type { ICellDataWithSpanInfo, ICopyPastePayload, ISheetDiscreteRangeLocation } from '../../services/clipboard/type';import {CellValueType,- cloneCellData,cloneCellDataMatrix,- cloneValue,createParagraphId,CustomRangeType,- DEFAULT_STYLES,generateRandomId,getNumfmtParseValueFilter,isTextFormat,@@ -41,7 +38,6 @@ import {Tools,willLoseNumericPrecision,} from '@univerjs/core';-import { DEFAULT_PADDING_DATA } from '@univerjs/engine-render';import {AddMergeUndoMutationFactory,AddWorksheetMergeMutation,@@ -57,6 +53,12 @@ import { COPY_TYPE } from '../../services/clipboard/type';import { isRichText } from '../editor/editing.render-controller';import { virtualizeDiscreteRanges } from '../utils/range-tools';+interface IExternalPasteNumberFormatResult {+ n?: IStyleData['n'];+ t?: CellValueType;+ v?: ICellData['v'];+}+// if special paste need append mutations instead of replace the default, it can use this function to generate default mutations./***@@ -73,62 +75,39 @@ export function getDefaultOnPasteCellMutations(payload: ICopyPastePayload,accessor: IAccessor) {- const redoMutationsInfo: IMutationInfo[] = [];- const undoMutationsInfo: IMutationInfo[] = [];if (payload.copyType === COPY_TYPE.CUT) {const { undos, redos } = getMoveRangeMutations(pasteFrom, pasteTo, accessor);- redoMutationsInfo.push(...redos);- undoMutationsInfo.push(...undos);- } else {- // clear style- const { undos: clearStyleUndos, redos: clearStyleRedos } = getClearCellStyleMutations(pasteTo, data, accessor);- redoMutationsInfo.push(...clearStyleRedos);- undoMutationsInfo.push(...clearStyleUndos);-- // clear value- const { undos: clearValueUndos, redos: clearValueRedos } = getClearCellValueMutations(pasteTo, data, accessor);- redoMutationsInfo.push(...clearValueRedos);- undoMutationsInfo.push(...clearValueUndos);-- // set values- const { undos: setValuesUndos, redos: setValuesRedos } = getSetCellValueMutations(pasteTo, pasteFrom, data, accessor);- redoMutationsInfo.push(...setValuesRedos);- undoMutationsInfo.push(...setValuesUndos);-- // set styles- const { undos: setStyleUndos, redos: setStyleRedos } = getSetCellStyleMutations(pasteTo, pasteFrom, data, accessor, true);- redoMutationsInfo.push(...setStyleRedos);- undoMutationsInfo.push(...setStyleUndos);-- // Do not process the custom attribute here, users can extend the paste event by themselves-- // clear and add merge- const { undos: clearMergeUndos, redos: clearMergeRedos } = getClearAndSetMergeMutations(- pasteTo,- data,- accessor- );- redoMutationsInfo.push(...clearMergeRedos);- undoMutationsInfo.push(...clearMergeUndos);+ return { undos, redos };}++ const redoMutationsInfo: IMutationInfo[] = [];+ const undoMutationsInfo: IMutationInfo[] = [];++ // Set cell value and style+ const { redo, undo } = getSetCellDataMutations(+ pasteTo,+ pasteFrom,+ data,+ accessor+ );+ redoMutationsInfo.push(redo);+ undoMutationsInfo.push(undo);++ // clear and add merge+ const { undos: clearMergeUndos, redos: clearMergeRedos } = getClearAndSetMergeMutations(+ pasteTo,+ data,+ accessor+ );+ redoMutationsInfo.push(...clearMergeRedos);+ undoMutationsInfo.push(...clearMergeUndos);+return {undos: undoMutationsInfo,redos: redoMutationsInfo,};}-/**- *- * @param from- * @param from.unitId- * @param from.subUnitId- * @param from.range- * @param to- * @param to.unitId- * @param to.subUnitId- * @param to.range- * @param accessor- */export function getMoveRangeMutations(from: {unitId: string;@@ -176,304 +155,276 @@ export function getMoveRangeMutations(};}-/**- *- * @param pasteTo- * @param pasteFrom- * @param matrix- * @param accessor- */-export function getSetCellValueMutations(+function getExternalPasteNumberFormatResult(+ value: ICellData['v'],+ currentCellStyle: Nullable<IStyleData> | undefined+): IExternalPasteNumberFormatResult {+ if (isTextFormat(currentCellStyle?.n?.pattern)) {+ return {+ n: currentCellStyle?.n,+ t: CellValueType.STRING,+ };+ }++ const content = String(value).trim();+ const numfmtValue = getNumfmtParseValueFilter(content);+ const result: IExternalPasteNumberFormatResult = {};++ if (numfmtValue?.v !== undefined && typeof numfmtValue.v === 'number') {+ // If the numeric string will lose precision when converted to a number, set the cell type to force string+ // e.g. 123456789123456789+ // e.g. 1212121212121212.2345+ if (!numfmtValue.z && willLoseNumericPrecision(content)) {+ result.t = CellValueType.FORCE_STRING;+ } else {+ result.v = numfmtValue.v;+ }+ }++ if (numfmtValue?.z) {+ result.n = { pattern: numfmtValue.z };+ }++ return result;+}++export function getSetCellDataMutations(pasteTo: ISheetDiscreteRangeLocation,pasteFrom: Nullable<ISheetDiscreteRangeLocation>,matrix: ObjectMatrix<ICellDataWithSpanInfo>,accessor: IAccessor-) {+): {+ redo: IMutationInfo;+ undo: IMutationInfo;+} {const { unitId, subUnitId, range } = pasteTo;- const worksheet = accessor.get(IUniverInstanceService).getUniverSheetInstance(unitId)?.getSheetBySheetId(subUnitId);- const redoMutationsInfo: IMutationInfo[] = [];- const undoMutationsInfo: IMutationInfo[] = [];+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), { unitId, subUnitId });+ const worksheet = target?.worksheet;const { mapFunc } = virtualizeDiscreteRanges([range]);- const valueMatrix = new ObjectMatrix<ICellData>();- matrix.forValue((row, col, value) => {- const { row: realRow, col: realCol } = mapFunc(row, col);+ const cellValueMatrix = new ObjectMatrix<ICellData>();- const cellValue: ICellData = {+ matrix.forValue((rowIndex, columnIndex, value) => {+ const { row, col } = mapFunc(rowIndex, columnIndex);++ const newStyle = { ...(value.s ?? {}) as IStyleData };+ if (newStyle.bd && Object.keys(newStyle.bd).length === 0) {+ newStyle.bd = {+ t: null,+ r: null,+ b: null,+ l: null,+ };+ }++ let cellValue: ICellData = {+ p: null,v: value.v,t: value.t,};- if (!value.p && value.v && !pasteFrom) {- // pasteFrom is null, means the data is pasted from outside, at this time, the data has no number format.- // If the paste to cell has a number format, google sheet will apply the number format, but excel will not.- // Here the text format need to be handled, other number format need to discuss. TODO: @wzhudev @ybzky- const style = worksheet?.getCellStyle(realRow, realCol);-- if (isTextFormat(style?.n?.pattern)) {- cellValue.t = CellValueType.STRING;- } else {- const content = String(value.v).trim();- const numfmtValue = getNumfmtParseValueFilter(content);- if (numfmtValue?.v !== undefined && typeof numfmtValue.v === 'number') {- // If the numeric string will lose precision when converted to a number, set the cell type to force string- // e.g. 123456789123456789- // e.g. 1212121212121212.2345- if (!numfmtValue.z && willLoseNumericPrecision(content)) {- cellValue.t = CellValueType.FORCE_STRING;- } else {- cellValue.v = numfmtValue.v;- }- }+ if (value.p?.body && isRichText(value.p.body)) {+ cellValue = {+ p: value.p,+ v: value.v,+ };+ } else if (!pasteFrom && value.v && !newStyle.n?.pattern) {+ /**+ * The `pasteFrom` is null, means the data is pasted from outside.+ * If the value's style has no number format, handle it as follows:+ * 1. The paste to cell has a number format, google sheets will apply the number format, but excel does not.+ * Here we only handle the text format, other number format are left unhandled now.+ * 2. If the above case does not apply, parse the value to check whether it has a number format.+ */+ const currentCellStyle = worksheet?.getCellStyle(row, col);+ const numfmtResult = getExternalPasteNumberFormatResult(value.v, currentCellStyle);++ if (numfmtResult.n) {+ newStyle.n = numfmtResult.n;+ }+ if (numfmtResult.t !== undefined) {+ cellValue.t = numfmtResult.t;+ }+ if (numfmtResult.v !== undefined) {+ cellValue.v = numfmtResult.v;}}- if (value.p?.body && isRichText(value.p.body)) {- const newValue = { p: cloneValue(value.p), v: value.v };- valueMatrix.setValue(realRow, realCol, newValue);- } else {- valueMatrix.setValue(realRow, realCol, cellValue && cloneCellData(cellValue)!);- }+ cellValue.s = Object.keys(newStyle).length > 0 ? newStyle : null;++ cellValueMatrix.setValue(row, col, cellValue);});- // set cell value and style- const setValuesMutation: ISetRangeValuesMutationParams = {++ const redoParams: ISetRangeValuesMutationParams = {unitId,subUnitId,- cellValue: cloneCellDataMatrix(valueMatrix.getMatrix()),+ cellValue: cloneCellDataMatrix(cellValueMatrix.getMatrix()),+ isOverrideStyle: true,};-- redoMutationsInfo.push({- id: SetRangeValuesMutation.id,- params: setValuesMutation,- });-- // undo- const undoSetValuesMutation: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(+ const undoParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(accessor,- setValuesMutation+ redoParams);- undoMutationsInfo.push({- id: SetRangeValuesMutation.id,- params: undoSetValuesMutation,- });return {- undos: undoMutationsInfo,- redos: redoMutationsInfo,+ redo: {+ id: SetRangeValuesMutation.id,+ params: redoParams,+ },+ undo: {+ id: SetRangeValuesMutation.id,+ params: undoParams,+ },};}-/**- *- * @param pasteTo- * @param pasteFrom- * @param matrix- * @param accessor- * @param _withRichFormat- */-export function getSetCellStyleMutations(+export function getSetCellValueMutations(pasteTo: ISheetDiscreteRangeLocation,pasteFrom: Nullable<ISheetDiscreteRangeLocation>,matrix: ObjectMatrix<ICellDataWithSpanInfo>,- accessor: IAccessor,- _withRichFormat = false-) {- const redoMutationsInfo: IMutationInfo[] = [];- const undoMutationsInfo: IMutationInfo[] = [];+ accessor: IAccessor+): {+ redo: IMutationInfo;+ undo: IMutationInfo;+} {const { unitId, subUnitId, range } = pasteTo;- const worksheet = accessor.get(IUniverInstanceService).getUniverSheetInstance(unitId)?.getSheetBySheetId(subUnitId);- const valueMatrix = new ObjectMatrix<ICellData>();-+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), { unitId, subUnitId });+ const worksheet = target?.worksheet;const { mapFunc } = virtualizeDiscreteRanges([range]);- matrix.forValue((row, col, value) => {- const newValue: ICellData = {- s: Object.assign({}, {- ...DEFAULT_STYLES,- pd: DEFAULT_PADDING_DATA,- bg: null,- cl: null,- }, value.s),- };-- // Here I don't know why when setting the border, an empty object is also assigned to the adjacent cells without borders.- // This is the fundamental cause of the problem. This should be unreasonable, so I bypassed this problem first.- const cellBd = (newValue.s as IStyleData).bd as IBorderData;- if (cellBd) {- const isValid = Object.keys(cellBd).length > 0;- if (!isValid) {- (newValue.s as IStyleData)!.bd = {- b: null,- l: null,- r: null,- t: null,- };- }- }+ const cellValueMatrix = new ObjectMatrix<ICellData>();- const { row: actualRow, col: actualCol } = mapFunc(row, col);+ matrix.forValue((rowIndex, columnIndex, value) => {+ const { row, col } = mapFunc(rowIndex, columnIndex);- // pasteFrom is null, means the data is pasted from outside, at this time, the data has no number format.- // If the paste to cell has a number format, google sheet will apply the number format, but excel will not.- // Here the text format need to be handled, other number format need to discuss. TODO: @wzhudev @ybzky- const style = worksheet?.getCellStyle(actualRow, actualCol);+ let cellValue: ICellData = {+ p: null,+ v: value.v,+ t: value.t,+ };- if (value.v && !pasteFrom && isTextFormat(style?.n?.pattern)) {- if (!newValue.s) {- newValue.s = {};+ if (value.p?.body && isRichText(value.p.body)) {+ cellValue = {+ p: value.p,+ v: value.v,+ };+ } else if (value.v && !pasteFrom && !(value.s as IStyleData)?.n?.pattern) {+ /**+ * The `pasteFrom` is null, means the data is pasted from outside.+ * If the value's style has no number format, handle it as follows:+ * 1. The paste to cell has a number format, google sheets will apply the number format, but excel does not.+ * Here we only handle the text format, other number format are left unhandled now.+ * 2. If the above case does not apply, parse the value to check whether it has a number format.+ */+ const currentCellStyle = worksheet?.getCellStyle(row, col);+ const numfmtResult = getExternalPasteNumberFormatResult(value.v, currentCellStyle);++ if (numfmtResult.t !== undefined) {+ cellValue.t = numfmtResult.t;}- (newValue.s as IStyleData).n = style?.n;- } else {- const content = String(value.v).trim();- const numfmtValue = getNumfmtParseValueFilter(content);- if (numfmtValue?.z) {- if (!newValue.s) {- newValue.s = {};- }- if (typeof newValue.s === 'object') {- if (!newValue.s?.n) {- newValue.s.n = { pattern: numfmtValue.z };- } else {- newValue.s.n.pattern = numfmtValue.z;- }- }+ if (numfmtResult.v !== undefined) {+ cellValue.v = numfmtResult.v;}}- valueMatrix.setValue(actualRow, actualCol, newValue);+ cellValueMatrix.setValue(row, col, cellValue);});- // set cell style- const setValuesMutation: ISetRangeValuesMutationParams = {++ const redoParams: ISetRangeValuesMutationParams = {unitId,subUnitId,- cellValue: cloneCellDataMatrix(valueMatrix.getMatrix()),+ cellValue: cloneCellDataMatrix(cellValueMatrix.getMatrix()),};-- redoMutationsInfo.push({- id: SetRangeValuesMutation.id,- params: setValuesMutation,- });-- // undo- const undoSetValuesMutation: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(+ const undoParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(accessor,- setValuesMutation+ redoParams);- undoMutationsInfo.push({- id: SetRangeValuesMutation.id,- params: undoSetValuesMutation,- });return {- undos: undoMutationsInfo,- redos: redoMutationsInfo,+ redo: {+ id: SetRangeValuesMutation.id,+ params: redoParams,+ },+ undo: {+ id: SetRangeValuesMutation.id,+ params: undoParams,+ },};}-/**- *- * @param pasteTo- * @param matrix- * @param accessor- */-export function getClearCellStyleMutations(+export function getSetCellStyleMutations(pasteTo: ISheetDiscreteRangeLocation,+ pasteFrom: Nullable<ISheetDiscreteRangeLocation>,matrix: ObjectMatrix<ICellDataWithSpanInfo>,accessor: IAccessor-) {- const redoMutationsInfo: IMutationInfo[] = [];- const undoMutationsInfo: IMutationInfo[] = [];- const clearStyleMatrix = new ObjectMatrix<ICellData>();+): {+ redo: IMutationInfo;+ undo: IMutationInfo;+} {const { unitId, subUnitId, range } = pasteTo;+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), { unitId, subUnitId });+ const worksheet = target?.worksheet;const { mapFunc } = virtualizeDiscreteRanges([range]);- matrix.forEach((rowIndex, row) => {- Object.keys(row).forEach((colIndexStr) => {- const colIndex = Number(colIndexStr);- const { row: actualRow, col: actualCol } = mapFunc(rowIndex, colIndex);- clearStyleMatrix.setValue(actualRow, actualCol, { s: null });- });- });- // clear style- if (clearStyleMatrix.getLength() > 0) {- const clearMutation: ISetRangeValuesMutationParams = {- subUnitId,- unitId,- cellValue: cloneCellDataMatrix(clearStyleMatrix.getMatrix()),- };- redoMutationsInfo.push({- id: SetRangeValuesMutation.id,- params: clearMutation,- });+ const cellValueMatrix = new ObjectMatrix<ICellData>();- // undo- const undoClearMutation: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(- accessor,- clearMutation- );+ matrix.forValue((rowIndex, columnIndex, value) => {+ const { row, col } = mapFunc(rowIndex, columnIndex);- undoMutationsInfo.push({- id: SetRangeValuesMutation.id,- params: undoClearMutation,- });- }-- return { undos: undoMutationsInfo, redos: redoMutationsInfo };-}+ const newStyle = { ...(value.s ?? {}) as IStyleData };+ if (newStyle.bd && Object.keys(newStyle.bd).length === 0) {+ newStyle.bd = {+ t: null,+ r: null,+ b: null,+ l: null,+ };+ }-/**- *- * @param pasteTo- * @param matrix- * @param accessor- */-export function getClearCellValueMutations(- pasteTo: ISheetDiscreteRangeLocation,- matrix: ObjectMatrix<ICellDataWithSpanInfo>,- accessor: IAccessor-) {- const redoMutationsInfo: IMutationInfo[] = [];- const undoMutationsInfo: IMutationInfo[] = [];- const clearValueMatrix = new ObjectMatrix<ICellData>();- const { unitId, subUnitId, range } = pasteTo;- const { mapFunc } = virtualizeDiscreteRanges([range]);+ if (!pasteFrom && value.v && !newStyle.n?.pattern) {+ /**+ * The `pasteFrom` is null, means the data is pasted from outside.+ * If the value's style has no number format, handle it as follows:+ * 1. The paste to cell has a number format, google sheets will apply the number format, but excel does not.+ * Here we only handle the text format, other number format are left unhandled now.+ * 2. If the above case does not apply, parse the value to check whether it has a number format.+ */+ const currentCellStyle = worksheet?.getCellStyle(row, col);+ const numfmtResult = getExternalPasteNumberFormatResult(value.v, currentCellStyle);++ if (numfmtResult.n) {+ newStyle.n = numfmtResult.n;+ }+ }- matrix.forValue((row, col, _value) => {- const { row: actualRow, col: actualCol } = mapFunc(row, col);- clearValueMatrix.setValue(actualRow, actualCol, { v: null, p: null });- });- if (clearValueMatrix.getLength() > 0) {- const clearMutation: ISetRangeValuesMutationParams = {- subUnitId,- unitId,- cellValue: cloneCellDataMatrix(clearValueMatrix.getMatrix()),- };- redoMutationsInfo.push({- id: SetRangeValuesMutation.id,- params: clearMutation,+ cellValueMatrix.setValue(row, col, {+ s: Object.keys(newStyle).length > 0 ? newStyle : null,});+ });- // undo- const undoClearMutation: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(- accessor,- clearMutation- );+ const redoParams: ISetRangeValuesMutationParams = {+ unitId,+ subUnitId,+ cellValue: cloneCellDataMatrix(cellValueMatrix.getMatrix()),+ isOverrideStyle: true,+ };+ const undoParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(+ accessor,+ redoParams+ );- undoMutationsInfo.push({+ return {+ redo: {id: SetRangeValuesMutation.id,- params: undoClearMutation,- });- }-- return { undos: undoMutationsInfo, redos: redoMutationsInfo };+ params: redoParams,+ },+ undo: {+ id: SetRangeValuesMutation.id,+ params: undoParams,+ },+ };}-/**- *- * @param pasteTo- * @param matrix- * @param accessor- */export function getClearAndSetMergeMutations(pasteTo: ISheetDiscreteRangeLocation,matrix: ObjectMatrix<ICellDataWithSpanInfo>,@@ -481,6 +432,7 @@ export function getClearAndSetMergeMutations() {const redoMutationsInfo: IMutationInfo[] = [];const undoMutationsInfo: IMutationInfo[] = [];+const { unitId, subUnitId, range } = pasteTo;const { startColumn, startRow, endColumn, endRow } = discreteRangeToRange(range);const mergeRangeData: IRange[] = [];@@ -565,10 +517,6 @@ export function getClearAndSetMergeMutations(return { redos: redoMutationsInfo, undos: undoMutationsInfo };}-/**- *- * @param text- */export function generateBody(text: string): IDocumentBody {if (!text.includes('\r') && Tools.isLegalUrl(text)) {const id = generateRandomId();diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.tsindex 77e932ac0c..7c6b2aa0b7 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.ts@@ -172,36 +172,7 @@ describe('Test clipboard', () => {fs: 12,ht: 0,it: 1,- ol: {- cl: {- rgb: 'rgb(0,0,0)',- },- s: 0,- },- pd: {- b: 2,- l: 2,- r: 2,- t: 0,- },- st: {- cl: {- rgb: 'rgb(0,0,0)',- },- s: 0,- },tb: 1,- td: 0,- tr: {- a: 0,- v: 0,- },- ul: {- cl: {- rgb: 'rgb(0,0,0)',- },- s: 0,- },vt: 2,});});@@ -303,16 +274,10 @@ describe('Test clipboard', () => {fs: 11,it: 0,bl: 0,- ul: { s: 0, cl: { rgb: 'rgb(0,0,0)' } },- st: { s: 0, cl: { rgb: 'rgb(0,0,0)' } },- ol: { s: 0, cl: { rgb: 'rgb(0,0,0)' } },- tr: { a: 0, v: 0 },- td: 0,cl: { rgb: 'rgb(0,0,0)' },ht: 0,vt: 2,tb: 1,- pd: { t: 0, b: 2, l: 2, r: 2 },});expect(L1CellStyle).toStrictEqual({n: { pattern: DEFAULT_TEXT_FORMAT_EXCEL },@@ -320,16 +285,10 @@ describe('Test clipboard', () => {fs: 11,it: 0,bl: 0,- ul: { s: 0, cl: { rgb: 'rgb(0,0,0)' } },- st: { s: 0, cl: { rgb: 'rgb(0,0,0)' } },- ol: { s: 0, cl: { rgb: 'rgb(0,0,0)' } },- tr: { a: 0, v: 0 },- td: 0,cl: { rgb: 'rgb(0,0,0)' },ht: 0,vt: 2,tb: 1,- pd: { t: 0, b: 2, l: 2, r: 2 },});});diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.tsindex de6f6992d4..debb87d813 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.ts@@ -149,43 +149,9 @@ describe('Test clipboard', () => {expect(getValues(2, 2, 2, 2)?.[0]?.[0]?.v).toEqual('Univer');expect(getStyles(2, 2, 2, 2)?.[0]?.[0]).toStrictEqual({bl: 1,- // cl: {- // rgb: '#000',- // },ff: 'Arial',fs: 10,- ht: 0,it: 1,- ol: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- pd: {- b: 2,- l: 2,- r: 2,- t: 0,- },- st: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- tb: 0,- td: 0,- tr: {- a: 0,- v: 0,- },- ul: {- // cl: {- // rgb: '#000',- // },- s: 0,- },vt: 3,});});diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.tsindex acd30dae9d..d160910cfd 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts@@ -36,6 +36,16 @@ import { COPY_TYPE } from '../type';import { clipboardTestBed } from './clipboard-test-bed';import { MockClipboard } from './mock-clipboard';+const EXPECTED_EXTERNAL_PASTE_STYLE = {+ bg: {+ rgb: 'rgb(255,0,0)',+ },+ ff: 'Arial',+ fs: 10,+ ht: 2,+ vt: 2,+};+describe('Test clipboard', () => {let univer: Univer;let get: Injector['get'];@@ -159,50 +169,7 @@ describe('Test clipboard', () => {const columnWidth = columnManager?.getColumnWidth(0);expect(columnWidth).toBe(88);expect(values && values[0][0]?.v).toBe('row1col2');- expect(styles && styles[0][0]).toStrictEqual({- bg: {- rgb: 'rgb(255,0,0)',- },- bl: 0,- // cl: {- // rgb: '#000',- // },- ff: 'Arial',- fs: 10,- ht: 2,- it: 0,- ol: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- pd: {- b: 2,- l: 2,- r: 2,- t: 0,- },- st: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- tb: 0,- td: 0,- tr: {- a: 0,- v: 0,- },- ul: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- vt: 2,- });+ expect(styles && styles[0][0]).toStrictEqual(EXPECTED_EXTERNAL_PASTE_STYLE);expect(mergedCells && mergedCells[0]).toStrictEqual({startRow: 0,startColumn: 0,@@ -232,50 +199,7 @@ describe('Test clipboard', () => {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)',- },- bl: 0,- // cl: {- // rgb: '#000',- // },- ff: 'Arial',- fs: 10,- ht: 2,- it: 0,- ol: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- pd: {- b: 2,- l: 2,- r: 2,- t: 0,- },- st: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- tb: 0,- td: 0,- tr: {- a: 0,- v: 0,- },- ul: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- vt: 2,- });+ expect(styles && styles[0][0]).toStrictEqual(EXPECTED_EXTERNAL_PASTE_STYLE);expect(mergedCells && mergedCells[0]).toStrictEqual({startRow,startColumn,@@ -305,50 +229,7 @@ describe('Test clipboard', () => {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)',- },- bl: 0,- // cl: {- // rgb: '#000',- // },- ff: 'Arial',- fs: 10,- ht: 2,- it: 0,- ol: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- pd: {- b: 2,- l: 2,- r: 2,- t: 0,- },- st: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- tb: 0,- td: 0,- tr: {- a: 0,- v: 0,- },- ul: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- vt: 2,- });+ expect(styles && styles[0][0]).toStrictEqual(EXPECTED_EXTERNAL_PASTE_STYLE);expect(values && values[0][2]?.v).toBe(undefined);expect(styles && styles[0][2]).toStrictEqual(undefined);expect(mergedCells && mergedCells[0]).toStrictEqual({@@ -382,94 +263,8 @@ describe('Test clipboard', () => {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)',- },- bl: 0,- // cl: {- // rgb: '#000',- // },- ff: 'Arial',- fs: 10,- ht: 2,- it: 0,- ol: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- pd: {- b: 2,- l: 2,- r: 2,- t: 0,- },- st: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- tb: 0,- td: 0,- tr: {- a: 0,- v: 0,- },- ul: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- vt: 2,- });- expect(styles && styles[1][0]).toStrictEqual({- bg: {- rgb: 'rgb(255,0,0)',- },- bl: 0,- // cl: {- // rgb: '#000',- // },- ff: 'Arial',- fs: 10,- ht: 2,- it: 0,- ol: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- pd: {- b: 2,- l: 2,- r: 2,- t: 0,- },- st: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- tb: 0,- td: 0,- tr: {- a: 0,- v: 0,- },- ul: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- vt: 2,- });+ expect(styles && styles[0][0]).toStrictEqual(EXPECTED_EXTERNAL_PASTE_STYLE);+ expect(styles && styles[1][0]).toStrictEqual(EXPECTED_EXTERNAL_PASTE_STYLE);expect(mergedCells).toStrictEqual([{startRow: 3,@@ -510,94 +305,8 @@ describe('Test clipboard', () => {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)',- },- bl: 0,- // cl: {- // rgb: '#000',- // },- ff: 'Arial',- fs: 10,- ht: 2,- it: 0,- ol: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- pd: {- b: 2,- l: 2,- r: 2,- t: 0,- },- st: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- tb: 0,- td: 0,- tr: {- a: 0,- v: 0,- },- ul: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- vt: 2,- });- expect(styles && styles[i][2]).toStrictEqual({- bg: {- rgb: 'rgb(255,0,0)',- },- bl: 0,- // cl: {- // rgb: '#000',- // },- ff: 'Arial',- fs: 10,- ht: 2,- it: 0,- ol: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- pd: {- b: 2,- l: 2,- r: 2,- t: 0,- },- st: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- tb: 0,- td: 0,- tr: {- a: 0,- v: 0,- },- ul: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- vt: 2,- });+ expect(styles && styles[i][0]).toStrictEqual(EXPECTED_EXTERNAL_PASTE_STYLE);+ expect(styles && styles[i][2]).toStrictEqual(EXPECTED_EXTERNAL_PASTE_STYLE);}expect(mergedCells).toStrictEqual([{@@ -676,50 +385,7 @@ describe('Test clipboard', () => {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)',- },- bl: 0,- // cl: {- // rgb: '#000',- // },- ff: 'Arial',- fs: 10,- ht: 2,- it: 0,- ol: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- pd: {- b: 2,- l: 2,- r: 2,- t: 0,- },- st: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- tb: 0,- td: 0,- tr: {- a: 0,- v: 0,- },- ul: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- vt: 2,- });+ expect(styles && styles[0][0]).toStrictEqual(EXPECTED_EXTERNAL_PASTE_STYLE);expect(mergedCells && mergedCells[0]).toStrictEqual({startRow,startColumn,@@ -814,50 +480,7 @@ describe('Test clipboard', () => {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)',- },- bl: 0,- // cl: {- // rgb: '#000',- // },- ff: 'Arial',- fs: 10,- ht: 2,- it: 0,- ol: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- pd: {- b: 2,- l: 2,- r: 2,- t: 0,- },- st: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- tb: 0,- td: 0,- tr: {- a: 0,- v: 0,- },- ul: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- vt: 2,- });+ expect(styles && styles[0][0]).toStrictEqual(EXPECTED_EXTERNAL_PASTE_STYLE);expect(mergedCells && mergedCells[0]).toStrictEqual({startRow: 9,startColumn: 5,@@ -941,50 +564,7 @@ describe('Test clipboard', () => {// first merged cells changedexpect(values && values[0][0]?.v).toBe('row1col2');- expect(styles && styles[0][0]).toStrictEqual({- bg: {- rgb: 'rgb(255,0,0)',- },- bl: 0,- // cl: {- // rgb: '#000',- // },- ff: 'Arial',- fs: 10,- ht: 2,- it: 0,- ol: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- pd: {- b: 2,- l: 2,- r: 2,- t: 0,- },- st: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- tb: 0,- td: 0,- tr: {- a: 0,- v: 0,- },- ul: {- // cl: {- // rgb: '#000',- // },- s: 0,- },- vt: 2,- });+ expect(styles && styles[0][0]).toStrictEqual(EXPECTED_EXTERNAL_PASTE_STYLE);// second merged cells not changedexpect(values && values[2][1]?.v).toBe('456');diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/utils.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/utils.spec.tsindex 924e3335f1..544dd6f6b4 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/utils.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/utils.spec.ts@@ -177,6 +177,15 @@ describe('test "mergeSetRangeValues"', () => {]);});+ it('does not merge setRangeValues mutations with different style override behavior', () => {+ const mutations: IMutationInfo[] = [+ { id: SetRangeValuesMutation.id, params: { unitId: '1', subUnitId: '2', isOverrideStyle: true, cellValue: { 1: { 2: { s: { fs: 12 } } } } } },+ { id: SetRangeValuesMutation.id, params: { unitId: '1', subUnitId: '2', cellValue: { 1: { 3: { s: { bl: 1 } } } } } },+ ];++ expect(mergeSetRangeValues(mutations)).toStrictEqual(mutations);+ });+it('If some setRangeValues appear discontinuously, they will be merged separately.', () => {const mutations: IMutationInfo[] = [{ id: 'whatever', params: {} },diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.tsindex 2042fe5272..3d50214205 100644--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts@@ -26,7 +26,7 @@ import type {IUniverSheetCopyDataModel,} from '../type';import type { IAfterProcessRule, IPastePlugin } from './paste-plugins/type';-import { createParagraphId, CustomRangeType, DEFAULT_WORKSHEET_ROW_HEIGHT, generateRandomId, getNumfmtParseValueFilter, isSafeUrl, numfmt, ObjectMatrix, skipParseTagNames } from '@univerjs/core';+import { createParagraphId, CustomRangeType, DEFAULT_WORKSHEET_ROW_HEIGHT, generateRandomId, getNumfmtParseValueFilter, isDefaultFormat, isSafeUrl, numfmt, ObjectMatrix, skipParseTagNames } from '@univerjs/core';import { handleStringToStyle, textTrim } from '@univerjs/ui';import { extractNodeStyle } from './parse-node-style';import parseToDom, { convertToCellStyle, generateParagraphs } from './utils';@@ -94,6 +94,14 @@ export class HtmlToUSMService {private _styleMap = new Map<string, CSSStyleDeclaration>();+ private _selectorStyleValueCache = new Map<string, string>();++ private _styleObjectCache = new Map<string, Record<string, string>>();++ private _computedStyleStringCache = new Map<string, string>();++ private _cellStyleDataCache = new Map<string, IStyleData>();+private _styleCache: Map<ChildNode, ITextStyle> = new Map();private _styleRules: IStyleRule[] = [];@@ -291,15 +299,36 @@ export class HtmlToUSMService {}private _getStyleBySelectorText(selectorText: string, cssText: string) {+ const cacheKey = `${selectorText}\0${cssText}`;+ if (this._selectorStyleValueCache.has(cacheKey)) {+ return this._selectorStyleValueCache.get(cacheKey)!;+ }+const css = this._styleMap.get(selectorText)?.getPropertyValue(cssText);if (!css) {+ this._selectorStyleValueCache.set(cacheKey, '');return '';}+ this._selectorStyleValueCache.set(cacheKey, css);return css;}+ private _getStyleObject(styleStr: string) {+ let styleObject = this._styleObjectCache.get(styleStr);+ if (!styleObject) {+ styleObject = turnToStyleObject(styleStr);+ this._styleObjectCache.set(styleStr, styleObject);+ }+ return styleObject;+ }+private _getStyle(node: HTMLElement, styleStr: string) {- const recordStyle: Record<string, string> = turnToStyleObject(styleStr);+ const styleCacheKey = `${styleStr}\0${node.nodeName}\0${node.id}\0${node.className}\0${node.style.cssText}`;+ if (this._computedStyleStringCache.has(styleCacheKey)) {+ return this._computedStyleStringCache.get(styleCacheKey)!;+ }++ const recordStyle: Record<string, string> = this._getStyleObject(styleStr);const style = node.style;// style represents inline styles with the highest priority, followed by selectorText which corresponds to stylesheet rules, and recordStyle pertains to inherited styles with the lowest priority.let newStyleStr = '';@@ -344,9 +373,19 @@ export class HtmlToUSMService {'';value && (newStyleStr += `${key}:${value};`);}+ this._computedStyleStringCache.set(styleCacheKey, newStyleStr);return newStyleStr;}+ private _getCellStyleData(styleStr = '') {+ let style = this._cellStyleDataCache.get(styleStr);+ if (!style) {+ style = handleStringToStyle(undefined, styleStr);+ this._cellStyleDataCache.set(styleStr, style);+ }+ return style;+ }+private _parseTable(html: string, tableElIndex: number) {const valueMatrix = new ObjectMatrix<ICellDataWithSpanInfo>();const colProperties = parseColGroup(html) ?? [];@@ -354,7 +393,7 @@ export class HtmlToUSMService {const parsedCellMatrix = this._parseTableByHtml(this._dom!, tableElIndex, this._getCurrentSkeleton()?.skeleton);parsedCellMatrix &&parsedCellMatrix.forValue((row, col, value) => {- let style = handleStringToStyle(undefined, value.style);+ let style = this._getCellStyleData(value.style);if (value?.richTextParma?.p?.body?.textRuns?.length) {const textLen = value?.richTextParma?.v?.length;for (let i = 0; i < value?.richTextParma?.p?.body?.textRuns?.length; i++) {@@ -459,8 +498,8 @@ export class HtmlToUSMService {let numfmtPattern: string | undefined;const pattern = this._getMsoNumfmtForNode(cell as HTMLElement);- if (pattern) {- cellText = cell.innerHTML;+ if (!isDefaultFormat(pattern)) {+ cellText = cell.childElementCount === 0 ? normalizePlainCellText(cell.textContent ?? '') : cell.innerHTML;if (cellText.includes('mso-spacerun:yes')) {cellText = cleanMsoSpaceRun(cellText);}@@ -559,7 +598,7 @@ export class HtmlToUSMService {} else if (node.nodeType === Node.ELEMENT_NODE) {const currentNodeStyle = this._getStyle(node as HTMLElement, styleStr);const parentStyles = parent ? styleCache.get(parent) : {};- const predefinedStyles = turnToStyleObject(currentNodeStyle);+ const predefinedStyles = this._getStyleObject(currentNodeStyle);const nodeStyles = extractNodeStyle(node as HTMLElement, predefinedStyles);styleCache.set(node, { ...parentStyles, ...nodeStyles });@@ -570,14 +609,22 @@ export class HtmlToUSMService {}private _getCellTextAndRichText(cell: Element, styleStr: string, skeleton?: SpreadsheetSkeleton) {+ if (cell.childElementCount === 0) {+ return {+ cellText: normalizePlainCellText(cell.textContent ?? ''),+ cellRichStyle: undefined,+ };+ }++ const cellHtml = cell.innerHTML;/*** mso-spacerun:yes is used to force spaces in html copied from excel.* if the remaining text is a number or parse to a number, return the remaining text directly.* e.g. excel cell value is 1234.567, and cell format is "#,##0.00", then the copied html is:* "<span style="mso-spacerun:yes"> </span>1,234.57 "*/- if (cell.innerHTML.includes('mso-spacerun:yes')) {- const cellText = cleanMsoSpaceRun(cell.innerHTML);+ if (cellHtml.includes('mso-spacerun:yes')) {+ const cellText = cleanMsoSpaceRun(cellHtml);const parseInfo = getNumfmtParseValueFilter(cellText);if (parseInfo && parseInfo.z && typeof parseInfo.v === 'number') {@@ -590,7 +637,7 @@ export class HtmlToUSMService {let cellText = '';let cellRichStyle;- const isRichText = /<[^>]+>/.test(cell.innerHTML);+ const isRichText = /<[^>]+>/.test(cellHtml);if (isRichText && skeleton) {const newDocBody: IDocumentBody = {dataStream: '',@@ -615,7 +662,7 @@ export class HtmlToUSMService {cellRichStyle = documentModel?.getSnapshot();cellText = newDocBody.dataStream;} else {- cellText = decodeHTMLEntities(cell.innerHTML.replace(/[\r\n]/g, ''));+ cellText = decodeHTMLEntities(cellHtml.replace(/[\r\n]/g, ''));}return {cellText,@@ -748,6 +795,10 @@ export class HtmlToUSMService {this._dom = null;this._styleCache.clear();this._styleMap.clear();+ this._selectorStyleValueCache.clear();+ this._styleObjectCache.clear();+ this._computedStyleStringCache.clear();+ this._cellStyleDataCache.clear();this._msoNumfmtMap.clear();}}@@ -875,6 +926,10 @@ function decodeHTMLEntities(input: string): string {return input.replace(/<|>|&|"|'| |<br>/g, (match) => entities[match]);}+function normalizePlainCellText(input: string): string {+ return input.replace(/[\r\n]/g, '').replace(/\u00A0/g, ' ');+}+function extractStyleProperty(styleString?: string, propertyName?: string) {if (!styleString || !propertyName) return null;const regex = new RegExp(`(${propertyName}\\s*:\\s*[^;]+);`, 'i');diff --git a/packages/sheets-ui/src/services/clipboard/utils.ts b/packages/sheets-ui/src/services/clipboard/utils.tsindex a647b8ba34..3cda40210c 100644--- a/packages/sheets-ui/src/services/clipboard/utils.ts+++ b/packages/sheets-ui/src/services/clipboard/utils.ts@@ -149,7 +149,8 @@ export function mergeCellValues(...cellValues: IObjectMatrixPrimitiveType<Nullabexport function getRangeValuesMergeable(m1: IMutationInfo<ISetRangeValuesMutationParams>, m2: IMutationInfo<ISetRangeValuesMutationParams>) {return m1.id === m2.id&& m1.params.unitId === m2.params.unitId- && m1.params.subUnitId === m2.params.subUnitId;+ && m1.params.subUnitId === m2.params.subUnitId+ && Boolean(m1.params.isOverrideStyle) === Boolean(m2.params.isOverrideStyle);}export function mergeSetRangeValues(mutations: IMutationInfo[]) {diff --git a/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.tsindex 6396bc93e8..727c9362e8 100644--- a/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts+++ b/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts@@ -32,7 +32,7 @@ import {} from '@univerjs/core';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { SheetsSelectionsService } from '../../../services/selections/selection.service';-import { SetRangeValuesMutation } from '../../mutations/set-range-values.mutation';+import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../../mutations/set-range-values.mutation';import { SetSelectionsOperation } from '../../operations/selection.operation';import { SetRangeValuesCommand } from '../set-range-values.command';import { createCommandTestBed } from './create-command-test-bed';@@ -133,6 +133,7 @@ const getTestWorkbookDataDemo = (): IWorkbookData => ({describe('Test set range values commands', () => {let univer: Univer;+ let injector: Injector;let get: Injector['get'];let commandService: ICommandService;let selectionManager: SheetsSelectionsService;@@ -149,6 +150,7 @@ describe('Test set range values commands', () => {beforeEach(() => {const testBed = createCommandTestBed(getTestWorkbookDataDemo());univer = testBed.univer;+ injector = testBed.injector;get = testBed.get;commandService = get(ICommandService);@@ -892,6 +894,55 @@ describe('Test set range values commands', () => {expect(getValue()?.p).toBeTruthy();});+ it('merges styles by default and restores the previous style on undo', async () => {+ const redoParams = {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: {+ 2: {+ 1: {+ v: 'B2 changed',+ s: { fs: 20 },+ },+ },+ },+ };+ const undoParams = injector.invoke((accessor) => SetRangeValuesUndoMutationFactory(accessor, redoParams));++ expect(await commandService.executeCommand(SetRangeValuesMutation.id, redoParams)).toBeTruthy();+ expect(getValues(2, 1, 2, 1)).toStrictEqual([[expect.objectContaining({ v: 'B2 changed' })]]);+ expect(getStyles(2, 1, 2, 1)).toStrictEqual([[{ bl: 0, fs: 20 }]]);++ expect(await commandService.executeCommand(SetRangeValuesMutation.id, undoParams)).toBeTruthy();+ expect(getValues(2, 1, 2, 1)).toStrictEqual([[expect.objectContaining({ v: 'B2' })]]);+ expect(getStyles(2, 1, 2, 1)).toStrictEqual([[{ bl: 0 }]]);+ });++ it('overrides styles when isOverrideStyle is true and restores the full previous style on undo', async () => {+ const redoParams = {+ unitId: 'test',+ subUnitId: 'sheet1',+ isOverrideStyle: true,+ cellValue: {+ 2: {+ 1: {+ v: 'B2 changed',+ s: { fs: 20 },+ },+ },+ },+ };+ const undoParams = injector.invoke((accessor) => SetRangeValuesUndoMutationFactory(accessor, redoParams));++ expect(await commandService.executeCommand(SetRangeValuesMutation.id, redoParams)).toBeTruthy();+ expect(getValues(2, 1, 2, 1)).toStrictEqual([[expect.objectContaining({ v: 'B2 changed' })]]);+ expect(getStyles(2, 1, 2, 1)).toStrictEqual([[{ fs: 20 }]]);++ expect(await commandService.executeCommand(SetRangeValuesMutation.id, undoParams)).toBeTruthy();+ expect(getValues(2, 1, 2, 1)).toStrictEqual([[expect.objectContaining({ v: 'B2' })]]);+ expect(getStyles(2, 1, 2, 1)).toStrictEqual([[{ bl: 0 }]]);+ });+it('set value when origin cell has text number format', async () => {function getParams() {const params: ISetRangeValuesCommandParams = {diff --git a/packages/sheets/src/commands/mutations/set-range-values.mutation.ts b/packages/sheets/src/commands/mutations/set-range-values.mutation.tsindex 3439bbef2a..5d227b0b99 100644--- a/packages/sheets/src/commands/mutations/set-range-values.mutation.ts+++ b/packages/sheets/src/commands/mutations/set-range-values.mutation.ts@@ -17,7 +17,6 @@import type {IAccessor,ICellData,- ICopyToOptionsData,IMutation,IMutationCommonParams,IObjectMatrixPrimitiveType,@@ -42,9 +41,10 @@ export interface ISetRangeValuesMutationParams extends IMutationCommonParams {cellValue?: IObjectMatrixPrimitiveType<Nullable<ICellData>>;/**- * @deprecated not a good design+ * Whether to override the style of the cell, used for paste related operations.+ * @default false*/- options?: ICopyToOptionsData;+ isOverrideStyle?: boolean;}export interface ISetRangeValuesRangeMutationParams extends ISetRangeValuesMutationParams {@@ -62,7 +62,7 @@ export const SetRangeValuesUndoMutationFactory = (accessor: IAccessor,params: ISetRangeValuesMutationParams): ISetRangeValuesMutationParams => {- const { unitId, subUnitId, cellValue } = params;+ const { unitId, subUnitId, cellValue, isOverrideStyle } = params;const univerInstanceService = accessor.get(IUniverInstanceService);const workbook = univerInstanceService.getUniverSheetInstance(unitId);@@ -87,14 +87,15 @@ export const SetRangeValuesUndoMutationFactory = (// transformStyle does not accept style idconst newStyle = styles.getStyleByCell(newVal);- cell.s = transformStyle(oldStyle, newStyle);+ cell.s = isOverrideStyle && Object.prototype.hasOwnProperty.call(newVal ?? {}, 's')+ ? oldStyle ?? null+ : transformStyle(oldStyle, newStyle);undoData.setValue(row, col, setNull(cell));});return {...params,- options: {},cellValue: undoData.getMatrix(),} as ISetRangeValuesMutationParams;};@@ -105,7 +106,7 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, botype: CommandType.MUTATION,handler: (accessor, params) => {- const { cellValue, subUnitId, unitId } = params;+ const { cellValue, subUnitId, unitId, isOverrideStyle } = params;const univerInstanceService = accessor.get(IUniverInstanceService);const workbook = univerInstanceService.getUnit<Workbook>(unitId);if (!workbook) {@@ -127,7 +128,7 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bocellMatrix.realDeleteValue(row, col);} else {let oldVal = cellMatrix.getValue(row, col) || {};- oldVal = mergeCellData(newVal, oldVal, styles);+ oldVal = mergeCellData(newVal, oldVal, styles, !!isOverrideStyle);if (Tools.isEmptyObject(oldVal)) {cellMatrix.realDeleteValue(row, col);@@ -142,7 +143,7 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bo};const overwriteCellPropertiesSet = new Set(['f', 'p', 'si', 'custom', 'ref', 'xf']);-function mergeCellData(newValue: ICellData, oldValue: ICellData, styles: Styles) {+function mergeCellData(newValue: ICellData, oldValue: ICellData, styles: Styles, isOverrideStyle = false) {const type = getCellType(styles, newValue, oldValue);Object.keys(newValue).forEach((key) => {const cellPropertyKey = key as keyof ICellData;@@ -154,7 +155,11 @@ function mergeCellData(newValue: ICellData, oldValue: ICellData, styles: Styles)oldValue.v = getCellValue(type, newValue);}} else if (cellPropertyKey === 's') {- handleStyle(styles, oldValue, newValue);+ if (isOverrideStyle) {+ overrideStyle(styles, oldValue, newValue);+ } else {+ handleStyle(styles, oldValue, newValue);+ }}});@@ -171,6 +176,27 @@ function mergeCellData(newValue: ICellData, oldValue: ICellData, styles: Styles)return oldValue;}+function overrideStyle(styles: Styles, oldValue: ICellData, newValue: ICellData) {+ if (newValue.s === undefined) {+ return;+ }++ if (newValue.s === null) {+ delete oldValue.s;+ return;+ }++ const styleValue = typeof newValue.s === 'string' ? styles.get(newValue.s) : newValue.s;+ const styleCell: ICellData = {};+ handleStyle(styles, styleCell, { s: styleValue });++ if (styleCell.s == null) {+ delete oldValue.s;+ } else {+ oldValue.s = styleCell.s;+ }+}+function updateCellProperty<K extends keyof ICellData>(cell: ICellData,key: K,