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.

fix(docs-ui): keep callout content paste valid in code blocks (#7944)

白熱b2ece9b1cd24
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/utils.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/utils.spec.ts
index f3cbedda4a..54d59562d7 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/utils.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/utils.spec.ts
@@ -14,17 +14,75 @@
* limitations under the License.
*/
+import { describe, expect, it, vi } from 'vitest';
import type { IDocumentBody } from '../../../../types/interfaces/i-document-data';
import type { IRetainAction } from '../action-types';
-import { describe, expect, it, vi } from 'vitest';
import { Tools } from '../../../../shared/tools';
import { BooleanNumber } from '../../../../types/enum/text-style';
-import { CustomRangeType } from '../../../../types/interfaces/i-document-data';
+import { CustomRangeType, DocumentBlockRangeType } from '../../../../types/interfaces/i-document-data';
import { PresetListType } from '../../preset-list-type';
+import { DataStreamTreeTokenType } from '../../types';
import { TextXActionType } from '../action-types';
-import { composeBody, getBodySlice, getTextRunSlice, isUselessRetainAction, SliceBodyType } from '../utils';
+import {
+ composeBody,
+ getBodySlice,
+ getBodySliceForTextXAction,
+ getTextRunSlice,
+ isUselessRetainAction,
+ SliceBodyType,
+} from '../utils';
describe('test text-x utils', () => {
+ it.each([SliceBodyType.copy, SliceBodyType.cut])('keeps both block sentinels in complete action slices (%s)', (type) => {
+ const tokens = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `A\r${tokens.BLOCK_START}B\r${tokens.BLOCK_END}C\r\n`,
+ blockRanges: [{
+ blockId: 'callout',
+ blockType: DocumentBlockRangeType.CALLOUT,
+ startIndex: 2,
+ endIndex: 5,
+ }],
+ };
+
+ expect(getBodySliceForTextXAction(body, 2, 5, false, type).blockRanges).toBeUndefined();
+ expect(getBodySliceForTextXAction(body, 3, 6, false, type).blockRanges).toBeUndefined();
+ const complete = getBodySliceForTextXAction(body, 2, 6, false, type);
+ expect(complete.blockRanges).toEqual([{
+ blockId: 'callout',
+ blockType: DocumentBlockRangeType.CALLOUT,
+ startIndex: 0,
+ endIndex: 3,
+ }]);
+ complete.blockRanges![0].blockId = 'pasted-callout';
+ expect(body.blockRanges![0].blockId).toBe('callout');
+
+ expect(getBodySlice(body, 3, 5, false, type).blockRanges).toEqual([{
+ blockId: 'callout',
+ blockType: DocumentBlockRangeType.CALLOUT,
+ startIndex: 0,
+ endIndex: 2,
+ }]);
+ });
+
+ it('keeps complete column groups in clipboard slices', () => {
+ const tokens = DataStreamTreeTokenType;
+ const columns = `${tokens.COLUMN_GROUP_START}${tokens.COLUMN_START}Alpha\r${tokens.COLUMN_END}${tokens.COLUMN_GROUP_END}`;
+ const body: IDocumentBody = {
+ dataStream: `A\r${columns}\r\n`,
+ columnGroups: [{ columnGroupId: 'columns', startIndex: 2, endIndex: columns.length + 1 }],
+ };
+
+ const slice = getBodySliceForTextXAction(body, 2, columns.length + 2, false, SliceBodyType.copy);
+
+ expect(slice.dataStream).toBe(columns);
+ expect(slice.columnGroups).toEqual([{
+ columnGroupId: 'columns',
+ startIndex: 0,
+ endIndex: columns.length - 1,
+ }]);
+ });
+
it('only clones text runs intersecting the requested slice', () => {
const body: IDocumentBody = {
dataStream: 'a'.repeat(10_000),
diff --git a/packages/core/src/docs/data-model/text-x/utils.ts b/packages/core/src/docs/data-model/text-x/utils.ts
index 630773ecee..d0cb244690 100644
--- a/packages/core/src/docs/data-model/text-x/utils.ts
+++ b/packages/core/src/docs/data-model/text-x/utils.ts
@@ -27,7 +27,7 @@ import type {
ISectionBreak,
ITextRun,
} from '../../../types/interfaces/i-document-data';
-import type { DocumentDataModel } from '../../data-model';
+import type { DocumentDataModel } from '../document-data-model';
import type { IRetainAction } from './action-types';
import { merge } from '../../../common/lodash';
import { UpdateDocsAttributeType } from '../../../shared/command-enum';
@@ -45,9 +45,9 @@ export enum SliceBodyType {
}
export enum SliceStructuralRangeMode {
- // General copy/slice behavior: keep the intersecting portion for backward compatibility.
+ // General slices keep the intersecting portion of each structural range.
intersect,
- // Mutation builders: only emit metadata for structural ranges fully carried by this action body.
+ // Mutation and clipboard bodies only carry complete structural ranges.
contained,
// ActionIterator splits: keep metadata on the chunk that carries the structural range end.
ending,
@@ -166,15 +166,19 @@ export function getBlockRangeSlice(
const newBlockRanges: IDocumentBlockRange[] = [];
for (const blockRange of blockRanges) {
- const clonedBlockRange = Tools.deepClone(blockRange);
- const { startIndex, endIndex } = clonedBlockRange;
+ const { startIndex, endIndex } = blockRange;
+ const included = mode === SliceStructuralRangeMode.contained
+ ? startIndex >= startOffset && endIndex < endOffset
+ : hasStructuralRangeInSlice(startIndex, endIndex, startOffset, endOffset, mode);
- if (hasStructuralRangeInSlice(startIndex, endIndex, startOffset, endOffset, mode)) {
- newBlockRanges.push({
- ...clonedBlockRange,
- ...getSlicedStructuralRange(startIndex, endIndex, startOffset, endOffset, mode),
- });
+ if (!included) {
+ continue;
}
+
+ newBlockRanges.push({
+ ...blockRange,
+ ...getSlicedStructuralRange(startIndex, endIndex, startOffset, endOffset, mode),
+ });
}
return newBlockRanges;
diff --git a/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts b/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts
index 827ee8c5b5..0c167c17b7 100644
--- a/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts
+++ b/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts
@@ -15,6 +15,7 @@
*/
import type { IDocumentBody, IDocumentData } from '@univerjs/core';
+import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { IDocImage } from '@univerjs/docs-drawing';
import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';
import {
@@ -46,6 +47,7 @@ import {
Univer,
UniverInstanceType,
validateDocBodyStructure,
+ validateDocumentStructure,
} from '@univerjs/core';
import {
DocSelectionManagerService,
@@ -543,6 +545,39 @@ describe('DocClipboardService table copy helpers', () => {
}
});
+ it.each([SliceBodyType.copy, SliceBodyType.cut])('copies column text without recreating its containing group (%s)', async (sliceType) => {
+ const tokens = DataStreamTreeTokenType;
+ const columnStream = `${tokens.COLUMN_GROUP_START}${tokens.COLUMN_START}Alpha\r${tokens.COLUMN_END}${tokens.COLUMN_GROUP_END}`;
+ const documentData: IDocumentData = {
+ id: 'copy-column-text',
+ documentStyle: {},
+ body: {
+ dataStream: `${columnStream}\r\n`,
+ paragraphs: [{ paragraphId: 'column-alpha', startIndex: 7 }],
+ columnGroups: [{ columnGroupId: 'columns', startIndex: 0, endIndex: columnStream.length - 1 }],
+ },
+ };
+ const testBed = createCommandTestBed(documentData, [
+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],
+ [IDocClipboardService, { useClass: DocClipboardService }],
+ ]);
+ try {
+ const service = testBed.get(IDocClipboardService);
+ const clipboard = testBed.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;
+ expect(await service.copy(sliceType, [{
+ startOffset: 2,
+ endOffset: 7,
+ collapsed: false,
+ segmentId: '',
+ }])).toBe(true);
+ const fragment = parseInternalClipboardFragment(clipboard.writes[0].custom?.[DOC_INTERNAL_FRAGMENT_MIME]);
+ expect(fragment?.body?.dataStream).toBe('Alpha');
+ expect(fragment?.body?.columnGroups ?? []).toEqual([]);
+ } finally {
+ testBed.univer.dispose();
+ }
+ });
+
it('returns false when writing copied content to the clipboard fails', async () => {
const documentData: IDocumentData = {
id: 'failed-copy-doc',
@@ -989,6 +1024,86 @@ describe('DocClipboardService table copy helpers', () => {
testBed.univer.dispose();
});
+ it.each([false, true])('keeps collaboration structure valid when pasting callout content into code (paragraph: %s)', async (includeParagraph) => {
+ const tokens = DataStreamTreeTokenType;
+ const code = `${tokens.BLOCK_START}Code${tokens.PARAGRAPH}${tokens.BLOCK_END}`;
+ const callout = `${tokens.BLOCK_START}Callout${tokens.PARAGRAPH}${tokens.BLOCK_END}`;
+ const clipboardInterface = new TestClipboardInterfaceService();
+ const testBed = createCommandTestBed({
+ id: 'callout-into-code',
+ documentStyle: {},
+ body: {
+ dataStream: `${code}${callout}\r\n`,
+ customBlocks: [],
+ customDecorations: [],
+ customRanges: [],
+ paragraphs: [
+ { startIndex: code.length - 2, paragraphId: 'code-paragraph' },
+ { startIndex: code.length + callout.length - 2, paragraphId: 'callout-paragraph' },
+ { startIndex: code.length + callout.length, paragraphId: 'root-paragraph' },
+ ],
+ sectionBreaks: [{ startIndex: code.length + callout.length + 1, sectionId: 'root-section' }],
+ blockRanges: [
+ { startIndex: 0, endIndex: code.length - 1, blockId: 'code', blockType: DocumentBlockRangeType.CODE },
+ { startIndex: code.length, endIndex: code.length + callout.length - 1, blockId: 'callout', blockType: DocumentBlockRangeType.CALLOUT },
+ ],
+ },
+ }, [
+ [IClipboardInterfaceService, { useValue: clipboardInterface }],
+ [IDocClipboardService, { useClass: DocClipboardService }],
+ ]);
+ const before = Tools.deepClone(testBed.doc.getSnapshot());
+ const remote = new DocumentDataModel(Tools.deepClone(before));
+ const commands = testBed.get(ICommandService);
+ const listener = commands.onMutationExecutedForCollab((command) => {
+ if (command.id === RichTextEditingMutation.id) {
+ remote.apply((command.params as IRichTextEditingMutationParams).actions);
+ }
+ });
+ try {
+ [InnerPasteCommand, RichTextEditingMutation, SetTextSelectionsOperation]
+ .forEach((command) => commands.registerCommand(command));
+ const selections = testBed.get(DocSelectionManagerService);
+ selections.__TEST_ONLY_setCurrentSelection({ unitId: testBed.doc.getUnitId(), subUnitId: '' });
+ const clipboard = testBed.get(IDocClipboardService);
+ expect(validateDocumentStructure(testBed.doc.getSnapshot())).toEqual([]);
+ expect(await clipboard.copy(SliceBodyType.copy, [{
+ startOffset: code.length + 1,
+ endOffset: code.length + callout.length - (includeParagraph ? 1 : 2),
+ collapsed: false,
+ segmentId: '',
+ }])).toBe(true);
+ const copied = parseInternalClipboardFragment(clipboardInterface.writes[0].custom?.[DOC_INTERNAL_FRAGMENT_MIME]);
+ expect(copied?.body?.blockRanges ?? []).toEqual([]);
+ selections.__TEST_ONLY_add([{
+ startOffset: 2,
+ endOffset: 2,
+ collapsed: true,
+ isActive: true,
+ segmentId: '',
+ }]);
+
+ expect(await clipboard.paste()).toBe(true);
+ const inserted = includeParagraph ? 'Callout\r' : 'Callout';
+ expect(testBed.doc.getBody()?.dataStream).toBe(`${code.slice(0, 2)}${inserted}${code.slice(2)}${callout}\r\n`);
+ expect(testBed.doc.getBody()?.blockRanges?.map((block) => block.blockId)).toEqual(['code', 'callout']);
+ expect(validateDocumentStructure(testBed.doc.getSnapshot())).toEqual([]);
+ const after = Tools.deepClone(testBed.doc.getSnapshot());
+ expect(remote.getSnapshot()).toEqual(after);
+
+ expect(await commands.executeCommand(UndoCommand.id)).toBe(true);
+ expect(testBed.doc.getSnapshot()).toEqual(before);
+ expect(remote.getSnapshot()).toEqual(before);
+ expect(await commands.executeCommand(RedoCommand.id)).toBe(true);
+ expect(testBed.doc.getSnapshot()).toEqual(after);
+ expect(remote.getSnapshot()).toEqual(after);
+ } finally {
+ listener.dispose();
+ remote.dispose();
+ testBed.univer.dispose();
+ }
+ });
+
it('copies and pastes a complete block range after itself', async () => {
const tokens = DataStreamTreeTokenType;
const blockStream = `${tokens.BLOCK_START}Callout${tokens.PARAGRAPH}${tokens.BLOCK_END}`;
diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
index 5d6bd7e68f..6310fb640c 100644
--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
@@ -33,6 +33,7 @@ import {
ErrorService,
generateRandomId,
getBodySlice,
+ getBodySliceForTextXAction,
ICommandService,
ILogService,
ImageSourceType,
@@ -875,23 +876,19 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
plainTextList?: readonly string[]
): Promise<void> {
const copyId = generateRandomId(6);
- const text =
- (plainTextList
- ? plainTextList.join('\n')
- : documentList.length > 1
- ? documentList.map((doc) => doc.body?.dataStream || '').join('\n')
- : documentList[0].body?.dataStream || '')
- .replaceAll(DataStreamTreeTokenType.TABLE_START, '')
- .replaceAll(DataStreamTreeTokenType.TABLE_END, '')
- .replaceAll(DataStreamTreeTokenType.TABLE_ROW_START, '')
- .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', ' ')
- .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, '');
+ const text = (plainTextList ?? documentList.map((doc) => doc.body?.dataStream || ''))
+ .join('\n')
+ .replaceAll(DataStreamTreeTokenType.TABLE_START, '')
+ .replaceAll(DataStreamTreeTokenType.TABLE_END, '')
+ .replaceAll(DataStreamTreeTokenType.TABLE_ROW_START, '')
+ .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', ' ')
+ .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, '');
let html = this._umdToHtml.convert(documentList);
let internalJson = '';
@@ -991,26 +988,13 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
continue;
}
- const deleteRange = { startOffset, endOffset, collapsed };
-
- const docBody = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.sliceBody(deleteRange.startOffset, deleteRange.endOffset, sliceType);
- if (docBody == null) {
- continue;
- }
-
- // Text inside a cell is not a nested table. Keep only completely copied table structures.
- if (docBody.tables?.length) {
- const completeTableIds = new Set(body.tables?.filter((table) => (
- table.startIndex >= startOffset && table.endIndex <= endOffset
- )).map((table) => table.tableId));
- docBody.tables = docBody.tables.filter((table) => completeTableIds.has(table.tableId));
- }
+ const docBody = getBodySliceForTextXAction(body, startOffset, endOffset, false, sliceType);
results.push(docBody);
plainTextResults.push(
copyContentHook?.(
- deleteRange.startOffset,
- deleteRange.endOffset,
+ startOffset,
+ endOffset,
{
body,
segmentId,