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(doc): copy form univer text and paste to univer (#1473)
Ran Luo4f3ab1306345
diff --git a/examples/src/data/docs/default-document-data-cn.ts b/examples/src/data/docs/default-document-data-cn.tsindex 4a8ee4ca2a..2aa2459104 100644--- a/examples/src/data/docs/default-document-data-cn.ts+++ b/examples/src/data/docs/default-document-data-cn.ts@@ -40,7 +40,7 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {},},{- st: 5,+ st: 6,ed: 9,ts: {fs: 16,@@ -53,7 +53,7 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {},{st: 9,- ed: 13,+ ed: 12,ts: {fs: 16,ff: 'Microsoft YaHei',@@ -64,7 +64,7 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {},},{- st: 13,+ st: 14,ed: 3057,ts: {fs: 12,diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.tsindex 31b673729b..4cf1f8686d 100644--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts@@ -25,10 +25,12 @@ import { copyContentCache, extractId, genId } from './copy-content-cache';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 PastePluginUniver from './html-to-udm/paste-plugins/plugin-univer';import { UDMToHtmlService } from './udm-to-html/convertor';HtmlToUDMService.use(PastePluginWord);HtmlToUDMService.use(PastePluginLark);+HtmlToUDMService.use(PastePluginUniver);function generateBody(text: string): IDocumentBody {// Convert all \n to \r, because we use \r to indicate paragraph break.@@ -104,6 +106,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServasync paste(items: ClipboardItem[]): Promise<boolean> {const body = await this._generateBodyFromClipboardItems(items);+return this._paste(body);}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 604905e7dd..635feeb5c0 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@@ -16,6 +16,7 @@import type { ITextStyle } from '@univerjs/core';import { BaselineOffset, BooleanNumber, ColorKit } from '@univerjs/core';+import { pixelToPt } from '@univerjs/engine-render';export function extractNodeStyle(node: HTMLElement): ITextStyle {const styles = node.style;@@ -74,6 +75,8 @@ export function extractNodeStyle(node: HTMLElement): ITextStyle {// TODO: @JOCS, hand other CSS value unit, rem, em, pt, %if (cssValue.endsWith('pt')) {docStyles.fs = fontSize;+ } else if (cssValue.endsWith('px')) {+ docStyles.fs = pixelToPt(fontSize);}}diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-univer.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-univer.tsnew file mode 100644index 0000000000..38a711526e--- /dev/null+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-univer.ts@@ -0,0 +1,56 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { IParagraph } from '@univerjs/core';+import { getParagraphStyle } from '../utils';+import type { IPastePlugin } from './type';++const univerPastePlugin: IPastePlugin = {+ name: 'univer-doc-paste-plugin-univer',+ checkPasteType(html: string) {+ return /UniverNormal/i.test(html);+ },++ stylesRules: [],++ afterProcessRules: [+ {+ filter(el: HTMLElement) {+ return el.tagName === 'P' && /UniverNormal/i.test(el.className);+ },+ handler(doc, el) {+ if (doc.paragraphs == null) {+ doc.paragraphs = [];+ }++ const paragraph: IParagraph = {+ startIndex: doc.dataStream.length,+ };++ const paragraphStyle = getParagraphStyle(el);++ if (paragraphStyle) {+ paragraph.paragraphStyle = paragraphStyle;+ }++ doc.paragraphs.push(paragraph);+ doc.dataStream += '\r';+ },+ },+ ],+};++export default univerPastePlugin;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 853998a072..eb81c8869d 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@@ -41,6 +41,13 @@ export function getParagraphStyle(el: HTMLElement): Nullable<IParagraphStyle> {break;}+ case 'line-height': {+ const lineHeightValue = Number.parseFloat(cssValue);+ paragraphStyle.lineSpacing = lineHeightValue;++ break;+ }+default: {break;}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 65a7cdad3e..7d19c86dae 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,46 @@*/import { describe, expect, it } from 'vitest';-import { UDMToHtmlService } from '../convertor';+import { BooleanNumber } from '@univerjs/core';+import { convertBodyToHtml, covertTextRunToHtml, getBodySliceHtml, UDMToHtmlService } from '../convertor';++function getTestBody() {+ return {+ dataStream: '荷塘月色\r作者:朱自清',+ textRuns: [+ {+ st: 1,+ ed: 3,+ ts: {+ fs: 24,+ ff: 'Microsoft YaHei',+ cl: {+ rgb: 'rgb(0, 0, 0)',+ },+ bl: BooleanNumber.TRUE,+ },+ },+ ],+ paragraphs: [+ {+ startIndex: 4,+ paragraphStyle: {+ spaceAbove: 10,+ lineSpacing: 2,+ spaceBelow: 0,+ },+ },+ {+ startIndex: 11,+ paragraphStyle: {+ spaceAbove: 10,+ lineSpacing: 2,+ spaceBelow: 0,+ },+ },+ ],+ };+}describe('test case in html and udm convert', () => {it('test case in html and udm convert and bodyList length is 1', () => {@@ -47,6 +86,36 @@ describe('test case in html and udm convert', () => {const html = convertor.convert(bodyList);- expect(html).toBe('=SUM(<span style="color: #9e6de3">F15:G18</span>)');+ expect(html).toBe('<p class="UniverNormal" >=SUM(<span style="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>';++ expect(covertTextRunToHtml(documentBody.dataStream, documentBody.textRuns[0])).toBe(expectedHtml);+ });++ it('Should get getBodySliceHtml', () => {+ const documentBody = getTestBody();+ 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>';++ expect(getBodySliceHtml(documentBody, 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>色';+ expect(getBodySliceHtml(documentBody, 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>';++ expect(convertBodyToHtml(documentBody)).toEqual(expectedHtml);});});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 89dd59713c..c838134232 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@@ -15,9 +15,9 @@*/import type { IDocumentBody, ITextRun } from '@univerjs/core';-import { BaselineOffset, BooleanNumber } from '@univerjs/core';+import { BaselineOffset, BooleanNumber, Tools } from '@univerjs/core';-function covertTextRunToHtml(dataStream: string, textRun: ITextRun): string {+export function covertTextRunToHtml(dataStream: string, textRun: ITextRun): string {const { st: start, ed, ts = {} } = textRun;const { ff, fs, it, bl, ul, st, ol, bg, cl, va } = ts;@@ -63,7 +63,7 @@ function covertTextRunToHtml(dataStream: string, textRun: ITextRun): string {// font sizeif (fs) {- style.push(`font-size: ${fs}px`);+ style.push(`font-size: ${fs}pt`);}// overline@@ -76,65 +76,94 @@ function covertTextRunToHtml(dataStream: string, textRun: ITextRun): string {style.push(`background: ${bg.rgb}`);}- return style.length ? `<span style="${style.join(';')}">${html}</span>` : html;+ return style.length ? `<span style="${style.join('; ')};">${html}</span>` : html;}-function translateDataStreamToHtml(body: IDocumentBody, withParagraphInfo: boolean = true): string {- const { dataStream, textRuns = [], paragraphs = [] } = body;- let cursorIndex = 0;+export function getBodySliceHtml(body: IDocumentBody, startIndex: number, endIndex: number) {+ const { dataStream, textRuns = [] } = body;+ let cursorIndex = startIndex;const spanList: string[] = [];- const paragraphList: string[] = [];for (const textRun of textRuns) {const { st, ed } = textRun;- if (st !== cursorIndex) {- spanList.push(dataStream.slice(cursorIndex, st));+ if (Tools.hasIntersectionBetweenTwoRanges(startIndex, endIndex, st, ed)) {+ if (st > cursorIndex) {+ spanList.push(dataStream.slice(cursorIndex, st));++ spanList.push(covertTextRunToHtml(dataStream, {+ ...textRun,+ ed: Math.min(ed, endIndex),+ }));+ } else {+ spanList.push(covertTextRunToHtml(dataStream, {+ ...textRun,+ st: cursorIndex,+ ed: Math.min(ed, endIndex),+ }));+ }}- spanList.push(covertTextRunToHtml(dataStream, textRun));-- cursorIndex = ed;-- if (withParagraphInfo) {- for (const paragraph of paragraphs) {- const { startIndex, paragraphStyle = {} } = paragraph;-- if (startIndex >= st && startIndex <= ed) {- const { spaceAbove, spaceBelow } = paragraphStyle;- const style: string[] = [];-- if (spaceAbove != null) {- if (typeof spaceAbove === 'number') {- style.push(`margin-top: ${spaceAbove}px`);- } else {- style.push(`margin-top: ${spaceAbove.v}px`);- }- }-- if (spaceBelow != null) {- if (typeof spaceBelow === 'number') {- style.push(`margin-bottom: ${spaceBelow}px`);- } else {- style.push(`margin-bottom: ${spaceBelow.v}px`);- }- }-- paragraphList.push(- `<p className="UniverNormal" ${- style.length ? `style="${style.join(';')}"` : ''- }>${spanList.join('')}</p>`- );- spanList.length = 0;+ cursorIndex = Math.max(startIndex, Math.min(ed, endIndex));+ }++ if (cursorIndex !== endIndex) {+ spanList.push(dataStream.slice(cursorIndex, endIndex));+ }++ return spanList.join('');+}++export function convertBodyToHtml(body: IDocumentBody, withParagraphInfo: boolean = true): string {+ if (withParagraphInfo && body.paragraphs?.length) {+ const { dataStream, paragraphs = [] } = body;+ let result = '';+ let cursorIndex = -1;+ for (const paragraph of paragraphs) {+ const { startIndex, paragraphStyle = {} } = paragraph;+ const { spaceAbove, spaceBelow, lineSpacing } = paragraphStyle;+ const style = [];++ if (spaceAbove != null) {+ if (typeof spaceAbove === 'number') {+ style.push(`margin-top: ${spaceAbove}px`);+ } else {+ style.push(`margin-top: ${spaceAbove.v}px`);+ }+ }++ if (spaceBelow != null) {+ if (typeof spaceBelow === 'number') {+ style.push(`margin-bottom: ${spaceBelow}px`);+ } else {+ style.push(`margin-bottom: ${spaceBelow.v}px`);}}++ if (lineSpacing != null) {+ style.push(`line-height: ${lineSpacing}`);+ }++ if (startIndex > cursorIndex + 1) {+ result += `<p class="UniverNormal" ${+ style.length ? `style="${style.join('; ')};"` : ''+ }>${getBodySliceHtml(body, cursorIndex + 1, startIndex)}</p>`;+ } else {+ result += `<p class="UniverNormal" ${+ style.length ? `style="${style.join('; ')};"` : ''+ }></p>`;+ }++ cursorIndex = startIndex;}- }- if (cursorIndex < dataStream.length) {- spanList.push(dataStream.slice(cursorIndex, dataStream.length));- }+ if (cursorIndex !== dataStream.length) {+ result += getBodySliceHtml(body, cursorIndex, dataStream.length);+ }- return paragraphList.join('') + spanList.join('');+ return result;+ } else {+ return getBodySliceHtml(body, 0, body.dataStream.length);+ }}export class UDMToHtmlService {@@ -147,14 +176,14 @@ export class UDMToHtmlService {// otherwise, the paragraph information will be discarded and a paragraph// will be generated for each bodyif (bodyList.length === 1) {- return translateDataStreamToHtml(bodyList[0]);+ return convertBodyToHtml(bodyList[0]);}let html = '';for (const body of bodyList) {html += '<p className="UniverNormal">';- html += translateDataStreamToHtml(body, false);+ html += convertBodyToHtml(body, false);html += '</p>';}