Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(doc): copy cut in doc (#456)

Ran Luo1aa74f36d550
diff --git a/packages/base-docs/src/commands/mutations/__tests__/apply-utils.spec.ts b/packages/base-docs/src/commands/mutations/__tests__/apply-utils.spec.ts
index 9f82d3f303..7459f05e3d 100644
--- a/packages/base-docs/src/commands/mutations/__tests__/apply-utils.spec.ts
+++ b/packages/base-docs/src/commands/mutations/__tests__/apply-utils.spec.ts
@@ -9,7 +9,7 @@ interface IMockBody {
textRuns: ITextRun[];
}
-describe('example', () => {
+describe('test case in apply utils', () => {
let body: Nullable<IMockBody> = null;
let updateTextRuns: ITextRun[] = [];
diff --git a/packages/base-docs/src/controllers/move-cursor.controller.ts b/packages/base-docs/src/controllers/move-cursor.controller.ts
index c1ffbe1a85..e5d2e4b032 100644
--- a/packages/base-docs/src/controllers/move-cursor.controller.ts
+++ b/packages/base-docs/src/controllers/move-cursor.controller.ts
@@ -262,7 +262,7 @@ export class MoveCursorController extends Disposable {
return;
}
- // TODO: @jocs, hardcode isBack to true, `_getTopOrBottomPosition` need to rewrite.
+ // TODO: @JOCS, hardcode isBack to true, `_getTopOrBottomPosition` need to rewrite.
return { ...position, isBack: true };
}
diff --git a/packages/base-docs/src/services/text-selection-manager.service.ts b/packages/base-docs/src/services/text-selection-manager.service.ts
index e001c3933f..66e80a3de1 100644
--- a/packages/base-docs/src/services/text-selection-manager.service.ts
+++ b/packages/base-docs/src/services/text-selection-manager.service.ts
@@ -117,10 +117,12 @@ export class TextSelectionManagerService implements IDisposable {
if (this._currentSelection == null) {
return;
}
+
this._replaceByParam({
...this._currentSelection,
textRanges,
});
+
this.refresh(this._currentSelection);
}
diff --git a/packages/ui-plugin-docs/package.json b/packages/ui-plugin-docs/package.json
index 35bb21f5a3..9b303ef98c 100644
--- a/packages/ui-plugin-docs/package.json
+++ b/packages/ui-plugin-docs/package.json
@@ -32,6 +32,7 @@
"esbuild": "node ./esbuild.config.mjs"
},
"dependencies": {
+ "@ctrl/tinycolor": "^4.0.2",
"@univerjs/base-docs": "*",
"@univerjs/base-render": "*",
"@univerjs/base-ui": "*",
diff --git a/packages/ui-plugin-docs/src/commands/commands/__test__/clipboard.command.spec.ts b/packages/ui-plugin-docs/src/commands/commands/__test__/clipboard.command.spec.ts
index 6c5b3d4864..e552babb76 100644
--- a/packages/ui-plugin-docs/src/commands/commands/__test__/clipboard.command.spec.ts
+++ b/packages/ui-plugin-docs/src/commands/commands/__test__/clipboard.command.spec.ts
@@ -5,11 +5,24 @@ import {
RichTextEditingMutation,
TextSelectionManagerService,
} from '@univerjs/base-docs';
-import { BooleanNumber, ICommand, ICommandService, IStyleBase, IUniverInstanceService, Univer } from '@univerjs/core';
+import {
+ BooleanNumber,
+ ICommand,
+ ICommandService,
+ IStyleBase,
+ IUniverInstanceService,
+ UndoCommand,
+ Univer,
+} from '@univerjs/core';
import { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { IInnerPasteCommandParams, InnerPasteCommand } from '../clipboard.command';
+import {
+ IInnerCutCommandParams,
+ IInnerPasteCommandParams,
+ InnerCutCommand,
+ InnerPasteCommand,
+} from '../clipboard.command';
import { createCommandTestBed } from './create-command-test-bed';
describe('test cases in clipboard', () => {
@@ -48,6 +61,7 @@ describe('test cases in clipboard', () => {
commandService = get(ICommandService);
commandService.registerCommand(InnerPasteCommand);
+ commandService.registerCommand(InnerCutCommand);
commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
const selectionManager = get(TextSelectionManagerService);
@@ -104,6 +118,25 @@ describe('test cases in clipboard', () => {
expect(getTextByPosition(0, 6)).toBe(`univer`);
expect(getTextByPosition(11, 17)).toBe('univer');
expect(getFormatValueAt('bl', 0)).toBe(BooleanNumber.TRUE);
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ });
+ });
+
+ describe('Test cut in multiple ranges', () => {
+ it('Should cut content to each selection ranges', async () => {
+ expect(getTextByPosition(0, 5)).toBe(`What’`);
+ expect(getFormatValueAt('bl', 0)).toBe(BooleanNumber.FALSE);
+
+ const commandParams: IInnerCutCommandParams = {
+ segmentId: '',
+ };
+
+ await commandService.executeCommand(InnerCutCommand.id, commandParams);
+
+ expect(getTextByPosition(0, 5)).toBe(`s New`);
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
});
});
});
diff --git a/packages/ui-plugin-docs/src/commands/commands/clipboard.command.ts b/packages/ui-plugin-docs/src/commands/commands/clipboard.command.ts
index c9cd321a82..6984c376cd 100644
--- a/packages/ui-plugin-docs/src/commands/commands/clipboard.command.ts
+++ b/packages/ui-plugin-docs/src/commands/commands/clipboard.command.ts
@@ -131,3 +131,78 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
return false;
},
};
+
+export interface IInnerCutCommandParams {
+ segmentId: string;
+}
+
+export const InnerCutCommand: ICommand<IInnerCutCommandParams> = {
+ id: 'doc.command.inner-cut',
+ type: CommandType.COMMAND,
+ handler: async (accessor, params: IInnerCutCommandParams) => {
+ const { segmentId } = params;
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const commandService = accessor.get(ICommandService);
+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);
+ const currentUniverService = accessor.get(IUniverInstanceService);
+
+ const selections = textSelectionManagerService.getSelections();
+
+ if (!Array.isArray(selections) || selections.length === 0) {
+ return false;
+ }
+
+ const docsModel = currentUniverService.getCurrentUniverDocInstance();
+ const unitId = docsModel.getUnitId();
+
+ const doMutation: ICommandInfo<IRichTextEditingMutationParams> = {
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId,
+ mutations: [],
+ },
+ };
+
+ const memoryCursor = new MemoryCursor();
+
+ memoryCursor.reset();
+
+ for (const selection of selections) {
+ const { startOffset, endOffset, collapsed } = selection;
+
+ const len = startOffset - memoryCursor.cursor;
+
+ if (collapsed) {
+ doMutation.params!.mutations.push({
+ t: 'r',
+ len,
+ segmentId,
+ });
+ } else {
+ doMutation.params!.mutations.push(
+ ...getRetainAndDeleteFromReplace(selection, segmentId, memoryCursor.cursor)
+ );
+ }
+
+ memoryCursor.reset();
+ memoryCursor.moveCursor(endOffset);
+ }
+
+ const result = commandService.syncExecuteCommand<
+ IRichTextEditingMutationParams,
+ IRichTextEditingMutationParams
+ >(doMutation.id, doMutation.params);
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [{ id: RichTextEditingMutation.id, params: result }],
+ redoMutations: [{ id: RichTextEditingMutation.id, params: doMutation.params }],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/ui-plugin-docs/src/controllers/clipboard.controller.ts b/packages/ui-plugin-docs/src/controllers/clipboard.controller.ts
index 18e0ade459..de5b7855cf 100644
--- a/packages/ui-plugin-docs/src/controllers/clipboard.controller.ts
+++ b/packages/ui-plugin-docs/src/controllers/clipboard.controller.ts
@@ -17,6 +17,7 @@ import {
DocCopyCommand,
DocCutCommand,
DocPasteCommand,
+ InnerCutCommand,
InnerPasteCommand,
} from '../commands/commands/clipboard.command';
import { IDocClipboardService } from '../services/clipboard/clipboard.service';
@@ -39,7 +40,9 @@ export class DocClipboardController extends Disposable {
[DocCopyCommand, DocCutCommand, DocPasteCommand].forEach((command) =>
this.disposeWithMe(this._commandService.registerAsMultipleCommand(command))
);
- [InnerPasteCommand].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+ [InnerPasteCommand, InnerCutCommand].forEach((command) =>
+ this.disposeWithMe(this._commandService.registerCommand(command))
+ );
}
private _commandExecutedListener() {
@@ -210,12 +213,62 @@ export class DocClipboardController extends Disposable {
}
private async _handleCopy() {
- console.log('copy');
- const bodys = this._getDocumentBodyInRanges();
- console.log(bodys);
+ const { _docClipboardService: clipboard } = this;
+ const documentBodyList = this._getDocumentBodyInRanges();
+
+ try {
+ clipboard.setClipboardData(documentBodyList);
+ } catch (_e) {
+ this._logService.error('[DocClipboardController] set clipboard failed');
+ }
}
private async _handleCut() {
- console.log('cut');
+ const {
+ segmentId,
+ endOffset: activeEndOffset,
+ style,
+ } = this._textSelectionRenderManager.getActiveRange() ?? {};
+ const ranges = this._textSelectionRenderManager.getAllTextRanges();
+
+ if (segmentId == null) {
+ this._logService.error('[DocClipboardController] segmentId is not existed');
+ }
+
+ if (activeEndOffset == null) {
+ return;
+ }
+
+ // Set content to clipboard.
+ this._handleCopy();
+
+ try {
+ this._commandService.executeCommand(InnerCutCommand.id, { segmentId });
+
+ let cursor = activeEndOffset;
+ for (const range of ranges) {
+ const { startOffset, endOffset } = range;
+
+ if (startOffset == null || endOffset == null) {
+ continue;
+ }
+
+ if (endOffset <= activeEndOffset) {
+ cursor -= endOffset - startOffset;
+ }
+ }
+
+ // move selection
+ this._textSelectionManagerService.replace([
+ {
+ startOffset: cursor,
+ endOffset: cursor,
+ collapsed: true,
+ style,
+ },
+ ]);
+ } catch (e) {
+ this._logService.error('[DocClipboardController] cut content failed');
+ }
}
}
diff --git a/packages/ui-plugin-docs/src/services/clipboard/__test__/html-and-udm-convert.spec.ts b/packages/ui-plugin-docs/src/services/clipboard/__test__/html-and-udm-convert.spec.ts
new file mode 100644
index 0000000000..49e78bff79
--- /dev/null
+++ b/packages/ui-plugin-docs/src/services/clipboard/__test__/html-and-udm-convert.spec.ts
@@ -0,0 +1,115 @@
+/* eslint-disable no-magic-numbers */
+import { BooleanNumber, IDocumentBody, Nullable } 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 { UDMToHtmlService } from '../udm-to-html/convertor';
+
+HtmlToUDMService.use(PastePluginWord);
+HtmlToUDMService.use(PastePluginLark);
+
+describe('test case in html and udm convert', () => {
+ let body: Nullable<IDocumentBody> = null;
+ let html: string = '';
+
+ beforeEach(() => {
+ body = {
+ dataStream: 'helloworld',
+ textRuns: [
+ {
+ st: 0,
+ ed: 5,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ },
+ },
+ {
+ st: 5,
+ ed: 10,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ it: BooleanNumber.TRUE,
+ },
+ },
+ ],
+ };
+
+ html = `<p
+ class="MsoNormal"
+ align="left"
+ style="
+ margin: 16.8pt 0cm 0cm;
+ text-align: left;
+ font-size: 10.5pt;
+ font-family: DengXian;
+ color: rgb(0, 0, 0);
+ font-style: normal;
+ font-variant-ligatures: normal;
+ font-variant-caps: normal;
+ font-weight: 400;
+ letter-spacing: normal;
+ orphans: 2;
+ text-indent: 0px;
+ text-transform: none;
+ widows: 2;
+ word-spacing: 0px;
+ -webkit-text-stroke-width: 0px;
+ white-space: normal;
+ text-decoration-thickness: initial;
+ text-decoration-style: initial;
+ text-decoration-color: initial;
+ background: white;
+ "
+><span style="font-size: 12pt; font-family: 宋体; color: rgb(18, 18, 18)"
+ >hello</span
+ ></p>
+<span
+ style="
+ font-style: normal;
+ font-variant-ligatures: normal;
+ font-variant-caps: normal;
+ font-weight: 400;
+ letter-spacing: normal;
+ orphans: 2;
+ text-align: start;
+ text-indent: 0px;
+ text-transform: none;
+ widows: 2;
+ word-spacing: 0px;
+ -webkit-text-stroke-width: 0px;
+ white-space: normal;
+ text-decoration-thickness: initial;
+ text-decoration-style: initial;
+ text-decoration-color: initial;
+ font-size: 12pt;
+ font-family: 宋体;
+ color: rgb(18, 18, 18);
+ "
+>world</span>`;
+ });
+
+ afterEach(() => {
+ body = null;
+ html = '';
+ });
+
+ describe('test cases in html-to-udm', () => {
+ it('should paste the case when convert html to udm', async () => {
+ const convertor = new HtmlToUDMService();
+ const udm = await convertor.convert(html);
+
+ expect(udm.dataStream).toBe('hello\rworld');
+ });
+ });
+
+ describe('test cases in udm-to-html', () => {
+ it('should paste the case when convert udm to html', async () => {
+ const convertor = new UDMToHtmlService();
+ const html = await convertor.convert([body!]);
+ console.log(html);
+ expect(html).toBe('<strong>hello</strong><strong><i>world</i></strong>');
+ });
+ });
+});
diff --git a/packages/ui-plugin-docs/src/services/clipboard/clipboard.service.ts b/packages/ui-plugin-docs/src/services/clipboard/clipboard.service.ts
index bed2403ad6..186619ba49 100644
--- a/packages/ui-plugin-docs/src/services/clipboard/clipboard.service.ts
+++ b/packages/ui-plugin-docs/src/services/clipboard/clipboard.service.ts
@@ -6,9 +6,11 @@ import {
import { Disposable, IDocumentBody, IUniverInstanceService, toDisposable } from '@univerjs/core';
import { createIdentifier, IDisposable } from '@wendellhu/redi';
+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 { UDMToHtmlService } from './udm-to-html/convertor';
HtmlToUDMService.use(PastePluginWord);
HtmlToUDMService.use(PastePluginLark);
@@ -23,6 +25,8 @@ export interface IDocClipboardHook {
export interface IDocClipboardService {
queryClipboardData(): Promise<IDocumentBody>;
+ setClipboardData(documentBodyList: IDocumentBody[]): Promise<void>;
+
addClipboardHook(hook: IDocClipboardHook): IDisposable;
}
@@ -31,6 +35,7 @@ export const IDocClipboardService = createIdentifier<IDocClipboardService>('doc.
export class DocClipboardService extends Disposable implements IDocClipboardService {
private _clipboardHooks: IDocClipboardHook[] = [];
private htmlToUDM = new HtmlToUDMService();
+ private UDMToHtml = new UDMToHtmlService();
constructor(
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@@ -49,8 +54,6 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
const text = await clipboardItem.getType(PLAIN_TEXT_CLIPBOARD_MIME_TYPE).then((blob) => blob && blob.text());
const html = await clipboardItem.getType(HTML_CLIPBOARD_MIME_TYPE).then((blob) => blob && blob.text());
- // console.log(text);
- // console.log(html);
if (!html) {
// TODO: @JOCS, Parsing paragraphs and sections
return {
@@ -58,9 +61,36 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
};
}
+ const copyId = extractId(html);
+
+ if (copyId) {
+ const copyCache = copyContentCache.get(copyId);
+
+ if (copyCache) {
+ return copyCache;
+ }
+ }
+
return this.htmlToUDM.convert(html);
}
+ async setClipboardData(documentBodyList: IDocumentBody[]): Promise<void> {
+ const copyId = genId();
+ const text =
+ documentBodyList.length > 1
+ ? documentBodyList.map((body) => body.dataStream).join('\n')
+ : documentBodyList[0].dataStream;
+ let html = this.UDMToHtml.convert(documentBodyList);
+
+ // Only cache copy content when the range is 1.
+ if (documentBodyList.length === 1) {
+ html = html.replace(/(<[a-z]+)/, (_p0, p1) => `${p1} data-copy-id="${copyId}"`);
+ copyContentCache.set(copyId, documentBodyList[0]);
+ }
+
+ return this._clipboardInterfaceService.write(text, html);
+ }
+
addClipboardHook(hook: IDocClipboardHook): IDisposable {
this._clipboardHooks.push(hook);
diff --git a/packages/ui-plugin-docs/src/services/clipboard/copy-content-cache.ts b/packages/ui-plugin-docs/src/services/clipboard/copy-content-cache.ts
new file mode 100644
index 0000000000..c73b8ab9e4
--- /dev/null
+++ b/packages/ui-plugin-docs/src/services/clipboard/copy-content-cache.ts
@@ -0,0 +1,36 @@
+import { IDocumentBody, LRUMap, Tools } from '@univerjs/core';
+
+const COPY_CONTENT_CACHE_LIMIT = 10;
+const ID_LENGTH = 6;
+
+export function genId() {
+ return Tools.generateRandomId(ID_LENGTH);
+}
+
+export function extractId(html: string) {
+ const match = html.match(/data-copy-id="([^\s]+)"/);
+
+ if (match && match[1]) {
+ return match[1];
+ }
+
+ return null;
+}
+
+export class CopyContentCache {
+ private _cache = new LRUMap<string, IDocumentBody>(COPY_CONTENT_CACHE_LIMIT);
+
+ set(id: string, clipboardData: IDocumentBody) {
+ this._cache.set(id, clipboardData);
+ }
+
+ get(id: string) {
+ return this._cache.get(id);
+ }
+
+ clear() {
+ this._cache.clear();
+ }
+}
+
+export const copyContentCache = new CopyContentCache();
diff --git a/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/converter.ts b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/converter.ts
index 55f615d538..da76034350 100644
--- a/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/converter.ts
+++ b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/converter.ts
@@ -1,6 +1,6 @@
import { IDocumentBody, ITextStyle, Nullable } from '@univerjs/core';
-import extractNodeStyle from './parse-node-style';
+import { extractNodeStyle } from './parse-node-style';
import parseToDom from './parse-to-dom';
import { IAfterProcessRule, IPastePlugin, IStyleRule } from './paste-plugins/type';
@@ -67,7 +67,7 @@ export class HtmlToUDMService {
for (const node of nodes) {
if (node.nodeType === Node.TEXT_NODE) {
// TODO: @JOCS, More characters need to be replaced, like `\b`
- const text = node.nodeValue?.replace(/\r\n/g, '');
+ const text = node.nodeValue?.replace(/[\r\n]/g, '');
let style;
if (parent && this.styleCache.has(parent)) {
diff --git a/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/parse-node-style.ts b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/parse-node-style.ts
index 458d5f8013..931046d594 100644
--- a/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/parse-node-style.ts
+++ b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/parse-node-style.ts
@@ -1,8 +1,9 @@
+import { TinyColor } from '@ctrl/tinycolor';
import { BaselineOffset, BooleanNumber, ITextStyle } from '@univerjs/core';
import { ptToPixel } from './utils';
-export default function extractNodeStyle(node: HTMLElement): ITextStyle {
+export function extractNodeStyle(node: HTMLElement): ITextStyle {
const styles = node.style;
const docStyles: ITextStyle = {};
const tagName = node.tagName.toLowerCase();
@@ -54,8 +55,11 @@ export default function extractNodeStyle(node: HTMLElement): ITextStyle {
case 'font-size': {
const fontSize = parseInt(cssValue);
- // TODO: @JOCS, hand other CSS value unit, rem, em, pt, %
- docStyles.fs = /pt$/.test(cssValue) ? ptToPixel(fontSize) : fontSize;
+
+ if (!Number.isNaN(fontSize)) {
+ // TODO: @JOCS, hand other CSS value unit, rem, em, pt, %
+ docStyles.fs = /pt$/.test(cssValue) ? ptToPixel(fontSize) : fontSize;
+ }
break;
}
@@ -98,17 +102,25 @@ export default function extractNodeStyle(node: HTMLElement): ITextStyle {
}
case 'color': {
- docStyles.cl = {
- rgb: cssValue,
- };
+ const color = new TinyColor(cssValue);
+
+ if (color.isValid) {
+ docStyles.cl = {
+ rgb: color.toRgbString(),
+ };
+ }
break;
}
case 'background-color': {
- docStyles.bg = {
- rgb: cssValue,
- };
+ const color = new TinyColor(cssValue);
+
+ if (color.isValid) {
+ docStyles.bg = {
+ rgb: color.toRgbString(),
+ };
+ }
break;
}
diff --git a/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/paste-plugins/plugin-lark.ts b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/paste-plugins/plugin-lark.ts
index 2f2fcaa36d..ae12305640 100644
--- a/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/paste-plugins/plugin-lark.ts
+++ b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/paste-plugins/plugin-lark.ts
@@ -1,6 +1,6 @@
import { BooleanNumber } from '@univerjs/core';
-import getInlineStyle from '../parse-node-style';
+import { extractNodeStyle as getInlineStyle } from '../parse-node-style';
import { IPastePlugin } from './type';
const wordPastePlugin: IPastePlugin = {
diff --git a/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.ts b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.ts
index fdcf90c38d..e47ac1a2b2 100644
--- a/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.ts
+++ b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.ts
@@ -1,6 +1,6 @@
import { BooleanNumber, IParagraph } from '@univerjs/core';
-import getInlineStyle from '../parse-node-style';
+import { extractNodeStyle as getInlineStyle } from '../parse-node-style';
import { getParagraphStyle } from '../utils';
import { IPastePlugin } from './type';
diff --git a/packages/ui-plugin-docs/src/services/clipboard/udm-to-html/convertor.ts b/packages/ui-plugin-docs/src/services/clipboard/udm-to-html/convertor.ts
new file mode 100644
index 0000000000..82f9718f67
--- /dev/null
+++ b/packages/ui-plugin-docs/src/services/clipboard/udm-to-html/convertor.ts
@@ -0,0 +1,142 @@
+import { BaselineOffset, BooleanNumber, IDocumentBody, ITextRun } from '@univerjs/core';
+
+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;
+
+ let html = dataStream.slice(start, ed);
+ const style: string[] = [];
+
+ // italic
+ if (it === BooleanNumber.TRUE) {
+ html = `<i>${html}</i>`;
+ }
+
+ // subscript and superscript
+ if (va === BaselineOffset.SUPERSCRIPT) {
+ html = `<sup>${html}</sup>`;
+ } else if (va === BaselineOffset.SUBSCRIPT) {
+ html = `<sub>${html}</sub>`;
+ }
+
+ // underline
+ if (ul?.s === BooleanNumber.TRUE) {
+ html = `<u>${html}</u>`;
+ }
+
+ // strick-through
+ if (st?.s === BooleanNumber.TRUE) {
+ html = `<s>${html}</s>`;
+ }
+
+ // bold
+ if (bl === BooleanNumber.TRUE) {
+ html = `<strong>${html}</strong>`;
+ }
+
+ // font family
+ if (ff) {
+ style.push(`font-family: ${ff}`);
+ }
+
+ // font color
+ if (cl) {
+ style.push(`color: ${cl.rgb}`);
+ }
+
+ // font size
+ if (fs) {
+ style.push(`font-size: ${fs}px`);
+ }
+
+ // overline
+ if (ol) {
+ style.push(`text-decoration: overline`);
+ }
+
+ // background color
+ if (bg) {
+ style.push(`background: ${bg.rgb}`);
+ }
+
+ 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;
+ const spanList: string[] = [];
+ const paragraphList: string[] = [];
+
+ for (const textRun of textRuns) {
+ const { st, ed } = textRun;
+ if (st !== cursorIndex) {
+ spanList.push(dataStream.slice(cursorIndex, st));
+ }
+
+ 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;
+ }
+ }
+ }
+ }
+
+ return paragraphList.join('') + spanList.join('');
+}
+
+export class UDMToHtmlService {
+ convert(bodyList: IDocumentBody[]): string {
+ if (bodyList.length === 0) {
+ throw new Error('The bodyList length at least to be 1');
+ }
+
+ // If only one selection range of content is copied, the paragraph information will be used,
+ // otherwise, the paragraph information will be discarded and a paragraph
+ // will be generated for each body
+ if (bodyList.length === 1) {
+ return translateDataStreamToHtml(bodyList[0]);
+ }
+
+ let html = '';
+
+ for (const body of bodyList) {
+ html += '<p className="UniverNormal">';
+ html += translateDataStreamToHtml(body, false);
+ html += '</p>';
+ }
+
+ return html;
+ }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a552212dfe..470c8e7828 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1108,6 +1108,9 @@ importers:
packages/ui-plugin-docs:
dependencies:
+ '@ctrl/tinycolor':
+ specifier: ^4.0.2
+ version: 4.0.2
'@univerjs/base-docs':
specifier: '*'
version: link:../base-docs