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
fix(docs-ui): upload pasted base64 images (#6985)
Univerae59468e2ff7
diff --git a/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.ts b/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.tsindex 479cd5d287..80a621b4bd 100644--- a/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.ts+++ b/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.ts@@ -20,6 +20,7 @@ import { BooleanNumber, HorizontalAlign, TextDecoration, TextDirection } from '.import { DocumentDataModel } from '../document-data-model';import { JSONX } from '../json-x/json-x';import { ParagraphStyleBuilder, RichTextBuilder, TextDecorationBuilder, TextStyleBuilder } from '../rich-text-builder';+import { DataStreamTreeTokenType } from '../types';function createDocSnapshot(id = 'doc-main'): IDocumentData {return {@@ -149,6 +150,54 @@ describe('DocumentDataModel + RichTextBuilder integration', () => {expect(model.getPlainText()).toContain('Hello World');expect(model.sliceBody(0, 5)?.dataStream).toContain('Hello');+ const partialParagraphModel = new DocumentDataModel({+ id: 'partial-paragraph',+ title: 'Partial Paragraph',+ documentStyle: {},+ body: {+ dataStream: 'First\rSecond\r',+ paragraphs: [+ { startIndex: 5, paragraphStyle: { horizontalAlign: HorizontalAlign.CENTER } },+ { startIndex: 12, paragraphStyle: { textStyle: { fs: 18 } } },+ ],+ },+ });+ expect(partialParagraphModel.sliceBody(0, 5)?.paragraphs?.[0]).toMatchObject({+ startIndex: 5,+ paragraphStyle: { horizontalAlign: HorizontalAlign.CENTER },+ });+ expect(partialParagraphModel.sliceBody(6, 12)?.paragraphs?.[0]).toMatchObject({+ startIndex: 6,+ paragraphStyle: { textStyle: { fs: 18 } },+ });+ partialParagraphModel.dispose();++ const tableStream = [+ DataStreamTreeTokenType.TABLE_START,+ DataStreamTreeTokenType.TABLE_ROW_START,+ DataStreamTreeTokenType.TABLE_CELL_START,+ 'Cell\r\n',+ DataStreamTreeTokenType.TABLE_CELL_END,+ DataStreamTreeTokenType.TABLE_ROW_END,+ DataStreamTreeTokenType.TABLE_END,+ ].join('');+ const partialTableModel = new DocumentDataModel({+ id: 'partial-table',+ title: 'Partial Table',+ documentStyle: {},+ body: {+ dataStream: tableStream,+ tables: [{ startIndex: 0, endIndex: tableStream.length, tableId: 'table-1' }],+ paragraphs: [{ startIndex: 7 }],+ },+ });+ expect(partialTableModel.sliceBody(1, tableStream.length - 1)?.tables?.[0]).toMatchObject({+ startIndex: 0,+ endIndex: tableStream.length - 2,+ tableId: 'table-1',+ });+ partialTableModel.dispose();+model.resetDrawing({} as any, []);expect(model.getDrawingsOrder()).toEqual([]);model.dispose();diff --git a/packages/core/src/docs/data-model/text-x/utils.ts b/packages/core/src/docs/data-model/text-x/utils.tsindex c13417f317..7b11e70671 100644--- a/packages/core/src/docs/data-model/text-x/utils.ts+++ b/packages/core/src/docs/data-model/text-x/utils.ts@@ -92,11 +92,11 @@ export function getTableSlice(const clonedTable = Tools.deepClone(table);const { startIndex, endIndex } = clonedTable;- if (startIndex >= startOffset && endIndex <= endOffset) {+ if (Math.max(startIndex, startOffset) < Math.min(endIndex, endOffset)) {newTables.push({...clonedTable,- startIndex: startIndex - startOffset,- endIndex: endIndex - startOffset,+ startIndex: Math.max(startIndex, startOffset) - startOffset,+ endIndex: Math.min(endIndex, endOffset) - startOffset,});}}@@ -130,15 +130,42 @@ export function getBlockRangeSlice(export function getParagraphsSlice(body: IDocumentBody,startOffset: number,- endOffset: number+ endOffset: number,+ type = SliceBodyType.cut) {const { paragraphs = [] } = body;const newParagraphs: IParagraph[] = [];- for (const paragraph of paragraphs) {- const { startIndex } = paragraph;- if (startIndex >= startOffset && startIndex < endOffset) {+ if (type === SliceBodyType.cut) {+ for (const paragraph of paragraphs) {+ const { startIndex } = paragraph;+ if (startIndex >= startOffset && startIndex < endOffset) {+ newParagraphs.push(Tools.deepClone(paragraph));+ }+ }++ if (newParagraphs.length) {+ return newParagraphs.map((p) => ({+ ...p,+ startIndex: p.startIndex - startOffset,+ }));+ }++ return;+ }++ const sortedParagraphs = [...paragraphs].sort((a, b) => a.startIndex - b.startIndex);++ for (let index = 0; index < sortedParagraphs.length; index++) {+ const paragraph = sortedParagraphs[index];+ const paragraphStart = index > 0 ? sortedParagraphs[index - 1].startIndex + 1 : 0;+ const paragraphEnd = paragraph.startIndex;+ const paragraphMarkInRange = paragraphEnd >= startOffset && paragraphEnd < endOffset;+ const paragraphTextIntersectsRange = Math.max(paragraphStart, startOffset) < Math.min(paragraphEnd, endOffset);++ if (paragraphMarkInRange || paragraphTextIntersectsRange) {const copy = Tools.deepClone(paragraph);+ copy.startIndex = Math.min(Math.max(paragraphEnd, startOffset), endOffset);newParagraphs.push(copy);}}@@ -222,7 +249,7 @@ export function getBodySlice(docBody.blockRanges = newBlockRanges;}- docBody.paragraphs = getParagraphsSlice(body, startOffset, endOffset);+ docBody.paragraphs = getParagraphsSlice(body, startOffset, endOffset, type);if (type === SliceBodyType.cut) {const customDecorations = getCustomDecorationSlice(body, startOffset, endOffset);diff --git a/packages/docs-ui/src/services/clipboard/__test__/clipboard.service.spec.ts b/packages/docs-ui/src/services/clipboard/__test__/clipboard.service.spec.tsnew file mode 100644index 0000000000..26b136c95b--- /dev/null+++ b/packages/docs-ui/src/services/clipboard/__test__/clipboard.service.spec.ts@@ -0,0 +1,113 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IDocumentBody, IDocumentData } from '@univerjs/core';+import type { IRectRangeWithStyle } from '@univerjs/engine-render';+import { DataStreamTreeTokenType, DOC_RANGE_TYPE } from '@univerjs/core';+import { ImageSourceType } from '@univerjs/drawing';+import { describe, expect, it, vi } from 'vitest';+import { DocClipboardService, getTableClipboardBodySlice } from '../clipboard.service';++describe('DocClipboardService table copy helpers', () => {+ it('should keep table metadata when copying an entire selected docs table', () => {+ const tokens = DataStreamTreeTokenType;+ const tableStream = `${tokens.TABLE_START}${tokens.TABLE_ROW_START}${tokens.TABLE_CELL_START}A\r\n${tokens.TABLE_CELL_END}${tokens.TABLE_CELL_START}B\r\n${tokens.TABLE_CELL_END}${tokens.TABLE_ROW_END}${tokens.TABLE_END}`;+ const dataStream = `Intro\r${tableStream}Tail\r`;+ const tableStart = 'Intro\r'.length;+ const tableEnd = tableStart + tableStream.length;+ const body: IDocumentBody = {+ dataStream,+ paragraphs: [+ { startIndex: 5 },+ { startIndex: tableStart + tokens.TABLE_START.length + tokens.TABLE_ROW_START.length + tokens.TABLE_CELL_START.length + 1 },+ { startIndex: tableStart + tokens.TABLE_START.length + tokens.TABLE_ROW_START.length + tokens.TABLE_CELL_START.length + 'A\r\n'.length + tokens.TABLE_CELL_END.length + tokens.TABLE_CELL_START.length + 1 },+ { startIndex: dataStream.length - 1 },+ ],+ sectionBreaks: [],+ tables: [{+ startIndex: tableStart,+ endIndex: tableEnd,+ tableId: 'table-1',+ }],+ };+ const range: IRectRangeWithStyle = {+ startOffset: tableStart,+ endOffset: tableEnd,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.RECT,+ tableId: 'table-1',+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 1,+ spanEntireRow: true,+ spanEntireColumn: true,+ spanEntireTable: true,+ };++ const slice = getTableClipboardBodySlice(body, range);++ expect(slice.dataStream).toBe(tableStream);+ expect(slice.tables).toEqual([{+ startIndex: 0,+ endIndex: tableStream.length,+ tableId: 'table-1',+ }]);+ });++ it('should upload base64 images embedded in pasted html before converting to docs drawings', async () => {+ let pastedDoc: Partial<IDocumentData> | undefined;+ const executeCommand = vi.fn(async (_id, params) => {+ pastedDoc = params.doc;+ return true;+ });+ const uploadImage = vi.fn(async (file: File) => {+ expect(file.type).toBe('image/png');++ return {+ imageSourceType: ImageSourceType.UUID,+ source: 'remote-file-id',+ };+ });+ const service = new DocClipboardService(+ { getCurrentUnitOfType: () => ({ getUnitId: () => 'doc-1' }) } as any,+ { error: vi.fn(), warn: vi.fn() } as any,+ { executeCommand } as any,+ {} as any,+ {+ getActiveTextRange: () => ({ segmentId: '', endOffset: 0 }),+ getTextRanges: () => [{ startOffset: 0, endOffset: 0 }],+ } as any+ ) as DocClipboardService;+ const source = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/lz6N4wAAAABJRU5ErkJggg==';++ service.addClipboardHook({ onBeforePasteImage: uploadImage });+ await service.legacyPaste({+ html: `<p><img src="${source}" width="2" height="3"></p>`,+ files: [],+ });++ const block = pastedDoc?.body?.customBlocks?.[0];+ const drawing = block ? pastedDoc?.drawings?.[block.blockId] : undefined;++ expect(uploadImage).toHaveBeenCalledTimes(1);+ expect(drawing).toMatchObject({+ imageSourceType: ImageSourceType.UUID,+ source: 'remote-file-id',+ });+ expect(JSON.stringify(pastedDoc)).not.toContain('data:image');+ });+});diff --git a/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.ts b/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.tsindex ac0bb82b0d..fc4fcd52c0 100644--- a/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.ts+++ b/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.ts@@ -14,14 +14,14 @@* limitations under the License.*/-import type { IDocumentBody, Nullable } from '@univerjs/core';-import { BooleanNumber } from '@univerjs/core';+import type { IDocumentBody, IDocumentData, Nullable } from '@univerjs/core';+import { BooleanNumber, DataStreamTreeTokenType, HorizontalAlign, PresetListType, TableSizeType } from '@univerjs/core';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { HtmlToUDMService } from '../html-to-udm/converter';import PastePluginLark from '../html-to-udm/paste-plugins/plugin-lark';import PastePluginWord from '../html-to-udm/paste-plugins/plugin-word';-import { createInternalClipboardFragment, embedInternalClipboardFragment, extractInternalClipboardFragmentFromHtml, wrapClipboardHtml } from '../internal-fragment';+import { createInternalClipboardDocData, createInternalClipboardDocDataList, createInternalClipboardFragment, embedInternalClipboardFragment, extractInternalClipboardFragmentFromHtml, wrapClipboardHtml } from '../internal-fragment';import { UDMToHtmlService } from '../udm-to-html/convertor';HtmlToUDMService.use(PastePluginWord);@@ -138,13 +138,124 @@ describe('test case in html and udm convert', () => {it('should normalize word and wps mso lists to real list paragraphs', () => {const convertor = new HtmlToUDMService();const udm = convertor.convert(`- <p class="MsoListParagraph" style="mso-list:l0 level1 lfo1">1. Alpha</p>+ <p class="MsoListParagraph" style="mso-list:l0 level1 lfo1">1) Alpha</p><p class="MsoListParagraph" style="mso-list:l0 level2 lfo1">a. Nested</p>`);expect(udm.body?.dataStream).toBe('Alpha\rNested\r');expect(udm.body?.paragraphs?.map((paragraph) => paragraph.bullet?.nestingLevel)).toEqual([0, 1]);});++ it('should preserve Word tab and nbsp separators between inline runs', () => {+ const convertor = new HtmlToUDMService();+ const udm = convertor.convert(`+ <p class="MsoNormal">+ <span>Nové místo</span>\t <span>Plasy</span> <span>parkoviště u lékařského domu</span>+ </p>+ `);++ expect(udm.body?.dataStream).toBe('Nové místo Plasy parkoviště u lékařského domu\r');+ });++ it('should preserve Word mso spacer and tab runs', () => {+ const convertor = new HtmlToUDMService();+ const udm = convertor.convert('<p class="MsoNormal"><span>New</span><span style="mso-spacerun:yes"> </span><span>place</span><span style="mso-tab-count:1"> </span><span>Plasy</span></p>');++ expect(udm.body?.dataStream).toBe('New place Plasy\r');+ });++ it('should paste base64 images from Word-compatible HTML as inline drawings', () => {+ const convertor = new HtmlToUDMService();+ const source = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/lz6N4wAAAABJRU5ErkJggg==';+ const udm = convertor.convert(`<p>Before</p><p><img src="${source}" data-width="320" data-height="180"></p>`);+ const block = udm.body?.customBlocks?.[0];+ const drawing = block ? udm.drawings?.[block.blockId] : undefined;++ expect(block).toBeTruthy();+ expect(drawing).toMatchObject({+ imageSourceType: 'BASE64',+ source,+ transform: { width: 320, height: 180 },+ });+ });++ it('should read raw Word image dimensions from html attributes', () => {+ const convertor = new HtmlToUDMService();+ const source = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/lz6N4wAAAABJRU5ErkJggg==';+ const udm = convertor.convert(`<p class="MsoNormal"><img width="611" height="453" src="${source}"></p>`);+ const block = udm.body?.customBlocks?.[0];+ const drawing = block ? udm.drawings?.[block.blockId] : undefined;++ expect(drawing).toMatchObject({+ transform: { width: 611, height: 453 },+ docTransform: { size: { width: 611, height: 453 } },+ });+ });++ it('should preserve Word table structure, cell styles, lists, and paragraph alignment', () => {+ const convertor = new HtmlToUDMService();+ const udm = convertor.convert(`+ <table class="MsoTableGrid">+ <colgroup><col style="width: 120pt"><col style="width: 80px"></colgroup>+ <tr style="height: 24pt">+ <td colspan="2" style="background:#D9EAF7;border:solid #4472C4 1.5pt">+ <p style="text-align:center">Merged Header</p>+ </td>+ </tr>+ <tr>+ <td style="background-color:#FFF2CC;border:1px solid #70AD47">+ <ul><li>Bullet in cell</li></ul>+ </td>+ <td><p>Plain cell</p></td>+ </tr>+ </table>+ `);+ const tableId = udm.body?.tables?.[0].tableId;+ const table = tableId ? udm.tableSource?.[tableId] : undefined;++ expect(table?.tableColumns.map((column) => column.size.width.v)).toEqual([160, 80]);+ expect(table?.tableRows[0].trHeight.val.v).toBe(32);+ expect(table?.tableRows[0].tableCells[0]).toMatchObject({+ columnSpan: 2,+ backgroundColor: { rgb: 'rgb(217,234,247)' },+ borderTop: { color: { rgb: 'rgb(68,114,196)' }, width: { v: 2 } },+ });+ expect(table?.tableRows[0].tableCells[1]).toMatchObject({ rowSpan: 0, columnSpan: 0 });+ expect(table?.tableRows[1].tableCells[0].backgroundColor?.rgb).toBe('rgb(255,242,204)');+ const headerEnd = (udm.body?.dataStream.indexOf('Merged Header') ?? 0) + 'Merged Header'.length;+ expect(udm.body?.paragraphs?.find((paragraph) => paragraph.startIndex === headerEnd)?.paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.CENTER);+ expect(udm.body?.paragraphs?.some((paragraph) => paragraph.bullet && udm.body?.dataStream.includes('Bullet in cell'))).toBe(true);+ });++ it('should distribute table width when clipboard html has no per-column widths', () => {+ const convertor = new HtmlToUDMService();+ const udm = convertor.convert(`+ <table class="MsoNormalTable UniverTable" style="border-collapse: collapse; width: 960px"><tbody>+ <tr style="height: 38px">+ <td colspan="4" style="background-color: rgb(236, 254, 255); border-top-width: 1px; border-top-style: solid; border-top-color: rgb(203, 213, 225); border-right-width: 1px; border-right-style: solid; border-right-color: rgb(203, 213, 225); border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: rgb(203, 213, 225); border-left-width: 1px; border-left-style: solid; border-left-color: rgb(203, 213, 225)">+ <p class="UniverNormal" style="text-align: center; font-family: Arial; font-size: 12pt; font-weight: bold"><strong>Layout and pagination sample</strong></p>+ </td>+ </tr>+ <tr style="height: 32px">+ <td class="UniverTableCell" style="background-color: rgb(240, 253, 250); border-top-width: 1px; border-top-style: solid; border-top-color: rgb(203, 213, 225); border-right-width: 1px; border-right-style: solid; border-right-color: rgb(203, 213, 225); border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: rgb(203, 213, 225); border-left-width: 1px; border-left-style: solid; border-left-color: rgb(203, 213, 225)"><p>Section</p></td>+ <td class="UniverTableCell" style="background-color: rgb(240, 253, 250); border-top-width: 1px; border-top-style: solid; border-top-color: rgb(203, 213, 225); border-right-width: 1px; border-right-style: solid; border-right-color: rgb(203, 213, 225); border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: rgb(203, 213, 225); border-left-width: 1px; border-left-style: solid; border-left-color: rgb(203, 213, 225)"><p>Signal</p></td>+ <td class="UniverTableCell" style="background-color: rgb(240, 253, 250); border-top-width: 1px; border-top-style: solid; border-top-color: rgb(203, 213, 225); border-right-width: 1px; border-right-style: solid; border-right-color: rgb(203, 213, 225); border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: rgb(203, 213, 225); border-left-width: 1px; border-left-style: solid; border-left-color: rgb(203, 213, 225)"><p>Details</p></td>+ <td class="UniverTableCell" style="background-color: rgb(240, 253, 250); border-top-width: 1px; border-top-style: solid; border-top-color: rgb(203, 213, 225); border-right-width: 1px; border-right-style: solid; border-right-color: rgb(203, 213, 225); border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: rgb(203, 213, 225); border-left-width: 1px; border-left-style: solid; border-left-color: rgb(203, 213, 225)"><p>Expected behavior</p></td>+ </tr>+ </tbody></table>+ `);+ const tableId = udm.body?.tables?.[0].tableId;+ const table = tableId ? udm.tableSource?.[tableId] : undefined;+ const titleCell = table?.tableRows[0].tableCells[0];++ expect(table?.size.width.v).toBe(960);+ expect(table?.tableColumns.map((column) => column.size.width.v)).toEqual([240, 240, 240, 240]);+ expect(table?.tableRows[0].trHeight.val.v).toBe(38);+ expect(titleCell?.columnSpan).toBe(4);+ expect(titleCell?.backgroundColor?.rgb).toBe('rgb(236,254,255)');+ expect(titleCell?.borderTop?.width?.v).toBe(1);+ expect(titleCell?.borderTop?.color.rgb).toBe('rgb(203,213,225)');+ });});describe('test cases in udm-to-html', () => {@@ -152,7 +263,7 @@ describe('test case in html and udm convert', () => {const convertor = new UDMToHtmlService();const html = await convertor.convert([{ body: body!, id: '', documentStyle: {} }]);- expect(html).toBe('<p class="UniverNormal" ><strong>hello</strong><strong><i>world</i></strong></p>');+ expect(html).toBe('<p class="UniverNormal" ><span style="font-family: Arial;"><strong>hello</strong></span><span style="font-family: Arial;"><strong><i>world</i></strong></span></p>');});it('should serialize structured doc metadata as semantic clipboard html', () => {@@ -182,6 +293,89 @@ describe('test case in html and udm convert', () => {expect(html).toContain('data-doc-type="ordered-list"');});+ it('should serialize table spans and cell formatting to Word-compatible HTML', () => {+ const convertor = new UDMToHtmlService();+ const dataStream = [+ DataStreamTreeTokenType.TABLE_START,+ DataStreamTreeTokenType.TABLE_ROW_START,+ DataStreamTreeTokenType.TABLE_CELL_START,+ 'Merged\r\n',+ DataStreamTreeTokenType.TABLE_CELL_END,+ DataStreamTreeTokenType.TABLE_CELL_START,+ '\r\n',+ DataStreamTreeTokenType.TABLE_CELL_END,+ DataStreamTreeTokenType.TABLE_ROW_END,+ DataStreamTreeTokenType.TABLE_ROW_START,+ DataStreamTreeTokenType.TABLE_CELL_START,+ 'A2\r\n',+ DataStreamTreeTokenType.TABLE_CELL_END,+ DataStreamTreeTokenType.TABLE_CELL_START,+ 'B2\r\n',+ DataStreamTreeTokenType.TABLE_CELL_END,+ DataStreamTreeTokenType.TABLE_ROW_END,+ DataStreamTreeTokenType.TABLE_END,+ ].join('');+ const html = convertor.convert([{+ id: '',+ documentStyle: {},+ body: {+ dataStream,+ tables: [{ startIndex: 0, endIndex: dataStream.length, tableId: 'table-1' }],+ paragraphs: [+ { startIndex: 9, paragraphStyle: { horizontalAlign: HorizontalAlign.CENTER } },+ { startIndex: 13 },+ { startIndex: 21 },+ { startIndex: 27 },+ ],+ sectionBreaks: [{ startIndex: 10 }, { startIndex: 14 }, { startIndex: 22 }, { startIndex: 28 }],+ },+ tableSource: {+ 'table-1': {+ tableId: 'table-1',+ tableColumns: [+ { size: { type: 1, width: { v: 120 } } },+ { size: { type: 1, width: { v: 80 } } },+ ],+ tableRows: [+ {+ trHeight: { val: { v: 32 }, hRule: 2 },+ tableCells: [+ {+ columnSpan: 2,+ backgroundColor: { rgb: '#D9EAF7' },+ borderTop: { color: { rgb: '#4472C4' }, width: { v: 2 } },+ borderRight: { color: { rgb: '#4472C4' }, width: { v: 2 } },+ borderBottom: { color: { rgb: '#4472C4' }, width: { v: 2 } },+ borderLeft: { color: { rgb: '#4472C4' }, width: { v: 2 } },+ },+ { rowSpan: 0, columnSpan: 0 },+ ],+ },+ {+ trHeight: { val: { v: 30 }, hRule: 0 },+ tableCells: [{ backgroundColor: { rgb: '#FFF2CC' } }, {}],+ },+ ],+ align: 0,+ indent: { v: 0 },+ textWrap: 0,+ position: {+ positionH: { relativeFrom: 0, posOffset: 0 },+ positionV: { relativeFrom: 0, posOffset: 0 },+ },+ dist: { distB: 0, distL: 0, distR: 0, distT: 0 },+ size: { type: 1, width: { v: 200 } },+ },+ },+ }]);++ expect(html).toContain('colspan="2"');+ expect(html).toContain('background-color: #D9EAF7');+ expect(html).toContain('border-top: 2px solid #4472C4');+ expect(html).toContain('text-align: center');+ expect(html).not.toContain('<td class="UniverTableCell"></td><td class="UniverTableCell"></td>');+ });+it('should serialize adjacent and nested list paragraphs as one semantic list tree', () => {const convertor = new UDMToHtmlService();const html = convertor.convert([{@@ -203,6 +397,131 @@ describe('test case in html and udm convert', () => {expect(html).toContain('</ul></li><li><p class="UniverNormal" >Two</p>');});+ it('should preserve copied internal table sources and list metadata', () => {+ const doc: IDocumentData = {+ id: '',+ documentStyle: {},+ body: {+ dataStream: `${DataStreamTreeTokenType.TABLE_START}${DataStreamTreeTokenType.TABLE_ROW_START}${DataStreamTreeTokenType.TABLE_CELL_START}Cell\r\n${DataStreamTreeTokenType.TABLE_CELL_END}${DataStreamTreeTokenType.TABLE_ROW_END}${DataStreamTreeTokenType.TABLE_END}\r\nBullet\r`,+ tables: [{+ startIndex: 0,+ endIndex: 10,+ tableId: 'table-1',+ }],+ paragraphs: [{+ startIndex: 5,+ }, {+ startIndex: 19,+ bullet: {+ listId: 'list-1',+ listType: PresetListType.BULLET_LIST,+ nestingLevel: 0,+ },+ }],+ },+ tableSource: {+ 'table-1': {+ tableId: 'table-1',+ tableColumns: [+ { size: { type: TableSizeType.SPECIFIED, width: { v: 88 } } },+ { size: { type: TableSizeType.SPECIFIED, width: { v: 176 } } },+ ],+ tableRows: [],+ } as any,+ },+ lists: {+ [PresetListType.BULLET_LIST]: {+ listType: PresetListType.BULLET_LIST,+ nestingLevel: {},+ },+ } as any,+ };++ const internalDocData = createInternalClipboardDocData(doc);++ expect(internalDocData.tableSource?.['table-1'].tableColumns?.map((column) => column.size.width.v)).toEqual([88, 176]);+ expect(internalDocData.lists?.[PresetListType.BULLET_LIST]).toBeDefined();+ });++ it('should preserve table sources when multiple copied fragments are merged for internal paste', () => {+ const createTableDoc = (tableId: string, text: string, widths: number[]): IDocumentData => {+ const dataStream = `${DataStreamTreeTokenType.TABLE_START}${DataStreamTreeTokenType.TABLE_ROW_START}${DataStreamTreeTokenType.TABLE_CELL_START}${text}\r\n${DataStreamTreeTokenType.TABLE_CELL_END}${DataStreamTreeTokenType.TABLE_ROW_END}${DataStreamTreeTokenType.TABLE_END}`;+ return {+ id: '',+ documentStyle: {},+ body: {+ dataStream,+ tables: [{+ startIndex: 0,+ endIndex: dataStream.length,+ tableId,+ }],+ paragraphs: [{+ startIndex: DataStreamTreeTokenType.TABLE_START.length + DataStreamTreeTokenType.TABLE_ROW_START.length + DataStreamTreeTokenType.TABLE_CELL_START.length + text.length,+ }],+ },+ tableSource: {+ [tableId]: {+ tableId,+ tableColumns: widths.map((width) => ({ size: { type: TableSizeType.SPECIFIED, width: { v: width } } })),+ tableRows: [],+ } as any,+ },+ };+ };++ const first = createTableDoc('table-1', 'A', [120, 240]);+ const second = createTableDoc('table-2', 'B', [90, 180]);+ const internalDocData = createInternalClipboardDocDataList([first, second]);++ expect(internalDocData?.body?.tables).toHaveLength(2);+ expect(internalDocData?.body?.tables?.[1].startIndex).toBe(first.body!.dataStream.length);+ expect(internalDocData?.tableSource?.['table-1'].tableColumns?.map((column) => column.size.width.v)).toEqual([120, 240]);+ expect(internalDocData?.tableSource?.['table-2'].tableColumns?.map((column) => column.size.width.v)).toEqual([90, 180]);+ });++ it('should paste docs feature coverage from html with styles, blocks, lists and table dimensions', () => {+ const convertor = new HtmlToUDMService();+ const pasted = convertor.convert(`+ <p class="UniverNormal" style="margin-top: 6px; margin-bottom: 10px; line-height: 150%; text-align: center; font-family: Arial; font-size: 13pt; color: #123456;"><strong><i><u>Styled paragraph</u></i></strong></p>+ <ul data-doc-type="bullet-list"><li><p class="UniverNormal">Bullet item</p></li></ul>+ <ol data-doc-type="ordered-list"><li><p class="UniverNormal">Number item</p></li></ol>+ <blockquote data-doc-type="quote"><p class="UniverNormal">Quote text</p></blockquote>+ <aside data-doc-type="callout" role="note"><p class="UniverNormal">Callout text</p></aside>+ <pre data-doc-type="code-block"><code>const x = 1;</code></pre>+ <table class="MsoNormalTable UniverTable" style="border-collapse: collapse; width: 300px;"><tbody>+ <tr style="height: 32px"><td class="UniverTableCell" colspan="2" style="background-color: #D9EAF7; border: 2px solid #4472C4;"><p class="UniverNormal" style="text-align: center; font-family: Arial; font-size: 12pt; font-weight: bold"><strong>Header</strong></p></td></tr>+ <tr><td class="UniverTableCell" style="width: 90px; border: 1px solid #999999"><p class="UniverNormal">Left</p></td><td class="UniverTableCell" style="width: 210px; border: 1px solid #999999"><p class="UniverNormal" style="color: #C81E1E;">Right</p></td></tr>+ </tbody></table>+ `);+ const body = pasted.body!;+ const styledParagraph = body.paragraphs![0];+ const styledRun = body.textRuns!.find((run) => body.dataStream.slice(run.st, run.ed).includes('Styled paragraph'))!;+ const bulletParagraph = body.paragraphs!.find((paragraph) => paragraph.bullet?.listType === PresetListType.BULLET_LIST);+ const orderedParagraph = body.paragraphs!.find((paragraph) => paragraph.bullet?.listType === PresetListType.ORDER_LIST);+ const blockTypes = body.blockRanges?.map((range) => range.blockType).sort();+ const tableId = body.tables?.[0].tableId;+ const table = tableId ? pasted.tableSource?.[tableId] : undefined;++ expect(styledParagraph.paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.CENTER);+ expect(styledParagraph.paragraphStyle?.lineSpacing).toBe(1.5);+ expect(styledRun.ts?.ff).toBe('Arial');+ expect(styledRun.ts?.fs).toBe(13);+ expect(styledRun.ts?.cl?.rgb).toBe('rgb(18,52,86)');+ expect(styledRun.ts?.bl).toBe(BooleanNumber.TRUE);+ expect(styledRun.ts?.it).toBe(BooleanNumber.TRUE);+ expect(styledRun.ts?.ul?.s).toBe(BooleanNumber.TRUE);+ expect(bulletParagraph).toBeDefined();+ expect(orderedParagraph).toBeDefined();+ expect(blockTypes).toEqual(['callout', 'code', 'quote']);+ expect(table).toBeDefined();+ const headerCell = table!.tableRows[0]!.tableCells[0]!;+ expect(table!.tableColumns.map((column) => column.size.width.v)).toEqual([90, 210]);+ expect(headerCell.columnSpan).toBe(2);+ expect(headerCell.backgroundColor?.rgb).toBe('rgb(217,234,247)');+ expect(headerCell.borderTop?.width?.v).toBe(2);+ });+it('should embed and extract an internal clipboard fragment through html', () => {const fragment = createInternalClipboardFragment({body: {@@ -213,6 +532,9 @@ describe('test case in html and udm convert', () => {const html = wrapClipboardHtml(embedInternalClipboardFragment('<p>Internal</p>', fragment));expect(html).toContain('StartFragment');+ expect(html).toContain('urn:schemas-microsoft-com:office:word');+ expect(html).toContain('Word.Document');+ expect(html).toContain('MsoNormalTable');expect(extractInternalClipboardFragmentFromHtml(html)?.body?.dataStream).toBe('Internal\r');});});diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.tsindex 8dcd1c8a68..d2bc4b229e 100644--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts@@ -37,7 +37,6 @@ import {PositionedObjectLayoutType,SliceBodyType,toDisposable,- Tools,UniverInstanceType,} from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';@@ -59,6 +58,8 @@ import LarkPastePlugin from './html-to-udm/paste-plugins/plugin-lark';import UniverPastePlugin from './html-to-udm/paste-plugins/plugin-univer';import WordPastePlugin from './html-to-udm/paste-plugins/plugin-word';import {+ createInternalClipboardDocData,+ createInternalClipboardDocDataList,createInternalClipboardFragment,DOC_INTERNAL_FRAGMENT_MIME,embedInternalClipboardFragment,@@ -89,7 +90,24 @@ export interface IDocClipboardService {addClipboardHook(hook: IDocClipboardHook): IDisposable;}-function getTableSlice(body: IDocumentBody, start: number, end: number): IDocumentBody {+export function getTableClipboardBodySlice(body: IDocumentBody, range: IRectRangeWithStyle): IDocumentBody {+ const { startOffset, endOffset, spanEntireTable, tableId } = range;++ if (startOffset == null || endOffset == null) {+ return { dataStream: '' };+ }++ if (spanEntireTable) {+ const tableRange = body.tables?.find((table) => table.tableId === tableId);+ if (tableRange) {+ return getBodySlice(body, tableRange.startIndex, tableRange.endIndex, false, SliceBodyType.copy);+ }+ }++ return getTableCellContentClipboardBodySlice(body, startOffset, endOffset);+}++function getTableCellContentClipboardBodySlice(body: IDocumentBody, start: number, end: number): IDocumentBody {const bodySlice = getBodySlice(body, start, end + 2); // +2 for '\r\n in last cell'const dataStream = DataStreamTreeTokenType.TABLE_START +@@ -179,7 +197,10 @@ export class DocClipboardService extends Disposable implements IDocClipboardServconst docUnitId = currentDocInstance?.getUnitId() || '';if (!html && !text && files.length) {html = await this._createImagePasteHtml(files);+ } else if (html && files.length) {+ html += await this._createImagePasteHtml(files);}+ html = await this._uploadBase64ImagesInHtml(html);if (!html && !text) {this._logService.warn('[DocClipboardController] html and text cannot be both empty!');return false;@@ -347,8 +368,11 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ.replaceAll(DataStreamTreeTokenType.TABLE_ROW_END, '').replaceAll(DataStreamTreeTokenType.TABLE_CELL_START, '').replaceAll(DataStreamTreeTokenType.TABLE_CELL_END, '')+ .replaceAll(DataStreamTreeTokenType.BLOCK_START, '')+ .replaceAll(DataStreamTreeTokenType.BLOCK_END, '')// Replace `\r\n` in table cell to white space.- .replaceAll('\r\n', ' ');+ .replaceAll('\r\n', ' ')+ .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, '');let html = this._umdToHtml.convert(documentList);let internalJson = '';@@ -358,32 +382,12 @@ export class DocClipboardService extends Disposable implements IDocClipboardServif (documentList.length === 1 && needCache) {html = html.replace(/(<[a-z]+)/, (_p0, p1) => `${p1} data-copy-id="${copyId}"`);const doc = documentList[0];- const cache: Partial<IDocumentData> = { body: doc.body };-- if (doc.body?.customBlocks?.length) {- cache.drawings = {};-- for (const block of doc.body.customBlocks) {- const { blockId } = block;- const drawing = doc.drawings?.[blockId];-- if (drawing) {- const id = generateRandomId(6);-- block.blockId = id;-- cache.drawings[id] = {- ...Tools.deepClone(drawing),- drawingId: id,- };- }- }- }+ const cache = createInternalClipboardDocData(doc);copyContentCache.set(copyId, cache);internalDocData = cache;- } else if (documentList.length === 1) {- internalDocData = { body: documentList[0].body };+ } else {+ internalDocData = createInternalClipboardDocDataList(documentList);}if (internalDocData) {@@ -439,14 +443,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServif (rangeType === DOC_RANGE_TYPE.RECT) {needCache = false;- const { spanEntireRow } = range as IRectRangeWithStyle;- let bodySlice: IDocumentBody;-- if (!spanEntireRow) {- bodySlice = getTableSlice(body, startOffset, endOffset);- } else {- bodySlice = getTableSlice(body, startOffset, endOffset);- }+ const bodySlice = getTableClipboardBodySlice(body, range as IRectRangeWithStyle);results.push(bodySlice);@@ -506,6 +503,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServif (!html && !text && files.length) {html = await this._createImagePasteHtml(files);}+ html = await this._uploadBase64ImagesInHtml(html) ?? '';return this._genDocDataFromHtmlAndText(html, text, undefined, internalJson);} catch (e) {@@ -551,6 +549,46 @@ export class DocClipboardService extends Disposable implements IDocClipboardServreturn doc;}+ private async _uploadBase64ImagesInHtml(html?: string): Promise<string | undefined> {+ if (!html || !html.includes('data:image/')) {+ return html;+ }++ const onBeforePasteImage = this._clipboardHooks.find((e) => e.onBeforePasteImage)?.onBeforePasteImage;+ if (!onBeforePasteImage) {+ return html;+ }++ const doc = new DOMParser().parseFromString(html, 'text/html');+ const images = Array.from(doc.querySelectorAll<HTMLImageElement>('img[src^="data:image/"]'));+ if (images.length === 0) {+ return html;+ }++ await Promise.all(images.map(async (image, index) => {+ if (image.dataset.imageSourceType && image.dataset.imageSourceType !== ImageSourceType.BASE64) {+ return;+ }++ const file = dataUrlToFile(image.getAttribute('src') || image.src, `pasted_image_${index}`);+ const uploaded = await onBeforePasteImage(file);+ if (!uploaded) {+ return;+ }++ image.dataset.imageSourceType = uploaded.imageSourceType;+ if (uploaded.imageSourceType === ImageSourceType.UUID) {+ image.dataset.source = uploaded.source;+ image.setAttribute('src', uploaded.source);+ } else {+ image.removeAttribute('data-source');+ image.setAttribute('src', uploaded.source);+ }+ }));++ return doc.documentElement.outerHTML;+ }+private async _createImagePasteHtml(files: File[]) {const doc: IDocumentData = {id: '',@@ -627,3 +665,18 @@ export class DocClipboardService extends Disposable implements IDocClipboardServreturn html;}}++function dataUrlToFile(dataUrl: string, fallbackName: string): File {+ const match = /^data:([^;,]+)(;base64)?,(.*)$/i.exec(dataUrl);+ if (!match) {+ throw new Error('[DocClipboardService] invalid image data url.');+ }++ const [, mimeType, base64Marker, payload] = match;+ const bytes = base64Marker+ ? Uint8Array.from(atob(payload), (char) => char.charCodeAt(0))+ : new TextEncoder().encode(decodeURIComponent(payload));+ const extension = mimeType.split('/')[1] || 'png';++ return new File([bytes], `${fallbackName}.${extension}`, { type: mimeType });+}diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/converter.tsindex 52a4e0233d..8004640c71 100644--- a/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts@@ -14,9 +14,10 @@* limitations under the License.*/-import type { IDocumentBody, IDocumentData, IParagraph, ITable, ITextStyle, Nullable } from '@univerjs/core';+import type { IDocumentBody, IDocumentData, IParagraph, ITable, ITableCell, ITableCellBorder, ITextStyle, Nullable } from '@univerjs/core';import type { IAfterProcessRule, IPastePlugin, IStyleRule } from './paste-plugins/type';import {+ ColorKit,CustomRangeType,DataStreamTreeTokenType,DrawingTypeEnum,@@ -27,6 +28,8 @@ import {PositionedObjectLayoutType,PresetListType,skipParseTagNames,+ TableRowHeightRule,+ TableSizeType,Tools,} from '@univerjs/core';import { ImageSourceType } from '@univerjs/drawing';@@ -50,6 +53,7 @@ function matchFilter(node: HTMLElement, filter: IStyleRule['filter']) {// TODO: get from page width.const DEFAULT_TABLE_WIDTH = 660;+const WORD_SPACE_PLACEHOLDER = '\uE000';interface ITableCache {table: ITable;@@ -62,6 +66,13 @@ interface IListContext {nestingLevel: number;}+interface IParsedHtmlTableCell {+ element: HTMLElement | null;+ rowSpan: number;+ colSpan: number;+ covered?: boolean;+}+/*** Convert html strings into data structures in univer, IDocumentBody.* Support plug-in, add custom rules,@@ -91,7 +102,8 @@ export class HtmlToUDMService {convert(html: string, metaConfig: { unitId?: string } = {}): Partial<IDocumentData> {const pastePlugin = HtmlToUDMService._pluginList.find((plugin) => plugin.checkPasteType(html));- const dom = parseToDom(html)!;+ const normalizedHtml = pastePlugin?.preprocessHtml?.(html) ?? html;+ const dom = parseToDom(normalizedHtml)!;const body: IDocumentBody = {dataStream: '',@@ -130,12 +142,11 @@ export class HtmlToUDMService {const body = doc.body!;for (const node of nodes) {if (node.nodeType === Node.TEXT_NODE) {- if (node.nodeValue?.trim() === '') {+ const text = normalizeTextNode(node);+ if (!text) {continue;}- // TODO: @JOCS, More characters need to be replaced, like `\b`- const text = node.nodeValue?.replace(/[\r\n]/g, '');let style;if (parent && this._styleCache.has(parent)) {@@ -146,21 +157,21 @@ export class HtmlToUDMService {if (style && Object.getOwnPropertyNames(style).length) {body.textRuns!.push({- st: body.dataStream.length - text!.length,+ st: body.dataStream.length - text.length,ed: body.dataStream.length,ts: style,});}} else if (node.nodeName === 'IMG') {const element = node as HTMLImageElement;- const imageSourceType = element.dataset.imageSourceType;+ const imageSourceType = element.dataset.imageSourceType ?? (element.src ? inferImageSourceType(element.src) : undefined);const source = imageSourceType === ImageSourceType.UUID ? element.dataset.source : element.src;if (source && imageSourceType) {- const width = Number(element.dataset.width || 100);- const height = Number(element.dataset.height || 100);- const docTransformWidth = Number(element.dataset.docTransformWidth || width);- const docTransformHeight = Number(element.dataset.docTransformHeight || height);+ const width = readImageSize(element, 'width') ?? 100;+ const height = readImageSize(element, 'height') ?? 100;+ const docTransformWidth = readCssSize(element.dataset.docTransformWidth || null, null, 'width') ?? width;+ const docTransformHeight = readCssSize(element.dataset.docTransformHeight || null, null, 'height') ?? height;const id = generateRandomId(6);doc.body?.customBlocks?.push({ startIndex: body.dataStream.length, blockId: id });@@ -197,6 +208,11 @@ export class HtmlToUDMService {continue;} else if (node.nodeType === Node.ELEMENT_NODE) {const element = node as HTMLElement;+ if (element.tagName.toUpperCase() === 'TABLE') {+ this._processHtmlTable(element, doc);+ continue;+ }+if (this._processCodeBlock(element, doc)) {continue;}@@ -307,7 +323,7 @@ export class HtmlToUDMService {private _processAfterDefaultBlock(node: HTMLElement, doc: Partial<IDocumentData>, paragraphAddedByPlugin: boolean): void {if (paragraphAddedByPlugin) {- this._applyWordListInfo(node, doc);+ this._applyListInfo(node, doc);this._lastParagraphIndex = doc.body!.dataStream.length - 1;return;}@@ -354,8 +370,10 @@ export class HtmlToUDMService {this._lastParagraphIndex = body.dataStream.length - 1;}- private _applyWordListInfo(node: HTMLElement, doc: Partial<IDocumentData>): void {- const listContext = extractWordListInfo(node);+ private _applyListInfo(node: HTMLElement, doc: Partial<IDocumentData>): void {+ const htmlListContext = this._listStack[this._listStack.length - 1];+ const wordListContext = extractWordListInfo(node);+ const listContext = htmlListContext ?? wordListContext;const paragraph = doc.body?.paragraphs?.[doc.body.paragraphs.length - 1];if (!listContext || !paragraph) {return;@@ -366,7 +384,95 @@ export class HtmlToUDMService {listType: listContext.listType,nestingLevel: listContext.nestingLevel,};- paragraph.startIndex -= stripListMarkerFromCurrentParagraph(doc.body!);+ if (wordListContext) {+ paragraph.startIndex -= stripListMarkerFromCurrentParagraph(doc.body!);+ }+ }++ private _processHtmlTable(node: HTMLElement, doc: Partial<IDocumentData>): void {+ const body = doc.body!;+ if (body.dataStream[body.dataStream.length - 1] !== '\r') {+ body.dataStream += '\r';+ body.paragraphs ??= [];+ body.paragraphs.push({+ startIndex: body.dataStream.length - 1,+ });+ }++ doc.tableSource ??= {};+ body.tables ??= [];+ body.sectionBreaks ??= [];++ const rows = collectHtmlTableRows(node);+ const grid = buildHtmlTableGrid(rows);+ const columnCount = Math.max(1, ...grid.map((row) => row.length));+ const table = genTableSource(0, columnCount, DEFAULT_TABLE_WIDTH);+ const tableWidth = readCssSize(node.getAttribute('width'), node.getAttribute('style'), 'width');+ const columnWidths = resolveHtmlTableColumnWidths(node, grid, columnCount, tableWidth);+ table.tableRows = [];+ table.tableColumns = columnWidths.map((width) => getTableColumn(width));+ table.size = {+ type: TableSizeType.SPECIFIED,+ width: { v: tableWidth ?? table.tableColumns.reduce((sum, column) => sum + column.size.width.v, 0) },+ };++ const startIndex = body.dataStream.length;+ body.dataStream += DataStreamTreeTokenType.TABLE_START;++ grid.forEach((row, rowIndex) => {+ const tableRow = getEmptyTableRow(0);+ const rowElement = rows[rowIndex];+ const height = rowElement ? readCssSize(rowElement.getAttribute('height'), rowElement.getAttribute('style'), 'height') : undefined;+ if (height != null) {+ tableRow.trHeight = {+ val: { v: height },+ hRule: TableRowHeightRule.EXACT,+ };+ }++ table.tableRows.push(tableRow);+ body.dataStream += DataStreamTreeTokenType.TABLE_ROW_START;++ for (let columnIndex = 0; columnIndex < columnCount; columnIndex++) {+ const parsedCell = row[columnIndex] ?? { element: null, rowSpan: 1, colSpan: 1, covered: true };+ const tableCell = parsedCell.covered+ ? { ...getEmptyTableCell(), rowSpan: 0, columnSpan: 0 }+ : createTableCellFromHtml(parsedCell.element!, parsedCell.rowSpan, parsedCell.colSpan);++ tableRow.tableCells.push(tableCell);+ this._appendHtmlTableCell(parsedCell, doc);+ }++ body.dataStream += DataStreamTreeTokenType.TABLE_ROW_END;+ });++ doc.tableSource[table.tableId] = table;+ body.dataStream += DataStreamTreeTokenType.TABLE_END;+ body.tables.push({+ startIndex,+ endIndex: body.dataStream.length,+ tableId: table.tableId,+ });+ }++ private _appendHtmlTableCell(cell: IParsedHtmlTableCell, doc: Partial<IDocumentData>): void {+ const body = doc.body!;+ body.dataStream += DataStreamTreeTokenType.TABLE_CELL_START;++ if (cell.element && !cell.covered) {+ this._process(cell.element, cell.element.childNodes, doc);+ }++ if (body.dataStream[body.dataStream.length - 1] !== '\r') {+ this._appendParagraph(doc, cell.element ?? document.createElement('td'));+ }++ body.sectionBreaks ??= [];+ body.sectionBreaks.push({+ startIndex: body.dataStream.length,+ });++ body.dataStream += `\n${DataStreamTreeTokenType.TABLE_CELL_END}`;}private _processBeforeTable(node: HTMLElement, doc: Partial<IDocumentData>): void {@@ -520,6 +626,313 @@ export class HtmlToUDMService {}}+function collectHtmlTableRows(table: HTMLElement): HTMLElement[] {+ const rows: HTMLElement[] = [];+ Array.from(table.children).forEach((child) => {+ const tagName = child.tagName.toUpperCase();+ if (tagName === 'TR') {+ rows.push(child as HTMLElement);+ } else if (tagName === 'TBODY' || tagName === 'THEAD' || tagName === 'TFOOT') {+ rows.push(...Array.from(child.children).filter((row) => row.tagName.toUpperCase() === 'TR') as HTMLElement[]);+ }+ });++ return rows;+}++function normalizeTextNode(node: ChildNode): string {+ const value = node.nodeValue ?? '';+ if (value.includes(WORD_SPACE_PLACEHOLDER)) {+ return value+ .replace(/[\t\u00A0]+/g, ' ')+ .replace(/[ \r\n]+/g, ' ')+ .replace(/ *\uE000+ */g, (match) => ' '.repeat(Array.from(match).filter((char) => char === WORD_SPACE_PLACEHOLDER).length));+ }++ const hasExplicitSpacing = /[\t\u00A0]/.test(value);+ const text = value+ .replace(/[\t\u00A0]+/g, ' ')+ .replace(/[ \r\n]+/g, ' ');++ if (text.trim()) {+ return text;+ }++ if (!hasExplicitSpacing) {+ return '';+ }++ return hasTextSibling(node.previousSibling, 'previous') && hasTextSibling(node.nextSibling, 'next') ? ' ' : '';+}++function inferImageSourceType(src: string): ImageSourceType {+ return src.startsWith('data:image/') ? ImageSourceType.BASE64 : ImageSourceType.URL;+}++function hasTextSibling(node: ChildNode | null, direction: 'previous' | 'next'): boolean {+ let current = node;+ while (current) {+ if (current.nodeType === Node.TEXT_NODE && current.nodeValue?.trim()) {+ return true;+ }++ if (current.nodeType === Node.ELEMENT_NODE && (current.textContent ?? '').trim()) {+ return true;+ }++ current = direction === 'previous' ? current.previousSibling : current.nextSibling;+ }++ return false;+}++function buildHtmlTableGrid(rows: HTMLElement[]): IParsedHtmlTableCell[][] {+ const grid: IParsedHtmlTableCell[][] = [];+ const occupied = new Set<string>();++ rows.forEach((row, rowIndex) => {+ const parsedRow: IParsedHtmlTableCell[] = [];+ let columnIndex = 0;++ getHtmlTableCells(row).forEach((cellElement) => {+ while (occupied.has(`${rowIndex}:${columnIndex}`)) {+ parsedRow[columnIndex] = { element: null, rowSpan: 1, colSpan: 1, covered: true };+ columnIndex++;+ }++ const rowSpan = Math.max(1, Number(cellElement.getAttribute('rowspan') ?? 1));+ const colSpan = Math.max(1, Number(cellElement.getAttribute('colspan') ?? 1));+ parsedRow[columnIndex] = { element: cellElement, rowSpan, colSpan };++ for (let rowOffset = 0; rowOffset < rowSpan; rowOffset++) {+ for (let columnOffset = 0; columnOffset < colSpan; columnOffset++) {+ if (rowOffset === 0 && columnOffset === 0) {+ continue;+ }++ occupied.add(`${rowIndex + rowOffset}:${columnIndex + columnOffset}`);+ if (rowOffset === 0) {+ parsedRow[columnIndex + columnOffset] = { element: null, rowSpan: 1, colSpan: 1, covered: true };+ }+ }+ }++ columnIndex += colSpan;+ });++ while (occupied.has(`${rowIndex}:${columnIndex}`)) {+ parsedRow[columnIndex] = { element: null, rowSpan: 1, colSpan: 1, covered: true };+ columnIndex++;+ }++ grid.push(parsedRow);+ });++ const columnCount = Math.max(0, ...grid.map((row) => row.length));+ grid.forEach((row) => {+ while (row.length < columnCount) {+ row.push({ element: null, rowSpan: 1, colSpan: 1, covered: true });+ }+ });++ return grid.length ? grid : [[]];+}++function getHtmlTableCells(row: HTMLElement): HTMLElement[] {+ return Array.from(row.children).filter((element) => {+ const tagName = element.tagName.toUpperCase();+ return tagName === 'TD' || tagName === 'TH';+ }) as HTMLElement[];+}++function collectHtmlTableColumnWidths(table: HTMLElement, grid: IParsedHtmlTableCell[][], columnCount: number): Array<number | undefined> {+ const widths: Array<number | undefined> = Array.from({ length: columnCount });+ Array.from(table.querySelectorAll('col')).forEach((col, index) => {+ if (index < widths.length) {+ widths[index] = readCssSize(col.getAttribute('width'), col.getAttribute('style'), 'width');+ }+ });++ grid.forEach((row) => {+ row.forEach((cell, columnIndex) => {+ if (!cell.element || widths[columnIndex] != null) {+ return;+ }++ const width = readCssSize(cell.element.getAttribute('width'), cell.element.getAttribute('style'), 'width');+ if (width != null && cell.colSpan <= 1) {+ widths[columnIndex] = width;+ }+ });+ });++ return widths;+}++function resolveHtmlTableColumnWidths(table: HTMLElement, grid: IParsedHtmlTableCell[][], columnCount: number, tableWidth?: number): number[] {+ const explicitWidths = collectHtmlTableColumnWidths(table, grid, columnCount);+ const fallbackTableWidth = tableWidth ?? DEFAULT_TABLE_WIDTH;+ const explicitTotal = explicitWidths.reduce<number>((sum, width) => sum + (width ?? 0), 0);+ const missingCount = explicitWidths.filter((width) => width == null).length;+ const fallbackColumnWidth = missingCount+ ? Math.max((fallbackTableWidth - explicitTotal) / missingCount, 1)+ : fallbackTableWidth / columnCount;++ return explicitWidths.map((width) => width ?? roundCssNumber(fallbackColumnWidth));+}++function createTableCellFromHtml(element: HTMLElement, rowSpan: number, colSpan: number): ITableCell {+ const cell = getEmptyTableCell();+ if (rowSpan > 1) {+ cell.rowSpan = rowSpan;+ }+ if (colSpan > 1) {+ cell.columnSpan = colSpan;+ }++ const style = element.getAttribute('style') ?? '';+ const width = readCssSize(element.getAttribute('width'), style, 'width');+ const backgroundColor = readCssColor(style, 'background-color') ?? readCssColor(style, 'background') ?? readHtmlAttributeColor(element, 'bgcolor');+ const borderTop = createTableCellBorder(style, 'top');+ const borderRight = createTableCellBorder(style, 'right');+ const borderBottom = createTableCellBorder(style, 'bottom');+ const borderLeft = createTableCellBorder(style, 'left');++ if (width != null) {+ cell.size = {+ type: TableSizeType.SPECIFIED,+ width: { v: width },+ };+ }+ if (backgroundColor) {+ cell.backgroundColor = { rgb: backgroundColor };+ }+ if (borderTop) {+ cell.borderTop = borderTop;+ }+ if (borderRight) {+ cell.borderRight = borderRight;+ }+ if (borderBottom) {+ cell.borderBottom = borderBottom;+ }+ if (borderLeft) {+ cell.borderLeft = borderLeft;+ }++ return cell;+}++function createTableCellBorder(style: string, side: 'top' | 'right' | 'bottom' | 'left'): ITableCellBorder | undefined {+ const sideStyle = readCssValue(style, `border-${side}`);+ const color = readCssColor(style, `border-${side}-color`) ??+ normalizeCssColor(sideStyle?.match(/(#[0-9a-f]{3,8}|rgb\([^)]+\))/i)?.[1]) ??+ readCssColor(style, 'border-color') ??+ normalizeCssColor(readCssValue(style, 'border')?.match(/(#[0-9a-f]{3,8}|rgb\([^)]+\))/i)?.[1]) ??+ readNamedBorderColor(style);+ const width = readCssLengthValue(readCssValue(style, `border-${side}-width`)) ??+ readCssLengthValue(sideStyle) ??+ readCssLengthValue(readCssValue(style, 'border-width')) ??+ readCssLengthValue(readCssValue(style, 'border'));++ if (!color && width == null) {+ return undefined;+ }++ return {+ color: { rgb: normalizeCssColor(color) ?? '#1f1f1f' },+ width: { v: width ?? 1 },+ };+}++function readNamedBorderColor(style: string): string | undefined {+ const match = style.match(/border(?:-[a-z]+)?\s*:\s*([^;]+)/i);+ if (!match) {+ return undefined;+ }++ const keyword = match[1].split(/\s+/).find((part) => {+ const normalized = part.toLowerCase();+ return normalized && !/^[0-9.]+/.test(normalized) && !['none', 'hidden', 'dotted', 'dashed', 'solid', 'double', 'groove', 'ridge', 'inset', 'outset'].includes(normalized);+ });++ return normalizeCssColor(keyword);+}++function readHtmlAttributeColor(element: HTMLElement, attributeName: string): string | undefined {+ return normalizeCssColor(element.getAttribute(attributeName));+}++function readCssColor(style: string, property: string): string | undefined {+ return normalizeCssColor(readCssValue(style, property));+}++function normalizeCssColor(value: string | null | undefined): string | undefined {+ if (!value) {+ return undefined;+ }++ try {+ const color = new ColorKit(value.trim());+ return color.isValid ? color.toRgbString() : undefined;+ } catch {+ return undefined;+ }+}++function readCssValue(style: string, property: string): string | undefined {+ const normalizedProperty = property.toLowerCase();+ const declaration = style+ .split(';')+ .map((part) => part.split(':'))+ .find(([name]) => name?.trim().toLowerCase() === normalizedProperty);++ return declaration?.slice(1).join(':').trim() || undefined;+}++function readCssSize(attributeValue: string | null, style: string | null, property: 'height' | 'width'): number | undefined {+ const styleMatch = readCssValue(style ?? '', property)?.match(/^([0-9.]+)\s*(px|pt|in|cm|mm)?$/i);+ if (styleMatch) {+ return toPixels(Number(styleMatch[1]), styleMatch[2]);+ }++ const attrMatch = attributeValue?.match(/([0-9.]+)\s*(px|pt|in|cm|mm)?/i);+ return attrMatch ? toPixels(Number(attrMatch[1]), attrMatch[2]) : undefined;+}++function readCssLengthValue(value: string | null | undefined): number | undefined {+ const match = value?.match(/(?:^|\s)([0-9.]+)\s*(px|pt|in|cm|mm)(?=\s|$)/i) ??+ value?.match(/^\s*([0-9.]+)\s*$/);++ return match ? toPixels(Number(match[1]), match[2]) : undefined;+}++function readImageSize(element: HTMLImageElement, property: 'height' | 'width'): number | undefined {+ const datasetValue = property === 'width' ? element.dataset.width : element.dataset.height;++ return readCssSize(datasetValue || null, null, property) ??+ readCssSize(element.getAttribute(property), element.getAttribute('style'), property);+}++function toPixels(value: number, unit?: string): number {+ switch (unit?.toLowerCase()) {+ case 'pt':+ return roundCssNumber(value * 4 / 3);+ case 'in':+ return roundCssNumber(value * 96);+ case 'cm':+ return roundCssNumber(value * 96 / 2.54);+ case 'mm':+ return roundCssNumber(value * 96 / 25.4);+ default:+ return roundCssNumber(value);+ }+}++function roundCssNumber(value: number): number {+ return Math.round(value * 100) / 100;+}+function isSafeUrl(url: string): boolean {try {const parsed = new URL(url, window.location.origin);@@ -574,20 +987,41 @@ function extractWordListInfo(node: HTMLElement): IListContext | null {return null;}- const marker = (node.textContent ?? '').trim().match(/^([0-9]+\.|[a-zA-Z]\.|[ivxlcdmIVXLCDM]+\.|[·•●○\-])/);- const ordered = Boolean(marker && !/[·•●○\-]/.test(marker[1]));+ {+ const marker = (node.textContent ?? '').trim().match(/^([0-9]+[.)]|[a-zA-Z][.)]|[ivxlcdmIVXLCDM]+[.)]|[\u2022\u00B7\u25CF\u25CB\u25AA\u25AB-])/);+ const markerText = marker?.[1] ?? '';+ const ordered = Boolean(markerText && !/^[\u2022\u00B7\u25CF\u25CB\u25AA\u25AB-]$/.test(markerText));- return {- listId: match?.[1] ?? 'mso-list',- listType: ordered ? PresetListType.ORDER_LIST : PresetListType.BULLET_LIST,- nestingLevel: Math.max(0, Number(match?.[2] ?? 1) - 1),- };+ return {+ listId: match?.[1] ?? 'mso-list',+ listType: ordered ? PresetListType.ORDER_LIST : PresetListType.BULLET_LIST,+ nestingLevel: Math.max(0, Number(match?.[2] ?? 1) - 1),+ };+ }}function stripListMarkerFromCurrentParagraph(body: IDocumentBody): number {const paragraphEnd = body.dataStream.endsWith('\r') ? body.dataStream.length - 1 : body.dataStream.length;const paragraphStart = Math.max(0, body.dataStream.lastIndexOf('\r', paragraphEnd - 1) + 1);const text = body.dataStream.slice(paragraphStart, paragraphEnd);+ {+ const marker = text.match(/^(\s*(?:[0-9]+[.)]|[a-zA-Z][.)]|[ivxlcdmIVXLCDM]+[.)]|[\u2022\u00B7\u25CF\u25CB\u25AA\u25AB-])\s*)/);+ if (marker) {+ const length = marker[1].length;+ body.dataStream = body.dataStream.slice(0, paragraphStart) + body.dataStream.slice(paragraphStart + length);+ body.textRuns?.forEach((textRun) => {+ if (textRun.st >= paragraphStart + length) {+ textRun.st -= length;+ textRun.ed -= length;+ } else if (textRun.ed > paragraphStart) {+ textRun.ed = Math.max(textRun.st, textRun.ed - length);+ }+ });++ return length;+ }+ }+const marker = text.match(/^(\s*(?:[0-9]+\.|[a-zA-Z]\.|[ivxlcdmIVXLCDM]+\.|[·•●○\-])\s*)/);if (!marker) {return 0;diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/parse-node-style.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/parse-node-style.tsindex fcc432b8a1..f946b539d7 100644--- a/packages/docs-ui/src/services/clipboard/html-to-udm/parse-node-style.ts+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/parse-node-style.ts@@ -138,7 +138,8 @@ export function extractNodeStyle(node: HTMLElement): ITextStyle {break;}- case 'background-color': {+ case 'background-color':+ case 'background': {const color = new ColorKit(cssValue);if (color.isValid) {diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.tsindex a30104fe63..a20bca5d3c 100644--- a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.ts+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.ts@@ -20,12 +20,32 @@ import { BooleanNumber } from '@univerjs/core';import { extractNodeStyle as getInlineStyle } from '../parse-node-style';import { getParagraphStyle } from '../utils';+const WORD_SPACE_PLACEHOLDER_ENTITY = '';+const WORD_TAB_WIDTH = 4;+const WordPastePlugin: IPastePlugin = {name: 'univer-doc-paste-plugin-word',checkPasteType(html: string) {return /word|mso|wps|kingsoft/i.test(html);},+ preprocessHtml(html: string) {+ return html.replace(/<span\b([^>]*)>([\s\S]*?)<\/span>/gi, (match, attributes, content) => {+ const isWordSpacer = /mso-spacerun\s*:\s*yes/i.test(attributes);+ const tabCount = readMsoTabCount(attributes);++ if (!isWordSpacer && tabCount == null) {+ return match;+ }++ const contentSpaceCount = countWordSpaces(content);+ const fallbackSpaceCount = tabCount == null ? 1 : Math.max(1, Math.round(tabCount * WORD_TAB_WIDTH));+ const spaceCount = Math.max(contentSpaceCount, fallbackSpaceCount);++ return WORD_SPACE_PLACEHOLDER_ENTITY.repeat(spaceCount);+ });+ },+stylesRules: [{filter: ['b'],@@ -65,4 +85,28 @@ const WordPastePlugin: IPastePlugin = {],};+function readMsoTabCount(attributes: string): number | undefined {+ const match = attributes.match(/mso-tab-count\s*:\s*([0-9.]+)/i);+ if (!match) {+ return undefined;+ }++ const count = Number(match[1]);+ return Number.isFinite(count) ? count : undefined;+}++function countWordSpaces(content: string): number {+ const entitySpaceCount = content.match(/ | |�*a0;/gi)?.length ?? 0;+ const text = content+ .replace(/ | |�*a0;/gi, '\u00A0')+ .replace(/<[^>]*>/g, '');+ const literalSpaceCount = text.match(/[\u00A0\t]/g)?.reduce((count, char) => count + (char === '\t' ? WORD_TAB_WIDTH : 1), 0) ?? 0;++ if (entitySpaceCount || literalSpaceCount) {+ return literalSpaceCount;+ }++ return text.replace(/\r?\n/g, '').match(/ /g)?.length ?? 0;+}+export default WordPastePlugin;diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/type.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/type.tsindex 358a1a0602..6978832c82 100644--- a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/type.ts+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/type.ts@@ -29,6 +29,7 @@ export interface IAfterProcessRule {export interface IPastePlugin {name: string;checkPasteType(html: string): boolean;+ preprocessHtml?(html: string): string;stylesRules: IStyleRule[];afterProcessRules: IAfterProcessRule[];}diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/utils.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/utils.tsindex 920b3ec395..8ad51e4f80 100644--- a/packages/docs-ui/src/services/clipboard/html-to-udm/utils.ts+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/utils.ts@@ -15,6 +15,7 @@*/import type { IParagraphStyle, Nullable } from '@univerjs/core';+import { HorizontalAlign } from '@univerjs/core';import { ptToPixel } from '@univerjs/engine-render';// TODO: @JOCS, Complete other missing attributes that exist in IParagraphStyle@@ -51,6 +52,11 @@ export function getParagraphStyle(el: HTMLElement): Nullable<IParagraphStyle> {break;}+ case 'text-align': {+ paragraphStyle.horizontalAlign = getHorizontalAlign(cssValue);+ break;+ }+default: {break;}@@ -59,3 +65,20 @@ export function getParagraphStyle(el: HTMLElement): Nullable<IParagraphStyle> {return Object.getOwnPropertyNames(paragraphStyle).length ? paragraphStyle : null;}++function getHorizontalAlign(value: string): HorizontalAlign {+ switch (value.trim().toLowerCase()) {+ case 'center':+ return HorizontalAlign.CENTER;+ case 'right':+ case 'end':+ return HorizontalAlign.RIGHT;+ case 'justify':+ return HorizontalAlign.JUSTIFIED;+ case 'left':+ case 'start':+ return HorizontalAlign.LEFT;+ default:+ return HorizontalAlign.UNSPECIFIED;+ }+}diff --git a/packages/docs-ui/src/services/clipboard/internal-fragment.ts b/packages/docs-ui/src/services/clipboard/internal-fragment.tsindex ce89c339c3..15b042fd2c 100644--- a/packages/docs-ui/src/services/clipboard/internal-fragment.ts+++ b/packages/docs-ui/src/services/clipboard/internal-fragment.ts@@ -15,7 +15,7 @@*/import type { IDocumentData } from '@univerjs/core';-import { Tools } from '@univerjs/core';+import { generateRandomId, Tools } from '@univerjs/core';export const DOC_INTERNAL_FRAGMENT_MIME = 'application/x-doc-fragment+json';export const DOC_INTERNAL_FRAGMENT_COMMENT_PREFIX = 'univer-doc-fragment:';@@ -51,6 +51,98 @@ export function parseInternalClipboardFragment(value?: string): Partial<IDocumenreturn null;}+export function createInternalClipboardDocData(doc: IDocumentData): Partial<IDocumentData> {+ const body = Tools.deepClone(doc.body);+ const internalDocData: Partial<IDocumentData> = { body };++ if (body?.tables?.length && doc.tableSource) {+ internalDocData.tableSource = {};+ body.tables.forEach((tableRange) => {+ const table = doc.tableSource?.[tableRange.tableId];+ if (table) {+ internalDocData.tableSource![tableRange.tableId] = Tools.deepClone(table);+ }+ });+ }++ const listTypes = new Set(body?.paragraphs?.map((paragraph) => paragraph.bullet?.listType).filter(Boolean));+ if (listTypes.size && doc.lists) {+ internalDocData.lists = {};+ listTypes.forEach((listType) => {+ const list = doc.lists?.[String(listType)];+ if (list) {+ internalDocData.lists![String(listType)] = Tools.deepClone(list);+ }+ });+ }++ if (body?.customBlocks?.length) {+ internalDocData.drawings = {};++ for (const block of body.customBlocks) {+ const { blockId } = block;+ const drawing = doc.drawings?.[blockId];++ if (drawing) {+ const id = generateRandomId(6);++ block.blockId = id;+ internalDocData.drawings[id] = {+ ...Tools.deepClone(drawing),+ drawingId: id,+ };+ }+ }+ }++ return internalDocData;+}++export function createInternalClipboardDocDataList(docs: IDocumentData[]): Partial<IDocumentData> | null {+ if (docs.length === 0) {+ return null;+ }++ if (docs.length === 1) {+ return createInternalClipboardDocData(docs[0]);+ }++ const merged: Partial<IDocumentData> = {+ body: {+ dataStream: '',+ },+ };++ for (const doc of docs) {+ const part = createInternalClipboardDocData(doc);+ const body = part.body;+ if (!body) {+ continue;+ }++ const offset = merged.body!.dataStream.length;+ merged.body!.dataStream += body.dataStream ?? '';+ appendOffsetRanges(merged.body!, body, offset);++ if (part.tableSource) {+ merged.tableSource ??= {};+ Object.assign(merged.tableSource, part.tableSource);+ }++ if (part.lists) {+ merged.lists ??= {};+ Object.assign(merged.lists, part.lists);+ }++ if (part.drawings) {+ merged.drawings ??= {};+ Object.assign(merged.drawings, part.drawings);+ }+ }++ return merged.body?.dataStream ? merged : null;+}+export function embedInternalClipboardFragment(html: string, fragmentJson: string): string {return `<!--${DOC_INTERNAL_FRAGMENT_COMMENT_PREFIX}${encodeBase64(fragmentJson)}-->${html}`;}@@ -69,8 +161,93 @@ export function extractInternalClipboardFragmentFromHtml(html?: string): Partialreturn parseInternalClipboardFragment(decodeBase64(match[1]));}+const WORD_CLIPBOARD_HTML_HEAD = `<head>+<meta http-equiv="Content-Type" content="text/html; charset=utf-8">+<meta name="ProgId" content="Word.Document">+<meta name="Generator" content="Microsoft Word 15">+<!--[if gte mso 9]><xml><w:WordDocument><w:View>Normal</w:View><w:Zoom>0</w:Zoom><w:TrackFormatting/><w:DoNotPromoteQF/></w:WordDocument></xml><![endif]-->+<style><!--+p.MsoNormal, li.MsoNormal, div.MsoNormal{margin:0cm;margin-bottom:8.0pt;line-height:115%;font-size:11.0pt;font-family:Arial,sans-serif;mso-pagination:widow-orphan;}+p.UniverNormal, li.UniverNormal, div.UniverNormal, p.univernormal, li.univernormal, div.univernormal{mso-style-name:univernormal;margin-top:0cm;margin-right:0cm;margin-bottom:8.0pt;margin-left:0cm;line-height:115%;mso-pagination:widow-orphan;font-size:11.0pt;font-family:Arial,sans-serif;mso-bidi-font-family:Arial;}+p.UniverHeading, li.UniverHeading, div.UniverHeading, p.univerheading, li.univerheading, div.univerheading{mso-style-name:univerheading;margin-top:6.0pt;margin-right:0cm;margin-bottom:4.0pt;margin-left:0cm;mso-pagination:widow-orphan;font-size:12.0pt;font-family:Arial,sans-serif;mso-bidi-font-family:Arial;font-weight:bold;}+table.MsoNormalTable, table.UniverTable{mso-style-name:"Normal Table";mso-tstyle-rowband-size:0;mso-tstyle-colband-size:0;mso-style-noshow:yes;mso-style-priority:99;mso-style-parent:"";mso-padding-alt:0cm 5.4pt 0cm 5.4pt;mso-para-margin:0cm;mso-pagination:widow-orphan;font-size:11.0pt;font-family:Arial,sans-serif;border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt;}+td.UniverTableCell, th.UniverTableCell{mso-padding-alt:0cm 5.4pt 0cm 5.4pt;}+--></style>+</head>`;+export function wrapClipboardHtml(fragmentHtml: string): string {- return `<html><head><meta charset="utf-8"></head><body><!--StartFragment-->${fragmentHtml}<!--EndFragment--></body></html>`;+ return `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">${WORD_CLIPBOARD_HTML_HEAD}<body lang="ZH-CN" style="tab-interval:21.0pt;word-wrap:break-word"><!--StartFragment-->${fragmentHtml}<!--EndFragment--></body></html>`;+}++function appendOffsetRanges(target: NonNullable<Partial<IDocumentData>['body']>, source: NonNullable<Partial<IDocumentData>['body']>, offset: number): void {+ if (source.textRuns?.length) {+ target.textRuns ??= [];+ target.textRuns.push(...source.textRuns.map((textRun) => ({+ ...textRun,+ st: textRun.st + offset,+ ed: textRun.ed + offset,+ })));+ }++ if (source.paragraphs?.length) {+ target.paragraphs ??= [];+ target.paragraphs.push(...source.paragraphs.map((paragraph) => ({+ ...paragraph,+ startIndex: paragraph.startIndex + offset,+ })));+ }++ if (source.sectionBreaks?.length) {+ target.sectionBreaks ??= [];+ target.sectionBreaks.push(...source.sectionBreaks.map((sectionBreak) => ({+ ...sectionBreak,+ startIndex: sectionBreak.startIndex + offset,+ })));+ }++ if (source.tables?.length) {+ target.tables ??= [];+ target.tables.push(...source.tables.map((table) => ({+ ...table,+ startIndex: table.startIndex + offset,+ endIndex: table.endIndex + offset,+ })));+ }++ if (source.blockRanges?.length) {+ target.blockRanges ??= [];+ target.blockRanges.push(...source.blockRanges.map((blockRange) => ({+ ...blockRange,+ startIndex: blockRange.startIndex + offset,+ endIndex: blockRange.endIndex + offset,+ })));+ }++ if (source.customRanges?.length) {+ target.customRanges ??= [];+ target.customRanges.push(...source.customRanges.map((customRange) => ({+ ...customRange,+ startIndex: customRange.startIndex + offset,+ endIndex: customRange.endIndex + offset,+ })));+ }++ if (source.customDecorations?.length) {+ target.customDecorations ??= [];+ target.customDecorations.push(...source.customDecorations.map((customDecoration) => ({+ ...customDecoration,+ startIndex: customDecoration.startIndex + offset,+ endIndex: customDecoration.endIndex + offset,+ })));+ }++ if (source.customBlocks?.length) {+ target.customBlocks ??= [];+ target.customBlocks.push(...source.customBlocks.map((customBlock) => ({+ ...customBlock,+ startIndex: customBlock.startIndex + offset,+ })));+ }}function encodeBase64(value: string): string {diff --git a/packages/docs-ui/src/services/clipboard/udm-to-html/__test__/convertor.spec.ts b/packages/docs-ui/src/services/clipboard/udm-to-html/__test__/convertor.spec.tsindex 918c6972de..04a1a98694 100644--- a/packages/docs-ui/src/services/clipboard/udm-to-html/__test__/convertor.spec.ts+++ b/packages/docs-ui/src/services/clipboard/udm-to-html/__test__/convertor.spec.ts@@ -15,7 +15,7 @@*/import type { IDocumentBody } from '@univerjs/core';-import { BooleanNumber } from '@univerjs/core';+import { BooleanNumber, DataStreamTreeTokenType, NamedStyleType, TableRowHeightRule, TableSizeType } from '@univerjs/core';import { describe, expect, it } from 'vitest';import { convertBodyToHtml, covertTextRunToHtml, getBodySliceHtml, UDMToHtmlService } from '../convertor';@@ -87,12 +87,12 @@ describe('test case in html and udm convert', () => {const html = convertor.convert(bodyList.map((b) => ({ body: b, id: '', documentStyle: {} })));- expect(html).toBe('<p class="UniverNormal" >=SUM(<span style="color: #9e6de3;">F15:G18</span>)</p>');+ expect(html).toBe('<p class="UniverNormal" >=SUM(<span style="font-family: Arial; color: #9e6de3;">F15:G18</span>)</p>');});it('Should convert textRun to Html', () => {const documentBody = getTestBody();- const expectedHtml = '<span style="font-family: Microsoft YaHei; color: rgb(0, 0, 0); font-size: 24pt;"><strong>塘月</strong></span>';+ const expectedHtml = '<span style="font-family: Microsoft YaHei; color: #000000; font-size: 24pt;"><strong>塘月</strong></span>';expect(covertTextRunToHtml(documentBody.dataStream, documentBody.textRuns![0])).toBe(expectedHtml);});@@ -102,21 +102,139 @@ describe('test case in html and udm convert', () => {let startIndex = 1;let endIndex = 3;- let expectedHtml = '<span style="font-family: Microsoft YaHei; color: rgb(0, 0, 0); font-size: 24pt;"><strong>塘月</strong></span>';+ let expectedHtml = '<span style="font-family: Microsoft YaHei; color: #000000; font-size: 24pt;"><strong>塘月</strong></span>';expect(getBodySliceHtml({ body: documentBody, id: '', documentStyle: {} }, startIndex, endIndex)).toEqual(expectedHtml);startIndex = 0;endIndex = 4;- expectedHtml = '荷<span style="font-family: Microsoft YaHei; color: rgb(0, 0, 0); font-size: 24pt;"><strong>塘月</strong></span>色';+ expectedHtml = '荷<span style="font-family: Microsoft YaHei; color: #000000; font-size: 24pt;"><strong>塘月</strong></span>色';expect(getBodySliceHtml({ body: documentBody, id: '', documentStyle: {} }, startIndex, endIndex)).toEqual(expectedHtml);});it('Should convert document body To Html(convertBodyToHtml)', () => {const documentBody = getTestBody();- const expectedHtml = '<p class="UniverNormal" style="margin-top: 10px; margin-bottom: 0px; line-height: 2;">荷<span style="font-family: Microsoft YaHei; color: rgb(0, 0, 0); font-size: 24pt;"><strong>塘月</strong></span>色</p><p class="UniverNormal" style="margin-top: 10px; margin-bottom: 0px; line-height: 2;">作者:朱自清</p>';+ const expectedHtml = '<p class="UniverNormal" style="margin-top: 10px; margin-bottom: 0px; line-height: 2;">荷<span style="font-family: Microsoft YaHei; color: #000000; font-size: 24pt;"><strong>塘月</strong></span>色</p><p class="UniverNormal" style="margin-top: 10px; margin-bottom: 0px; line-height: 2;">作者:朱自清</p>';expect(convertBodyToHtml({ body: documentBody, id: '', documentStyle: {} })).toEqual(expectedHtml);});+ it('serializes embedded tables as paragraph siblings and strips data stream control chars', () => {+ const tokens = DataStreamTreeTokenType;+ const prefix = 'Intro\r';+ const tableStart = prefix.length;+ const cellText = 'Cell text';+ const tableStream = `${tokens.TABLE_START}${tokens.TABLE_ROW_START}${tokens.TABLE_CELL_START}${cellText}\r\n${tokens.TABLE_CELL_END}${tokens.TABLE_ROW_END}${tokens.TABLE_END}`;+ const tableEnd = tableStart + tableStream.length;+ const dataStream = `${prefix}${tableStream}\r\n`;++ const html = convertBodyToHtml({+ id: '',+ documentStyle: {},+ tableSource: {+ 'table-1': {+ tableId: 'table-1',+ tableColumns: [{+ size: {+ type: TableSizeType.SPECIFIED,+ width: { v: 120 },+ },+ }],+ tableRows: [{+ trHeight: {+ hRule: TableRowHeightRule.AUTO,+ val: { v: 32 },+ },+ tableCells: [{}],+ }],+ },+ } as any,+ body: {+ dataStream,+ paragraphs: [+ { startIndex: prefix.length - 1 },+ { startIndex: tableStart + tokens.TABLE_START.length + tokens.TABLE_ROW_START.length + tokens.TABLE_CELL_START.length + cellText.length },+ ],+ sectionBreaks: [],+ tables: [{+ startIndex: tableStart,+ endIndex: tableEnd,+ tableId: 'table-1',+ }],+ },+ });++ expect(html).toContain('<p class="UniverNormal" >Intro</p><table');+ expect(html).not.toMatch(/<p[^>]*>\s*<table/i);+ expect(html).not.toContain(tokens.TABLE_START);+ expect(html).not.toContain(tokens.TABLE_CELL_START);+ expect(html).toContain('Cell text');+ });++ it('serializes title paragraphs as headings and hides block boundary tokens', () => {+ const tokens = DataStreamTreeTokenType;+ const title = 'Docs Table 2.0 playground';+ const code = 'const cell = {};';+ const blockStart = title.length + 1;+ const dataStream = `${title}\r${tokens.BLOCK_START}${code}${tokens.BLOCK_END}\r\n`;++ const html = convertBodyToHtml({+ id: '',+ documentStyle: {},+ body: {+ dataStream,+ paragraphs: [+ {+ startIndex: title.length,+ paragraphStyle: {+ namedStyleType: NamedStyleType.TITLE,+ },+ },+ {+ startIndex: dataStream.length - 2,+ },+ ],+ sectionBreaks: [],+ blockRanges: [{+ startIndex: blockStart,+ endIndex: blockStart + tokens.BLOCK_START.length + code.length - 1,+ blockType: 'code',+ }] as any,+ },+ });++ expect(html).toContain('<p class="UniverHeading" role="heading" aria-level="1" data-heading-level="1" >Docs Table 2.0 playground</p>');+ expect(html).toContain('const cell = {};');+ expect(html).not.toContain(tokens.BLOCK_START);+ expect(html).not.toContain(tokens.BLOCK_END);+ });++ it('serializes paragraph-level text style for Word copy', () => {+ const title = 'Styled paragraph';+ const html = convertBodyToHtml({+ id: '',+ documentStyle: {},+ body: {+ dataStream: `${title}\r\n`,+ paragraphs: [{+ startIndex: title.length,+ paragraphStyle: {+ textStyle: {+ fs: 22,+ bl: BooleanNumber.TRUE,+ cl: { rgb: '#4B5563' },+ ff: 'Arial',+ },+ },+ }],+ sectionBreaks: [],+ },+ });++ expect(html).toContain('font-size: 22pt');+ expect(html).toContain('font-weight: bold');+ expect(html).toContain('color: #4B5563');+ expect(html).toContain('font-family: Arial');+ expect(html).toContain('<strong>Styled paragraph</strong>');+ });});diff --git a/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts b/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.tsindex 632dcb6661..5956abd485 100644--- a/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts+++ b/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts@@ -14,13 +14,15 @@* limitations under the License.*/-import type { IDocumentBody, IDocumentData, IParagraph, ITextRun } from '@univerjs/core';+import type { IDocumentBody, IDocumentData, IParagraph, ITable, ITableCell, ITextRun, ITextStyle } from '@univerjs/core';import type { IDocImage } from '@univerjs/docs-drawing';import type { DataStreamTreeNode } from '@univerjs/engine-render';-import { BaselineOffset, BooleanNumber, CustomRangeType, DataStreamTreeNodeType, DrawingTypeEnum, NamedStyleType, PresetListType, Tools } from '@univerjs/core';+import { BaselineOffset, BooleanNumber, CustomRangeType, DataStreamTreeNodeType, DrawingTypeEnum, HorizontalAlign, NamedStyleType, PresetListType, Tools } from '@univerjs/core';import { ImageSourceType } from '@univerjs/drawing';import { parseDataStreamToTree } from '@univerjs/engine-render';+const DEFAULT_CLIPBOARD_FONT_FAMILY = 'Arial';+function covertImageToHtml(item: IDocImage) {const transformObjectToString = (obj: Record<string, string | number | undefined>) => {let result = '';@@ -47,7 +49,7 @@ export function covertTextRunToHtml(dataStream: string, textRun: ITextRun): striconst { st: start, ed, ts = {} } = textRun;const { ff, fs, it, bl, ul, st, ol, bg, cl, va } = ts;- let html = escapeHtml(dataStream.slice(start, ed));+ let html = escapeInlineText(dataStream.slice(start, ed));const style: string[] = [];// italic@@ -78,13 +80,11 @@ export function covertTextRunToHtml(dataStream: string, textRun: ITextRun): stri}// font family- if (ff) {- style.push(`font-family: ${ff}`);- }+ style.push(`font-family: ${ff ?? DEFAULT_CLIPBOARD_FONT_FAMILY}`);// font color- if (cl) {- style.push(`color: ${cl.rgb}`);+ if (cl?.rgb) {+ style.push(`color: ${normalizeCssColor(cl.rgb)}`);}// font size@@ -98,8 +98,8 @@ export function covertTextRunToHtml(dataStream: string, textRun: ITextRun): stri}// background color- if (bg) {- style.push(`background: ${bg.rgb}`);+ if (bg?.rgb) {+ style.push(`background: ${normalizeCssColor(bg.rgb)}`);}return style.length ? `<span style="${style.join('; ')};">${html}</span>` : html;@@ -117,7 +117,7 @@ function getBodyInlineSlice(body: IDocumentBody, startIndex: number, endIndex: nconst { st, ed } = textRun;if (Tools.hasIntersectionBetweenTwoRanges(startIndex, endIndex, st, ed)) {if (st > cursorIndex) {- spanList.push(escapeHtml(dataStream.slice(cursorIndex, st)));+ spanList.push(escapeInlineText(dataStream.slice(cursorIndex, st)));spanList.push(covertTextRunToHtml(dataStream, {...textRun,@@ -136,7 +136,7 @@ function getBodyInlineSlice(body: IDocumentBody, startIndex: number, endIndex: n}if (cursorIndex !== endIndex) {- spanList.push(escapeHtml(dataStream.slice(cursorIndex, endIndex)));+ spanList.push(escapeInlineText(dataStream.slice(cursorIndex, endIndex)));}return spanList.join('');@@ -208,6 +208,8 @@ export function getBodySliceHtml(doc: IDocumentData, startIndex: number, endIndeinterface IHtmlResult {html: string;listStack?: IListHtmlContext[];+ tableIndex?: number;+ tableStack?: ITableHtmlContext[];}interface IListHtmlContext {@@ -216,6 +218,12 @@ interface IListHtmlContext {listType: string;}+interface ITableHtmlContext {+ table?: ITable;+ rowIndex: number;+ columnIndex: number;+}+export function convertBodyToHtml(doc: IDocumentData): string {const body = doc.body || {} as IDocumentBody;const { paragraphs = [], sectionBreaks = [] } = body;@@ -265,9 +273,16 @@ function processNode(node: DataStreamTreeNode, doc: IDocumentData, result: IHtmlconst { children, startIndex, endIndex } = node;const paragraph = doc.body?.paragraphs?.find((p) => p.startIndex === endIndex) ?? {} as IParagraph;const { paragraphStyle = {} } = paragraph;- const { spaceAbove, spaceBelow, lineSpacing } = paragraphStyle;+ const { horizontalAlign, spaceAbove, spaceBelow, lineSpacing } = paragraphStyle;const style = [];+ if (horizontalAlign != null) {+ const align = getTextAlign(horizontalAlign);+ if (align) {+ style.push(`text-align: ${align}`);+ }+ }+if (spaceAbove != null) {if (typeof spaceAbove === 'number') {style.push(`margin-top: ${spaceAbove}px`);@@ -288,18 +303,28 @@ function processNode(node: DataStreamTreeNode, doc: IDocumentData, result: IHtmlstyle.push(`line-height: ${lineSpacing}`);}- const innerHtml = (() => {- const childHtml = children.map((table) => {- const childResult: IHtmlResult = { html: '' };- processNode(table, doc, childResult);- closeListStack(childResult);- return childResult.html;- }).join('');+ style.push(...serializeTextStyle(paragraphStyle.textStyle));++ const inlineHtml = applySemanticTextStyle(getBodySliceHtml(doc, startIndex, endIndex), paragraphStyle.textStyle);+ const childHtml = children.map((table) => {+ const childResult: IHtmlResult = { html: '' };+ processNode(table, doc, childResult);+ closeListStack(childResult);+ return childResult.html;+ }).join('');- return `${childHtml}${getBodySliceHtml(doc, startIndex, endIndex)}`;- })();+ if (childHtml) {+ if (hasVisibleHtml(inlineHtml)) {+ renderParagraphNodeHtml(doc, paragraph, startIndex, endIndex, inlineHtml, style, result);+ } else {+ closeListStack(result);+ }- renderParagraphNodeHtml(doc, paragraph, startIndex, endIndex, innerHtml, style, result);+ result.html += childHtml;+ break;+ }++ renderParagraphNodeHtml(doc, paragraph, startIndex, endIndex, inlineHtml, style, result);break;}@@ -308,21 +333,40 @@ function processNode(node: DataStreamTreeNode, doc: IDocumentData, result: IHtmlconst { children } = node;closeListStack(result);- result.html += '<table class="UniverTable" style="width: 100%; border-collapse: collapse;"><tbody>';+ result.tableIndex ??= 0;+ result.tableStack ??= [];+ const tableRange = doc.body?.tables?.[result.tableIndex++];+ const table = tableRange ? doc.tableSource?.[tableRange.tableId] : undefined;+ const width = table?.tableColumns?.reduce((sum, column) => sum + (column.size?.width?.v ?? 0), 0);+ const tableStyle = [+ 'border-collapse: collapse',+ width ? `width: ${roundCssNumber(width)}px` : 'width: 100%',+ ].join('; ');++ result.tableStack.push({ table, rowIndex: -1, columnIndex: 0 });+ result.html += `<table class="MsoNormalTable UniverTable" style="${tableStyle};"><tbody>`;for (const row of children) {processNode(row, doc, result);}result.html += '</tbody></table>';+ result.tableStack.pop();break;}case DataStreamTreeNodeType.TABLE_ROW: {const { children } = node;+ const tableContext = result.tableStack?.[result.tableStack.length - 1];+ if (tableContext) {+ tableContext.rowIndex++;+ tableContext.columnIndex = 0;+ }+ const row = tableContext?.table?.tableRows?.[tableContext.rowIndex];+ const rowStyle = row?.trHeight?.val?.v != null ? ` style="height: ${roundCssNumber(row.trHeight.val.v)}px"` : '';- result.html += '<tr class="UniverTableRow">';+ result.html += `<tr class="UniverTableRow"${rowStyle}>`;for (const cell of children) {processNode(cell, doc, result);}@@ -333,8 +377,18 @@ function processNode(node: DataStreamTreeNode, doc: IDocumentData, result: IHtmlcase DataStreamTreeNodeType.TABLE_CELL: {const { children } = node;+ const tableContext = result.tableStack?.[result.tableStack.length - 1];+ const row = tableContext?.table?.tableRows?.[tableContext.rowIndex];+ const cell = row?.tableCells?.[tableContext?.columnIndex ?? 0];+ if (tableContext) {+ tableContext.columnIndex++;+ }++ if (cell?.rowSpan === 0 || cell?.columnSpan === 0) {+ break;+ }- result.html += '<td class="UniverTableCell">';+ result.html += `<td class="UniverTableCell"${serializeTableCellAttributes(cell)}>`;for (const n of children) {processNode(n, doc, result);}@@ -362,6 +416,10 @@ function renderParagraphNodeHtml(doc: IDocumentData, paragraph: IParagraph, starfunction renderBlockParagraphHtml(doc: IDocumentData, paragraph: IParagraph, startIndex: number, endIndex: number, innerHtml: string, style: string[]): string {const blockRange = doc.body?.blockRanges?.find((range) => range.startIndex <= startIndex && endIndex <= range.endIndex + 1);+ if (blockRange && !hasVisibleHtml(innerHtml)) {+ return '';+ }+const paragraphHtml = renderHeadingParagraphHtml(paragraph, innerHtml, style)?? `<p class="UniverNormal" ${style.length ? `style="${style.join('; ')};"` : ''}>${innerHtml}</p>`;@@ -383,7 +441,7 @@ function renderHeadingParagraphHtml(paragraph: IParagraph, innerHtml: string, streturn null;}- return `<h${headingLevel} class="UniverHeading" ${style.length ? `style="${style.join('; ')};"` : ''}>${innerHtml}</h${headingLevel}>`;+ return `<p class="UniverHeading" role="heading" aria-level="${headingLevel}" data-heading-level="${headingLevel}" ${style.length ? `style="${style.join('; ')};"` : ''}>${innerHtml}</p>`;}function renderListParagraphItemHtml(doc: IDocumentData, paragraph: IParagraph, innerHtml: string, style: string[]): { tag: 'ol' | 'ul'; level: number; listType: string; listStyle: string | null; html: string } | null {@@ -448,8 +506,132 @@ function closeListStack(result: IHtmlResult): void {}}+function serializeTableCellAttributes(cell?: ITableCell): string {+ if (!cell) {+ return '';+ }++ const attributes: string[] = [];+ const styles: string[] = [];++ if ((cell.rowSpan ?? 1) > 1) {+ attributes.push(`rowspan="${cell.rowSpan}"`);+ }+ if ((cell.columnSpan ?? 1) > 1) {+ attributes.push(`colspan="${cell.columnSpan}"`);+ }+ if (cell.size?.width?.v != null) {+ styles.push(`width: ${roundCssNumber(cell.size.width.v)}px`);+ }+ if (cell.backgroundColor?.rgb) {+ styles.push(`background-color: ${cell.backgroundColor.rgb}`);+ }++ ([+ ['top', cell.borderTop],+ ['right', cell.borderRight],+ ['bottom', cell.borderBottom],+ ['left', cell.borderLeft],+ ] as const).forEach(([side, border]) => {+ if (!border) {+ return;+ }++ styles.push(`border-${side}: ${roundCssNumber(border.width?.v ?? 1)}px solid ${border.color?.rgb ?? '#1f1f1f'}`);+ });++ if (styles.length) {+ attributes.push(`style="${styles.join('; ')};"`);+ }++ return attributes.length ? ` ${attributes.join(' ')}` : '';+}++function serializeTextStyle(textStyle: ITextStyle | undefined): string[] {+ if (!textStyle) {+ return [];+ }++ const { ff, fs, it, bl, ul, st, ol, bg, cl } = textStyle;+ const style: string[] = [];++ style.push(`font-family: ${ff ?? DEFAULT_CLIPBOARD_FONT_FAMILY}`);++ if (fs != null) {+ style.push(`font-size: ${fs}pt`);+ }++ if (cl?.rgb) {+ style.push(`color: ${normalizeCssColor(cl.rgb)}`);+ }++ if (bg?.rgb) {+ style.push(`background-color: ${normalizeCssColor(bg.rgb)}`);+ }++ if (bl === BooleanNumber.TRUE) {+ style.push('font-weight: bold');+ }++ if (it === BooleanNumber.TRUE) {+ style.push('font-style: italic');+ }++ const textDecorations: string[] = [];+ if (ul?.s === BooleanNumber.TRUE) {+ textDecorations.push('underline');+ }+ if (st?.s === BooleanNumber.TRUE) {+ textDecorations.push('line-through');+ }+ if (ol?.s === BooleanNumber.TRUE) {+ textDecorations.push('overline');+ }+ if (textDecorations.length) {+ style.push(`text-decoration: ${textDecorations.join(' ')}`);+ }++ return style;+}++function applySemanticTextStyle(html: string, textStyle: ITextStyle | undefined): string {+ if (!textStyle || !hasVisibleHtml(html)) {+ return html;+ }++ let result = html;+ if (textStyle.it === BooleanNumber.TRUE) {+ result = `<i>${result}</i>`;+ }+ if (textStyle.ul?.s === BooleanNumber.TRUE) {+ result = `<u>${result}</u>`;+ }+ if (textStyle.st?.s === BooleanNumber.TRUE) {+ result = `<s>${result}</s>`;+ }+ if (textStyle.bl === BooleanNumber.TRUE) {+ result = `<strong>${result}</strong>`;+ }++ return result;+}++function normalizeCssColor(color: string): string {+ const rgb = color.match(/^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})(?:\s*,\s*[\d.]+)?\s*\)$/i);+ if (!rgb) {+ return color;+ }++ return `#${rgb.slice(1, 4).map((part) => Math.max(0, Math.min(255, Number(part))).toString(16).padStart(2, '0')).join('')}`;+}++function roundCssNumber(value: number): number {+ return Math.round(value * 100) / 100;+}+function getHeadingLevel(namedStyleType?: NamedStyleType): number | null {switch (namedStyleType) {+ case NamedStyleType.TITLE:case NamedStyleType.HEADING_1: return 1;case NamedStyleType.HEADING_2: return 2;case NamedStyleType.HEADING_3: return 3;@@ -459,6 +641,22 @@ function getHeadingLevel(namedStyleType?: NamedStyleType): number | null {}}+function getTextAlign(horizontalAlign: HorizontalAlign): string | null {+ switch (horizontalAlign) {+ case HorizontalAlign.LEFT:+ return 'left';+ case HorizontalAlign.CENTER:+ return 'center';+ case HorizontalAlign.RIGHT:+ return 'right';+ case HorizontalAlign.JUSTIFIED:+ case HorizontalAlign.BOTH:+ return 'justify';+ default:+ return null;+ }+}+function isOrderedListType(listType: string): boolean {return listType.includes('ORDER') || listType === PresetListType.ORDER_LIST;}@@ -482,6 +680,22 @@ function escapeHtml(value: string): string {.replace(/"/g, '"');}+function escapeInlineText(value: string): string {+ return escapeHtml(stripDataStreamControlChars(value)).replace(/\r\n|\r|\n/g, '<br>');+}++function stripDataStreamControlChars(value: string): string {+ return value.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, '');+}++function hasVisibleHtml(html: string): boolean {+ return /<(?:img|br)\b/i.test(html) || html+ .replace(/<[^>]+>/g, '')+ .replace(/ /gi, ' ')+ .trim()+ .length > 0;+}+export class UDMToHtmlService {convert(docList: IDocumentData[]): string {if (docList.length === 0) {diff --git a/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts b/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.tsindex 14159a229f..8d646c14f6 100644--- a/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts+++ b/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts@@ -98,6 +98,29 @@ describe('BrowserClipboardService', () => {expect(document.execCommand).toHaveBeenCalledWith('copy');});+ it('should write raw sanitized html during legacy copy event', async () => {+ vi.mocked(supportClipboardAPI).mockReturnValue(false);+ const { service } = createService();+ const clipboardData = {+ setData: vi.fn(),+ };++ vi.mocked(document.execCommand).mockImplementation(() => {+ const event = new Event('copy', { cancelable: true }) as ClipboardEvent;+ Object.defineProperty(event, 'clipboardData', {+ value: clipboardData,+ });+ document.dispatchEvent(event);+ return true;+ });++ await service.write('plain', '<div onclick="alert(1)" style="color:red">rich</div>');++ expect(clipboardData.setData).toHaveBeenCalledWith('text/plain', 'plain');+ expect(clipboardData.setData).toHaveBeenCalledWith('text/html', '<div style="color: red">rich</div>');+ expect(document.body.lastElementChild?.textContent).not.toBe('rich');+ });+it('should sanitize html before legacy copy', async () => {vi.mocked(supportClipboardAPI).mockReturnValue(false);const { service } = createService();diff --git a/packages/ui/src/services/clipboard/clipboard-interface.service.ts b/packages/ui/src/services/clipboard/clipboard-interface.service.tsindex e597e155cc..a00c9ad0b9 100644--- a/packages/ui/src/services/clipboard/clipboard-interface.service.ts+++ b/packages/ui/src/services/clipboard/clipboard-interface.service.ts@@ -186,7 +186,7 @@ export class BrowserClipboardService extends Disposable implements IClipboardIntasync write(text: string, html: string, customData?: Record<string, string>): Promise<void> {if (!this.supportClipboard) {- return this._legacyCopyHtml(html);+ return this._legacyCopyHtml(text, html);}try {@@ -260,21 +260,45 @@ export class BrowserClipboardService extends Disposable implements IClipboardInt}}- private _legacyCopyHtml(html: string): void {+ private _legacyCopyHtml(text: string, html: string): void {const activeElement = document.activeElement;- const container = createCopyHtmlContainer();- document.body.appendChild(container);- container.replaceChildren(sanitizeHtmlForClipboard(html));+ const sanitizedHtml = serializeSanitizedHtmlForClipboard(html);+ let handledByClipboardEvent = false;++ const onCopy = (event: ClipboardEvent) => {+ if (!event.clipboardData) {+ return;+ }++ event.preventDefault();+ event.clipboardData.setData(PLAIN_TEXT_CLIPBOARD_MIME_TYPE, text);+ event.clipboardData.setData(HTML_CLIPBOARD_MIME_TYPE, sanitizedHtml);+ handledByClipboardEvent = true;+ };++ document.addEventListener('copy', onCopy);try {- select(container);document.execCommand('copy');++ if (!handledByClipboardEvent) {+ const container = createCopyHtmlContainer();+ document.body.appendChild(container);+ container.innerHTML = sanitizedHtml;++ try {+ select(container);+ document.execCommand('copy');+ } finally {+ document.body.removeChild(container);+ }+ }} finally {+ document.removeEventListener('copy', onCopy);+if (activeElement instanceof HTMLElement) {activeElement.focus();}-- document.body.removeChild(container);}}@@ -345,6 +369,12 @@ function sanitizeHtmlForClipboard(html: string): DocumentFragment {return fragment;}+function serializeSanitizedHtmlForClipboard(html: string): string {+ const container = document.createElement('div');+ container.appendChild(sanitizeHtmlForClipboard(html));+ return container.innerHTML;+}+function sanitizeHtmlNode(node: Node): Node | null {if (node.nodeType === Node.TEXT_NODE) {return document.createTextNode(node.textContent ?? '');