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: support paste from word and lark to univer doc (#439)

Ran Luoe2bc73c730e3
diff --git a/packages/base-docs/src/basics/memory-cursor.ts b/packages/base-docs/src/basics/memory-cursor.ts
index 0387ac2386..5f737a62dc 100644
--- a/packages/base-docs/src/basics/memory-cursor.ts
+++ b/packages/base-docs/src/basics/memory-cursor.ts
@@ -1,4 +1,4 @@
-class MemoryCursor {
+export class MemoryCursor {
cursor: number = 0;
reset() {
@@ -10,5 +10,3 @@ class MemoryCursor {
this.cursor += pos;
}
}
-
-export default MemoryCursor;
diff --git a/packages/base-docs/src/commands/commands/core-editing.command.ts b/packages/base-docs/src/commands/commands/core-editing.command.ts
index 0592a59514..291f37e8a6 100644
--- a/packages/base-docs/src/commands/commands/core-editing.command.ts
+++ b/packages/base-docs/src/commands/commands/core-editing.command.ts
@@ -103,7 +103,7 @@ export interface IDeleteCommandParams {
}
/**
- * The command to delete text.
+ * The command to delete text, mainly used in BACKSPACE.
*/
export const DeleteCommand: ICommand<IDeleteCommandParams> = {
id: 'doc.command.delete-text',
@@ -131,6 +131,7 @@ export const DeleteCommand: ICommand<IDeleteCommandParams> = {
IRichTextEditingMutationParams,
IRichTextEditingMutationParams
>(doMutation.id, doMutation.params);
+
if (result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
@@ -301,15 +302,16 @@ export const CoverCommand: ICommand<ICoverCommandParams> = {
},
};
-function getRetainAndDeleteFromReplace(
+export function getRetainAndDeleteFromReplace(
range: ITextRange,
- segmentId?: string
+ segmentId: string = '',
+ memoryCursor: number = 0
): Array<IRetainMutationParams | IDeleteMutationParams> {
const { startOffset, endOffset, collapsed } = range;
const dos: Array<IRetainMutationParams | IDeleteMutationParams> = [];
- const textStart = startOffset + (collapsed ? -1 : 0);
- const textEnd = endOffset - 1;
+ const textStart = startOffset + (collapsed ? -1 : 0) - memoryCursor;
+ const textEnd = endOffset - 1 - memoryCursor;
if (textStart > 0) {
dos.push({
diff --git a/packages/base-docs/src/commands/commands/inline-format.command.ts b/packages/base-docs/src/commands/commands/inline-format.command.ts
index 024ae3d377..5480d8a81f 100644
--- a/packages/base-docs/src/commands/commands/inline-format.command.ts
+++ b/packages/base-docs/src/commands/commands/inline-format.command.ts
@@ -13,7 +13,7 @@ import {
IUniverInstanceService,
} from '@univerjs/core';
-import MemoryCursor from '../../basics/memory-cursor';
+import { MemoryCursor } from '../../basics/memory-cursor';
import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
import { IRichTextEditingMutationParams, RichTextEditingMutation } from '../mutations/core-editing.mutation';
diff --git a/packages/base-docs/src/commands/mutations/core-editing.mutation.ts b/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
index 9521eb3eee..032d734787 100644
--- a/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
+++ b/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
@@ -7,7 +7,7 @@ import {
UpdateDocsAttributeType,
} from '@univerjs/core';
-import MemoryCursor from '../../basics/memory-cursor';
+import { MemoryCursor } from '../../basics/memory-cursor';
import { DeleteApply } from './functions/delete-apply';
import { InsertApply } from './functions/insert-apply';
import { UpdateAttributeApply } from './functions/update-apply';
diff --git a/packages/base-docs/src/commands/mutations/functions/insert-apply.ts b/packages/base-docs/src/commands/mutations/functions/insert-apply.ts
index cad28b8d5c..6d5e7d88ed 100644
--- a/packages/base-docs/src/commands/mutations/functions/insert-apply.ts
+++ b/packages/base-docs/src/commands/mutations/functions/insert-apply.ts
@@ -30,10 +30,17 @@ export function InsertApply(
throw new Error('no body has changed');
}
- bodyModel.insert(insertBody, currentIndex);
-
updateAttributeByInsert(body, insertBody, textLength, currentIndex);
+ if (insertBody.dataStream.length > 1 && /\r/.test(insertBody.dataStream)) {
+ // TODO: @JOCS, The DocumentModel needs to be rewritten to better support the
+ // large area of updates that are brought about by the paste, abstract the
+ // methods associated with the DocumentModel insertion, and support atomic operations
+ bodyModel.reset(body);
+ } else {
+ bodyModel.insert(insertBody, currentIndex);
+ }
+
console.log('插入的model打印', bodyModel, textLength, currentIndex);
}
diff --git a/packages/base-docs/src/doc-plugin.ts b/packages/base-docs/src/doc-plugin.ts
index e27d63d8c0..c9a3f9b2cb 100644
--- a/packages/base-docs/src/doc-plugin.ts
+++ b/packages/base-docs/src/doc-plugin.ts
@@ -91,7 +91,7 @@ export class DocPlugin extends Plugin {
this._initializeDependencies(_injector);
- this.initializeCommands();
+ this._initializeCommands();
}
initialize(): void {
@@ -106,7 +106,7 @@ export class DocPlugin extends Plugin {
// this._markDocAsFocused();
}
- initializeCommands(): void {
+ private _initializeCommands(): void {
(
[
MoveCursorOperation,
@@ -151,7 +151,7 @@ export class DocPlugin extends Plugin {
});
}
- initialConfig(config: IDocPluginConfig) {
+ private initialConfig(config: IDocPluginConfig) {
this._currentUniverService.docAdded$.subscribe((documentModel) => {
if (documentModel == null) {
throw new Error('documentModel is null');
diff --git a/packages/base-docs/src/index.ts b/packages/base-docs/src/index.ts
index d92e2600ab..2457e2bd7a 100644
--- a/packages/base-docs/src/index.ts
+++ b/packages/base-docs/src/index.ts
@@ -1,8 +1,10 @@
export * from './basics/component-tools';
export * from './basics/docs-view-key';
+export { MemoryCursor } from './basics/memory-cursor';
export {
CoverCommand,
DeleteCommand,
+ getRetainAndDeleteFromReplace,
type ICoverCommandParams,
type IDeleteCommandParams,
type IIMEInputCommandParams,
@@ -28,6 +30,6 @@ export {
RichTextEditingMutation,
} from './commands/mutations/core-editing.mutation';
export { MoveCursorOperation, MoveSelectionOperation } from './commands/operations/cursor.operation';
-export * from './doc-plugin';
+export { DocPlugin, type IDocPluginConfig } from './doc-plugin';
export { DocSkeletonManagerService } from './services/doc-skeleton-manager.service';
export { TextSelectionManagerService } from './services/text-selection-manager.service';
diff --git a/packages/base-docs/src/services/doc-skeleton-manager.service.ts b/packages/base-docs/src/services/doc-skeleton-manager.service.ts
index 9dc0a580e9..a67638f8a1 100644
--- a/packages/base-docs/src/services/doc-skeleton-manager.service.ts
+++ b/packages/base-docs/src/services/doc-skeleton-manager.service.ts
@@ -85,11 +85,13 @@ export class DocSkeletonManagerService implements IDisposable {
setCurrent(searchParm: IDocSkeletonManagerSearch): Nullable<IDocSkeletonManagerParam> {
const param = this._getCurrentBySearch(searchParm);
+
if (param != null) {
if (param.dirty) {
param.skeleton.makeDirty(true);
param.dirty = false;
}
+
param.skeleton.calculate();
} else {
const { unitId } = searchParm;
diff --git a/packages/base-docs/src/views/doc-canvas-view.ts b/packages/base-docs/src/views/doc-canvas-view.ts
index 11b54f390b..4a2daa147b 100644
--- a/packages/base-docs/src/views/doc-canvas-view.ts
+++ b/packages/base-docs/src/views/doc-canvas-view.ts
@@ -43,7 +43,6 @@ export class DocCanvasView {
@IConfigService private readonly _configService: IConfigService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
- // @IRenderingEngine private readonly _engine: Engine,
@Inject(Injector) private readonly _injector: Injector
) {
this._currentUniverService.currentDoc$.subscribe((documentModel) => {
@@ -52,6 +51,7 @@ export class DocCanvasView {
}
const unitId = documentModel.getUnitId();
+
if (!this._loadedMap.has(unitId)) {
this._currentDocumentModel = documentModel;
this._addNewRender();
@@ -103,6 +103,7 @@ export class DocCanvasView {
scene.on(EVENT_TYPE.wheel, (evt: unknown, state: EventState) => {
const e = evt as IWheelEvent;
+
if (e.ctrlKey) {
const deltaFactor = Math.abs(e.deltaX);
let scrollNum = deltaFactor < 40 ? 0.2 : deltaFactor < 80 ? 0.4 : 0.2;
@@ -141,6 +142,7 @@ export class DocCanvasView {
this._addComponent(currentRender);
const should = this._currentDocumentModel.getShouldRenderLoopImmediately();
+
if (should) {
engine.runRenderLoop(() => {
scene.render();
diff --git a/packages/base-render/src/basics/font-cache.ts b/packages/base-render/src/basics/font-cache.ts
index 12a778bcff..8c77063384 100644
--- a/packages/base-render/src/basics/font-cache.ts
+++ b/packages/base-render/src/basics/font-cache.ts
@@ -230,6 +230,7 @@ export class FontCache {
}
this.setFontMeasureCache(fontString, content, cache);
+
return cache;
}
diff --git a/packages/base-render/src/components/component.ts b/packages/base-render/src/components/component.ts
index 724b37b0b6..ee35c2ec28 100644
--- a/packages/base-render/src/components/component.ts
+++ b/packages/base-render/src/components/component.ts
@@ -27,6 +27,7 @@ export class RenderComponent<T, U> extends BaseObject {
getExtensionsByOrder() {
const extensionArray = Array.from(this._extensions.values());
extensionArray.sort(sortRules);
+
return extensionArray;
}
diff --git a/packages/base-render/src/components/docs/doc-skeleton.ts b/packages/base-render/src/components/docs/doc-skeleton.ts
index 05010bcd3d..c755d25ad4 100644
--- a/packages/base-render/src/components/docs/doc-skeleton.ts
+++ b/packages/base-render/src/components/docs/doc-skeleton.ts
@@ -501,6 +501,7 @@ export class DocumentSkeleton extends Skeleton {
wrapStrategy: WrapStrategy.UNSPECIFIED,
},
} = documentStyle;
+
const skeleton = this.__getNullSke();
const docsConfig: IDocsConfig = {
diff --git a/packages/base-render/src/components/docs/document.ts b/packages/base-render/src/components/docs/document.ts
index 318c7ac646..67bcb96643 100644
--- a/packages/base-render/src/components/docs/document.ts
+++ b/packages/base-render/src/components/docs/document.ts
@@ -175,6 +175,7 @@ export class Documents extends DocComponent {
override draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
const documentSkeleton = this.getSkeleton();
+
if (!documentSkeleton) {
return;
}
@@ -195,6 +196,7 @@ export class Documents extends DocComponent {
const parentScale = this.getParentScale();
const extensions = this.getExtensionsByOrder();
const scale = getScale(parentScale);
+
for (const extension of extensions) {
extension.clearCache();
}
@@ -267,6 +269,7 @@ export class Documents extends DocComponent {
let alignOffset;
let rotateTranslateXListApply = null;
+
if (vertexAngle !== 0) {
const {
rotateTranslateXList,
diff --git a/packages/base-render/src/render-manager.service.ts b/packages/base-render/src/render-manager.service.ts
index 4005fd1054..024dcae7f3 100644
--- a/packages/base-render/src/render-manager.service.ts
+++ b/packages/base-render/src/render-manager.service.ts
@@ -93,12 +93,14 @@ export class RenderManagerService implements IRenderManagerService {
private _createRender(unitId: string, engine: Engine, isMainScene: boolean = true): IRender {
const existItem = this.getRenderById(unitId);
let shouldDestroyEngine = true;
+
if (existItem != null) {
const existEngine = existItem.engine;
if (existEngine === engine) {
shouldDestroyEngine = false;
}
}
+
this._disposeItem(existItem, shouldDestroyEngine);
const { width, height } = DEFAULT_SCENE_SIZE;
diff --git a/packages/common-plugin-data/src/docs/default-document-data-en.ts b/packages/common-plugin-data/src/docs/default-document-data-en.ts
index adf4c9ddb3..6939031281 100644
--- a/packages/common-plugin-data/src/docs/default-document-data-en.ts
+++ b/packages/common-plugin-data/src/docs/default-document-data-en.ts
@@ -254,6 +254,9 @@ export const DEFAULT_DOCUMENT_DATA_EN: IDocumentData = {
nestingLevel: 0,
textStyle: {
fs: 20,
+ cl: {
+ rgb: 'rgb(0, 255, 0)',
+ },
},
},
paragraphStyle: {
diff --git a/packages/core/src/docs/domain/data-stream-tree-node.ts b/packages/core/src/docs/domain/data-stream-tree-node.ts
index b92dd471aa..e797229e4b 100644
--- a/packages/core/src/docs/domain/data-stream-tree-node.ts
+++ b/packages/core/src/docs/domain/data-stream-tree-node.ts
@@ -84,7 +84,7 @@ export class DataStreamTreeNode {
}
split(index: number) {
- const { children, parent, startIndex, endIndex, nodeType, content = '' } = this.getProps();
+ const { children, parent, startIndex, nodeType, content = '' } = this.getProps();
if (this.exclude(index)) {
return;
@@ -152,14 +152,17 @@ export class DataStreamTreeNode {
if (index == null) {
return -1;
}
+
return index;
}
remove() {
this.children = [];
+
if (this.parent == null) {
return;
}
+
this.parent.children.splice(this.getPositionInParent(), 1);
this.parent = null;
}
@@ -220,6 +223,7 @@ export class DataStreamTreeNode {
for (let i = 0, len = this.content.length; i < len; i++) {
const char = this.content[i];
+
if (char === DataStreamTreeTokenType.CUSTOM_BLOCK) {
this.blocks.push(this.startIndex + i);
}
diff --git a/packages/core/src/docs/domain/document-body-model.ts b/packages/core/src/docs/domain/document-body-model.ts
index 7af096612d..b4a52b5936 100644
--- a/packages/core/src/docs/domain/document-body-model.ts
+++ b/packages/core/src/docs/domain/document-body-model.ts
@@ -240,7 +240,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
insert(insertBody: IDocumentBody, insertIndex = 0) {
const dataStream = insertBody.dataStream;
let dataStreamLen = dataStream.length;
- const insertedNode = this.getParagraphByTree(this.children, insertIndex);
+ const insertedNode = this.getParagraphByIndex(this.children, insertIndex);
if (insertedNode == null) {
return;
@@ -279,6 +279,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
currentNode.selfPlus(dataStreamLen, currentNode.getPositionInParent());
const children = currentNode.children;
let isStartFix = false;
+
for (const node of children) {
if (node === insertedLastNode) {
isStartFix = true;
@@ -328,7 +329,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
this.deleteTree(nodes, currentIndex, textLength);
}
- private getParagraphByTree(nodes: DataStreamTreeNode[], insertIndex: number): Nullable<DataStreamTreeNode> {
+ private getParagraphByIndex(nodes: DataStreamTreeNode[], insertIndex: number): Nullable<DataStreamTreeNode> {
for (const node of nodes) {
const { children } = node;
@@ -340,7 +341,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
return node;
}
- return this.getParagraphByTree(children, insertIndex);
+ return this.getParagraphByIndex(children, insertIndex);
}
return null;
diff --git a/packages/core/src/docs/domain/document-model.ts b/packages/core/src/docs/domain/document-model.ts
index 2b892dfa79..fe2bcd89cf 100644
--- a/packages/core/src/docs/domain/document-model.ts
+++ b/packages/core/src/docs/domain/document-model.ts
@@ -230,6 +230,7 @@ export class DocumentModel extends DocumentModelSimple {
override updateDocumentId(unitId: string) {
super.updateDocumentId(unitId);
+
this._unitId = unitId;
}
diff --git a/packages/core/src/shared/common.ts b/packages/core/src/shared/common.ts
index 98315d310d..b52f67b921 100644
--- a/packages/core/src/shared/common.ts
+++ b/packages/core/src/shared/common.ts
@@ -506,6 +506,7 @@ export function getDocsUpdateBody(model: IDocumentData, segmentId?: string) {
if (segmentId) {
const { headers, footers } = model;
+
if (headers?.[segmentId]) {
body = headers[segmentId].body;
} else if (footers?.[segmentId]) {
diff --git a/packages/core/src/shared/doc-tool.ts b/packages/core/src/shared/doc-tool.ts
index 40dd7213b1..0bca8f0f20 100644
--- a/packages/core/src/shared/doc-tool.ts
+++ b/packages/core/src/shared/doc-tool.ts
@@ -81,9 +81,5 @@ export function deleteContent(content: string, start: number, end: number) {
return content;
}
- // if (start === end) {
- // start -= 1;
- // }
-
return content.slice(0, start) + content.slice(end);
}
diff --git a/packages/core/src/shared/tools.ts b/packages/core/src/shared/tools.ts
index c88c2cd81d..fcc93ee057 100644
--- a/packages/core/src/shared/tools.ts
+++ b/packages/core/src/shared/tools.ts
@@ -633,4 +633,13 @@ export class Tools {
}
return new ObjectArray<T>(array);
}
+
+ static hasIntersectionBetweenTwoRanges(
+ range1Start: number,
+ range1End: number,
+ range2Start: number,
+ range2End: number
+ ) {
+ return range1End >= range2Start && range2End >= range1Start;
+ }
}
diff --git a/packages/ui-plugin-docs/package.json b/packages/ui-plugin-docs/package.json
index 3c5ccd4c3d..4ac54cea54 100644
--- a/packages/ui-plugin-docs/package.json
+++ b/packages/ui-plugin-docs/package.json
@@ -54,6 +54,7 @@
"@types/react": "^18.2.37",
"@types/react-dom": "^18.2.15",
"@vitest/coverage-istanbul": "^0.34.6",
+ "happy-dom": "^12.10.3",
"less": "^4.2.0",
"ts-node": "^10.9.1",
"vitest": "^0.34.6"
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
new file mode 100644
index 0000000000..6c5b3d4864
--- /dev/null
+++ b/packages/ui-plugin-docs/src/commands/commands/__test__/clipboard.command.spec.ts
@@ -0,0 +1,109 @@
+/* eslint-disable no-magic-numbers */
+
+import {
+ NORMAL_TEXT_SELECTION_PLUGIN_NAME,
+ RichTextEditingMutation,
+ TextSelectionManagerService,
+} from '@univerjs/base-docs';
+import { BooleanNumber, ICommand, ICommandService, IStyleBase, IUniverInstanceService, Univer } from '@univerjs/core';
+import { Injector } from '@wendellhu/redi';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { IInnerPasteCommandParams, InnerPasteCommand } from '../clipboard.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('test cases in clipboard', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+
+ function getFormatValueAt(key: keyof IStyleBase, pos: number) {
+ const univerInstanceService = get(IUniverInstanceService);
+ const docsModel = univerInstanceService.getUniverDocInstance('test-doc');
+
+ if (docsModel?.body?.textRuns == null) {
+ return;
+ }
+
+ for (const textRun of docsModel.body?.textRuns) {
+ const { st, ed, ts = {} } = textRun;
+
+ if (st <= pos && ed >= pos) {
+ return ts[key];
+ }
+ }
+ }
+
+ function getTextByPosition(start: number, end: number) {
+ const univerInstanceService = get(IUniverInstanceService);
+ const docsModel = univerInstanceService.getUniverDocInstance('test-doc');
+
+ return docsModel?.body?.dataStream.slice(start, end);
+ }
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed();
+ univer = testBed.univer;
+ get = testBed.get;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(InnerPasteCommand);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+
+ const selectionManager = get(TextSelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
+ unitId: 'test-doc',
+ });
+
+ selectionManager.add([
+ {
+ startOffset: 0,
+ endOffset: 5,
+ collapsed: false,
+ segmentId: '',
+ },
+ ]);
+
+ selectionManager.add([
+ {
+ startOffset: 10,
+ endOffset: 15,
+ collapsed: false,
+ segmentId: '',
+ },
+ ]);
+ });
+
+ afterEach(() => univer.dispose());
+
+ describe('Test paste in multiple ranges', () => {
+ it('Should paste content to each selection ranges', async () => {
+ expect(getTextByPosition(0, 5)).toBe(`What’`);
+ expect(getFormatValueAt('bl', 0)).toBe(BooleanNumber.FALSE);
+
+ const commandParams: IInnerPasteCommandParams = {
+ segmentId: '',
+ body: {
+ dataStream: 'univer',
+ textRuns: [
+ {
+ st: 0,
+ ed: 6,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ },
+ },
+ ],
+ },
+ };
+
+ await commandService.executeCommand(InnerPasteCommand.id, commandParams);
+
+ expect(getTextByPosition(0, 6)).toBe(`univer`);
+ expect(getTextByPosition(11, 17)).toBe('univer');
+ expect(getFormatValueAt('bl', 0)).toBe(BooleanNumber.TRUE);
+ });
+ });
+});
diff --git a/packages/ui-plugin-docs/src/commands/commands/__test__/create-command-test-bed.ts b/packages/ui-plugin-docs/src/commands/commands/__test__/create-command-test-bed.ts
new file mode 100644
index 0000000000..4453722cb0
--- /dev/null
+++ b/packages/ui-plugin-docs/src/commands/commands/__test__/create-command-test-bed.ts
@@ -0,0 +1,63 @@
+import { createCommandTestBed as createTestBed } from '@univerjs/base-docs/commands/commands/__tests__/create-command-test-bed.js';
+import { BooleanNumber, IDocumentData } from '@univerjs/core';
+
+const TEST_DOCUMENT_DATA_EN: IDocumentData = {
+ id: 'test-doc',
+ body: {
+ dataStream: 'What’s New in the 2022\r Gartner Hype Cycle for Emerging Technologies\r\n',
+ textRuns: [
+ {
+ st: 0,
+ ed: 22,
+ ts: {
+ bl: BooleanNumber.FALSE,
+ fs: 24,
+ cl: {
+ rgb: 'rgb(0, 40, 86)',
+ },
+ },
+ },
+ {
+ st: 23,
+ ed: 68,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ fs: 24,
+ cl: {
+ rgb: 'rgb(0, 40, 86)',
+ },
+ },
+ },
+ ],
+ paragraphs: [
+ {
+ startIndex: 22,
+ },
+ {
+ startIndex: 68,
+ paragraphStyle: {
+ spaceAbove: 20,
+ indentFirstLine: 20,
+ },
+ },
+ ],
+ sectionBreaks: [],
+ customBlocks: [],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+};
+
+export function createCommandTestBed() {
+ const { univer, get, doc } = createTestBed(TEST_DOCUMENT_DATA_EN);
+
+ return { univer, get, doc };
+}
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 adda4f043d..c9cd321a82 100644
--- a/packages/ui-plugin-docs/src/commands/commands/clipboard.command.ts
+++ b/packages/ui-plugin-docs/src/commands/commands/clipboard.command.ts
@@ -1,7 +1,22 @@
+import {
+ getRetainAndDeleteFromReplace,
+ IRichTextEditingMutationParams,
+ MemoryCursor,
+ RichTextEditingMutation,
+ TextSelectionManagerService,
+} from '@univerjs/base-docs';
import { CopyCommand, CutCommand, PasteCommand } from '@univerjs/base-ui';
-import { CommandType, FOCUSING_DOC, IMultiCommand } from '@univerjs/core';
-
-import { IDocClipboardService } from '../../services/clipboard/clipboard.service';
+import {
+ CommandType,
+ FOCUSING_DOC,
+ ICommand,
+ ICommandInfo,
+ ICommandService,
+ IDocumentBody,
+ IMultiCommand,
+ IUndoRedoService,
+ IUniverInstanceService,
+} from '@univerjs/core';
export const DocCopyCommand: IMultiCommand = {
id: CopyCommand.id,
@@ -10,10 +25,7 @@ export const DocCopyCommand: IMultiCommand = {
multi: true,
priority: 1100,
preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),
- handler: async (accessor, params) => {
- const docClipboardService = accessor.get(IDocClipboardService);
- return docClipboardService.copy();
- },
+ handler: async () => true,
};
export const DocCutCommand: IMultiCommand = {
@@ -23,10 +35,7 @@ export const DocCutCommand: IMultiCommand = {
multi: true,
priority: 1100,
preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),
- handler: async (accessor, params) => {
- const docClipboardService = accessor.get(IDocClipboardService);
- return docClipboardService.cut();
- },
+ handler: async () => true,
};
export const DocPasteCommand: IMultiCommand = {
@@ -36,8 +45,89 @@ export const DocPasteCommand: IMultiCommand = {
multi: true,
priority: 1100,
preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),
- handler: async (accessor, params) => {
- const docClipboardService = accessor.get(IDocClipboardService);
- return docClipboardService.paste();
+ handler: async () => true,
+};
+
+export interface IInnerPasteCommandParams {
+ segmentId: string;
+ body: IDocumentBody;
+}
+
+export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
+ id: 'doc.command.inner-paste',
+ type: CommandType.COMMAND,
+ handler: async (accessor, params: IInnerPasteCommandParams) => {
+ const { segmentId, body } = 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)
+ );
+ }
+
+ doMutation.params!.mutations.push({
+ t: 'i',
+ body,
+ len: body.dataStream.length,
+ line: 0,
+ segmentId,
+ });
+
+ 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 38f9325f8e..18e0ade459 100644
--- a/packages/ui-plugin-docs/src/controllers/clipboard.controller.ts
+++ b/packages/ui-plugin-docs/src/controllers/clipboard.controller.ts
@@ -1,20 +1,221 @@
-import { Disposable, ICommandService, IUniverInstanceService } from '@univerjs/core';
+import { DocSkeletonManagerService, TextSelectionManagerService } from '@univerjs/base-docs';
+import { ITextSelectionRenderManager } from '@univerjs/base-render';
+import {
+ Disposable,
+ ICommandInfo,
+ ICommandService,
+ IDocumentBody,
+ ILogService,
+ IParagraph,
+ ITextRun,
+ IUniverInstanceService,
+ Tools,
+} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
-import { DocCopyCommand } from '../commands/commands/clipboard.command';
+import {
+ DocCopyCommand,
+ DocCutCommand,
+ DocPasteCommand,
+ InnerPasteCommand,
+} from '../commands/commands/clipboard.command';
import { IDocClipboardService } from '../services/clipboard/clipboard.service';
export class DocClipboardController extends Disposable {
constructor(
+ @ILogService private readonly _logService: ILogService,
@ICommandService private readonly _commandService: ICommandService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
- @IDocClipboardService private readonly _docClipboardService: IDocClipboardService
+ @IDocClipboardService private readonly _docClipboardService: IDocClipboardService,
+ @ITextSelectionRenderManager private _textSelectionRenderManager: ITextSelectionRenderManager,
+ @Inject(TextSelectionManagerService) private _textSelectionManagerService: TextSelectionManagerService,
+ @Inject(DocSkeletonManagerService) private _docSkeletonManagerService: DocSkeletonManagerService
) {
super();
+ this._commandExecutedListener();
}
initialize() {
- [DocCopyCommand, DocCopyCommand, DocCopyCommand].forEach((command) =>
+ [DocCopyCommand, DocCutCommand, DocPasteCommand].forEach((command) =>
this.disposeWithMe(this._commandService.registerAsMultipleCommand(command))
);
+ [InnerPasteCommand].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+ }
+
+ private _commandExecutedListener() {
+ const updateCommandList = [DocCutCommand.id, DocCopyCommand.id, DocPasteCommand.id];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (!updateCommandList.includes(command.id)) {
+ return;
+ }
+
+ switch (command.id) {
+ case DocPasteCommand.id: {
+ this._handlePaste();
+ break;
+ }
+
+ case DocCopyCommand.id: {
+ this._handleCopy();
+ break;
+ }
+
+ case DocCutCommand.id: {
+ this._handleCut();
+ break;
+ }
+
+ default:
+ throw new Error(`Unhandled command ${command.id}`);
+ }
+ })
+ );
+ }
+
+ private async _handlePaste() {
+ const { _docClipboardService: clipboard } = this;
+ 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;
+ }
+
+ try {
+ const body = await clipboard.queryClipboardData();
+
+ this._commandService.executeCommand(InnerPasteCommand.id, { body, segmentId });
+
+ // When doc has multiple selections, the cursor moves to the last pasted content's end.
+ let cursor = activeEndOffset;
+ for (const range of ranges) {
+ const { startOffset, endOffset } = range;
+
+ if (startOffset == null || endOffset == null) {
+ continue;
+ }
+
+ if (endOffset <= activeEndOffset) {
+ cursor += body.dataStream.length - (endOffset - startOffset);
+ }
+ }
+
+ // move selection
+ this._textSelectionManagerService.replace([
+ {
+ startOffset: cursor,
+ endOffset: cursor,
+ collapsed: true,
+ style,
+ },
+ ]);
+ } catch (_e) {
+ this._logService.error('[DocClipboardController] clipboard is empty');
+ }
+ }
+
+ private _getDocumentBodyInRanges(): IDocumentBody[] {
+ const ranges = this._textSelectionRenderManager.getAllTextRanges();
+ const skeletonObject = this._docSkeletonManagerService.getCurrent();
+
+ if (skeletonObject == null) {
+ return [];
+ }
+
+ const { skeleton } = skeletonObject;
+ const { dataStream, textRuns = [], paragraphs = [] } = skeleton.getModel().getBodyModel().getBody();
+
+ const results: IDocumentBody[] = [];
+
+ for (const range of ranges) {
+ const { startOffset, endOffset, collapsed } = range;
+
+ if (collapsed) {
+ continue;
+ }
+
+ if (startOffset == null || endOffset == null) {
+ continue;
+ }
+
+ const docBody: IDocumentBody = {
+ dataStream: dataStream.slice(startOffset, endOffset),
+ };
+
+ const newTextRuns: ITextRun[] = [];
+
+ for (const textRun of textRuns) {
+ const clonedTextRun = Tools.deepClone(textRun);
+ const { st, ed } = clonedTextRun;
+ if (Tools.hasIntersectionBetweenTwoRanges(st, ed, startOffset, endOffset)) {
+ if (startOffset >= st && startOffset <= ed) {
+ newTextRuns.push({
+ ...clonedTextRun,
+ st: startOffset,
+ ed: Math.min(endOffset, ed),
+ });
+ } else if (endOffset >= st && endOffset <= ed) {
+ newTextRuns.push({
+ ...clonedTextRun,
+ st: Math.max(startOffset, st),
+ ed: endOffset,
+ });
+ } else {
+ newTextRuns.push(clonedTextRun);
+ }
+ }
+ }
+
+ if (newTextRuns.length) {
+ docBody.textRuns = newTextRuns.map((tr) => {
+ const { st, ed } = tr;
+ return {
+ ...tr,
+ st: st - startOffset,
+ ed: ed - startOffset,
+ };
+ });
+ }
+
+ const newParagraphs: IParagraph[] = [];
+
+ for (const paragraph of paragraphs) {
+ const { startIndex } = paragraph;
+ if (startIndex >= startOffset && startIndex <= endOffset) {
+ newParagraphs.push(Tools.deepClone(paragraph));
+ }
+ }
+
+ if (newParagraphs.length) {
+ docBody.paragraphs = newParagraphs.map((p) => ({
+ ...p,
+ startIndex: p.startIndex - startOffset,
+ }));
+ }
+
+ results.push(docBody);
+ }
+
+ return results;
+ }
+
+ private async _handleCopy() {
+ console.log('copy');
+ const bodys = this._getDocumentBodyInRanges();
+ console.log(bodys);
+ }
+
+ private async _handleCut() {
+ console.log('cut');
}
}
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 6fb0d4c64a..bed2403ad6 100644
--- a/packages/ui-plugin-docs/src/services/clipboard/clipboard.service.ts
+++ b/packages/ui-plugin-docs/src/services/clipboard/clipboard.service.ts
@@ -1,7 +1,18 @@
-import { IClipboardInterfaceService } from '@univerjs/base-ui';
-import { Disposable, IUniverInstanceService, toDisposable } from '@univerjs/core';
+import {
+ HTML_CLIPBOARD_MIME_TYPE,
+ IClipboardInterfaceService,
+ PLAIN_TEXT_CLIPBOARD_MIME_TYPE,
+} from '@univerjs/base-ui';
+import { Disposable, IDocumentBody, IUniverInstanceService, toDisposable } from '@univerjs/core';
import { createIdentifier, IDisposable } from '@wendellhu/redi';
+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';
+
+HtmlToUDMService.use(PastePluginWord);
+HtmlToUDMService.use(PastePluginLark);
+
export interface IClipboardPropertyItem {}
export interface IDocClipboardHook {
@@ -10,9 +21,7 @@ export interface IDocClipboardHook {
}
export interface IDocClipboardService {
- copy(): Promise<boolean>;
- cut(): Promise<boolean>;
- paste(): Promise<boolean>;
+ queryClipboardData(): Promise<IDocumentBody>;
addClipboardHook(hook: IDocClipboardHook): IDisposable;
}
@@ -21,6 +30,7 @@ export const IDocClipboardService = createIdentifier<IDocClipboardService>('doc.
export class DocClipboardService extends Disposable implements IDocClipboardService {
private _clipboardHooks: IDocClipboardHook[] = [];
+ private htmlToUDM = new HtmlToUDMService();
constructor(
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@@ -29,22 +39,34 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
super();
}
- copy(): Promise<boolean> {
- throw new Error('Method not implemented.');
- }
+ async queryClipboardData(): Promise<IDocumentBody> {
+ const clipboardItems = await this._clipboardInterfaceService.read();
- cut(): Promise<boolean> {
- throw new Error('Method not implemented.');
- }
+ if (clipboardItems.length === 0) {
+ return Promise.reject();
+ }
+ const clipboardItem = clipboardItems[0];
+ 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());
- paste(): Promise<boolean> {
- throw new Error('Method not implemented.');
+ // console.log(text);
+ // console.log(html);
+ if (!html) {
+ // TODO: @JOCS, Parsing paragraphs and sections
+ return {
+ dataStream: text,
+ };
+ }
+
+ return this.htmlToUDM.convert(html);
}
addClipboardHook(hook: IDocClipboardHook): IDisposable {
this._clipboardHooks.push(hook);
+
return toDisposable(() => {
const index = this._clipboardHooks.indexOf(hook);
+
if (index > -1) {
this._clipboardHooks.splice(index, 1);
}
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
new file mode 100644
index 0000000000..55f615d538
--- /dev/null
+++ b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/converter.ts
@@ -0,0 +1,109 @@
+import { IDocumentBody, ITextStyle, Nullable } from '@univerjs/core';
+
+import extractNodeStyle from './parse-node-style';
+import parseToDom from './parse-to-dom';
+import { IAfterProcessRule, IPastePlugin, IStyleRule } from './paste-plugins/type';
+
+function matchFilter(node: HTMLElement, filter: IStyleRule['filter']) {
+ const tagName = node.tagName.toLowerCase();
+
+ if (typeof filter === 'string') {
+ return tagName === filter;
+ }
+
+ if (Array.isArray(filter)) {
+ return filter.some((name) => name === tagName);
+ }
+
+ return filter(node);
+}
+
+/**
+ * Convert html strings into data structures in univer, IDocumentBody.
+ * Support plug-in, add custom rules,
+ */
+export class HtmlToUDMService {
+ private static pluginList: IPastePlugin[] = [];
+
+ static use(plugin: IPastePlugin) {
+ if (this.pluginList.includes(plugin)) {
+ throw new Error(`Univer paste plugin ${plugin.name} already added`);
+ }
+
+ this.pluginList.push(plugin);
+ }
+
+ private styleCache: Map<ChildNode, ITextStyle> = new Map();
+
+ private styleRules: IStyleRule[] = [];
+
+ private afterProcessRules: IAfterProcessRule[] = [];
+
+ convert(html: string): IDocumentBody {
+ const pastePlugin = HtmlToUDMService.pluginList.find((plugin) => plugin.checkPasteType(html));
+
+ const dom = parseToDom(html);
+
+ const newDocBody: IDocumentBody = {
+ dataStream: '',
+ textRuns: [],
+ };
+
+ if (pastePlugin) {
+ this.styleRules = [...pastePlugin.stylesRules];
+ this.afterProcessRules = [...pastePlugin.afterProcessRules];
+ }
+
+ this.styleCache.clear();
+ this.process(null, dom?.childNodes!, newDocBody);
+ this.styleCache.clear();
+ this.styleRules = [];
+ this.afterProcessRules = [];
+
+ return newDocBody;
+ }
+
+ private process(parent: Nullable<ChildNode>, nodes: NodeListOf<ChildNode>, doc: IDocumentBody) {
+ 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, '');
+ let style;
+
+ if (parent && this.styleCache.has(parent)) {
+ style = this.styleCache.get(parent);
+ }
+
+ doc.dataStream += text;
+
+ if (style && Object.getOwnPropertyNames(style).length) {
+ doc.textRuns!.push({
+ st: doc.dataStream.length - text!.length,
+ ed: doc.dataStream.length,
+ ts: style,
+ });
+ }
+ } else if (node.nodeType === Node.ELEMENT_NODE) {
+ const parentStyles = parent ? this.styleCache.get(parent) : {};
+ const styleRule = this.styleRules.find(({ filter }) => matchFilter(node as HTMLElement, filter));
+ const nodeStyles = styleRule
+ ? styleRule.getStyle(node as HTMLElement)
+ : extractNodeStyle(node as HTMLElement);
+
+ this.styleCache.set(node, { ...parentStyles, ...nodeStyles });
+
+ const { childNodes } = node;
+
+ this.process(node, childNodes, doc);
+
+ const afterProcessRule = this.afterProcessRules.find(({ filter }) =>
+ matchFilter(node as HTMLElement, filter)
+ );
+
+ if (afterProcessRule) {
+ afterProcessRule.handler(doc, node as HTMLElement);
+ }
+ }
+ }
+ }
+}
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
new file mode 100644
index 0000000000..458d5f8013
--- /dev/null
+++ b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/parse-node-style.ts
@@ -0,0 +1,124 @@
+import { BaselineOffset, BooleanNumber, ITextStyle } from '@univerjs/core';
+
+import { ptToPixel } from './utils';
+
+export default function extractNodeStyle(node: HTMLElement): ITextStyle {
+ const styles = node.style;
+ const docStyles: ITextStyle = {};
+ const tagName = node.tagName.toLowerCase();
+
+ switch (tagName) {
+ case 'b':
+ case 'em':
+ case 'strong': {
+ docStyles.bl = BooleanNumber.TRUE;
+ break;
+ }
+
+ case 's': {
+ docStyles.st = {
+ s: BooleanNumber.TRUE,
+ };
+ break;
+ }
+
+ case 'u': {
+ docStyles.ul = {
+ s: BooleanNumber.TRUE,
+ };
+ break;
+ }
+
+ case 'i': {
+ docStyles.it = BooleanNumber.TRUE;
+ break;
+ }
+
+ case 'sub':
+ case 'sup': {
+ docStyles.va = tagName === 'sup' ? BaselineOffset.SUPERSCRIPT : BaselineOffset.SUBSCRIPT;
+ break;
+ }
+ }
+
+ for (let i = 0; i < styles.length; i++) {
+ const cssRule = styles[i];
+ const cssValue = styles.getPropertyValue(cssRule);
+
+ switch (cssRule) {
+ case 'font-family': {
+ docStyles.ff = cssValue;
+
+ break;
+ }
+
+ case 'font-size': {
+ const fontSize = parseInt(cssValue);
+ // TODO: @JOCS, hand other CSS value unit, rem, em, pt, %
+ docStyles.fs = /pt$/.test(cssValue) ? ptToPixel(fontSize) : fontSize;
+
+ break;
+ }
+
+ case 'font-style': {
+ if (cssValue === 'italic') {
+ docStyles.it = BooleanNumber.TRUE;
+ }
+
+ break;
+ }
+
+ case 'font-weight': {
+ const MIDDLE_FONT_WEIGHT = 400;
+
+ if (Number(cssValue) > MIDDLE_FONT_WEIGHT) {
+ docStyles.bl = BooleanNumber.TRUE;
+ }
+
+ break;
+ }
+
+ case 'text-decoration': {
+ // TODO: @JOCS, Parse CSS values like: underline dotted;
+ if (/underline/.test(cssValue)) {
+ docStyles.ul = {
+ s: BooleanNumber.TRUE,
+ };
+ } else if (/overline/.test(cssValue)) {
+ docStyles.ol = {
+ s: BooleanNumber.TRUE,
+ };
+ } else if (/line-through/.test(cssValue)) {
+ docStyles.st = {
+ s: BooleanNumber.TRUE,
+ };
+ }
+
+ break;
+ }
+
+ case 'color': {
+ docStyles.cl = {
+ rgb: cssValue,
+ };
+
+ break;
+ }
+
+ case 'background-color': {
+ docStyles.bg = {
+ rgb: cssValue,
+ };
+
+ break;
+ }
+
+ default: {
+ // console.log(`Unhandled css rule ${cssRule}`);
+ break;
+ }
+ }
+ }
+
+ return docStyles;
+}
diff --git a/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/parse-to-dom.ts b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/parse-to-dom.ts
new file mode 100644
index 0000000000..efdba9bc0d
--- /dev/null
+++ b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/parse-to-dom.ts
@@ -0,0 +1,7 @@
+export default function parseToDom(rawHtml: string) {
+ const parser = new DOMParser();
+ const html = `<x-univer id="univer-root">${rawHtml}</x-univer>`;
+ const doc = parser.parseFromString(html, 'text/html');
+
+ return doc.querySelector('#univer-root');
+}
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
new file mode 100644
index 0000000000..2f2fcaa36d
--- /dev/null
+++ b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/paste-plugins/plugin-lark.ts
@@ -0,0 +1,47 @@
+import { BooleanNumber } from '@univerjs/core';
+
+import getInlineStyle from '../parse-node-style';
+import { IPastePlugin } from './type';
+
+const wordPastePlugin: IPastePlugin = {
+ name: 'univer-doc-paste-plugin-lark',
+ checkPasteType(html: string) {
+ return /lark-record-clipboard/i.test(html);
+ },
+ // TODO: @JOCS, support inline code copy from lark.
+ stylesRules: [
+ {
+ filter: ['s'],
+ getStyle(node) {
+ const inlineStyle = getInlineStyle(node);
+
+ return {
+ st: {
+ s: BooleanNumber.TRUE,
+ },
+ ...inlineStyle,
+ };
+ },
+ },
+ ],
+
+ afterProcessRules: [
+ {
+ filter(el: HTMLElement) {
+ return el.tagName === 'DIV' && /ace-line/i.test(el.className);
+ },
+ handler(doc) {
+ if (doc.paragraphs == null) {
+ doc.paragraphs = [];
+ }
+
+ doc.paragraphs.push({
+ startIndex: doc.dataStream.length,
+ });
+ doc.dataStream += '\r';
+ },
+ },
+ ],
+};
+
+export default wordPastePlugin;
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
new file mode 100644
index 0000000000..fdcf90c38d
--- /dev/null
+++ b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.ts
@@ -0,0 +1,51 @@
+import { BooleanNumber, IParagraph } from '@univerjs/core';
+
+import getInlineStyle from '../parse-node-style';
+import { getParagraphStyle } from '../utils';
+import { IPastePlugin } from './type';
+
+const wordPastePlugin: IPastePlugin = {
+ name: 'univer-doc-paste-plugin-word',
+ checkPasteType(html: string) {
+ return /word|mso/i.test(html);
+ },
+
+ stylesRules: [
+ {
+ filter: ['b'],
+ getStyle(node) {
+ const inlineStyle = getInlineStyle(node);
+
+ return { bl: BooleanNumber.TRUE, ...inlineStyle };
+ },
+ },
+ ],
+
+ afterProcessRules: [
+ {
+ filter(el: HTMLElement) {
+ return el.tagName === 'P' && /mso/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 wordPastePlugin;
diff --git a/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/paste-plugins/type.ts b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/paste-plugins/type.ts
new file mode 100644
index 0000000000..ac6934c1f6
--- /dev/null
+++ b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/paste-plugins/type.ts
@@ -0,0 +1,18 @@
+import { IDocumentBody, ITextStyle } from '@univerjs/core';
+
+export interface IStyleRule {
+ filter: string | string[] | ((node: HTMLElement) => boolean);
+ getStyle(node: HTMLElement): ITextStyle;
+}
+
+export interface IAfterProcessRule {
+ filter: string | string[] | ((node: HTMLElement) => boolean);
+ handler(doc: IDocumentBody, node: HTMLElement): void;
+}
+
+export interface IPastePlugin {
+ name: string;
+ checkPasteType(html: string): boolean;
+ stylesRules: IStyleRule[];
+ afterProcessRules: IAfterProcessRule[];
+}
diff --git a/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/utils.ts b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/utils.ts
new file mode 100644
index 0000000000..b4337af90b
--- /dev/null
+++ b/packages/ui-plugin-docs/src/services/clipboard/html-to-udm/utils.ts
@@ -0,0 +1,42 @@
+import { IParagraphStyle, Nullable } from '@univerjs/core';
+
+// TODO: @JOCS, Complete other missing attributes that exist in IParagraphStyle
+export function getParagraphStyle(el: HTMLElement): Nullable<IParagraphStyle> {
+ const styles = el.style;
+
+ const paragraphStyle: IParagraphStyle = {};
+
+ for (let i = 0; i < styles.length; i++) {
+ const cssRule = styles[i];
+ const cssValue = styles.getPropertyValue(cssRule);
+
+ switch (cssRule) {
+ case 'margin-top': {
+ const marginTopValue = parseInt(cssValue);
+ paragraphStyle.spaceAbove = /pt/.test(cssValue) ? ptToPixel(marginTopValue) : marginTopValue;
+ break;
+ }
+
+ case 'margin-bottom': {
+ const marginBottomValue = parseInt(cssValue);
+ paragraphStyle.spaceBelow = /pt/.test(cssValue) ? ptToPixel(marginBottomValue) : marginBottomValue;
+
+ break;
+ }
+
+ default: {
+ // console.log(`Unhandled css rule ${cssRule} in getParagraphStyle`);
+ break;
+ }
+ }
+ }
+
+ return Object.getOwnPropertyNames(paragraphStyle).length ? paragraphStyle : null;
+}
+
+export function ptToPixel(pt: number) {
+ // 1 pixel * 0.75 = 1 pt
+ const PX_TO_PT_RATIO = 0.75;
+
+ return pt / PX_TO_PT_RATIO;
+}
diff --git a/packages/ui-plugin-docs/vitest.config.ts b/packages/ui-plugin-docs/vitest.config.ts
index 3c74cf802f..e840ca961a 100644
--- a/packages/ui-plugin-docs/vitest.config.ts
+++ b/packages/ui-plugin-docs/vitest.config.ts
@@ -2,6 +2,7 @@ import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
+ environment: 'happy-dom',
coverage: {
provider: 'istanbul',
},
diff --git a/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts b/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts
index e4d8baf1cf..2a6609bb99 100644
--- a/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts
+++ b/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts
@@ -46,6 +46,7 @@ export const SheetPasteCommand: IMultiCommand = {
logService.log('[SheetPasteCommand]', 'the focusing element is', document.activeElement);
const result = document.execCommand('paste');
+
if (!result) {
logService.log(
'[SheetPasteCommand]',
diff --git a/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts b/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts
index f55e3a71ee..27c9f5a5a2 100644
--- a/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts
+++ b/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts
@@ -185,6 +185,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
const colStyles = getColStyle(getArrayFromTo(startColumn, endColumn), hooks);
// row styles and table contents
const rowContents: string[] = [];
+
matrix.forRow((row, cols) => {
// TODO: cols here should filtered out those in span cells
rowContents.push(getRowContent(row, cols, hooks, matrix));
@@ -736,6 +737,7 @@ function getTDContent(
const mergedProperties = mergeProperties(properties);
const str = zipClipboardPropertyItemToString(mergedProperties);
const content = hooks.reduce((acc, hook) => acc || hook.onCopyCellContent?.(row, col) || '', '');
+
return `<td${str}>${content}</td>`;
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0219f44983..eb61586dce 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1186,6 +1186,9 @@ importers:
'@vitest/coverage-istanbul':
specifier: ^0.34.6
version: 0.34.6([email protected])
+ happy-dom:
+ specifier: ^12.10.3
+ version: 12.10.3
less:
specifier: ^4.2.0
version: 4.2.0