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.

refactor(sheet): copy&paste (#2631)

waterhydroxylf21d88308596
diff --git a/packages/core/src/shared/common.ts b/packages/core/src/shared/common.ts
index 7255db7b97..0a1ffa4c70 100644
--- a/packages/core/src/shared/common.ts
+++ b/packages/core/src/shared/common.ts
@@ -270,7 +270,7 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
if (str.indexOf('text-decoration-line') > -1) {
str = str.replace(/(text-decoration-line:\s*[^;]+)(?=;)/g, (_, p1) => `${p1} underline`);
} else {
- str += 'text-decoration-line: underline; ';
+ str += 'text-decoration: underline; ';
}
if (style.ul.cl && str.indexOf('text-decoration-color') === -1) {
str += `text-decoration-color: ${getColorStyle(style.ul.cl)}; `;
@@ -374,7 +374,7 @@ export function handleStyleToString(style: IStyleData, isCell: boolean = false)
'tr',
() => {
if (style.tr) {
- str += `data-rotate: (${style.tr?.a}deg${style.tr?.v ? ` ,${style.tr?.v}` : ''});`;
+ str += `--data-rotate: (${style.tr?.a}deg${style.tr?.v ? ` ,${style.tr?.v}` : ''});`;
}
},
],
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-border.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-border.spec.ts
index 1506ebf972..425bf2f00b 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-border.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-border.spec.ts
@@ -168,27 +168,26 @@ describe('Test clipboard', () => {
expect(convertBorderColor(getStyles(cellData.getValue(2, 2)?.s)?.bd)).toStrictEqual({
b: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
- l: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
- t: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
});
expect(worksheet.getMergeData().length).toBe(1);
+ // Cells within merged cells inherit the style of the main cell by default.
expect(convertBorderColor(getStyles(cellData.getValue(9, 2)?.s)?.bd)).toStrictEqual({
- l: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
- t: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
+ b: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
+ r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
});
expect(convertBorderColor(getStyles(cellData.getValue(13, 2)?.s)?.bd)).toStrictEqual({
- l: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
b: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
+ r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
});
expect(convertBorderColor(getStyles(cellData.getValue(9, 3)?.s)?.bd)).toStrictEqual({
+ b: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
- t: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
});
expect(convertBorderColor(getStyles(cellData.getValue(13, 3)?.s)?.bd)).toStrictEqual({
- r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
b: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
+ r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
});
});
@@ -218,16 +217,16 @@ describe('Test clipboard', () => {
expect(worksheet.getMergeData().length).toBe(1);
expect(convertBorderColor(getStyles(cellData.getValue(9, 2)?.s)?.bd)).toStrictEqual({
- l: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
- t: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
+ r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
+ b: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
});
expect(convertBorderColor(getStyles(cellData.getValue(13, 2)?.s)?.bd)).toStrictEqual({
- l: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
+ r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
b: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
});
expect(convertBorderColor(getStyles(cellData.getValue(9, 3)?.s)?.bd)).toStrictEqual({
r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
- t: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
+ b: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
});
expect(convertBorderColor(getStyles(cellData.getValue(13, 3)?.s)?.bd)).toStrictEqual({
r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
@@ -261,27 +260,25 @@ describe('Test clipboard', () => {
expect(convertBorderColor(getStyles(cellData.getValue(2, 2)?.s)?.bd)).toStrictEqual({
b: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
- l: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
- t: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
});
expect(worksheet.getMergeData().length).toBe(1);
expect(convertBorderColor(getStyles(cellData.getValue(9, 2)?.s)?.bd)).toStrictEqual({
- l: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
- t: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
+ b: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
+ r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
});
expect(convertBorderColor(getStyles(cellData.getValue(13, 2)?.s)?.bd)).toStrictEqual({
- l: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
b: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
+ r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
});
expect(convertBorderColor(getStyles(cellData.getValue(9, 3)?.s)?.bd)).toStrictEqual({
+ b: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
- t: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
});
expect(convertBorderColor(getStyles(cellData.getValue(13, 3)?.s)?.bd)).toStrictEqual({
- r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
b: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
+ r: { cl: { rgb: 'rgb(0,0,0)' }, s: 1 },
});
});
});
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.ts
index b8da922804..ea1b8d8d84 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
@@ -162,7 +162,7 @@ describe('Test clipboard', () => {
rgb: '#000',
},
ff: 'Arial',
- fs: 11,
+ fs: 10,
ht: 0,
it: 1,
ol: {
@@ -212,17 +212,17 @@ describe('Test clipboard', () => {
expect(richTextStyle?.body?.dataStream).toBe('univer\r\n');
expect(richTextStyle?.body?.paragraphs).toStrictEqual([{ startIndex: 6 }]);
expect(richTextStyle?.body?.textRuns).toStrictEqual([
- { ed: 1, st: 0, ts: { fs: 9.75, ff: 'Arial' } },
+ { ed: 1, st: 0, ts: { fs: 10, ff: 'Arial' } },
{
st: 1, ed: 4, ts: {
bl: 1,
cl:
{ rgb: 'rgb(217,210,233)' },
- ff: 'Arial', fs: 17.25, it: 1,
+ ff: 'Arial', fs: 18, it: 1,
},
},
{
- ed: 6, st: 4, ts: { fs: 9.75, ff: 'Arial' },
+ ed: 6, st: 4, ts: { fs: 10, ff: 'Arial' },
},
]);
});
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-rotate.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-rotate.spec.ts
index eddb086644..151093699b 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-rotate.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-rotate.spec.ts
@@ -149,7 +149,7 @@ describe('Test clipboard', () => {
expect(res).toBeTruthy();
const cellData = worksheet.getCellMatrix();
- expect(getStyles(cellData.getValue(1, 1)!.s)?.tr!.a).toBeFalsy();
+ expect(getStyles(cellData.getValue(1, 1)!.s)?.tr?.a).toBeFalsy();
expect(getStyles(cellData.getValue(2, 1)!.s)?.tr!.a).toBe(-45);
expect(getStyles(cellData.getValue(3, 1)!.s)?.tr!.a).toBe(45);
expect(getStyles(cellData.getValue(4, 1)!.s)?.tr).toStrictEqual({ a: 0, v: 1 });
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.ts
index 7de6f4c363..06a2d1daca 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
@@ -176,7 +176,7 @@ describe('Test clipboard', () => {
rgb: '#000',
},
ff: 'Arial',
- fs: 11,
+ fs: 10,
ht: 2,
it: 0,
ol: {
@@ -255,7 +255,7 @@ describe('Test clipboard', () => {
rgb: '#000',
},
ff: 'Arial',
- fs: 11,
+ fs: 10,
ht: 2,
it: 0,
ol: {
@@ -334,7 +334,7 @@ describe('Test clipboard', () => {
rgb: '#000',
},
ff: 'Arial',
- fs: 11,
+ fs: 10,
ht: 2,
it: 0,
ol: {
@@ -417,7 +417,7 @@ describe('Test clipboard', () => {
rgb: '#000',
},
ff: 'Arial',
- fs: 11,
+ fs: 10,
ht: 2,
it: 0,
ol: {
@@ -461,7 +461,7 @@ describe('Test clipboard', () => {
rgb: '#000',
},
ff: 'Arial',
- fs: 11,
+ fs: 10,
ht: 2,
it: 0,
ol: {
@@ -551,7 +551,7 @@ describe('Test clipboard', () => {
rgb: '#000',
},
ff: 'Arial',
- fs: 11,
+ fs: 10,
ht: 2,
it: 0,
ol: {
@@ -595,7 +595,7 @@ describe('Test clipboard', () => {
rgb: '#000',
},
ff: 'Arial',
- fs: 11,
+ fs: 10,
ht: 2,
it: 0,
ol: {
@@ -723,7 +723,7 @@ describe('Test clipboard', () => {
rgb: '#000',
},
ff: 'Arial',
- fs: 11,
+ fs: 10,
ht: 2,
it: 0,
ol: {
@@ -885,7 +885,7 @@ describe('Test clipboard', () => {
rgb: '#000',
},
ff: 'Arial',
- fs: 11,
+ fs: 10,
ht: 2,
it: 0,
ol: {
@@ -1030,7 +1030,7 @@ describe('Test clipboard', () => {
rgb: '#000',
},
ff: 'Arial',
- fs: 11,
+ fs: 10,
ht: 2,
it: 0,
ol: {
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/constant.ts b/packages/sheets-ui/src/services/clipboard/__tests__/constant.ts
index da1e7b0a2d..859b567cbb 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/constant.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/constant.ts
@@ -29,7 +29,7 @@ export const borderSampleByGoogle = '<google-sheets-html-origin><style type="tex
export const borderSampleByUniver = '<html><head></head><body><google data-copy-id="PgwMK9" -sheets-html-origin=""><table xmlns="http://www.w3.org/1999/xhtml" cellspacing="0" cellpadding="0" dir="ltr" style="table-layout:fixed;font-size:10pt;font-family:Arial;width:0px;border-collapse:collapse;border:none"><colgroup><col width="73"><col width="73"><col width="73"><col width="73"></colgroup>\n<tbody><tr style="height: 19px;"><td></td><td></td><td></td><td></td></tr><tr style="height: 19px;"><td></td><td style="border-bottom: 0.5pt solid #000000; border-top: 0.5pt solid #000000; border-right: 0.5pt solid #000000; border-left: 0.5pt solid #000000; "></td><td style="border-bottom: 0.5pt solid #000000; border-top: 0.5pt solid #000000; border-right: 0.5pt solid #000000; border-left: 0.5pt solid #000000; "></td><td></td></tr><tr style="height: 19px;"><td></td><td style="border-bottom: 0.5pt solid #000000; border-top: 0.5pt solid #000000; border-right: 0.5pt solid #000000; border-left: 0.5pt solid #000000; "></td><td style="border-bottom: 0.5pt solid #000000; border-top: 0.5pt solid #000000; border-right: 0.5pt solid #000000; border-left: 0.5pt solid #000000; "></td><td></td></tr><tr style="height: 19px;"><td></td><td style="border-bottom: 0.5pt solid #000000; border-top: 0.5pt solid #000000; border-right: 0.5pt solid #000000; border-left: 0.5pt solid #000000; "></td><td style="border-bottom: 0.5pt solid #000000; border-top: 0.5pt solid #000000; border-right: 0.5pt solid #000000; border-left: 0.5pt solid #000000; "></td><td></td></tr><tr style="height: 19px;"><td></td><td style="border-bottom: 0.5pt solid #000000; border-top: 0.5pt solid #000000; border-right: 0.5pt solid #000000; border-left: 0.5pt solid #000000; "></td><td style="border-bottom: 0.5pt solid #000000; border-top: 0.5pt solid #000000; border-right: 0.5pt solid #000000; border-left: 0.5pt solid #000000; "></td><td></td></tr><tr style="height: 19px;"><td></td><td style="border-bottom: 0.5pt solid #000000; border-top: 0.5pt solid #000000; border-right: 0.5pt solid #000000; border-left: 0.5pt solid #000000; "></td><td style="border-bottom: 0.5pt solid #000000; border-top: 0.5pt solid #000000; border-right: 0.5pt solid #000000; border-left: 0.5pt solid #000000; "></td><td></td></tr><tr style="height: 19px;"><td></td><td></td><td></td><td></td></tr><tr style="height: 19px;"><td></td><td></td><td></td><td></td></tr><tr style="height: 19px;"><td></td><td rowspan="5" colspan="2" style="border-top: 0.5pt solid #000000; border-left: 0.5pt solid #000000; ;border-bottom: 0.5pt solid #000000; border-right: 0.5pt solid #000000; "></td><td></td></tr><tr style="height: 19px;"><td></td><td></td></tr><tr style="height: 19px;"><td></td><td></td></tr><tr style="height: 19px;"><td></td><td></td></tr><tr style="height: 19px;"><td></td><td></td></tr><tr style="height: 19px;"><td></td><td></td><td></td><td></td></tr></tbody></table></google></body></html>';
// rotate
-export const rotateSampleByUniver = '<html><head></head><body><google data-copy-id="1rz7ZZ" -sheets-html-origin=""><table xmlns="http://www.w3.org/1999/xhtml" cellspacing="0" cellpadding="0" dir="ltr" style="table-layout:fixed;font-size:10pt;font-family:Arial;width:0px;border-collapse:collapse;border:none"><colgroup><col width="73"></colgroup>\n<tbody><tr style="height: 19px;"><td>univer</td></tr><tr style="height: 46.67004020088826px;"><td style="data-rotate: (-45deg);">univer</td></tr><tr style="height: 46.67004020088826px;"><td style="data-rotate: (45deg);">univer</td></tr><tr style="height: 48.00140380859375px;"><td style="data-rotate: (0deg ,1);">univer</td></tr><tr style="height: 48.00140380859375px;"><td style="data-rotate: (-90deg);">univer</td></tr><tr style="height: 48.00140380859375px;"><td style="data-rotate: (90deg);">univer</td></tr></tbody></table></google></body></html>';
+export const rotateSampleByUniver = '<html><head></head><body><google data-copy-id="1rz7ZZ" -sheets-html-origin=""><table xmlns="http://www.w3.org/1999/xhtml" cellspacing="0" cellpadding="0" dir="ltr" style="table-layout:fixed;font-size:10pt;font-family:Arial;width:0px;border-collapse:collapse;border:none"><colgroup><col width="73"></colgroup>\n<tbody><tr style="height: 19px;"><td>univer</td></tr><tr style="height: 46.67004020088826px;"><td style="--data-rotate: (-45deg);">univer</td></tr><tr style="height: 46.67004020088826px;"><td style="--data-rotate: (45deg);">univer</td></tr><tr style="height: 48.00140380859375px;"><td style="--data-rotate: (0deg ,1);">univer</td></tr><tr style="height: 48.00140380859375px;"><td style="--data-rotate: (-90deg);">univer</td></tr><tr style="height: 48.00140380859375px;"><td style="--data-rotate: (90deg);">univer</td></tr></tbody></table></google></body></html>';
// alignment
export const alignmentSampleByExcel = '<html xmlns:v="urn:schemas-microsoft-com:vml"\r\nxmlns:o="urn:schemas-microsoft-com:office:office"\r\nxmlns:x="urn:schemas-microsoft-com:office:excel"\r\nxmlns="http://www.w3.org/TR/REC-html40">\r\n\r\n<head>\r\n<meta http-equiv=Content-Type content="text/html; charset=utf-8">\r\n<meta name=ProgId content=Excel.Sheet>\r\n<meta name=Generator content="Microsoft Excel 15">\r\n<link id=Main-File rel=Main-File\r\nhref="file:////Users/yuanbin/Library/Group%20Containers/UBF8T346G9.Office/TemporaryItems/msohtmlclip/clip.htm">\r\n<link rel=File-List\r\nhref="file:////Users/yuanbin/Library/Group%20Containers/UBF8T346G9.Office/TemporaryItems/msohtmlclip/clip_filelist.xml">\r\n<style>\r\n\x3C!--table\r\n\t{mso-displayed-decimal-separator:"\\.";\r\n\tmso-displayed-thousand-separator:"\\,";}\r\n@page\r\n\t{margin:.75in .7in .75in .7in;\r\n\tmso-header-margin:.3in;\r\n\tmso-footer-margin:.3in;}\r\ntr\r\n\t{mso-height-source:auto;\r\n\tmso-ruby-visibility:none;}\r\ncol\r\n\t{mso-width-source:auto;\r\n\tmso-ruby-visibility:none;}\r\nbr\r\n\t{mso-data-placement:same-cell;}\r\ntd\r\n\t{padding-top:1px;\r\n\tpadding-right:1px;\r\n\tpadding-left:1px;\r\n\tmso-ignore:padding;\r\n\tcolor:black;\r\n\tfont-size:12.0pt;\r\n\tfont-weight:400;\r\n\tfont-style:normal;\r\n\ttext-decoration:none;\r\n\tfont-family:等线;\r\n\tmso-generic-font-family:auto;\r\n\tmso-font-charset:134;\r\n\tmso-number-format:General;\r\n\ttext-align:general;\r\n\tvertical-align:middle;\r\n\tborder:none;\r\n\tmso-background-source:auto;\r\n\tmso-pattern:auto;\r\n\tmso-protection:locked visible;\r\n\twhite-space:nowrap;\r\n\tmso-rotate:0;}\r\n.xl65\r\n\t{text-align:left;\r\n\tvertical-align:bottom;}\r\n.xl66\r\n\t{text-align:right;\r\n\tvertical-align:bottom;}\r\n.xl67\r\n\t{text-align:center;\r\n\tvertical-align:bottom;}\r\n.xl68\r\n\t{vertical-align:top;}\r\n.xl69\r\n\t{color:#44546A;\r\n\tfont-size:11.0pt;\r\n\tfont-weight:700;}\r\n.xl70\r\n\t{vertical-align:bottom;}\r\nruby\r\n\t{ruby-align:left;}\r\nrt\r\n\t{color:windowtext;\r\n\tfont-size:9.0pt;\r\n\tfont-weight:400;\r\n\tfont-style:normal;\r\n\ttext-decoration:none;\r\n\tfont-family:等线;\r\n\tmso-generic-font-family:auto;\r\n\tmso-font-charset:134;\r\n\tmso-char-type:none;\r\n\tdisplay:none;}\r\n-->\r\n</style>\r\n</head>\r\n\r\n<body link="#0563C1" vlink="#954F72">\r\n\r\n<table border=0 cellpadding=0 cellspacing=0 width=522 style=\'border-collapse:\r\n collapse;width:390pt\'>\r\n <col width=87 span=6 style=\'width:65pt\'>\r\n <tr height=88 style=\'mso-height-source:userset;height:66.0pt\'>\r\n\x3C!--StartFragment-->\r\n <td height=88 class=xl65 width=87 style=\'height:66.0pt;width:65pt\'>左对齐</td>\r\n <td class=xl66 width=87 style=\'width:65pt\'>右对齐</td>\r\n <td class=xl67 width=87 style=\'width:65pt\'>中间对齐</td>\r\n <td class=xl68 width=87 style=\'width:65pt\'>顶部</td>\r\n <td class=xl70 width=87 style=\'width:65pt\'>底部对齐</td>\r\n <td class=xl69 width=87 style=\'width:65pt\'>居中对齐</td>\r\n\x3C!--EndFragment-->\r\n </tr>\r\n</table>\r\n\r\n</body>\r\n\r\n</html>\r\n';
diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
index d1968b6ab6..82bed2f3d4 100644
--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
@@ -443,7 +443,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
const mergeData = worksheet?.getMergeData();
- if (mergeData) {
+ if (mergeData.length) {
const pastedRangeLapWithMergedCell = mergeData.some((m) => {
return rangeIntersectWithDiscreteRange(m, pasteTarget.pastedRange) && !discreteRangeContainsRange(pasteTarget.pastedRange, m);
});
@@ -485,8 +485,19 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
newValue.s = styles?.getStyleByCell(value);
cellMatrix.setValue(row, col, newValue);
}
- });
+ if (value.colSpan || value.rowSpan) {
+ for (let rStart = 0; rStart < value.rowSpan!; rStart++) {
+ for (let cStart = 0; cStart < value.colSpan!; cStart++) {
+ if (rStart === 0 && cStart === 0) continue;
+
+ const r = row + rStart;
+ const c = col + cStart;
+ cellMatrix.setValue(r, c, { s: styles?.getStyleByCell(value) });
+ }
+ }
+ }
+ });
const pasteTarget = this._getPastedRange(cellMatrix);
if (!pasteTarget) return false;
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.ts
index 17d1f1aa8f..a5a87857ca 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
@@ -16,7 +16,7 @@
import type { IDocumentBody, IDocumentData, ITextRun, ITextStyle, Nullable } from '@univerjs/core';
import { ObjectMatrix, skipParseTagNames } from '@univerjs/core';
-import { handleStringToStyle } from '@univerjs/ui';
+import { handleStringToStyle, textTrim } from '@univerjs/ui';
import type { IPastePlugin } from '@univerjs/docs-ui';
import type { SpreadsheetSkeleton } from '@univerjs/engine-render';
@@ -42,25 +42,25 @@ export interface IParsedTablesInfo {
const sheetStyleRules: string[] =
[
- 'color_color',
- 'background_background',
- 'font-size_fontSize',
- 'text-align_textAlign',
- 'vertical-align_verticalAlign',
- 'font-weight_fontWeight',
- 'font-style_fontStyle',
- 'font-family_fontFamily',
- 'text-decoration_textDecoration',
- 'white-space_whiteSpace',
- 'word-wrap_wordWrap',
- ];
-
-const borderRules: string[] =
- [
- 'border-left_borderLeft',
- 'border-right_borderRight',
- 'border-top_borderTop',
- 'border-bottom_borderBottom',
+ // Rich Text Style Rules,
+ 'color',
+ 'background',
+ 'font-size',
+ 'text-align',
+ 'vertical-align',
+ 'font-weight',
+ 'font-style',
+ 'font-family',
+ 'text-decoration',
+ 'white-space',
+ 'word-wrap',
+ // Border Style Rules,
+ 'border-left',
+ 'border-right',
+ 'border-top',
+ 'border-bottom',
+ // Custom Style Rules, '--' needs to be used as a prefix.
+ '--data-rotate',
];
function matchFilter(node: HTMLElement, filter: IStyleRule['filter']) {
@@ -81,15 +81,6 @@ interface IHtmlToUSMServiceProps {
getCurrentSkeleton: () => Nullable<ISheetSkeletonManagerParam>;
}
-function hideIframe(iframe: HTMLIFrameElement) {
- iframe.style.display = 'none';
- iframe.style.width = '0';
- iframe.style.height = '0';
- iframe.setAttribute('tabindex', '-1');
- iframe.setAttribute('aria-hidden', 'true');
- iframe.setAttribute('title', 'hidden iframe');
-}
-
export class HtmlToUSMService {
private static pluginList: IPastePlugin[] = [];
@@ -101,40 +92,47 @@ export class HtmlToUSMService {
this.pluginList.push(plugin);
}
+ private _styleMap = new Map<string, CSSStyleDeclaration>();
+
private _styleCache: Map<ChildNode, ITextStyle> = new Map();
private _styleRules: IStyleRule[] = [];
private _afterProcessRules: IAfterProcessRule[] = [];
- private _htmlElement: HTMLIFrameElement;
+ private _dom: HTMLElement | null = null;
private _getCurrentSkeleton: () => Nullable<ISheetSkeletonManagerParam>;
constructor(props: IHtmlToUSMServiceProps) {
this._getCurrentSkeleton = props.getCurrentSkeleton;
- this._htmlElement = document.createElement('iframe');
- this._htmlElement.style.display = 'none';
- document.body.appendChild(this._htmlElement);
- hideIframe(this._htmlElement);
}
// eslint-disable-next-line max-lines-per-function
convert(html: string): IUniverSheetCopyDataModel {
- if (this._htmlElement.contentDocument) {
- this._htmlElement.contentDocument.open();
- this._htmlElement.contentDocument.write(html);
- this._htmlElement.contentDocument.close();
- }
- html = html.replace(/<!--[\s\S]*?-->/g, '').replace(/<style[\s\S]*?<\/style>/g, '');
-
const pastePlugin = HtmlToUSMService.pluginList.find((plugin) => plugin.checkPasteType(html));
if (pastePlugin) {
this._styleRules = [...pastePlugin.stylesRules];
this._afterProcessRules = [...pastePlugin.afterProcessRules];
}
const valueMatrix = new ObjectMatrix<ICellDataWithSpanInfo>();
- const dom = parseToDom(html);
+ this._dom = parseToDom(html);
+ // Convert stylesheets to map
+ const style = this._dom.querySelector('style');
+ if (style) {
+ const shadowHost = document.createElement('div');
+ const shadowRoot = shadowHost.attachShadow({ mode: 'open' });
+ document.body.appendChild(shadowHost);
+ shadowRoot.appendChild(style);
+ for (const rule of style.sheet!.cssRules) {
+ const cssRule = rule as CSSStyleRule;
+ const selectorText = cssRule.selectorText;
+ const style = cssRule.style;
+ this._styleMap.set(selectorText, style);
+ }
+ style.remove();
+ shadowHost.remove();
+ }
const newDocBody: IDocumentBody = {
dataStream: '',
textRuns: [],
@@ -145,7 +143,7 @@ export class HtmlToUSMService {
// pick tables
const tableStrings = html.match(/<table\b[^>]*>([\s\S]*?)<\/table>/gi);
const tables: IParsedTablesInfo[] = [];
- this.process(null, dom?.childNodes!, newDocBody, tables);
+ this.process(null, this._dom.childNodes!, newDocBody, tables);
const { paragraphs, dataStream, textRuns } = newDocBody;
// use paragraph to split rows
@@ -216,9 +214,9 @@ export class HtmlToUSMService {
}
}
if (tableStrings) {
- tableStrings.forEach((t) => {
+ tableStrings.forEach((t, index) => {
const curRow = valueMatrix.getDataRange().endRow + 1;
- const { cellMatrix, rowProperties: tableRowProp, colProperties: tableColProp } = this._parseTable(t!);
+ const { cellMatrix, rowProperties: tableRowProp, colProperties: tableColProp } = this._parseTable(t!, index);
if (cellMatrix) {
cellMatrix.forValue((row, col, value) => {
valueMatrix.setValue(curRow + row, col, value);
@@ -230,6 +228,7 @@ export class HtmlToUSMService {
rowProperties.push(...tableRowProp);
});
}
+ this.dispose();
return {
rowProperties,
colProperties,
@@ -237,11 +236,69 @@ export class HtmlToUSMService {
};
}
- private _parseTable(html: string) {
+ private _getStyleBySelectorText(selectorText: string, cssText: string) {
+ const css = this._styleMap.get(selectorText)?.getPropertyValue(cssText);
+ if (!css) {
+ return '';
+ }
+ return css;
+ }
+
+ // eslint-disable-next-line complexity
+ private _getStyle(node: HTMLElement, styleStr: string) {
+ const recordStyle: Record<string, string> = turnToStyleObject(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 = '';
+ for (let l = 0; l < sheetStyleRules.length; l++) {
+ const key = sheetStyleRules[l];
+
+ // retrieve multiple sources for a node and compile them into a cohesive new style string.
+ if (key === 'background') {
+ let value = '';
+ node.classList.forEach((className) => {
+ value = this._getStyleBySelectorText(`.${className}`, 'background-color') || this._getStyleBySelectorText(`.${className}`, key);
+ });
+ const bgColor = style.getPropertyValue('background-color') || value ||
+ this._getStyleBySelectorText(`#${node.id}`, 'background-color') || this._getStyleBySelectorText(`#${node.id}`, key) ||
+ this._getStyleBySelectorText(node.nodeName.toLowerCase(), key) || this._getStyleBySelectorText(node.nodeName, 'background-color') || recordStyle['background-color'] || '';
+ bgColor && (newStyleStr += `background:${bgColor};`);
+ continue;
+ }
+ if (key === 'text-decoration') {
+ let value = '';
+ node.classList.forEach((className) => {
+ value = this._getStyleBySelectorText(`.${className}`, 'text-decoration-line') || this._getStyleBySelectorText(`.${className}`, key);
+ });
+ const textDecoration = style.getPropertyValue('text-decoration-line') || style.getPropertyValue('text-decoration') || value ||
+ this._getStyleBySelectorText(`#${node.id}`, 'text-decoration-line') || this._getStyleBySelectorText(`#${node.id}`, key) ||
+ this._getStyleBySelectorText(node.nodeName.toLowerCase(), key) || this._getStyleBySelectorText(node.nodeName, 'text-decoration-line') || recordStyle['text-decoration-line'] || '';
+ textDecoration && (newStyleStr += `text-decoration:${textDecoration};`);
+ continue;
+ }
+
+ let value = '';
+ node.classList.forEach((className) => {
+ value = this._getStyleBySelectorText(`.${className}`, key);
+ });
+
+ value =
+ style.getPropertyValue(key) ||
+ this._getStyleBySelectorText(`#${node.id}`, key) ||
+ value ||
+ this._getStyleBySelectorText(node.nodeName.toLowerCase(), key) ||
+ recordStyle[key] ||
+ '';
+ value && (newStyleStr += `${key}:${value};`);
+ }
+ return newStyleStr;
+ }
+
+ private _parseTable(html: string, tableElIndex: number) {
const valueMatrix = new ObjectMatrix<ICellDataWithSpanInfo>();
const colProperties = parseColGroup(html) ?? [];
const { rowProperties = [] } = parseTableRows(html);
- const parsedCellMatrix = parseTableByHtml(this._htmlElement, this._getCurrentSkeleton()?.skeleton);
+ const parsedCellMatrix = this._parseTableByHtml(this._dom!, tableElIndex, this._getCurrentSkeleton()?.skeleton);
parsedCellMatrix &&
parsedCellMatrix.forValue((row, col, value) => {
let style = handleStringToStyle(undefined, value.style);
@@ -284,6 +341,155 @@ export class HtmlToUSMService {
};
}
+ private _parseTableByHtml(htmlElement: HTMLElement, tableElIndex: number, skeleton?: SpreadsheetSkeleton) {
+ const cellMatrix = new ObjectMatrix<IParsedCellValueByClipboard>();
+ const tableEle = htmlElement.querySelectorAll('table')[tableElIndex];
+ if (!tableEle) {
+ return cellMatrix;
+ }
+ // user agent stylesheet can be provided here
+ const tableStyle = this._getStyle(tableEle, '');
+ const rows = tableEle?.querySelectorAll('tr');
+
+ for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
+ const row = rows[rowIndex];
+ const rowStyle = this._getStyle(row, tableStyle);
+ const cells = row.querySelectorAll('td, th');
+ let colSetValueIndex = 0;
+ for (let colIndex = 0; colIndex < cells.length;) {
+ const cell = cells[colIndex];
+ let cellStyle = '';
+ const rowSpan = Number(cell.getAttribute('rowSpan')) || 1;
+ const colSpan = Number(cell.getAttribute('colSpan')) || 1;
+
+ cellStyle = this._getStyle(cell as HTMLElement, rowStyle);
+
+ // If the cell above has a border-bottom and its value is not 'none',
+ // remove the border-top of the current cell.
+ // If the cell to the left has a border-right and its value is not 'none',
+ // remove the border-left of the current cell.
+ // Check and remove borders based on adjacent merged cells
+ if (rowIndex > 0) {
+ const cellValueAbove = cellMatrix.getValue(rowIndex - 1, colSetValueIndex);
+ if (cellValueAbove?.style?.includes('border-bottom') && cellStyle.includes('border-top')) {
+ const borderBottom = extractStyleProperty(cellValueAbove.style!, 'border-bottom');
+ if (borderBottom && textTrim(borderBottom.substr(borderBottom.indexOf(':') + 1)) !== 'none') {
+ cellStyle = cellStyle.replace(/border-top:[^;]+;/, '');
+ }
+ }
+ }
+
+ if (colIndex > 0) {
+ const cellValueLeft = cellMatrix.getValue(rowIndex, colSetValueIndex - 1);
+ if (cellValueLeft?.style?.includes('border-right') && cellStyle.includes('border-left')) {
+ const borderRight = extractStyleProperty(cellValueLeft.style!, 'border-right');
+ if (borderRight && textTrim(borderRight.substr(borderRight.indexOf(':') + 1)) !== 'none') {
+ cellStyle = cellStyle.replace(/border-left:[^;]+;/, '');
+ }
+ }
+ }
+
+ // Determine whether it is rich text based on whether there are html tags
+ const { cellText, cellRichStyle } = this._getCellTextAndRichText(cell, cellStyle, skeleton);
+
+ const cellValue = {
+ rowSpan,
+ colSpan,
+ content: cellText,
+ style: cellStyle,
+ richTextParma: {
+ p: cellRichStyle,
+ v: cellText,
+ },
+ };
+
+ if (cellMatrix.getValue(rowIndex, colSetValueIndex)) {
+ colSetValueIndex += 1;
+ continue;
+ } else {
+ // Clone the style of merged cells to each individual cell; switch to cloning only border styles if there are issues later.
+ if ((rowSpan > 1 || colSpan > 1)) {
+ setMergedCellStyle(cellMatrix, cellStyle, cellValue, { colSpan, rowSpan, rowIndex, colIndex, colSetValueIndex });
+ } else {
+ cellMatrix.setValue(rowIndex, colSetValueIndex, cellValue);
+ }
+ colSetValueIndex += colSpan;
+ colIndex++;
+ }
+ }
+ }
+ return cellMatrix;
+ }
+
+ private _parseCellHtml(parent: Nullable<ChildNode>, nodes: NodeListOf<ChildNode>, doc: IDocumentBody, styleCache: Map<ChildNode, ITextStyle> = new Map(), styleStr: string) {
+ for (const node of nodes) {
+ if (node.nodeType === Node.TEXT_NODE) {
+ const text = node.nodeValue?.replace(/[\r\n]/g, '');
+ let style;
+
+ if (parent && styleCache.has(parent)) {
+ style = styleCache.get(parent);
+ }
+
+ doc.dataStream += text;
+
+ if (style && Object.getOwnPropertyNames(style).length) {
+ doc.textRuns!.push({
+ st: doc.dataStream.length - text!.length,
+ ed: doc.dataStream.length,
+ ts: style,
+ });
+ }
+ } else if (node.nodeType === Node.COMMENT_NODE || node.nodeName === 'STYLE') {
+ continue;
+ } 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 nodeStyles = extractNodeStyle(node as HTMLElement, predefinedStyles);
+
+ styleCache.set(node, { ...parentStyles, ...nodeStyles });
+ const { childNodes } = node;
+ this._parseCellHtml(node, childNodes, doc, styleCache, currentNodeStyle);
+ }
+ }
+ }
+
+ private _getCellTextAndRichText(cell: Element, styleStr: string, skeleton?: SpreadsheetSkeleton) {
+ let cellText = '';
+ let cellRichStyle;
+ const isRichText = /<[^>]+>/.test(cell.innerHTML);
+ if (isRichText && skeleton) {
+ const newDocBody: IDocumentBody = {
+ dataStream: '',
+ textRuns: [],
+ };
+ // Rich text parsing method, refer to the doc
+ this._parseCellHtml(null, cell.childNodes, newDocBody, undefined, styleStr);
+ const documentModel = skeleton.getBlankCellDocumentModel()?.documentModel;
+ const p = documentModel?.getSnapshot();
+ const singleDataStream = `${newDocBody.dataStream}\r\n`;
+ const documentData = {
+ ...p, ...{
+ body: {
+ dataStream: singleDataStream,
+ textRuns: newDocBody.textRuns,
+ paragraphs: generateParagraphs(singleDataStream),
+ },
+ },
+ };
+ documentModel?.reset(documentData);
+ cellRichStyle = documentModel?.getSnapshot();
+ cellText = newDocBody.dataStream;
+ } else {
+ cellText = decodeHTMLEntities(cell.innerHTML.replace(/[\r\n]/g, ''));
+ }
+ return {
+ cellText,
+ cellRichStyle,
+ };
+ }
+
private _generateDocumentDataModelSnapshot(snapshot: Partial<IDocumentData>) {
const currentSkeleton = this._getCurrentSkeleton();
if (currentSkeleton == null) {
@@ -369,7 +575,9 @@ export class HtmlToUSMService {
}
dispose() {
- document.body.removeChild(this._htmlElement);
+ this._dom = null;
+ this._styleCache.clear();
+ this._styleMap.clear();
}
}
@@ -400,6 +608,16 @@ function parseTableRows(html: string): {
};
}
+function turnToStyleObject(styleStr: string) {
+ const styleObj: Record<string, string> = {};
+ const styleArr = styleStr.split(';');
+ styleArr.forEach((style) => {
+ const [key, value] = style.split(':');
+ styleObj[key] = value;
+ });
+ return styleObj;
+}
+
function parseProperties(propertyStr: string): IClipboardPropertyItem {
if (!propertyStr) {
return {};
@@ -463,143 +681,6 @@ function decodeHTMLEntities(input: string): string {
return input.replace(/&lt;|&gt;|&amp;|&quot;|&#39;|&nbsp;|<br>/g, (match) => entities[match]);
}
-function extractBordersAndKeepOthers(styleString: string, bordersToKeep: string[]) {
- if (!styleString) return '';
- const borderRegex = /border(-top|-right|-bottom|-left)?\s*:\s*([^;]+);/g;
-
- const extractedBorders: Record<string, string> = {};
-
- const withoutBorders = styleString.replace(borderRegex, (match, p1, p2) => {
- const borderType = `border${p1 || ''}`;
- extractedBorders[borderType] = p2.trim();
- return '';
- });
-
- let newStyleString = bordersToKeep
- .map((border) => {
- if (border === 'border' && extractedBorders[border]) {
- return `border: ${extractedBorders[border]};`;
- } else if (extractedBorders[border]) {
- return `${border}: ${extractedBorders[border]};`;
- }
- return '';
- })
- .filter((style) => style)
- .join(' ');
-
- newStyleString += ` ${withoutBorders.trim()}`;
-
- return newStyleString.trim();
-}
-
-function parseTableByHtml(htmlElement: HTMLIFrameElement, skeleton?: SpreadsheetSkeleton) {
- const cellMatrix = new ObjectMatrix<IParsedCellValueByClipboard>();
- const tableEle = htmlElement.contentDocument?.querySelector('table');
- if (!tableEle) {
- return cellMatrix;
- }
- const rows = tableEle?.querySelectorAll('tr');
-
- for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
- const row = rows[rowIndex];
- const cells = row.querySelectorAll('td, th');
- let colSetValueIndex = 0;
- for (let colIndex = 0; colIndex < cells.length;) {
- const cell = cells[colIndex];
- let cellStyle = '';
- const rowSpan = Number(cell.getAttribute('rowSpan')) || 1;
- const colSpan = Number(cell.getAttribute('colSpan')) || 1;
- // If there is a class attribute, use getComputedStyle
- cellStyle = getCellStyle(cell);
-
- if (rowSpan > 1 && colSpan > 1) {
- // compatible google sheet;The border style of merged cells in Google is set on the right and bottom sides of the merged cells
- if (!cellStyle.includes('border-top') && !cellStyle.includes('border-left')) {
- const topStyle = extractStyleProperty(cellMatrix.getValue(rowIndex - 1, colIndex)?.style, 'border-bottom');
- const leftStyle = extractStyleProperty(cellMatrix.getValue(rowIndex, colIndex - 1)?.style, 'border-right');
- if (topStyle) {
- cellStyle += `border-top:${topStyle};`;
- }
- if (leftStyle) {
- cellStyle += `border-left:${leftStyle};`;
- }
- }
- }
-
- // Determine whether it is rich text based on whether there are html tags
- const { cellText, cellRichStyle } = getCellTextAndRichText(cell, skeleton);
-
- const cellValue = (rowSpan > 1 || colSpan > 1)
- ? {
- rowSpan,
- colSpan,
- content: cellText,
- style: cellStyle,
- richTextParma: {
- p: cellRichStyle,
- v: cellText,
- },
- }
- : {
- content: cellText,
- style: cellStyle,
- richTextParma: {
- p: cellRichStyle,
- v: cellText,
- },
- };
-
- if (cellMatrix.getValue(rowIndex, colSetValueIndex)) {
- colSetValueIndex += 1;
- continue;
- } else {
- // Clone the style of merged cells to each individual cell; switch to cloning only border styles if there are issues later.
- if ((rowSpan > 1 || colSpan > 1)) {
- setMergedCellStyle(cellMatrix, cellStyle, cellValue, { colSpan, rowSpan, rowIndex, colIndex, colSetValueIndex });
- } else {
- cellMatrix.setValue(rowIndex, colSetValueIndex, cellValue);
- }
- colSetValueIndex += colSpan;
- colIndex++;
- }
- }
- }
- return cellMatrix;
-}
-
-function parseCellHtml(parent: Nullable<ChildNode>, nodes: NodeListOf<ChildNode>, doc: IDocumentBody, styleCache: Map<ChildNode, ITextStyle> = new Map()) {
- for (const node of nodes) {
- if (node.nodeType === Node.TEXT_NODE) {
- const text = node.nodeValue?.replace(/[\r\n]/g, '');
- let style;
-
- if (parent && styleCache.has(parent)) {
- style = styleCache.get(parent);
- }
-
- doc.dataStream += text;
-
- if (style && Object.getOwnPropertyNames(style).length) {
- doc.textRuns!.push({
- st: doc.dataStream.length - text!.length,
- ed: doc.dataStream.length,
- ts: style,
- });
- }
- } else if (node.nodeType === Node.COMMENT_NODE || node.nodeName === 'STYLE') {
- continue;
- } else if (node.nodeType === Node.ELEMENT_NODE) {
- const parentStyles = parent ? styleCache.get(parent) : {};
- const predefinedStyles = getComputedStyle(node as HTMLElement);
- const nodeStyles = extractNodeStyle(node as HTMLElement, predefinedStyles);
-
- styleCache.set(node, { ...parentStyles, ...nodeStyles });
- const { childNodes } = node;
- parseCellHtml(node, childNodes, doc, styleCache);
- }
- }
-}
-
function extractStyleProperty(styleString?: string, propertyName?: string) {
if (!styleString || !propertyName) return null;
const regex = new RegExp(`(${propertyName}\\s*:\\s*[^;]+);`, 'i');
@@ -610,76 +691,10 @@ function extractStyleProperty(styleString?: string, propertyName?: string) {
return null;
}
-function getCellStyle(cell: Element) {
- let cellStyle = '';
- const hasClass = cell.getAttribute('class');
- const computedStyle = getComputedStyle(cell);
- if (hasClass) {
- sheetStyleRules.forEach((rule) => {
- const [originName, camelName] = rule.split('_');
- const ruleValue = computedStyle.getPropertyValue(originName) || computedStyle[camelName as keyof typeof computedStyle];
- if (ruleValue) {
- cellStyle += `${originName}:${ruleValue};`;
- }
- });
- } else {
- const regex = /<\w+\s+[^>]*?style="([^"]*)"/gi;
- const match = regex.exec(cell.outerHTML);
- if (match?.[1]) {
- cellStyle = match[1];
- }
- }
-
- borderRules.forEach((rule) => {
- const [originName, camelName] = rule.split('_');
- const ruleValue = computedStyle.getPropertyValue(originName) || computedStyle[camelName as keyof typeof computedStyle];
- if (ruleValue) {
- cellStyle += `${originName}:${ruleValue};`;
- }
- });
- return cellStyle;
-}
-
-function getCellTextAndRichText(cell: Element, skeleton?: SpreadsheetSkeleton) {
- let cellText = '';
- let cellRichStyle;
- const isRichText = /<[^>]+>/.test(cell.innerHTML);
- if (isRichText && skeleton) {
- const newDocBody: IDocumentBody = {
- dataStream: '',
- textRuns: [],
- };
- // Rich text parsing method, refer to the doc
- parseCellHtml(null, cell.childNodes, newDocBody);
- const documentModel = skeleton.getBlankCellDocumentModel()?.documentModel;
- const p = documentModel?.getSnapshot();
- const singleDataStream = `${newDocBody.dataStream}\r\n`;
- const documentData = {
- ...p, ...{
- body: {
- dataStream: singleDataStream,
- textRuns: newDocBody.textRuns,
- paragraphs: generateParagraphs(singleDataStream),
- },
- },
- };
- documentModel?.reset(documentData);
- cellRichStyle = documentModel?.getSnapshot();
- cellText = newDocBody.dataStream;
- } else {
- cellText = decodeHTMLEntities(cell.innerHTML.replace(/[\r\n]/g, ''));
- }
- return {
- cellText,
- cellRichStyle,
- };
-}
-
function setMergedCellStyle(
cellMatrix: ObjectMatrix<IParsedCellValueByClipboard>,
cellStyle: string,
- cellValue:
- {
+ cellValue: {
content: string;
style: string;
richTextParma: {
@@ -688,7 +703,6 @@ function setMergedCellStyle(
};
rowSpan?: number;
colSpan?: number;
-
},
indexParams: {
colSpan: number;
@@ -698,36 +712,15 @@ function setMergedCellStyle(
colSetValueIndex: number;
}) {
const { rowSpan, colSpan, rowIndex, colSetValueIndex } = indexParams;
- if (rowSpan === 1) {
- for (let i = colSetValueIndex; i < colSetValueIndex + colSpan; i++) {
- cellMatrix.setValue(rowIndex, i, { style: extractBordersAndKeepOthers(cellStyle, ['border-top', 'border-bottom']) });
- }
- cellMatrix.setValue(rowIndex, colSetValueIndex + colSpan - 1, { style: extractBordersAndKeepOthers(cellStyle, ['border-top', 'border-bottom', 'border-right']) });
- cellMatrix.setValue(rowIndex, colSetValueIndex, { ...cellValue, style: extractBordersAndKeepOthers(cellStyle, ['border-top', 'border-bottom', 'border-left']) });
- } else if (colSpan === 1) {
- for (let i = rowIndex; i < rowIndex + rowSpan; i++) {
- cellMatrix.setValue(i, colSetValueIndex, { style: extractBordersAndKeepOthers(cellStyle, ['border-left', 'border-right']) });
- }
- cellMatrix.setValue(rowIndex + rowSpan - 1, colSetValueIndex, { style: extractBordersAndKeepOthers(cellStyle, ['border-left', 'border-right', 'border-bottom']) });
- cellMatrix.setValue(rowIndex, colSetValueIndex, { ...cellValue, style: extractBordersAndKeepOthers(cellStyle, ['border-left', 'border-right', 'border-top']) });
- } else {
- for (let i = colSetValueIndex; i < colSetValueIndex + colSpan; i++) {
- cellMatrix.setValue(rowIndex, i, { style: extractBordersAndKeepOthers(cellStyle, ['border-top']) });
- cellMatrix.setValue(rowIndex + rowSpan - 1, i, { style: extractBordersAndKeepOthers(cellStyle, ['border-bottom']) });
- }
- for (let i = rowIndex; i < rowIndex + rowSpan; i++) {
- cellMatrix.setValue(i, colSetValueIndex, { style: extractBordersAndKeepOthers(cellStyle, ['border-left']) });
- cellMatrix.setValue(i, colSetValueIndex + colSpan - 1, { style: extractBordersAndKeepOthers(cellStyle, ['border-right']) });
- }
- cellMatrix.setValue(rowIndex + rowSpan - 1, colSetValueIndex, { style: extractBordersAndKeepOthers(cellStyle, ['border-left', 'border-bottom']) });
- cellMatrix.setValue(rowIndex, colSetValueIndex + colSpan - 1, { style: extractBordersAndKeepOthers(cellStyle, ['border-right', 'border-top']) });
- cellMatrix.setValue(rowIndex + rowSpan - 1, colSetValueIndex + colSpan - 1, { style: extractBordersAndKeepOthers(cellStyle, ['border-right', 'border-bottom']) });
- cellMatrix.setValue(rowIndex, colSetValueIndex, { ...cellValue, style: extractBordersAndKeepOthers(cellStyle, ['border-top', 'border-left']) });
- for (let i = rowIndex; i < rowIndex + rowSpan; i++) {
- for (let j = colSetValueIndex; j < colSetValueIndex + colSpan; j++) {
- if (!cellMatrix.getValue(i, j)) {
- cellMatrix.setValue(i, j, { style: extractBordersAndKeepOthers(cellStyle, []) });
- }
+
+ for (let i = rowIndex; i < rowIndex + rowSpan; i++) {
+ for (let j = colSetValueIndex; j < colSetValueIndex + colSpan; j++) {
+ // Set the value of the top-left cell with cellValue and style
+ if (i === rowIndex && j === colSetValueIndex) {
+ cellMatrix.setValue(i, j, { ...cellValue, style: cellStyle });
+ } else {
+ // Set the style for all other cells
+ cellMatrix.setValue(i, j, { style: cellStyle });
}
}
}
diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/parse-node-style.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/parse-node-style.ts
index e7744c173b..dc7006f67b 100644
--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/parse-node-style.ts
+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/parse-node-style.ts
@@ -18,7 +18,7 @@ import type { ITextStyle } from '@univerjs/core';
import { BaselineOffset, BooleanNumber, ColorKit } from '@univerjs/core';
import { DEFAULT_BACKGROUND_COLOR_RGB, DEFAULT_BACKGROUND_COLOR_RGBA } from '@univerjs/ui';
-export function extractNodeStyle(node: HTMLElement, predefinedStyles?: CSSStyleDeclaration): ITextStyle {
+export function extractNodeStyle(node: HTMLElement, predefinedStyles?: Record<string, string>): ITextStyle {
const styles = predefinedStyles ?? node.style;
const docStyles: ITextStyle = {};
const tagName = node.tagName.toLowerCase();
@@ -61,82 +61,75 @@ export function extractNodeStyle(node: HTMLElement, predefinedStyles?: CSSStyleD
return docStyles;
}
-// eslint-disable-next-line complexity
-function parseStyleByProperty(styles: CSSStyleDeclaration, docStyles: ITextStyle) {
- for (let i = 0; i < styles.length; i++) {
- const cssRule = styles[i];
- const cssValue = styles.getPropertyValue(cssRule);
- switch (cssRule) {
- case 'font-family': {
- docStyles.ff = cssValue;
- break;
- }
- case 'font-size': {
- const fontSize = Number.parseInt(cssValue);
- if (!Number.isNaN(fontSize)) {
- // TODO: @ybzky need other font size unit support
- if (cssValue.endsWith('pt')) {
- docStyles.fs = fontSize;
- } else if (cssValue.endsWith('px')) {
- const transformedFontSize = fontSize * 0.75;
- docStyles.fs = transformedFontSize;
- }
- }
- break;
- }
- case 'font-style': {
- if (cssValue === 'italic') {
- docStyles.it = BooleanNumber.TRUE;
+function parseStyleByProperty(styles: CSSStyleDeclaration | Record<string, string>, docStyles: ITextStyle) {
+ if (styles instanceof CSSStyleDeclaration) {
+ for (let i = 0; i < styles.length; i++) {
+ const cssRule = styles[i];
+ const cssValue = styles.getPropertyValue(cssRule);
+ handleStyle(cssRule, cssValue, docStyles);
+ }
+ } else {
+ for (const cssRule in styles) {
+ const cssValue = styles[cssRule];
+ handleStyle(cssRule, cssValue, docStyles);
+ }
+ }
+}
+
+function handleStyle(cssRule: string, cssValue: string, docStyles: ITextStyle) {
+ switch (cssRule) {
+ case 'font-family':
+ docStyles.ff = cssValue;
+ break;
+ case 'font-size': {
+ const fontSize = Number.parseInt(cssValue);
+ if (!Number.isNaN(fontSize)) {
+ if (cssValue.endsWith('pt')) {
+ docStyles.fs = fontSize;
+ } else if (cssValue.endsWith('px')) {
+ docStyles.fs = fontSize * 0.75;
}
- break;
}
- case 'font-weight': {
- const MIDDLE_FONT_WEIGHT = 400;
- if (Number(cssValue) > MIDDLE_FONT_WEIGHT || cssValue === 'bold') {
- docStyles.bl = BooleanNumber.TRUE;
- }
- break;
+ break;
+ }
+ case 'font-style':
+ if (cssValue === 'italic') {
+ docStyles.it = BooleanNumber.TRUE;
}
- case 'text-decoration': {
- // TODO: @JOCS, Parse CSS values like: underline dotted;
- if (/underline/.test(cssValue)) {
- docStyles.ul = {
- s: BooleanNumber.TRUE,
- };
- } else if (/overline/.test(cssValue)) {
- docStyles.ol = {
- s: BooleanNumber.TRUE,
- };
- } else if (/line-through/.test(cssValue)) {
- docStyles.st = {
- s: BooleanNumber.TRUE,
- };
- }
- break;
+ break;
+ case 'font-weight': {
+ const MIDDLE_FONT_WEIGHT = 400;
+ if (Number(cssValue) > MIDDLE_FONT_WEIGHT || cssValue === 'bold') {
+ docStyles.bl = BooleanNumber.TRUE;
}
- case 'color': {
- const color = new ColorKit(cssValue);
- if (color.isValid) {
- docStyles.cl = {
- rgb: color.toRgbString(),
- };
- }
- break;
+ break;
+ }
+ case 'text-decoration': {
+ if (/underline/.test(cssValue)) {
+ docStyles.ul = { s: BooleanNumber.TRUE };
+ } else if (/overline/.test(cssValue)) {
+ docStyles.ol = { s: BooleanNumber.TRUE };
+ } else if (/line-through/.test(cssValue)) {
+ docStyles.st = { s: BooleanNumber.TRUE };
}
- case 'background-color': {
- const color = new ColorKit(cssValue);
- const bgColor = color.isValid ? color.toRgbString() : '';
- if (bgColor !== DEFAULT_BACKGROUND_COLOR_RGB && bgColor !== DEFAULT_BACKGROUND_COLOR_RGBA) {
- docStyles.bg = {
- rgb: color.toRgbString(),
- };
- }
- break;
+ break;
+ }
+ case 'color': {
+ const color = new ColorKit(cssValue);
+ if (color.isValid) {
+ docStyles.cl = { rgb: color.toRgbString() };
}
- default: {
- // console.log(`Unhandled css rule ${cssRule}`);
- break;
+ break;
+ }
+ case 'background-color': {
+ const color = new ColorKit(cssValue);
+ const bgColor = color.isValid ? color.toRgbString() : '';
+ if (bgColor !== DEFAULT_BACKGROUND_COLOR_RGB && bgColor !== DEFAULT_BACKGROUND_COLOR_RGBA) {
+ docStyles.bg = { rgb: bgColor };
}
+ break;
}
+ default:
+ break;
}
-}
+};
diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/utils.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/utils.ts
index 5344ab9003..e3aa4f9a4f 100644
--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/utils.ts
+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/utils.ts
@@ -19,11 +19,9 @@ import { DataStreamTreeTokenType, Tools } from '@univerjs/core';
import { ptToPixel } from '@univerjs/engine-render';
export default function parseToDom(rawHtml: string) {
- const parser = new DOMParser();
- const html = `<x-univer id="univer-root">${rawHtml}</x-univer>`;
- const doc = parser.parseFromString(html, 'text/html');
-
- return doc.querySelector('#univer-root');
+ const template = document.createElement('body');
+ template.innerHTML = rawHtml;
+ return template;
}
// TODO: @JOCS, Complete other missing attributes that exist in IParagraphStyle
diff --git a/packages/ui/src/utils/cell.ts b/packages/ui/src/utils/cell.ts
index ae491627f0..a3e120f3af 100644
--- a/packages/ui/src/utils/cell.ts
+++ b/packages/ui/src/utils/cell.ts
@@ -500,7 +500,7 @@ export function handleStringToStyle($dom?: HTMLElement, cssStyle: string = '') {
arr.splice(0, 2);
const color = arr.join('');
const lineType = getBorderStyleType(type);
- if (lineType !== BorderStyleTypes.NONE) {
+ if (lineType !== BorderStyleTypes.NONE && color) {
const obj = {
cl: {
rgb: color,
@@ -524,7 +524,7 @@ export function handleStringToStyle($dom?: HTMLElement, cssStyle: string = '') {
};
}
}
- } else if (key === 'data-rotate') {
+ } else if (key === '--data-rotate') {
const regex = /[+-]?\d+/;
const match = value.match(regex);