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): stabilize structural text editing (#7223)

Univer4943935f268f
diff --git a/packages/core/src/docs/data-model/index.ts b/packages/core/src/docs/data-model/index.ts
index 6c5903c9f6..e874345ed2 100644
--- a/packages/core/src/docs/data-model/index.ts
+++ b/packages/core/src/docs/data-model/index.ts
@@ -38,11 +38,15 @@ export { updateAttributeByDelete } from './text-x/apply-utils/delete-apply';
export { updateAttributeByInsert } from './text-x/apply-utils/insert-apply';
export * from './text-x/build-utils';
export { getPlainText } from './text-x/build-utils/parse';
+export { validateDocBodyStructure, validateDocumentStructure } from './text-x/structure-validator';
+export type { DocStructureIssueCode, IDocStructureIssue } from './text-x/structure-validator';
export { TextX } from './text-x/text-x';
export type { TPriority } from './text-x/text-x';
export {
composeBody,
getBodySlice,
+ getBodySliceForSplitTextXAction,
+ getBodySliceForTextXAction,
getCustomBlockSlice,
getCustomDecorationSlice,
getCustomRangeSlice,
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/action-iterator.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/action-iterator.spec.ts
index 5c6abd06ab..9c63ddab18 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/action-iterator.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/action-iterator.spec.ts
@@ -16,8 +16,10 @@
import { describe, expect, it } from 'vitest';
import { BooleanNumber } from '../../../../types/enum/text-style';
+import { DataStreamTreeTokenType } from '../../types';
import { ActionIterator } from '../action-iterator';
import { TextXActionType } from '../action-types';
+import { TextX } from '../text-x';
describe('Test action iterator', () => {
it('test action iterator basic use', () => {
@@ -152,4 +154,41 @@ describe('Test action iterator', () => {
len: 5,
}]);
});
+
+ it('preserves table metadata on the chunk containing the table end when an insert action is split', () => {
+ const T = DataStreamTreeTokenType;
+ const tableStream = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.PARAGRAPH}`;
+ const iterator = new ActionIterator([{
+ t: TextXActionType.INSERT,
+ body: {
+ dataStream: tableStream,
+ tables: [{ startIndex: 0, endIndex: tableStream.length, tableId: 'table-1' }],
+ },
+ len: tableStream.length,
+ }]);
+
+ const partialAction = iterator.next(4);
+ const restAction = iterator.next();
+
+ expect(partialAction.body?.tables).toBeUndefined();
+ expect(restAction.body?.tables).toEqual([{ startIndex: -4, endIndex: tableStream.length - 4, tableId: 'table-1' }]);
+
+ const body = { dataStream: '' };
+ TextX.apply(body, [partialAction, restAction]);
+ expect(body).toMatchObject({
+ dataStream: tableStream,
+ tables: [{ startIndex: 0, endIndex: tableStream.length, tableId: 'table-1' }],
+ });
+
+ const fullIterator = new ActionIterator([{
+ t: TextXActionType.INSERT,
+ body: {
+ dataStream: tableStream,
+ tables: [{ startIndex: 0, endIndex: tableStream.length, tableId: 'table-1' }],
+ },
+ len: tableStream.length,
+ }]);
+
+ expect(fullIterator.next().body?.tables).toEqual([{ startIndex: 0, endIndex: tableStream.length, tableId: 'table-1' }]);
+ });
});
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.ts
index 19d1a9aa7d..ed1be2eec2 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.ts
@@ -20,7 +20,7 @@ import { describe, expect, it } from 'vitest';
import { DataStreamTreeTokenType } from '../../types';
import { deleteBlockRanges, insertBlockRanges } from '../apply-utils/common';
import { getPlainText } from '../build-utils/parse';
-import { getBodySlice } from '../utils';
+import { getBodySlice, getBodySliceForTextXAction } from '../utils';
describe('document block ranges', () => {
it('moves following block ranges when text is inserted before them', () => {
@@ -63,6 +63,18 @@ describe('document block ranges', () => {
]);
});
+ it('does not include partial block ranges in action bodies', () => {
+ const body: IDocumentBody = {
+ dataStream: `A\r${DataStreamTreeTokenType.BLOCK_START}B\r${DataStreamTreeTokenType.BLOCK_END}C\r\n`,
+ blockRanges: [{ blockId: 'callout-1', blockType: DocumentBlockRangeType.CALLOUT, startIndex: 2, endIndex: 5 }],
+ };
+
+ const slice = getBodySliceForTextXAction(body, 3, 5, false);
+
+ expect(slice.dataStream).toBe('B\r');
+ expect(slice.blockRanges).toBeUndefined();
+ });
+
it('removes fully deleted block ranges', () => {
const body: IDocumentBody = {
dataStream: `${DataStreamTreeTokenType.BLOCK_START}A\r${DataStreamTreeTokenType.BLOCK_END}\n`,
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/body-structure-validator.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/body-structure-validator.spec.ts
new file mode 100644
index 0000000000..53cd1b5354
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/__tests__/body-structure-validator.spec.ts
@@ -0,0 +1,128 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentBody } from '../../../../types/interfaces';
+import { describe, expect, it } from 'vitest';
+import { DataStreamTreeTokenType } from '../../types';
+import { validateDocBodyStructure, validateDocumentStructure } from '../structure-validator';
+
+describe('validateDocBodyStructure', () => {
+ it('accepts a valid plain document body', () => {
+ const body: IDocumentBody = {
+ dataStream: `A${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 1, paragraphId: 'para-1' }],
+ sectionBreaks: [{ startIndex: 2 }],
+ };
+
+ expect(validateDocBodyStructure(body)).toEqual([]);
+ });
+
+ it('reports root bodies without a minimum paragraph and section pair', () => {
+ const body: IDocumentBody = {
+ dataStream: 'A',
+ };
+
+ expect(validateDocBodyStructure(body).map((issue) => issue.code)).toEqual([
+ 'missing-root-paragraph',
+ 'missing-root-section-break',
+ ]);
+ });
+
+ it('reports paragraph and section metadata that do not point to matching tokens', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 4, paragraphId: 'bad-para' }],
+ sectionBreaks: [{ startIndex: 5 }],
+ columnGroups: [{ startIndex: 0, endIndex: 5, columnGroupId: 'cg-1' }],
+ };
+
+ expect(validateDocBodyStructure(body).map((issue) => issue.code)).toEqual([
+ 'paragraph-token-mismatch',
+ 'section-break-token-mismatch',
+ ]);
+ });
+
+ it('reports columns that have no paragraph or section child', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 5, paragraphId: 'root' }],
+ sectionBreaks: [{ startIndex: 6 }],
+ columnGroups: [{ startIndex: 0, endIndex: 4, columnGroupId: 'cg-1' }],
+ };
+
+ expect(validateDocBodyStructure(body).map((issue) => issue.code)).toContain('empty-column');
+ });
+
+ it('reports table cells that have no section child', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}A${T.PARAGRAPH}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 4, paragraphId: 'cell' },
+ { startIndex: 8, paragraphId: 'after-table' },
+ ],
+ sectionBreaks: [{ startIndex: 9 }],
+ tables: [{ startIndex: 0, endIndex: 8, tableId: 'table-1' }],
+ };
+
+ expect(validateDocBodyStructure(body).map((issue) => issue.code)).toContain('empty-table-cell');
+ });
+
+ it('reports unbalanced structural tokens', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 3, paragraphId: 'para-1' }],
+ sectionBreaks: [{ startIndex: 5 }],
+ };
+
+ expect(validateDocBodyStructure(body).map((issue) => issue.code)).toContain('unbalanced-column-group');
+ });
+
+ it('validates header and footer bodies with segment diagnostics', () => {
+ const T = DataStreamTreeTokenType;
+ const issues = validateDocumentStructure({
+ body: {
+ dataStream: `${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 0, paragraphId: 'body' }],
+ sectionBreaks: [{ startIndex: 1 }],
+ },
+ headers: {
+ 'header-1': {
+ headerId: 'header-1',
+ body: { dataStream: 'bad-header' },
+ },
+ },
+ footers: {
+ 'footer-1': {
+ footerId: 'footer-1',
+ body: {
+ dataStream: `${T.PARAGRAPH}bad-footer`,
+ paragraphs: [{ startIndex: 0, paragraphId: 'footer' }],
+ },
+ },
+ },
+ });
+
+ expect(issues.map((issue) => `${issue.segmentType}:${issue.segmentId}:${issue.code}`)).toEqual([
+ 'header:header-1:missing-root-paragraph',
+ 'header:header-1:missing-root-section-break',
+ 'footer:footer-1:missing-root-section-break',
+ ]);
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/column-groups.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/column-groups.spec.ts
index 9ade44c581..bfb6221e10 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/column-groups.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/column-groups.spec.ts
@@ -19,7 +19,10 @@ import type { TextXAction } from '../action-types';
import { describe, expect, it } from 'vitest';
import { DataStreamTreeTokenType } from '../../types';
import { TextXActionType } from '../action-types';
+import { BuildTextUtils } from '../build-utils';
+import { validateDocBodyStructure } from '../structure-validator';
import { TextX } from '../text-x';
+import { getBodySliceForTextXAction } from '../utils';
describe('TextX column groups', () => {
it('adds inserted column group metadata to documents without existing column groups', () => {
@@ -91,6 +94,27 @@ describe('TextX column groups', () => {
expect(body.columnGroups).toEqual([{ startIndex: 0, endIndex: 10, columnGroupId: 'cg-1' }]);
});
+ it('does not expand a column group when text is inserted after the closing boundary token', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}Z${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 3, paragraphId: 'left' },
+ { startIndex: 6, paragraphId: 'after' },
+ ],
+ sectionBreaks: [{ startIndex: 7 }],
+ columnGroups: [{ startIndex: 0, endIndex: 5, columnGroupId: 'cg-1' }],
+ };
+
+ TextX.apply(body, [
+ { t: TextXActionType.RETAIN, len: 6 },
+ { t: TextXActionType.INSERT, body: { dataStream: 'X' }, len: 1 },
+ ]);
+
+ expect(body.dataStream).toBe(`${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}XZ${T.PARAGRAPH}${T.SECTION_BREAK}`);
+ expect(body.columnGroups).toEqual([{ startIndex: 0, endIndex: 5, columnGroupId: 'cg-1' }]);
+ });
+
it('returns deleted column groups in delete undo bodies', () => {
const T = DataStreamTreeTokenType;
const body: IDocumentBody = {
@@ -109,4 +133,91 @@ describe('TextX column groups', () => {
expect(body.columnGroups).toEqual([]);
expect(actions[0].body?.columnGroups).toEqual([{ startIndex: 0, endIndex: 4, columnGroupId: 'cg-1' }]);
});
+
+ it('does not include partial column groups in action bodies', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 3, paragraphId: 'left' }],
+ sectionBreaks: [{ startIndex: 5 }],
+ columnGroups: [{ startIndex: 0, endIndex: 4, columnGroupId: 'cg-1' }],
+ };
+
+ const slice = getBodySliceForTextXAction(body, 2, 4, false);
+
+ expect(slice.dataStream).toBe(`A${T.PARAGRAPH}`);
+ expect(slice.columnGroups).toBeUndefined();
+ });
+
+ it('keeps a minimum paragraph when replacing all text in a column', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 3, paragraphId: 'left' }],
+ sectionBreaks: [{ startIndex: 6 }],
+ columnGroups: [{ startIndex: 0, endIndex: 5, columnGroupId: 'cg-1' }],
+ };
+
+ const actions = BuildTextUtils.selection.delete(
+ [{ startOffset: 2, endOffset: 4, collapsed: false }],
+ body,
+ 0,
+ { dataStream: 'X' }
+ );
+
+ TextX.apply(body, actions);
+
+ expect(body.dataStream).toBe(`${T.COLUMN_GROUP_START}${T.COLUMN_START}X${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`);
+ expect(body.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([3]);
+ expect(body.columnGroups).toEqual([{ startIndex: 0, endIndex: 5, columnGroupId: 'cg-1' }]);
+ });
+
+ it('allows deleting a paragraph sentinel when another column paragraph remains', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}B${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 3, paragraphId: 'first' },
+ { startIndex: 5, paragraphId: 'second' },
+ ],
+ sectionBreaks: [{ startIndex: 8 }],
+ columnGroups: [{ startIndex: 0, endIndex: 7, columnGroupId: 'cg-1' }],
+ };
+
+ const actions = BuildTextUtils.selection.delete(
+ [{ startOffset: 4, endOffset: 6, collapsed: false }],
+ body
+ );
+
+ TextX.apply(body, actions);
+
+ expect(body.dataStream).toBe(`${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`);
+ expect(body.columnGroups).toEqual([{ startIndex: 0, endIndex: 5, columnGroupId: 'cg-1' }]);
+ });
+
+ it('keeps column boundary tokens balanced when deleting across a column edge', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}Alpha${T.PARAGRAPH}${T.SECTION_BREAK}${T.COLUMN_END}${T.COLUMN_START}${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 7, paragraphId: 'left' },
+ { startIndex: 11, paragraphId: 'right' },
+ ],
+ sectionBreaks: [
+ { startIndex: 8 },
+ { startIndex: 14 },
+ ],
+ columnGroups: [{ startIndex: 0, endIndex: 13, columnGroupId: 'cg-1' }],
+ };
+
+ const actions = BuildTextUtils.selection.delete(
+ [{ startOffset: 4, endOffset: 10, collapsed: false }],
+ body
+ );
+
+ TextX.apply(body, actions);
+
+ expect(validateDocBodyStructure(body)).toEqual([]);
+ expect(body.dataStream).toBe(`${T.COLUMN_GROUP_START}${T.COLUMN_START}Al${T.SECTION_BREAK}${T.COLUMN_END}${T.COLUMN_START}${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`);
+ });
});
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/tables.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/tables.spec.ts
index 3a84a42447..7e4a9e1719 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/tables.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/tables.spec.ts
@@ -15,12 +15,84 @@
*/
import type { IDocumentBody } from '../../../../types/interfaces';
+import type { TextXAction } from '../action-types';
import { describe, expect, it } from 'vitest';
import { DataStreamTreeTokenType } from '../../types';
import { TextXActionType } from '../action-types';
+import { BuildTextUtils } from '../build-utils';
import { TextX } from '../text-x';
+import { getBodySliceForTextXAction } from '../utils';
describe('TextX tables', () => {
+ it('does not include table metadata when slicing text inside an existing table', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 7, paragraphId: 'cell' },
+ { startIndex: 12, paragraphId: 'after-table' },
+ ],
+ sectionBreaks: [
+ { startIndex: 8 },
+ { startIndex: 13 },
+ ],
+ tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
+ };
+
+ const slice = getBodySliceForTextXAction(body, 4, 8, false);
+
+ expect(slice.dataStream).toBe(`ell${T.PARAGRAPH}`);
+ expect(slice.tables).toBeUndefined();
+ });
+
+ it('includes table metadata in action bodies only when the full table range is sliced', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 7, paragraphId: 'cell' },
+ { startIndex: 12, paragraphId: 'after-table' },
+ ],
+ sectionBreaks: [
+ { startIndex: 8 },
+ { startIndex: 13 },
+ ],
+ tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
+ };
+
+ const slice = getBodySliceForTextXAction(body, 0, 12, false);
+
+ expect(slice.tables).toEqual([{ startIndex: 0, endIndex: 12, tableId: 'table-1' }]);
+ });
+
+ it('adds inserted table metadata to documents without existing tables', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `A${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 1, paragraphId: 'before' }],
+ sectionBreaks: [{ startIndex: 2 }],
+ };
+
+ TextX.apply(body, [
+ { t: TextXActionType.RETAIN, len: 2 },
+ {
+ t: TextXActionType.INSERT,
+ body: {
+ dataStream: `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}B${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.PARAGRAPH}`,
+ paragraphs: [
+ { startIndex: 4, paragraphId: 'cell' },
+ { startIndex: 9, paragraphId: 'after-table' },
+ ],
+ sectionBreaks: [{ startIndex: 5 }],
+ tables: [{ startIndex: 0, endIndex: 9, tableId: 'table-1' }],
+ },
+ len: 10,
+ },
+ ]);
+
+ expect(body.tables).toEqual([{ startIndex: 2, endIndex: 11, tableId: 'table-1' }]);
+ });
+
it('shifts table metadata when content is inserted at the table start boundary', () => {
const T = DataStreamTreeTokenType;
const body: IDocumentBody = {
@@ -48,4 +120,149 @@ describe('TextX tables', () => {
expect(body.dataStream).toBe(`A${T.PARAGRAPH}${T.PARAGRAPH}${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}B${T.PARAGRAPH}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.SECTION_BREAK}`);
expect(body.tables).toEqual([{ startIndex: 3, endIndex: 10, tableId: 'table-1' }]);
});
+
+ it('shifts table metadata when text is inserted inside a table cell', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}After${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 7, paragraphId: 'cell' },
+ { startIndex: 18, paragraphId: 'after' },
+ ],
+ sectionBreaks: [
+ { startIndex: 8 },
+ { startIndex: 19 },
+ ],
+ tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
+ };
+
+ TextX.apply(body, [
+ { t: TextXActionType.RETAIN, len: 6 },
+ {
+ t: TextXActionType.INSERT,
+ body: { dataStream: '++' },
+ len: 2,
+ },
+ ]);
+
+ expect(body.dataStream).toBe(`${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cel++l${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}After${T.PARAGRAPH}${T.SECTION_BREAK}`);
+ expect(body.tables).toEqual([{ startIndex: 0, endIndex: 14, tableId: 'table-1' }]);
+ expect(body.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([9, 20]);
+ });
+
+ it('shifts table end metadata when text is inserted before the paragraph after a table', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 7, paragraphId: 'cell' },
+ { startIndex: 12, paragraphId: 'after' },
+ ],
+ sectionBreaks: [
+ { startIndex: 8 },
+ { startIndex: 13 },
+ ],
+ tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
+ };
+
+ TextX.apply(body, [
+ { t: TextXActionType.RETAIN, len: 12 },
+ { t: TextXActionType.INSERT, body: { dataStream: '啊手' }, len: 2 },
+ ]);
+
+ expect(body.dataStream).toBe(`${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}啊手${T.PARAGRAPH}${T.SECTION_BREAK}`);
+ expect(body.tables).toEqual([{ startIndex: 0, endIndex: 14, tableId: 'table-1' }]);
+ expect(body.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([7, 14]);
+ });
+
+ it('keeps table metadata aligned after composing IME updates inside a table cell', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}After${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 7, paragraphId: 'cell' },
+ { startIndex: 18, paragraphId: 'after' },
+ ],
+ sectionBreaks: [
+ { startIndex: 8 },
+ { startIndex: 19 },
+ ],
+ tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
+ };
+
+ const firstUpdate: TextXAction[] = [
+ { t: TextXActionType.RETAIN, len: 6 },
+ { t: TextXActionType.INSERT, body: { dataStream: '啊' }, len: 1 },
+ ];
+ const secondUpdate: TextXAction[] = [
+ { t: TextXActionType.RETAIN, len: 6 },
+ { t: TextXActionType.DELETE, len: 1 },
+ { t: TextXActionType.INSERT, body: { dataStream: '啊手' }, len: 2 },
+ ];
+
+ TextX.apply(body, TextX.compose(firstUpdate, secondUpdate));
+
+ expect(body.dataStream).toBe(`${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cel啊手l${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}After${T.PARAGRAPH}${T.SECTION_BREAK}`);
+ expect(body.tables).toEqual([{ startIndex: 0, endIndex: 14, tableId: 'table-1' }]);
+ expect(body.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([9, 20]);
+ });
+
+ it('keeps table metadata aligned after composing insert-then-delete IME updates inside a table cell', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}After${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 7, paragraphId: 'cell' },
+ { startIndex: 18, paragraphId: 'after' },
+ ],
+ sectionBreaks: [
+ { startIndex: 8 },
+ { startIndex: 19 },
+ ],
+ tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
+ };
+
+ const firstUpdate: TextXAction[] = [
+ { t: TextXActionType.RETAIN, len: 6 },
+ { t: TextXActionType.INSERT, body: { dataStream: '啊' }, len: 1 },
+ ];
+ const secondUpdate: TextXAction[] = [
+ { t: TextXActionType.RETAIN, len: 6 },
+ { t: TextXActionType.INSERT, body: { dataStream: '啊手' }, len: 2 },
+ { t: TextXActionType.DELETE, len: 1 },
+ ];
+
+ TextX.apply(body, TextX.compose(firstUpdate, secondUpdate));
+
+ expect(body.dataStream).toBe(`${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cel啊手l${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}After${T.PARAGRAPH}${T.SECTION_BREAK}`);
+ expect(body.tables).toEqual([{ startIndex: 0, endIndex: 14, tableId: 'table-1' }]);
+ expect(body.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([9, 20]);
+ });
+
+ it('keeps a minimum paragraph and section break when replacing all text in a table cell', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}A${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 4, paragraphId: 'cell' }],
+ sectionBreaks: [
+ { startIndex: 5 },
+ { startIndex: 9 },
+ ],
+ tables: [{ startIndex: 0, endIndex: 8, tableId: 'table-1' }],
+ };
+
+ const actions = BuildTextUtils.selection.delete(
+ [{ startOffset: 3, endOffset: 6, collapsed: false }],
+ body,
+ 0,
+ { dataStream: 'X' }
+ );
+
+ TextX.apply(body, actions);
+
+ expect(body.dataStream).toBe(`${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}X${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.SECTION_BREAK}`);
+ expect(body.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([4]);
+ expect(body.sectionBreaks?.map((sectionBreak) => sectionBreak.startIndex)).toEqual([5, 9]);
+ expect(body.tables).toEqual([{ startIndex: 0, endIndex: 8, tableId: 'table-1' }]);
+ });
});
diff --git a/packages/core/src/docs/data-model/text-x/action-iterator.ts b/packages/core/src/docs/data-model/text-x/action-iterator.ts
index 0584229983..fe2bc049f5 100644
--- a/packages/core/src/docs/data-model/text-x/action-iterator.ts
+++ b/packages/core/src/docs/data-model/text-x/action-iterator.ts
@@ -19,7 +19,7 @@
import type { TextXAction } from './action-types';
import { Tools } from '../../../shared/tools';
import { TextXActionType } from './action-types';
-import { getBodySlice } from './utils';
+import { getBodySliceForSplitTextXAction } from './utils';
export class ActionIterator {
private _index = 0;
@@ -73,7 +73,7 @@ export class ActionIterator {
return Tools.deepClone({
...nextAction,
len: length,
- body: getBodySlice(nextAction.body!, offset, offset + length, false),
+ body: getBodySliceForSplitTextXAction(nextAction.body!, offset, offset + length, false),
});
}
} else {
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
index dee3bd3bb0..beccf76cdb 100644
--- a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
@@ -31,6 +31,7 @@ import { shallowEqual } from '../../../../common/equal';
import { horizontalLineSegmentsSubtraction, sortRulesFactory, Tools } from '../../../../shared';
import { isSameStyleTextRun } from '../../../../shared/compare';
import { cloneParagraphWithId } from '../../../paragraph-id';
+import { DataStreamTreeTokenType } from '../../types';
import { getBodySlice } from '../utils';
// Internal TextX undo marker: restored delete bodies keep their captured paragraph ids.
@@ -409,12 +410,15 @@ export function insertCustomBlocks(
}
export function insertTables(body: IDocumentBody, insertBody: IDocumentBody, textLength: number, currentIndex: number) {
- const { tables } = body;
-
- if (tables == null) {
+ if (!body.tables && !insertBody.tables?.length) {
return;
}
+ if (!body.tables) {
+ body.tables = [];
+ }
+
+ const { tables } = body;
for (let i = 0, len = tables.length; i < len; i++) {
const table = tables[i];
const { startIndex, endIndex } = table;
@@ -422,7 +426,7 @@ export function insertTables(body: IDocumentBody, insertBody: IDocumentBody, tex
if (startIndex >= currentIndex) {
table.startIndex += textLength;
table.endIndex += textLength;
- } else if (endIndex > currentIndex) {
+ } else if (endIndex > currentIndex || (endIndex === currentIndex && body.dataStream[currentIndex + textLength] === DataStreamTreeTokenType.PARAGRAPH)) {
table.endIndex += textLength;
}
}
@@ -457,7 +461,7 @@ export function insertColumnGroups(body: IDocumentBody, insertBody: IDocumentBod
if (startIndex >= currentIndex) {
columnGroup.startIndex += textLength;
columnGroup.endIndex += textLength;
- } else if (endIndex >= currentIndex) {
+ } else if (endIndex > currentIndex || (endIndex === currentIndex && body.dataStream[currentIndex + textLength] === DataStreamTreeTokenType.COLUMN_GROUP_END)) {
columnGroup.endIndex += textLength;
}
}
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/replace-selection.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/replace-selection.spec.ts
new file mode 100644
index 0000000000..5f3b180557
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/replace-selection.spec.ts
@@ -0,0 +1,141 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentBody } from '../../../../../types/interfaces';
+import { describe, expect, it } from 'vitest';
+import { BuildTextUtils } from '..';
+import { DocumentDataModel } from '../../../document-data-model';
+import { DataStreamTreeTokenType } from '../../../types';
+import { TextX } from '../../text-x';
+import { replaceSelectionTextRuns, replaceSelectionTextX } from '../text-x-utils';
+
+describe('replaceSelectionTextX', () => {
+ it('keeps the document minimum paragraph and section sentinels when replacing all content', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `A${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 1, paragraphId: 'para_minimum' }],
+ sectionBreaks: [{ startIndex: 2 }],
+ };
+ const doc = new DocumentDataModel({ body });
+
+ const textX = replaceSelectionTextX({
+ selection: { startOffset: 0, endOffset: 3, collapsed: false },
+ body: { dataStream: 'X' },
+ doc,
+ });
+
+ expect(textX).toBeTruthy();
+ if (textX) {
+ TextX.apply(body, textX.serialize());
+ expect(body.dataStream).toBe(`X${T.PARAGRAPH}${T.SECTION_BREAK}`);
+ expect(body.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([1]);
+ expect(body.sectionBreaks?.map((sectionBreak) => sectionBreak.startIndex)).toEqual([2]);
+ }
+ });
+
+ it('keeps the document minimum sentinels when replacing text runs over all content', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `A${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 1, paragraphId: 'para_minimum' }],
+ sectionBreaks: [{ startIndex: 2 }],
+ };
+ const doc = new DocumentDataModel({ body });
+
+ const textX = replaceSelectionTextRuns({
+ selection: { startOffset: 0, endOffset: 3, collapsed: false },
+ body: { dataStream: 'X' },
+ doc,
+ themeService: {} as never,
+ });
+
+ expect(textX).toBeTruthy();
+ if (textX) {
+ TextX.apply(body, textX.serialize());
+ expect(body.dataStream).toBe(`X${T.PARAGRAPH}${T.SECTION_BREAK}`);
+ }
+ });
+
+ it('allows deleting a paragraph sentinel when another root paragraph remains', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `A${T.PARAGRAPH}B${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 1, paragraphId: 'first' },
+ { startIndex: 3, paragraphId: 'second' },
+ ],
+ sectionBreaks: [{ startIndex: 4 }],
+ };
+
+ const actions = BuildTextUtils.selection.delete(
+ [{ startOffset: 2, endOffset: 4, collapsed: false }],
+ body
+ );
+
+ TextX.apply(body, actions);
+
+ expect(body.dataStream).toBe(`A${T.PARAGRAPH}${T.SECTION_BREAK}`);
+ expect(body.sectionBreaks?.map((sectionBreak) => sectionBreak.startIndex)).toEqual([2]);
+ });
+
+ it('keeps the next paragraph metadata aligned when deleting the first paragraph', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `Title${T.PARAGRAPH}Body${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 5, paragraphId: 'first' },
+ { startIndex: 10, paragraphId: 'second' },
+ ],
+ sectionBreaks: [{ startIndex: 11 }],
+ };
+
+ const actions = BuildTextUtils.selection.delete(
+ [{ startOffset: 0, endOffset: 6, collapsed: false }],
+ body
+ );
+
+ TextX.apply(body, actions);
+
+ expect(body.dataStream).toBe(`Body${T.PARAGRAPH}${T.SECTION_BREAK}`);
+ expect(body.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([4]);
+ expect(body.sectionBreaks?.map((sectionBreak) => sectionBreak.startIndex)).toEqual([5]);
+ });
+
+ it('does not duplicate paragraph metadata when deleting a bulleted first paragraph', () => {
+ const T = DataStreamTreeTokenType;
+ const bullet = { listId: 'list-1', listType: 'bullet', nestingLevel: 0 } as never;
+ const body: IDocumentBody = {
+ dataStream: `Title${T.PARAGRAPH}Body${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 5, paragraphId: 'first', bullet },
+ { startIndex: 10, paragraphId: 'second' },
+ ],
+ sectionBreaks: [{ startIndex: 11 }],
+ };
+
+ const actions = BuildTextUtils.selection.delete(
+ [{ startOffset: 0, endOffset: 6, collapsed: false }],
+ body
+ );
+
+ TextX.apply(body, actions);
+
+ expect(body.dataStream).toBe(`Body${T.PARAGRAPH}${T.SECTION_BREAK}`);
+ expect(body.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([4]);
+ expect(body.paragraphs).toHaveLength(1);
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts b/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
index eddc28f66d..566c0d8a7d 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
@@ -23,9 +23,10 @@ import type { TextXAction } from '../action-types';
import type { TextXSelection } from '../text-x';
import fastDiff from 'fast-diff';
import { Tools, UpdateDocsAttributeType } from '../../../../shared';
+import { DataStreamTreeTokenType } from '../../types';
import { TextXActionType } from '../action-types';
import { TextX } from '../text-x';
-import { getBodySlice, getTextRunSlice } from '../utils';
+import { getBodySlice, getBodySliceForTextXAction, getTextRunSlice } from '../utils';
import { excludePointsFromRange, getIntersectingCustomRanges, getSelectionForAddCustomRange } from './custom-range';
export interface IDeleteCustomRangeParam {
@@ -161,6 +162,191 @@ export function addCustomRangeTextX(param: IAddCustomRangeTextXParam) {
// If the selection contains line breaks,
// paragraph information needs to be preserved when performing the CUT operation
+interface IStructuralTextContainer {
+ startOffset: number;
+ endOffset: number;
+ paragraphs: number[];
+ sectionBreaks: number[];
+ require: 'paragraph-or-section' | 'paragraph-and-section';
+}
+
+function isOffsetDeleted(offset: number, selections: ITextRange[]) {
+ return selections.some((selection) => offset >= selection.startOffset && offset < selection.endOffset);
+}
+
+function isInsertInContainer(insertOffset: number, container: IStructuralTextContainer) {
+ return insertOffset >= container.startOffset && insertOffset <= container.endOffset;
+}
+
+function protectLastDeletedOffset(offsets: number[], selections: ITextRange[], protectedOffsets: Set<number>) {
+ if (offsets.length && offsets.every((offset) => isOffsetDeleted(offset, selections))) {
+ protectedOffsets.add(offsets[offsets.length - 1]);
+ }
+}
+
+function protectDeletedColumnBoundaryTokens(body: IDocumentBody, selections: ITextRange[], protectedOffsets: Set<number>) {
+ // Plain text selection edits may cross column edges, but structural column tokens must stay atomic.
+ for (let i = 0; i < body.dataStream.length; i++) {
+ const char = body.dataStream[i];
+ if (
+ (
+ char === DataStreamTreeTokenType.COLUMN_GROUP_START ||
+ char === DataStreamTreeTokenType.COLUMN_START ||
+ char === DataStreamTreeTokenType.COLUMN_END ||
+ char === DataStreamTreeTokenType.COLUMN_GROUP_END
+ ) &&
+ isOffsetDeleted(i, selections)
+ ) {
+ protectedOffsets.add(i);
+ }
+ }
+}
+
+function collectStructuralTextContainers(body: IDocumentBody): IStructuralTextContainer[] {
+ const containers: IStructuralTextContainer[] = [{
+ startOffset: 0,
+ endOffset: body.dataStream.length,
+ paragraphs: [],
+ sectionBreaks: [],
+ require: 'paragraph-and-section',
+ }];
+ const columnStack: IStructuralTextContainer[] = [];
+ const cellStack: IStructuralTextContainer[] = [];
+
+ const getActiveContainer = () => {
+ if (cellStack.length) {
+ return cellStack[cellStack.length - 1];
+ }
+
+ if (columnStack.length) {
+ return columnStack[columnStack.length - 1];
+ }
+
+ return containers[0];
+ };
+
+ for (let i = 0; i < body.dataStream.length; i++) {
+ const char = body.dataStream[i];
+
+ if (char === DataStreamTreeTokenType.COLUMN_START) {
+ columnStack.push({
+ startOffset: i + 1,
+ endOffset: i + 1,
+ paragraphs: [],
+ sectionBreaks: [],
+ require: 'paragraph-or-section',
+ });
+ } else if (char === DataStreamTreeTokenType.COLUMN_END) {
+ const column = columnStack.pop();
+ if (column) {
+ column.endOffset = i;
+ containers.push(column);
+ }
+ } else if (char === DataStreamTreeTokenType.TABLE_CELL_START) {
+ cellStack.push({
+ startOffset: i + 1,
+ endOffset: i + 1,
+ paragraphs: [],
+ sectionBreaks: [],
+ require: 'paragraph-and-section',
+ });
+ } else if (char === DataStreamTreeTokenType.TABLE_CELL_END) {
+ const cell = cellStack.pop();
+ if (cell) {
+ cell.endOffset = i;
+ containers.push(cell);
+ }
+ } else if (char === DataStreamTreeTokenType.PARAGRAPH) {
+ getActiveContainer().paragraphs.push(i);
+ } else if (char === DataStreamTreeTokenType.SECTION_BREAK) {
+ getActiveContainer().sectionBreaks.push(i);
+ }
+ }
+
+ return containers;
+}
+
+function normalizeSelectionsForStructuralSentinels(
+ selections: ITextRange[],
+ body: IDocumentBody,
+ insertBody: Nullable<IDocumentBody>
+) {
+ if (!selections.length) {
+ return selections;
+ }
+
+ const insertOffset = selections[0].startOffset;
+ const insertDataStream = insertBody?.dataStream ?? '';
+ const insertHasParagraph = insertDataStream.includes(DataStreamTreeTokenType.PARAGRAPH);
+ const insertHasSectionBreak = insertDataStream.includes(DataStreamTreeTokenType.SECTION_BREAK);
+ const protectedOffsets = new Set<number>();
+
+ // Plain text edits must not leave the document root, columns, or table cells without parser children.
+ collectStructuralTextContainers(body).forEach((container) => {
+ const insertAppliesToContainer = insertBody && isInsertInContainer(insertOffset, container);
+
+ if (container.require === 'paragraph-or-section') {
+ const offsets = [...container.paragraphs, ...container.sectionBreaks].sort((a, b) => a - b);
+ if (!insertAppliesToContainer || (!insertHasParagraph && !insertHasSectionBreak)) {
+ protectLastDeletedOffset(offsets, selections, protectedOffsets);
+ }
+ return;
+ }
+
+ if (!insertAppliesToContainer || !insertHasParagraph) {
+ protectLastDeletedOffset(container.paragraphs, selections, protectedOffsets);
+ }
+
+ if (!insertAppliesToContainer || !insertHasSectionBreak) {
+ protectLastDeletedOffset(container.sectionBreaks, selections, protectedOffsets);
+ }
+ });
+ protectDeletedColumnBoundaryTokens(body, selections, protectedOffsets);
+
+ if (!protectedOffsets.size) {
+ return selections;
+ }
+
+ const normalizedSelections: ITextRange[] = [];
+ selections.forEach((selection) => {
+ let startOffset = selection.startOffset;
+
+ for (let offset = selection.startOffset; offset < selection.endOffset; offset++) {
+ if (!protectedOffsets.has(offset)) {
+ continue;
+ }
+
+ if (startOffset < offset) {
+ normalizedSelections.push({
+ ...selection,
+ startOffset,
+ endOffset: offset,
+ collapsed: false,
+ });
+ }
+
+ startOffset = offset + 1;
+ }
+
+ if (startOffset < selection.endOffset) {
+ normalizedSelections.push({
+ ...selection,
+ startOffset,
+ endOffset: selection.endOffset,
+ collapsed: false,
+ });
+ }
+ });
+
+ return normalizedSelections.length
+ ? normalizedSelections
+ : [{
+ ...selections[0],
+ endOffset: selections[0].startOffset,
+ collapsed: true,
+ }];
+}
+
export function deleteSelectionTextX(
selections: ITextRange[],
body: IDocumentBody,
@@ -169,6 +355,7 @@ export function deleteSelectionTextX(
keepBullet: boolean = true
): Array<TextXAction> {
selections.sort((a, b) => a.startOffset - b.startOffset);
+ selections = normalizeSelectionsForStructuralSentinels(selections, body, insertBody);
const dos: Array<TextXAction> = [];
const { paragraphs = [] } = body;
@@ -203,7 +390,7 @@ export function deleteSelectionTextX(
});
}
- if (paragraphInRange && keepBullet) {
+ if (paragraphInRange?.bullet && keepBullet) {
const nextParagraph = paragraphs.find((p) => p.startIndex - memoryCursor >= (selections[selections.length - 1].endOffset - 1));
if (nextParagraph) {
if (nextParagraph.startIndex > cursor) {
@@ -227,7 +414,7 @@ export function deleteSelectionTextX(
},
],
},
- coverType: UpdateDocsAttributeType.REPLACE,
+ coverType: UpdateDocsAttributeType.COVER,
});
}
}
@@ -283,6 +470,17 @@ export const replaceSelectionTextX = (params: IReplaceSelectionTextXParams) => {
const body = doc.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (!body) return false;
+ const normalizedSelections = normalizeSelectionsForStructuralSentinels([selection], body, insertBody);
+ const selectionAdjusted = normalizedSelections.length !== 1 ||
+ normalizedSelections[0].startOffset !== selection.startOffset ||
+ normalizedSelections[0].endOffset !== selection.endOffset;
+
+ if (selectionAdjusted) {
+ const textX = new TextX();
+ textX.push(...deleteSelectionTextX([selection], body, 0, insertBody));
+ return textX;
+ }
+
const oldBody = selection.collapsed ? null : getBodySlice(body, selection.startOffset, selection.endOffset);
const diffs = fastDiff(oldBody ? oldBody.dataStream : '', insertBody.dataStream);
let cursor = 0;
@@ -293,7 +491,7 @@ export const replaceSelectionTextX = (params: IReplaceSelectionTextXParams) => {
const action: TextXAction = {
t: TextXActionType.RETAIN,
body: {
- ...getBodySlice(insertBody, cursor, cursor + text.length, false),
+ ...getBodySliceForTextXAction(insertBody, cursor, cursor + text.length, false),
dataStream: '',
},
len: text.length,
@@ -305,7 +503,7 @@ export const replaceSelectionTextX = (params: IReplaceSelectionTextXParams) => {
case 1: {
const action: TextXAction = {
t: TextXActionType.INSERT,
- body: getBodySlice(insertBody, cursor, cursor + text.length),
+ body: getBodySliceForTextXAction(insertBody, cursor, cursor + text.length),
len: text.length,
};
cursor += text.length;
@@ -349,6 +547,17 @@ export const replaceSelectionTextRuns = (params: IReplaceSelectionTextRunsParams
const body = doc.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (!body) return false;
+ const normalizedSelections = normalizeSelectionsForStructuralSentinels([selection], body, insertBody);
+ const selectionAdjusted = normalizedSelections.length !== 1 ||
+ normalizedSelections[0].startOffset !== selection.startOffset ||
+ normalizedSelections[0].endOffset !== selection.endOffset;
+
+ if (selectionAdjusted) {
+ const textX = new TextX();
+ textX.push(...deleteSelectionTextX([selection], body, 0, insertBody));
+ return textX;
+ }
+
const oldBody = selection.collapsed ? null : getBodySlice(body, selection.startOffset, selection.endOffset);
const diffs = fastDiff(oldBody ? oldBody.dataStream : '', insertBody.dataStream);
let cursor = 0;
@@ -383,7 +592,7 @@ export const replaceSelectionTextRuns = (params: IReplaceSelectionTextRunsParams
case 1: {
const action: TextXAction = {
t: TextXActionType.INSERT,
- body: getBodySlice(insertBody, cursor, cursor + text.length),
+ body: getBodySliceForTextXAction(insertBody, cursor, cursor + text.length),
len: text.length,
};
cursor += text.length;
diff --git a/packages/core/src/docs/data-model/text-x/structure-validator.ts b/packages/core/src/docs/data-model/text-x/structure-validator.ts
new file mode 100644
index 0000000000..930af0d5ed
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/structure-validator.ts
@@ -0,0 +1,209 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentBody, IDocumentData } from '../../../types/interfaces/i-document-data';
+import { DataStreamTreeTokenType } from '../types';
+
+export type DocStructureIssueCode =
+ | 'missing-root-paragraph'
+ | 'missing-root-section-break'
+ | 'paragraph-token-mismatch'
+ | 'section-break-token-mismatch'
+ | 'empty-column'
+ | 'empty-table-cell'
+ | 'unbalanced-column-group'
+ | 'unbalanced-table';
+
+export interface IDocStructureIssue {
+ code: DocStructureIssueCode;
+ segmentType: 'body' | 'header' | 'footer';
+ segmentId?: string;
+ index?: number;
+ message: string;
+}
+
+interface IValidationContext {
+ segmentType: IDocStructureIssue['segmentType'];
+ segmentId?: string;
+}
+
+function createIssue(
+ context: IValidationContext,
+ code: DocStructureIssueCode,
+ message: string,
+ index?: number
+): IDocStructureIssue {
+ return {
+ ...context,
+ code,
+ index,
+ message,
+ };
+}
+
+function validateMinimumRootSentinels(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {
+ if (!body.dataStream.includes(DataStreamTreeTokenType.PARAGRAPH)) {
+ issues.push(createIssue(context, 'missing-root-paragraph', 'Document body must contain at least one paragraph sentinel.'));
+ }
+
+ if (!body.dataStream.includes(DataStreamTreeTokenType.SECTION_BREAK)) {
+ issues.push(createIssue(context, 'missing-root-section-break', 'Document body must contain at least one section break sentinel.'));
+ }
+}
+
+function validateParagraphMetadata(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {
+ for (const paragraph of body.paragraphs ?? []) {
+ if (body.dataStream[paragraph.startIndex] !== DataStreamTreeTokenType.PARAGRAPH) {
+ issues.push(createIssue(
+ context,
+ 'paragraph-token-mismatch',
+ 'Paragraph metadata must point to a paragraph sentinel.',
+ paragraph.startIndex
+ ));
+ }
+ }
+}
+
+function validateSectionBreakMetadata(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {
+ for (const sectionBreak of body.sectionBreaks ?? []) {
+ if (body.dataStream[sectionBreak.startIndex] !== DataStreamTreeTokenType.SECTION_BREAK) {
+ issues.push(createIssue(
+ context,
+ 'section-break-token-mismatch',
+ 'Section break metadata must point to a section break sentinel.',
+ sectionBreak.startIndex
+ ));
+ }
+ }
+}
+
+function validateStructuralContainers(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {
+ const columnGroupStack: number[] = [];
+ const columnStack: Array<{ startIndex: number; hasChild: boolean }> = [];
+ const tableStack: number[] = [];
+ const tableRowStack: number[] = [];
+ const tableCellStack: Array<{ startIndex: number; hasParagraph: boolean; hasSectionBreak: boolean }> = [];
+
+ for (let i = 0; i < body.dataStream.length; i++) {
+ const char = body.dataStream[i];
+ const column = columnStack[columnStack.length - 1];
+ const cell = tableCellStack[tableCellStack.length - 1];
+
+ if (char === DataStreamTreeTokenType.PARAGRAPH) {
+ if (column) {
+ column.hasChild = true;
+ }
+
+ if (cell) {
+ cell.hasParagraph = true;
+ }
+ } else if (char === DataStreamTreeTokenType.SECTION_BREAK) {
+ if (column) {
+ column.hasChild = true;
+ }
+
+ if (cell) {
+ cell.hasSectionBreak = true;
+ }
+ } else if (char === DataStreamTreeTokenType.COLUMN_GROUP_START) {
+ columnGroupStack.push(i);
+ } else if (char === DataStreamTreeTokenType.COLUMN_START) {
+ columnStack.push({ startIndex: i, hasChild: false });
+ } else if (char === DataStreamTreeTokenType.COLUMN_END) {
+ const closedColumn = columnStack.pop();
+ if (!closedColumn) {
+ issues.push(createIssue(context, 'unbalanced-column-group', 'Column end token has no matching column start.', i));
+ } else if (!closedColumn.hasChild) {
+ issues.push(createIssue(context, 'empty-column', 'Column must contain at least one paragraph or section child.', closedColumn.startIndex));
+ }
+ } else if (char === DataStreamTreeTokenType.COLUMN_GROUP_END) {
+ if (columnStack.length > 0 || columnGroupStack.length === 0) {
+ issues.push(createIssue(context, 'unbalanced-column-group', 'Column group closes while a column is still open.', i));
+ columnStack.length = 0;
+ } else {
+ columnGroupStack.pop();
+ }
+ } else if (char === DataStreamTreeTokenType.TABLE_START) {
+ tableStack.push(i);
+ } else if (char === DataStreamTreeTokenType.TABLE_ROW_START) {
+ tableRowStack.push(i);
+ } else if (char === DataStreamTreeTokenType.TABLE_CELL_START) {
+ tableCellStack.push({ startIndex: i, hasParagraph: false, hasSectionBreak: false });
+ } else if (char === DataStreamTreeTokenType.TABLE_CELL_END) {
+ const closedCell = tableCellStack.pop();
+ if (!closedCell) {
+ issues.push(createIssue(context, 'unbalanced-table', 'Table cell end token has no matching start.', i));
+ } else if (!closedCell.hasParagraph || !closedCell.hasSectionBreak) {
+ issues.push(createIssue(context, 'empty-table-cell', 'Table cell must contain a paragraph and section break child.', closedCell.startIndex));
+ }
+ } else if (char === DataStreamTreeTokenType.TABLE_ROW_END) {
+ if (tableCellStack.length > 0 || tableRowStack.length === 0) {
+ issues.push(createIssue(context, 'unbalanced-table', 'Table row closes while a cell is still open.', i));
+ tableCellStack.length = 0;
+ } else {
+ tableRowStack.pop();
+ }
+ } else if (char === DataStreamTreeTokenType.TABLE_END) {
+ if (tableCellStack.length > 0 || tableRowStack.length > 0 || tableStack.length === 0) {
+ issues.push(createIssue(context, 'unbalanced-table', 'Table closes while a row or cell is still open.', i));
+ tableCellStack.length = 0;
+ tableRowStack.length = 0;
+ } else {
+ tableStack.pop();
+ }
+ }
+ }
+
+ if (columnGroupStack.length > 0 || columnStack.length > 0) {
+ issues.push(createIssue(context, 'unbalanced-column-group', 'Column group or column token is not closed.', body.dataStream.length));
+ }
+
+ if (tableStack.length > 0 || tableRowStack.length > 0 || tableCellStack.length > 0) {
+ issues.push(createIssue(context, 'unbalanced-table', 'Table, row, or cell token is not closed.', body.dataStream.length));
+ }
+}
+
+export function validateDocBodyStructure(
+ body: IDocumentBody,
+ context: IValidationContext = { segmentType: 'body' }
+): IDocStructureIssue[] {
+ const issues: IDocStructureIssue[] = [];
+
+ validateMinimumRootSentinels(body, issues, context);
+ validateParagraphMetadata(body, issues, context);
+ validateSectionBreakMetadata(body, issues, context);
+ validateStructuralContainers(body, issues, context);
+
+ return issues;
+}
+
+export function validateDocumentStructure(snapshot: Pick<IDocumentData, 'body' | 'headers' | 'footers'>): IDocStructureIssue[] {
+ const issues: IDocStructureIssue[] = [];
+
+ if (snapshot.body) {
+ issues.push(...validateDocBodyStructure(snapshot.body, { segmentType: 'body' }));
+ }
+
+ for (const [headerId, header] of Object.entries(snapshot.headers ?? {})) {
+ issues.push(...validateDocBodyStructure(header.body, { segmentType: 'header', segmentId: headerId }));
+ }
+
+ for (const [footerId, footer] of Object.entries(snapshot.footers ?? {})) {
+ issues.push(...validateDocBodyStructure(footer.body, { segmentType: 'footer', segmentId: footerId }));
+ }
+
+ return issues;
+}
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 b944a94fe3..828f34f2df 100644
--- a/packages/core/src/docs/data-model/text-x/utils.ts
+++ b/packages/core/src/docs/data-model/text-x/utils.ts
@@ -27,6 +27,41 @@ export enum SliceBodyType {
cut,
}
+export enum SliceStructuralRangeMode {
+ // General copy/slice behavior: keep the intersecting portion for backward compatibility.
+ intersect,
+ // Mutation builders: only emit metadata for structural ranges fully carried by this action body.
+ contained,
+ // ActionIterator splits: keep metadata on the chunk that carries the structural range end.
+ ending,
+}
+
+function hasStructuralRangeInSlice(startIndex: number, endIndex: number, startOffset: number, endOffset: number, mode: SliceStructuralRangeMode) {
+ if (mode === SliceStructuralRangeMode.contained) {
+ return startIndex >= startOffset && endIndex <= endOffset;
+ }
+
+ if (mode === SliceStructuralRangeMode.ending) {
+ return startIndex < endOffset && endIndex > startOffset && endIndex <= endOffset;
+ }
+
+ return Math.max(startIndex, startOffset) < Math.min(endIndex, endOffset);
+}
+
+function getSlicedStructuralRange(startIndex: number, endIndex: number, startOffset: number, endOffset: number, mode: SliceStructuralRangeMode) {
+ if (mode === SliceStructuralRangeMode.intersect) {
+ return {
+ startIndex: Math.max(startIndex, startOffset) - startOffset,
+ endIndex: Math.min(endIndex, endOffset) - startOffset,
+ };
+ }
+
+ return {
+ startIndex: startIndex - startOffset,
+ endIndex: endIndex - startOffset,
+ };
+}
+
export function getTextRunSlice(
body: IDocumentBody,
startOffset: number,
@@ -85,7 +120,8 @@ export function getTextRunSlice(
export function getTableSlice(
body: IDocumentBody,
startOffset: number,
- endOffset: number
+ endOffset: number,
+ mode = SliceStructuralRangeMode.intersect
) {
const { tables = [] } = body;
const newTables = [];
@@ -93,11 +129,10 @@ export function getTableSlice(
const clonedTable = Tools.deepClone(table);
const { startIndex, endIndex } = clonedTable;
- if (Math.max(startIndex, startOffset) < Math.min(endIndex, endOffset)) {
+ if (hasStructuralRangeInSlice(startIndex, endIndex, startOffset, endOffset, mode)) {
newTables.push({
...clonedTable,
- startIndex: Math.max(startIndex, startOffset) - startOffset,
- endIndex: Math.min(endIndex, endOffset) - startOffset,
+ ...getSlicedStructuralRange(startIndex, endIndex, startOffset, endOffset, mode),
});
}
}
@@ -107,7 +142,8 @@ export function getTableSlice(
export function getBlockRangeSlice(
body: IDocumentBody,
startOffset: number,
- endOffset: number
+ endOffset: number,
+ mode = SliceStructuralRangeMode.intersect
) {
const { blockRanges = [] } = body;
const newBlockRanges: IDocumentBlockRange[] = [];
@@ -116,11 +152,10 @@ export function getBlockRangeSlice(
const clonedBlockRange = Tools.deepClone(blockRange);
const { startIndex, endIndex } = clonedBlockRange;
- if (startIndex >= startOffset && endIndex < endOffset) {
+ if (hasStructuralRangeInSlice(startIndex, endIndex, startOffset, endOffset, mode)) {
newBlockRanges.push({
...clonedBlockRange,
- startIndex: startIndex - startOffset,
- endIndex: endIndex - startOffset,
+ ...getSlicedStructuralRange(startIndex, endIndex, startOffset, endOffset, mode),
});
}
}
@@ -131,7 +166,8 @@ export function getBlockRangeSlice(
export function getColumnGroupSlice(
body: IDocumentBody,
startOffset: number,
- endOffset: number
+ endOffset: number,
+ mode = SliceStructuralRangeMode.intersect
) {
const { columnGroups = [] } = body;
const newColumnGroups: ICustomColumnGroup[] = [];
@@ -140,11 +176,10 @@ export function getColumnGroupSlice(
const clonedColumnGroup = Tools.deepClone(columnGroup);
const { startIndex, endIndex } = clonedColumnGroup;
- if (startIndex >= startOffset && endIndex < endOffset) {
+ if (hasStructuralRangeInSlice(startIndex, endIndex, startOffset, endOffset, mode)) {
newColumnGroups.push({
...clonedColumnGroup,
- startIndex: startIndex - startOffset,
- endIndex: endIndex - startOffset,
+ ...getSlicedStructuralRange(startIndex, endIndex, startOffset, endOffset, mode),
});
}
}
@@ -254,7 +289,8 @@ export function getBodySlice(
startOffset: number,
endOffset: number,
returnEmptyArray = true,
- type = SliceBodyType.cut
+ type = SliceBodyType.cut,
+ structuralRangeMode = SliceStructuralRangeMode.intersect
): IDocumentBody {
const { dataStream } = body;
@@ -264,17 +300,17 @@ export function getBodySlice(
docBody.textRuns = getTextRunSlice(body, startOffset, endOffset, returnEmptyArray);
- const newTables = getTableSlice(body, startOffset, endOffset);
+ const newTables = getTableSlice(body, startOffset, endOffset, structuralRangeMode);
if (newTables.length) {
docBody.tables = newTables;
}
- const newBlockRanges = getBlockRangeSlice(body, startOffset, endOffset);
+ const newBlockRanges = getBlockRangeSlice(body, startOffset, endOffset, structuralRangeMode);
if (newBlockRanges.length) {
docBody.blockRanges = newBlockRanges;
}
- const newColumnGroups = getColumnGroupSlice(body, startOffset, endOffset);
+ const newColumnGroups = getColumnGroupSlice(body, startOffset, endOffset, structuralRangeMode);
if (newColumnGroups.length) {
docBody.columnGroups = newColumnGroups;
}
@@ -301,6 +337,26 @@ export function getBodySlice(
return docBody;
}
+export function getBodySliceForTextXAction(
+ body: IDocumentBody,
+ startOffset: number,
+ endOffset: number,
+ returnEmptyArray = true,
+ type = SliceBodyType.cut
+): IDocumentBody {
+ return getBodySlice(body, startOffset, endOffset, returnEmptyArray, type, SliceStructuralRangeMode.contained);
+}
+
+export function getBodySliceForSplitTextXAction(
+ body: IDocumentBody,
+ startOffset: number,
+ endOffset: number,
+ returnEmptyArray = true,
+ type = SliceBodyType.cut
+): IDocumentBody {
+ return getBodySlice(body, startOffset, endOffset, returnEmptyArray, type, SliceStructuralRangeMode.ending);
+}
+
export function normalizeBody(body: IDocumentBody): IDocumentBody {
const { dataStream, textRuns, paragraphs, customRanges, customDecorations, tables, columnGroups, blockRanges } = body;
let leftOffset = 0;
diff --git a/packages/docs-ui/src/commands/commands/__tests__/doc-block-move.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/doc-block-move.command.spec.ts
index f5d30063aa..5d9d6f1a8a 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/doc-block-move.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/doc-block-move.command.spec.ts
@@ -25,7 +25,7 @@ import {
} from '@univerjs/core';
import { DocBlockMoveValidatorService, RichTextEditingMutation } from '@univerjs/docs';
import { afterEach, describe, expect, it } from 'vitest';
-import { buildMoveDocBlockActions, MoveDocBlockCommand } from '../doc-block-move.command';
+import { buildMoveDocBlockActions, buildReplaceDocumentBodyActions, MoveDocBlockCommand } from '../doc-block-move.command';
import { createCommandTestBed } from './create-command-test-bed';
describe('buildMoveDocBlockActions', () => {
@@ -244,9 +244,9 @@ describe('MoveDocBlockCommand', () => {
{ paragraphId: 'para_docs_ui_fixture_36', startIndex: 1 },
{ paragraphId: 'para_docs_ui_fixture_37', startIndex: 5 },
{ paragraphId: 'para_docs_ui_fixture_38', startIndex: 9 },
- { paragraphId: 'para_docs_ui_fixture_39', startIndex: 12 },
+ { paragraphId: 'para_docs_ui_fixture_39', startIndex: 13 },
],
- sectionBreaks: [{ startIndex: 13 }],
+ sectionBreaks: [{ startIndex: 14 }],
columnGroups: [{ columnGroupId: 'column-group-1', startIndex: 2, endIndex: 12 }],
}));
const commandService = testBed.get(ICommandService);
@@ -316,6 +316,34 @@ describe('MoveDocBlockCommand', () => {
});
});
+describe('buildReplaceDocumentBodyActions', () => {
+ it('uses TextX and local body patches instead of replacing whole body fields', () => {
+ const previousDocumentData = createDocument('A\rB\rC\r\n', {
+ paragraphs: [{ paragraphId: 'para_docs_ui_fixture_42', startIndex: 1 }, { paragraphId: 'para_docs_ui_fixture_43', startIndex: 3 }, { paragraphId: 'para_docs_ui_fixture_44', startIndex: 5 }],
+ sectionBreaks: [{ startIndex: 6 }],
+ });
+ const sourceRange = { startOffset: 0, endOffset: 2 };
+ const targetOffset = 6;
+ const { nextDocumentData, movedRange } = buildMoveDocBlockActions({
+ documentData: previousDocumentData,
+ sourceRange,
+ targetOffset,
+ });
+
+ const actions = buildReplaceDocumentBodyActions(previousDocumentData, nextDocumentData, {
+ movedRange,
+ sourceRange,
+ targetOffset,
+ });
+ const serializedActions = JSON.stringify(actions);
+
+ expect(actions).not.toBeNull();
+ expect(serializedActions).not.toContain('["body","dataStream"');
+ expect(serializedActions).not.toContain('["body","paragraphs",{"r"');
+ expect(serializedActions).toContain('"et":"text-x"');
+ });
+});
+
function createDocument(dataStream: string, body: Partial<NonNullable<IDocumentData['body']>>): IDocumentData {
return {
id: 'test-doc',
diff --git a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts
index 11c2415bac..d09a7d2f6c 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts
@@ -996,7 +996,7 @@ describe('misc document commands', () => {
await awaitTime(0);
expect(getBody()?.dataStream).toBe('Body\r\n');
- expect(getBody()?.paragraphs?.[0].startIndex).toBe(0);
+ expect(getBody()?.paragraphs?.[0].startIndex).toBe(4);
});
it('removes the character before the cursor when Backspace is pressed inside text', async () => {
diff --git a/packages/docs-ui/src/commands/commands/__tests__/replace-content.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/replace-content.command.spec.ts
index ae68956499..b569de2b6e 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/replace-content.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/replace-content.command.spec.ts
@@ -19,6 +19,7 @@ import { ICommandService, IUniverInstanceService, RedoCommand, UndoCommand, Univ
import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
+ buildReplaceSnapshotActions,
CoverContentCommand,
ReplaceContentCommand,
ReplaceSelectionCommand,
@@ -246,6 +247,26 @@ describe('replace or cover content of document', () => {
expect(getDataStream()).toBe('=SUM(A2:B4)\r\n');
});
+ it('builds replacement snapshot body changes without whole body replace', () => {
+ const previousSnapshot = getDocumentData();
+ const nextSnapshot = {
+ ...previousSnapshot,
+ body: {
+ dataStream: 'Snapshot\r\n',
+ paragraphs: [{ paragraphId: 'para_replace_snapshot_shape', startIndex: 8 }],
+ sectionBreaks: [{ startIndex: 9 }],
+ textRuns: [],
+ },
+ };
+
+ const actions = buildReplaceSnapshotActions(previousSnapshot, nextSnapshot);
+ const serializedActions = JSON.stringify(actions);
+
+ expect(actions).not.toBeNull();
+ expect(serializedActions).toContain('"et":"text-x"');
+ expect(serializedActions).not.toContain('["body",{"r"');
+ });
+
it('replaces the active selection through the real rich text mutation flow', async () => {
univer.dispose();
const testBed = createCommandTestBed(getDocumentData());
diff --git a/packages/docs-ui/src/commands/commands/doc-block-move.command.ts b/packages/docs-ui/src/commands/commands/doc-block-move.command.ts
index 9644768c2d..36ddfd0610 100644
--- a/packages/docs-ui/src/commands/commands/doc-block-move.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-block-move.command.ts
@@ -17,7 +17,7 @@
import type { DocumentDataModel, ICommand, IDocumentBody, IDocumentData, JSONXActions } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
-import { CommandType, ICommandService, IUniverInstanceService, JSONX, Tools, UniverInstanceType } from '@univerjs/core';
+import { CommandType, getBodySliceForTextXAction, ICommandService, IUniverInstanceService, JSONX, TextX, Tools, UniverInstanceType } from '@univerjs/core';
import { DocBlockMoveValidatorService, RichTextEditingMutation } from '@univerjs/docs';
export interface IMoveDocBlockCommandParams {
@@ -37,6 +37,30 @@ export interface IMoveDocBlockActionResult {
};
}
+export interface IMoveDocBlockTextChange {
+ movedRange: {
+ startOffset: number;
+ endOffset: number;
+ };
+ sourceRange: {
+ startOffset: number;
+ endOffset: number;
+ };
+ targetOffset: number;
+}
+
+const DOC_BLOCK_MOVE_BODY_PATCH_KEYS = [
+ 'paragraphs',
+ 'sectionBreaks',
+ 'tables',
+ 'columnGroups',
+ 'customBlocks',
+ 'blockRanges',
+ 'customRanges',
+ 'customDecorations',
+ 'textRuns',
+] as const satisfies Array<keyof NonNullable<IDocumentData['body']>>;
+
export const MoveDocBlockCommand: ICommand<IMoveDocBlockCommandParams> = {
id: 'doc.command.move-block',
type: CommandType.COMMAND,
@@ -70,7 +94,11 @@ export const MoveDocBlockCommand: ICommand<IMoveDocBlockCommandParams> = {
previousDocumentData,
result: moveResult,
});
- const actions = buildReplaceDocumentBodyActions(previousDocumentData, nextDocumentData);
+ const actions = buildReplaceDocumentBodyActions(previousDocumentData, nextDocumentData, {
+ sourceRange,
+ targetOffset,
+ movedRange,
+ });
if (!actions) {
return false;
@@ -140,7 +168,7 @@ export function buildMoveDocBlockActions(params: {
};
}
-function buildReplaceDocumentBodyActions(previousDocumentData: IDocumentData, nextDocumentData: IDocumentData): JSONXActions | null {
+export function buildReplaceDocumentBodyActions(previousDocumentData: IDocumentData, nextDocumentData: IDocumentData, move?: IMoveDocBlockTextChange): JSONXActions | null {
const jsonX = JSONX.getInstance();
const previousBody = previousDocumentData.body;
const nextBody = nextDocumentData.body;
@@ -149,22 +177,216 @@ function buildReplaceDocumentBodyActions(previousDocumentData: IDocumentData, ne
return null;
}
- const rawActions = [
- jsonX.replaceOp(['body', 'dataStream'], previousBody.dataStream, nextBody.dataStream),
- jsonX.replaceOp(['body', 'paragraphs'], previousBody.paragraphs, nextBody.paragraphs),
- jsonX.replaceOp(['body', 'sectionBreaks'], previousBody.sectionBreaks, nextBody.sectionBreaks),
- jsonX.replaceOp(['body', 'tables'], previousBody.tables, nextBody.tables),
- jsonX.replaceOp(['body', 'columnGroups'], previousBody.columnGroups, nextBody.columnGroups),
- jsonX.replaceOp(['body', 'customBlocks'], previousBody.customBlocks, nextBody.customBlocks),
- jsonX.replaceOp(['body', 'blockRanges'], previousBody.blockRanges, nextBody.blockRanges),
- jsonX.replaceOp(['body', 'customRanges'], previousBody.customRanges, nextBody.customRanges),
- jsonX.replaceOp(['body', 'customDecorations'], previousBody.customDecorations, nextBody.customDecorations),
- jsonX.replaceOp(['body', 'textRuns'], previousBody.textRuns, nextBody.textRuns),
- ].filter(Boolean) as JSONXActions[];
+ const rawActions: JSONXActions[] = [];
+ let intermediateDocumentData = Tools.deepClone(previousDocumentData);
+
+ const moveTextAction = move ? buildMoveBodyTextAction(previousBody, nextBody, move) : null;
+ if (moveTextAction) {
+ rawActions.push(moveTextAction);
+ intermediateDocumentData = JSONX.apply(intermediateDocumentData, moveTextAction) as unknown as IDocumentData;
+ }
+
+ const residualTextAction = buildSingleBodyTextChangeAction(intermediateDocumentData.body, nextBody);
+ if (residualTextAction) {
+ rawActions.push(residualTextAction);
+ intermediateDocumentData = JSONX.apply(intermediateDocumentData, residualTextAction) as unknown as IDocumentData;
+ }
+
+ if (!moveTextAction) {
+ collectBodyPatchActions(intermediateDocumentData.body, nextBody, rawActions);
+ }
return rawActions.reduce((acc, cur) => JSONX.compose(acc, cur), null as JSONXActions);
}
+function buildMoveBodyTextAction(previousBody: IDocumentBody, nextBody: IDocumentBody, move: IMoveDocBlockTextChange): JSONXActions | null {
+ const dataStreamLength = previousBody.dataStream.length;
+ const startOffset = clamp(move.sourceRange.startOffset, 0, dataStreamLength);
+ const endOffset = clamp(move.sourceRange.endOffset, startOffset, dataStreamLength);
+ const targetOffset = clamp(move.targetOffset, 0, dataStreamLength);
+ const moveLength = endOffset - startOffset;
+
+ if (moveLength <= 0 || (targetOffset >= startOffset && targetOffset <= endOffset)) {
+ return null;
+ }
+
+ const textX = new TextX();
+ const insertOffset = move.movedRange.startOffset;
+ const insertBody = getBodySliceForTextXAction(nextBody, insertOffset, insertOffset + moveLength, false);
+
+ if (targetOffset < startOffset) {
+ textX.retain(targetOffset);
+ textX.insert(moveLength, insertBody);
+ textX.retain(startOffset - targetOffset);
+ textX.delete(moveLength);
+ } else {
+ textX.retain(startOffset);
+ textX.delete(moveLength);
+ textX.retain(targetOffset - endOffset);
+ textX.insert(moveLength, insertBody);
+ }
+
+ return JSONX.getInstance().editOp(textX.serialize(), ['body']);
+}
+
+function buildSingleBodyTextChangeAction(previousBody: IDocumentBody | undefined, nextBody: IDocumentBody): JSONXActions | null {
+ const textChange = getSingleDataStreamChange(previousBody?.dataStream, nextBody.dataStream);
+
+ if (!textChange) {
+ return null;
+ }
+
+ const textX = new TextX();
+ textX.retain(textChange.start);
+ if (textChange.insertLength > 0) {
+ textX.insert(
+ textChange.insertLength,
+ getBodySliceForTextXAction(nextBody, textChange.start, textChange.start + textChange.insertLength, false)
+ );
+ }
+ if (textChange.deleteLength > 0) {
+ textX.delete(textChange.deleteLength);
+ }
+
+ return JSONX.getInstance().editOp(textX.serialize(), ['body']);
+}
+
+function getSingleDataStreamChange(previousDataStream: string | undefined, nextDataStream: string | undefined): { start: number; deleteLength: number; insertLength: number } | null {
+ if (previousDataStream == null || nextDataStream == null || previousDataStream === nextDataStream) {
+ return null;
+ }
+
+ let start = 0;
+ while (
+ start < previousDataStream.length &&
+ start < nextDataStream.length &&
+ previousDataStream[start] === nextDataStream[start]
+ ) {
+ start++;
+ }
+
+ let previousEnd = previousDataStream.length;
+ let nextEnd = nextDataStream.length;
+ while (
+ previousEnd > start &&
+ nextEnd > start &&
+ previousDataStream[previousEnd - 1] === nextDataStream[nextEnd - 1]
+ ) {
+ previousEnd--;
+ nextEnd--;
+ }
+
+ return {
+ start,
+ deleteLength: previousEnd - start,
+ insertLength: nextEnd - start,
+ };
+}
+
+function collectBodyPatchActions(previousBody: IDocumentBody | undefined, nextBody: IDocumentBody, actions: JSONXActions[]): void {
+ for (const key of DOC_BLOCK_MOVE_BODY_PATCH_KEYS) {
+ collectPatchActions(
+ JSONX.getInstance(),
+ ['body', key],
+ previousBody?.[key],
+ nextBody[key],
+ actions
+ );
+ }
+}
+
+function collectPatchActions(
+ jsonX: JSONX,
+ path: (string | number)[],
+ oldValue: unknown,
+ newValue: unknown,
+ actions: JSONXActions[]
+): void {
+ if (isEmptyArrayEquivalent(oldValue, newValue)) {
+ return;
+ }
+
+ if (Tools.diffValue(oldValue, newValue)) {
+ return;
+ }
+
+ if (oldValue == null) {
+ actions.push(jsonX.insertOp(path, newValue));
+ return;
+ }
+
+ if (newValue == null) {
+ actions.push(jsonX.removeOp(path, oldValue));
+ return;
+ }
+
+ if (Array.isArray(oldValue) && Array.isArray(newValue)) {
+ collectArrayPatchActions(jsonX, path, oldValue, newValue, actions);
+ return;
+ }
+
+ if (isPlainObject(oldValue) && isPlainObject(newValue)) {
+ const keys = new Set([...Object.keys(oldValue), ...Object.keys(newValue)]);
+
+ keys.forEach((key) => {
+ collectPatchActions(
+ jsonX,
+ [...path, key],
+ (oldValue as Record<string, unknown>)[key],
+ (newValue as Record<string, unknown>)[key],
+ actions
+ );
+ });
+ return;
+ }
+
+ actions.push(jsonX.replaceOp(path, oldValue, newValue));
+}
+
+function collectArrayPatchActions(
+ jsonX: JSONX,
+ path: (string | number)[],
+ oldItems: unknown[],
+ newItems: unknown[],
+ actions: JSONXActions[]
+): void {
+ if (oldItems.length === newItems.length) {
+ oldItems.forEach((item, index) => collectPatchActions(jsonX, [...path, index], item, newItems[index], actions));
+ return;
+ }
+
+ let prefix = 0;
+ while (prefix < oldItems.length && prefix < newItems.length && Tools.diffValue(oldItems[prefix], newItems[prefix])) {
+ prefix++;
+ }
+
+ let oldSuffix = oldItems.length - 1;
+ let newSuffix = newItems.length - 1;
+ while (oldSuffix >= prefix && newSuffix >= prefix && Tools.diffValue(oldItems[oldSuffix], newItems[newSuffix])) {
+ oldSuffix--;
+ newSuffix--;
+ }
+
+ for (let index = oldSuffix; index >= prefix; index--) {
+ actions.push(jsonX.removeOp([...path, index], oldItems[index]));
+ }
+
+ for (let index = prefix; index <= newSuffix; index++) {
+ actions.push(jsonX.insertOp([...path, index], newItems[index]));
+ }
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return value != null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function isEmptyArrayEquivalent(oldValue: unknown, newValue: unknown): boolean {
+ return (
+ (oldValue == null && Array.isArray(newValue) && newValue.length === 0) ||
+ (newValue == null && Array.isArray(oldValue) && oldValue.length === 0)
+ );
+}
+
function remapBodyIndexesAfterMove(
body: IDocumentBody,
startOffset: number,
diff --git a/packages/docs-ui/src/commands/commands/replace-content.command.ts b/packages/docs-ui/src/commands/commands/replace-content.command.ts
index e7842e2d89..c3bd6337b9 100644
--- a/packages/docs-ui/src/commands/commands/replace-content.command.ts
+++ b/packages/docs-ui/src/commands/commands/replace-content.command.ts
@@ -52,7 +52,7 @@ export interface IReplaceSnapshotCommandParams {
export const ReplaceSnapshotCommand: ICommand<IReplaceSnapshotCommandParams> = {
id: 'doc.command-replace-snapshot',
type: CommandType.COMMAND,
- // eslint-disable-next-line max-lines-per-function, complexity
+
handler: (accessor, params: IReplaceSnapshotCommandParams) => {
const { unitId, snapshot, textRanges, segmentId = '', options } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -104,79 +104,89 @@ export const ReplaceSnapshotCommand: ICommand<IReplaceSnapshotCommandParams> = {
doMutation.params.options = options;
}
- const rawActions: JSONXActions = [];
+ doMutation.params.actions = buildReplaceSnapshotActions({
+ body: prevBody,
+ documentStyle: prevDocumentStyle,
+ tableSource: prevTableSource,
+ footers: prevFooters,
+ headers: prevHeaders,
+ lists: prevLists,
+ drawings: prevDrawings,
+ drawingsOrder: prevDrawingsOrder,
+ } as IDocumentData, {
+ body,
+ documentStyle,
+ tableSource,
+ footers,
+ headers,
+ lists,
+ drawings,
+ drawingsOrder,
+ } as IDocumentData);
- const jsonX = JSONX.getInstance();
+ const result = commandService.syncExecuteCommand<
+ IRichTextEditingMutationParams,
+ IRichTextEditingMutationParams
+ >(doMutation.id, doMutation.params);
- if (!Tools.diffValue(prevDocumentStyle, documentStyle)) {
- const actions = jsonX.replaceOp(['documentStyle'], prevDocumentStyle, documentStyle);
- if (actions != null) {
- rawActions.push(actions);
- }
- }
+ return Boolean(result);
+ },
- if (!Tools.diffValue(body, prevBody)) {
- const actions = jsonX.replaceOp(['body'], prevBody, body);
- if (actions != null) {
- rawActions.push(actions);
- }
- }
+};
- if (!Tools.diffValue(tableSource, prevTableSource)) {
- const actions = jsonX.replaceOp(['tableSource'], prevTableSource, tableSource);
- if (actions != null) {
- rawActions.push(actions);
- }
- }
+export function buildReplaceSnapshotActions(previousSnapshot: IDocumentData, snapshot: IDocumentData): JSONXActions | null {
+ const jsonX = JSONX.getInstance();
+ const rawActions: JSONXActions[] = [];
- if (!Tools.diffValue(footers, prevFooters)) {
- const actions = jsonX.replaceOp(['footers'], prevFooters, footers);
- if (actions != null) {
- rawActions.push(actions);
- }
- }
+ const bodyAction = buildReplaceSnapshotBodyAction(previousSnapshot.body, snapshot.body);
+ if (bodyAction) {
+ rawActions.push(bodyAction);
+ }
- if (!Tools.diffValue(headers, prevHeaders)) {
- const actions = jsonX.replaceOp(['headers'], prevHeaders, headers);
- if (actions != null) {
- rawActions.push(actions);
- }
- }
+ collectTopLevelReplaceAction(jsonX, rawActions, ['documentStyle'], previousSnapshot.documentStyle, snapshot.documentStyle);
+ collectTopLevelReplaceAction(jsonX, rawActions, ['tableSource'], previousSnapshot.tableSource, snapshot.tableSource);
+ collectTopLevelReplaceAction(jsonX, rawActions, ['footers'], previousSnapshot.footers, snapshot.footers);
+ collectTopLevelReplaceAction(jsonX, rawActions, ['headers'], previousSnapshot.headers, snapshot.headers);
+ collectTopLevelReplaceAction(jsonX, rawActions, ['lists'], previousSnapshot.lists, snapshot.lists);
+ collectTopLevelReplaceAction(jsonX, rawActions, ['drawings'], previousSnapshot.drawings, snapshot.drawings);
+ collectTopLevelReplaceAction(jsonX, rawActions, ['drawingsOrder'], previousSnapshot.drawingsOrder, snapshot.drawingsOrder);
- if (!Tools.diffValue(lists, prevLists)) {
- const actions = jsonX.replaceOp(['lists'], prevLists, lists);
- if (actions != null) {
- rawActions.push(actions);
- }
- }
+ return rawActions.reduce((acc, cur) => JSONX.compose(acc, cur as JSONXActions), null as JSONXActions);
+}
- if (!Tools.diffValue(drawings, prevDrawings)) {
- const actions = jsonX.replaceOp(['drawings'], prevDrawings, drawings);
- if (actions != null) {
- rawActions.push(actions);
- }
- }
+function buildReplaceSnapshotBodyAction(previousBody: IDocumentBody | undefined, body: IDocumentBody | undefined): JSONXActions | null {
+ if (!previousBody || !body || Tools.diffValue(previousBody, body)) {
+ return null;
+ }
- if (!Tools.diffValue(drawingsOrder, prevDrawingsOrder)) {
- const actions = jsonX.replaceOp(['drawingsOrder'], prevDrawingsOrder, drawingsOrder);
- if (actions != null) {
- rawActions.push(actions);
- }
- }
+ const textX = new TextX();
+ if (previousBody.dataStream.length > 0) {
+ textX.delete(previousBody.dataStream.length);
+ }
- doMutation.params.actions = rawActions.reduce((acc, cur) => {
- return JSONX.compose(acc, cur as JSONXActions);
- }, null as JSONXActions);
+ if (body.dataStream.length > 0) {
+ textX.insert(body.dataStream.length, body);
+ }
- const result = commandService.syncExecuteCommand<
- IRichTextEditingMutationParams,
- IRichTextEditingMutationParams
- >(doMutation.id, doMutation.params);
+ return JSONX.getInstance().editOp(textX.serialize(), ['body']);
+}
- return Boolean(result);
- },
+function collectTopLevelReplaceAction(
+ jsonX: JSONX,
+ rawActions: JSONXActions[],
+ path: string[],
+ previousValue: unknown,
+ value: unknown
+): void {
+ if (Tools.diffValue(previousValue, value)) {
+ return;
+ }
-};
+ const action = jsonX.replaceOp(path, previousValue, value);
+ if (action != null) {
+ rawActions.push(action);
+ }
+}
interface IReplaceContentCommandParams {
unitId: string;
diff --git a/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts b/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts
index 79fe4d27bf..4b23b73602 100644
--- a/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts
+++ b/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts
@@ -206,8 +206,8 @@ function createService(renderManagerServiceClass: unknown = RenderManagerService
id: EDITOR_ID,
body: {
dataStream: 'abc\r\n',
- paragraphs: [{ startIndex: 0, paragraphId: createParagraphId(new Set()) }],
- sectionBreaks: [],
+ paragraphs: [{ startIndex: 3, paragraphId: createParagraphId(new Set()) }],
+ sectionBreaks: [{ startIndex: 4 }],
customRanges: [],
tables: [],
textRuns: [],
diff --git a/packages/docs-ui/src/services/editor/editor.ts b/packages/docs-ui/src/services/editor/editor.ts
index 7262f5065f..9da5d71881 100644
--- a/packages/docs-ui/src/services/editor/editor.ts
+++ b/packages/docs-ui/src/services/editor/editor.ts
@@ -345,11 +345,11 @@ export class Editor extends Disposable implements IEditor {
body: {
dataStream: `${text}\r\n`,
paragraphs: [{
- startIndex: 0,
+ startIndex: text.length,
paragraphId: createParagraphId(new Set()),
}],
customRanges: [],
- sectionBreaks: [],
+ sectionBreaks: [{ startIndex: text.length + 1 }],
tables: [],
textRuns: [],
},
diff --git a/packages/docs-ui/src/views/ParagraphMenu.tsx b/packages/docs-ui/src/views/ParagraphMenu.tsx
index fb144d93a2..3f0a3afaee 100644
--- a/packages/docs-ui/src/views/ParagraphMenu.tsx
+++ b/packages/docs-ui/src/views/ParagraphMenu.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { DocumentDataModel, IDocumentBlockRange, IDocumentBody, IParagraph, ITextRun } from '@univerjs/core';
+import type { DocumentDataModel, IDocumentBlockRange, IDocumentBody, IParagraph, ITextRun, JSONXActions } from '@univerjs/core';
import type { IDocBlockMoveValidationContext } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IPopup, IValueOption, RectPopupDirection } from '@univerjs/ui';
@@ -29,6 +29,7 @@ import {
JSONX,
NamedStyleType,
SliceBodyType,
+ TextX,
Tools,
UniverInstanceType,
} from '@univerjs/core';
@@ -613,19 +614,132 @@ export function unwrapBlockRangeBody(documentBody: IDocumentBody, blockRange: ID
};
}
-function buildReplaceBodyActions(previousBody: IDocumentBody, nextBody: IDocumentBody) {
- const jsonX = JSONX.getInstance();
- return [
- jsonX.replaceOp(['body', 'dataStream'], previousBody.dataStream, nextBody.dataStream),
- jsonX.replaceOp(['body', 'paragraphs'], previousBody.paragraphs, nextBody.paragraphs),
- jsonX.replaceOp(['body', 'sectionBreaks'], previousBody.sectionBreaks, nextBody.sectionBreaks),
- jsonX.replaceOp(['body', 'textRuns'], previousBody.textRuns, nextBody.textRuns),
- jsonX.replaceOp(['body', 'customRanges'], previousBody.customRanges, nextBody.customRanges),
- jsonX.replaceOp(['body', 'customDecorations'], previousBody.customDecorations, nextBody.customDecorations),
- jsonX.replaceOp(['body', 'customBlocks'], previousBody.customBlocks, nextBody.customBlocks),
- jsonX.replaceOp(['body', 'tables'], previousBody.tables, nextBody.tables),
- jsonX.replaceOp(['body', 'blockRanges'], previousBody.blockRanges, nextBody.blockRanges),
- ].reduce((acc, action) => JSONX.compose(acc, action), null as ReturnType<typeof JSONX.compose>);
+const UNWRAP_BLOCK_BODY_PATCH_KEYS = [
+ 'paragraphs',
+ 'sectionBreaks',
+ 'textRuns',
+ 'customRanges',
+ 'customDecorations',
+ 'customBlocks',
+ 'tables',
+ 'columnGroups',
+ 'blockRanges',
+] as const satisfies Array<keyof IDocumentBody>;
+
+export function buildUnwrapBlockRangeActions(previousBody: IDocumentBody, nextBody: IDocumentBody, blockRange: IDocumentBlockRange): JSONXActions | null {
+ const endTokenOffset = getEndTokenOffset(previousBody, blockRange);
+ const textX = new TextX();
+
+ textX.retain(blockRange.startIndex);
+ textX.delete(1);
+ textX.retain(Math.max(0, endTokenOffset - blockRange.startIndex - 1));
+ textX.delete(1);
+
+ const textAction = JSONX.getInstance().editOp(textX.serialize(), ['body']);
+ const intermediateBody = Tools.deepClone(previousBody);
+ TextX.apply(intermediateBody, textX.serialize());
+
+ const rawActions = [textAction];
+ collectUnwrapBlockBodyPatchActions(intermediateBody, nextBody, rawActions);
+
+ return rawActions.reduce((acc, action) => JSONX.compose(acc, action), null as JSONXActions);
+}
+
+function collectUnwrapBlockBodyPatchActions(previousBody: IDocumentBody, nextBody: IDocumentBody, actions: JSONXActions[]): void {
+ for (const key of UNWRAP_BLOCK_BODY_PATCH_KEYS) {
+ collectUnwrapPatchActions(
+ JSONX.getInstance(),
+ ['body', key],
+ previousBody[key],
+ nextBody[key],
+ actions
+ );
+ }
+}
+
+function collectUnwrapPatchActions(
+ jsonX: JSONX,
+ path: (string | number)[],
+ oldValue: unknown,
+ newValue: unknown,
+ actions: JSONXActions[]
+): void {
+ if (isEmptyArrayEquivalent(oldValue, newValue) || Tools.diffValue(oldValue, newValue)) {
+ return;
+ }
+
+ if (oldValue == null) {
+ actions.push(jsonX.insertOp(path, newValue));
+ return;
+ }
+
+ if (newValue == null) {
+ actions.push(jsonX.removeOp(path, oldValue));
+ return;
+ }
+
+ if (Array.isArray(oldValue) && Array.isArray(newValue)) {
+ collectUnwrapArrayPatchActions(jsonX, path, oldValue, newValue, actions);
+ return;
+ }
+
+ if (isPlainObject(oldValue) && isPlainObject(newValue)) {
+ const keys = new Set([...Object.keys(oldValue), ...Object.keys(newValue)]);
+ keys.forEach((key) => collectUnwrapPatchActions(
+ jsonX,
+ [...path, key],
+ (oldValue as Record<string, unknown>)[key],
+ (newValue as Record<string, unknown>)[key],
+ actions
+ ));
+ return;
+ }
+
+ actions.push(jsonX.replaceOp(path, oldValue, newValue));
+}
+
+function collectUnwrapArrayPatchActions(
+ jsonX: JSONX,
+ path: (string | number)[],
+ oldItems: unknown[],
+ newItems: unknown[],
+ actions: JSONXActions[]
+): void {
+ if (oldItems.length === newItems.length) {
+ oldItems.forEach((item, index) => collectUnwrapPatchActions(jsonX, [...path, index], item, newItems[index], actions));
+ return;
+ }
+
+ let prefix = 0;
+ while (prefix < oldItems.length && prefix < newItems.length && Tools.diffValue(oldItems[prefix], newItems[prefix])) {
+ prefix++;
+ }
+
+ let oldSuffix = oldItems.length - 1;
+ let newSuffix = newItems.length - 1;
+ while (oldSuffix >= prefix && newSuffix >= prefix && Tools.diffValue(oldItems[oldSuffix], newItems[newSuffix])) {
+ oldSuffix--;
+ newSuffix--;
+ }
+
+ for (let index = oldSuffix; index >= prefix; index--) {
+ actions.push(jsonX.removeOp([...path, index], oldItems[index]));
+ }
+
+ for (let index = prefix; index <= newSuffix; index++) {
+ actions.push(jsonX.insertOp([...path, index], newItems[index]));
+ }
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return value != null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function isEmptyArrayEquivalent(oldValue: unknown, newValue: unknown): boolean {
+ return (
+ (oldValue == null && Array.isArray(newValue) && newValue.length === 0) ||
+ (newValue == null && Array.isArray(oldValue) && oldValue.length === 0)
+ );
}
function getTargetSelectionRange(target: IDocBlockMenuTarget | null | undefined, paragraph?: IMutiPageParagraphBound | null): ITextRangeWithStyle | null {
@@ -877,7 +991,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
const previousBody = doc.getBody()!;
const { body, range } = unwrapBlockRangeBody(previousBody, latestTarget.blockRange);
- const actions = buildReplaceBodyActions(previousBody, body);
+ const actions = buildUnwrapBlockRangeActions(previousBody, body, latestTarget.blockRange);
const segmentId = activeParagraphBound?.segmentId ?? '';
const success = await commandService.executeCommand(RichTextEditingMutation.id, {
diff --git a/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts b/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
index 381f448674..ddf0f96fb7 100644
--- a/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
+++ b/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
@@ -19,7 +19,7 @@ import type { IDocBlockMoveValidationContext } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IMutiPageParagraphBound } from '../../services/doc-event-manager.service';
import type { IDocBlockMenuTarget } from '../../services/doc-paragraph-menu.service';
-import { DataStreamTreeTokenType, DocumentBlockRangeType, DocumentBlockType, NamedStyleType } from '@univerjs/core';
+import { DataStreamTreeTokenType, DocumentBlockRangeType, DocumentBlockType, JSONX, NamedStyleType } from '@univerjs/core';
import { DocBlockMoveValidatorService } from '@univerjs/docs';
import { describe, expect, it } from 'vitest';
import { DeleteCurrentParagraphCommand } from '../../commands/commands/doc-delete.command';
@@ -29,6 +29,7 @@ import { AlignCenterCommand } from '../../commands/commands/paragraph-align.comm
import { H2HeadingCommand, SetParagraphNamedStyleCommand } from '../../commands/commands/set-heading.command';
import { DOC_PARAGRAPH_T_EDIT_MENU_ID, INSERT_BELLOW_MENU_ID } from '../../menu/paragraph-menu';
import {
+ buildUnwrapBlockRangeActions,
getParagraphFormattingRange,
getParagraphMenuCommandParams,
getParagraphMenuCommandTargetRange,
@@ -248,6 +249,33 @@ describe('ParagraphMenu command behavior', () => {
});
});
+ it('builds unwrap actions with TextX and local patches instead of replacing whole body fields', () => {
+ const blockRange = {
+ blockId: 'block-1',
+ blockType: DocumentBlockRangeType.CODE,
+ startIndex: 0,
+ endIndex: 2,
+ };
+ const previousBody = blockRangeBody(DocumentBlockRangeType.CODE, {
+ indentStart: { v: 12 },
+ indentEnd: { v: 8 },
+ spaceAbove: { v: 4 },
+ spaceBelow: { v: 6 },
+ textStyle: { ff: 'monospace', fs: 12 },
+ });
+ const { body } = unwrapBlockRangeBody(previousBody, blockRange);
+
+ const actions = buildUnwrapBlockRangeActions(previousBody, body, blockRange);
+ const serializedActions = JSON.stringify(actions);
+
+ expect(actions).not.toBeNull();
+ expect(serializedActions).toContain('"et":"text-x"');
+ expect(serializedActions).not.toContain('["body","dataStream"');
+ expect(serializedActions).not.toContain('["body","paragraphs",{"r"');
+ const appliedBody = (JSONX.apply({ id: 'doc-1', body: previousBody, documentStyle: {} }, actions!) as unknown as { body: IDocumentBody }).body;
+ expect(normalizeOptionalArrays(appliedBody)).toEqual(normalizeOptionalArrays(body));
+ });
+
it('routes explicit and declared insert actions below the active block', () => {
expect(shouldUseInsertBelowRange('doc.command.insert-image', { id: 'image' })).toBe(true);
expect(shouldUseInsertBelowRange('docs.operation.insert-embed', { id: 'docs.operation.insert-embed.below' })).toBe(true);
@@ -289,3 +317,9 @@ describe('ParagraphMenu command behavior', () => {
}]);
});
});
+
+function normalizeOptionalArrays(body: IDocumentBody): IDocumentBody {
+ return Object.fromEntries(
+ Object.entries(body).filter(([, value]) => !Array.isArray(value) || value.length > 0)
+ ) as IDocumentBody;
+}
diff --git a/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts b/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts
index f8fbbfee8b..cd51f78042 100644
--- a/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts
+++ b/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts
@@ -14,9 +14,10 @@
* limitations under the License.
*/
-import { DeleteDirection, ICommandService } from '@univerjs/core';
+import { DeleteDirection, getRichTextEditPath, ICommandService, JSONX, TextXActionType } from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { createTestBed } from '../../../facade/__tests__/create-test-bed';
+import { RichTextEditingMutation } from '../../mutations/core-editing.mutation';
import { DeleteTextCommand, InsertTextCommand, UpdateTextCommand } from '../core-editing.command';
describe('core editing commands', () => {
@@ -47,6 +48,174 @@ describe('core editing commands', () => {
expect(testBed.univerAPI.getActiveDocument()?.save().body?.dataStream).toBe('Hello\r\n');
});
+ it('does not delete the document minimum paragraph sentinel', () => {
+ const result = commandService.syncExecuteCommand(DeleteTextCommand.id, {
+ unitId: 'test',
+ range: {
+ startOffset: 6,
+ endOffset: 6,
+ collapsed: true,
+ },
+ direction: DeleteDirection.RIGHT,
+ });
+
+ expect(result).toBe(true);
+ expect(testBed.univerAPI.getActiveDocument()?.save().body?.dataStream).toBe('Hello,\r\n');
+ });
+
+ it('does not delete the minimum paragraph sentinel in a header segment', () => {
+ testBed.univer.dispose();
+ testBed = createTestBed({
+ id: 'test',
+ body: {
+ dataStream: 'Body\r\n',
+ paragraphs: [{ startIndex: 4, paragraphId: 'body' }],
+ sectionBreaks: [{ startIndex: 5 }],
+ },
+ headers: {
+ 'header-1': {
+ headerId: 'header-1',
+ body: {
+ dataStream: 'Head\r\n',
+ paragraphs: [{ startIndex: 4, paragraphId: 'header' }],
+ sectionBreaks: [{ startIndex: 5 }],
+ },
+ },
+ },
+ documentStyle: {},
+ });
+ commandService = testBed.get(ICommandService);
+
+ const result = commandService.syncExecuteCommand(DeleteTextCommand.id, {
+ unitId: 'test',
+ segmentId: 'header-1',
+ range: {
+ startOffset: 4,
+ endOffset: 4,
+ collapsed: true,
+ },
+ direction: DeleteDirection.RIGHT,
+ });
+
+ expect(result).toBe(true);
+ expect(testBed.doc.getSnapshot().headers?.['header-1'].body.dataStream).toBe('Head\r\n');
+ });
+
+ it('keeps a header segment structurally valid when replacing all text', () => {
+ testBed.univer.dispose();
+ testBed = createTestBed({
+ id: 'test',
+ body: {
+ dataStream: 'B\r\n',
+ paragraphs: [{ startIndex: 1, paragraphId: 'body' }],
+ sectionBreaks: [{ startIndex: 2 }],
+ },
+ headers: {
+ 'header-1': {
+ headerId: 'header-1',
+ body: {
+ dataStream: 'LongHead\r\n',
+ paragraphs: [{ startIndex: 8, paragraphId: 'header' }],
+ sectionBreaks: [{ startIndex: 9 }],
+ },
+ },
+ },
+ documentStyle: {},
+ });
+ commandService = testBed.get(ICommandService);
+
+ const result = commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: 'test',
+ segmentId: 'header-1',
+ body: { dataStream: 'X' },
+ range: {
+ startOffset: 0,
+ endOffset: 10,
+ collapsed: false,
+ segmentId: 'header-1',
+ },
+ });
+
+ expect(result).toBe(true);
+ expect(testBed.doc.getSnapshot().headers?.['header-1'].body.dataStream).toBe('X\r\n');
+ });
+
+ it('keeps a footer segment structurally valid when replacing all text', () => {
+ testBed.univer.dispose();
+ testBed = createTestBed({
+ id: 'test',
+ body: {
+ dataStream: 'B\r\n',
+ paragraphs: [{ startIndex: 1, paragraphId: 'body' }],
+ sectionBreaks: [{ startIndex: 2 }],
+ },
+ footers: {
+ 'footer-1': {
+ footerId: 'footer-1',
+ body: {
+ dataStream: 'LongFooter\r\n',
+ paragraphs: [{ startIndex: 10, paragraphId: 'footer' }],
+ sectionBreaks: [{ startIndex: 11 }],
+ },
+ },
+ },
+ documentStyle: {},
+ });
+ commandService = testBed.get(ICommandService);
+
+ const result = commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: 'test',
+ segmentId: 'footer-1',
+ body: { dataStream: 'Y' },
+ range: {
+ startOffset: 0,
+ endOffset: 12,
+ collapsed: false,
+ segmentId: 'footer-1',
+ },
+ });
+
+ expect(result).toBe(true);
+ expect(testBed.doc.getSnapshot().footers?.['footer-1'].body.dataStream).toBe('Y\r\n');
+ });
+
+ it('rejects invalid rich text mutations in header segments and rolls them back', () => {
+ testBed.univer.dispose();
+ testBed = createTestBed({
+ id: 'test',
+ body: {
+ dataStream: 'Body\r\n',
+ paragraphs: [{ startIndex: 4, paragraphId: 'body' }],
+ sectionBreaks: [{ startIndex: 5 }],
+ },
+ headers: {
+ 'header-1': {
+ headerId: 'header-1',
+ body: {
+ dataStream: 'Head\r\n',
+ paragraphs: [{ startIndex: 4, paragraphId: 'header' }],
+ sectionBreaks: [{ startIndex: 5 }],
+ },
+ },
+ },
+ documentStyle: {},
+ });
+ commandService = testBed.get(ICommandService);
+
+ const actions = JSONX.getInstance().editOp([
+ { t: TextXActionType.RETAIN, len: 4 },
+ { t: TextXActionType.DELETE, len: 2 },
+ ], getRichTextEditPath(testBed.doc, 'header-1'));
+
+ expect(() => commandService.syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId: 'test',
+ segmentId: 'header-1',
+ actions,
+ textRanges: null,
+ })).toThrow('[DocStructure] header header-1');
+ expect(testBed.doc.getSnapshot().headers?.['header-1'].body.dataStream).toBe('Head\r\n');
+ });
+
it('expands deletion to whole custom entities', () => {
testBed.univer.dispose();
testBed = createTestBed({
diff --git a/packages/docs/src/commands/commands/core-editing.command.ts b/packages/docs/src/commands/commands/core-editing.command.ts
index 001fb41962..21d93fd7b9 100644
--- a/packages/docs/src/commands/commands/core-editing.command.ts
+++ b/packages/docs/src/commands/commands/core-editing.command.ts
@@ -67,7 +67,9 @@ export const InsertTextCommand: ICommand<IInsertTextCommandParams> = {
}
const activeRange = docSelectionManagerService.getActiveTextRange();
- const originBody = docDataModel.getSelfOrHeaderFooterModel(activeRange?.segmentId ?? '')?.getBody();
+ const rangeSegmentId = 'segmentId' in range ? (range as ITextRange & { segmentId?: string }).segmentId : undefined;
+ const targetSegmentId = segmentId ?? rangeSegmentId ?? activeRange?.segmentId ?? '';
+ const originBody = docDataModel.getSelfOrHeaderFooterModel(targetSegmentId)?.getBody();
if (originBody == null) {
return false;
@@ -186,16 +188,12 @@ export const DeleteTextCommand: ICommand<IDeleteTextCommandParams> = {
const textX = new TextX();
const jsonX = JSONX.getInstance();
- const cursor = 0;
- textX.push({
- t: TextXActionType.RETAIN,
- len: start - cursor,
- });
-
- textX.push({
- t: TextXActionType.DELETE,
- len: end - start + 1,
- });
+ textX.push(...BuildTextUtils.selection.delete([{
+ ...range,
+ startOffset: start,
+ endOffset: end + 1,
+ collapsed: false,
+ }], body));
const path = getRichTextEditPath(docDataModel, segmentId);
doMutation.params.actions = jsonX.editOp(textX.serialize(), path);
diff --git a/packages/docs/src/commands/mutations/core-editing.mutation.ts b/packages/docs/src/commands/mutations/core-editing.mutation.ts
index 17ad4fcb03..58121afaeb 100644
--- a/packages/docs/src/commands/mutations/core-editing.mutation.ts
+++ b/packages/docs/src/commands/mutations/core-editing.mutation.ts
@@ -17,7 +17,7 @@
import type { DocumentDataModel, IExecutionOptions, IMutation, IMutationCommonParams, JSONXActions, Nullable } from '@univerjs/core';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IDocStateChangeInfo } from '../../services/doc-state-emit.service';
-import { CommandType, IUniverInstanceService, JSONX, UniverInstanceType } from '@univerjs/core';
+import { CommandType, IUniverInstanceService, JSONX, UniverInstanceType, validateDocBodyStructure } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
import { DocSelectionManagerService } from '../../services/doc-selection-manager.service';
import { DocSkeletonManagerService } from '../../services/doc-skeleton-manager.service';
@@ -43,6 +43,41 @@ export interface IRichTextEditingMutationParams extends IMutationCommonParams {
const RichTextEditingMutationId = 'doc.mutation.rich-text-editing';
+function getSegmentType(documentDataModel: DocumentDataModel, segmentId: string) {
+ if (!segmentId) {
+ return 'body' as const;
+ }
+
+ const { headers, footers } = documentDataModel.getSnapshot();
+ if (headers?.[segmentId]) {
+ return 'header' as const;
+ }
+
+ if (footers?.[segmentId]) {
+ return 'footer' as const;
+ }
+
+ return 'body' as const;
+}
+
+function assertValidDocBodyStructure(documentDataModel: DocumentDataModel, segmentId: string) {
+ const segmentModel = documentDataModel.getSelfOrHeaderFooterModel(segmentId);
+ const body = segmentModel?.getBody();
+ if (!body) {
+ return;
+ }
+
+ const segmentType = getSegmentType(documentDataModel, segmentId);
+ const issues = validateDocBodyStructure(body, { segmentType, segmentId: segmentId || undefined });
+ if (!issues.length) {
+ return;
+ }
+
+ const detail = issues.map((issue) => `${issue.code}${issue.index == null ? '' : `@${issue.index}`}`).join(', ');
+ const segmentLabel = segmentId ? `${segmentType} ${segmentId}` : segmentType;
+ throw new Error(`[DocStructure] ${segmentLabel}: ${detail}`);
+}
+
/**
* The core mutator to change rich text actions. The execution result would be undo mutation params. Could be directly
* send to undo redo service (will be used by the triggering command).
@@ -99,6 +134,12 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
// Step 1: Update Doc Data Model.
const undoActions = JSONX.invertWithDoc(actions, documentDataModel.getSnapshot());
documentDataModel.apply(actions);
+ try {
+ assertValidDocBodyStructure(documentDataModel, segmentId);
+ } catch (error) {
+ documentDataModel.apply(undoActions);
+ throw error;
+ }
// Step 2: Update Doc View Model.
documentViewModel?.reset(documentDataModel);