Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(docs): stabilize structural boundary editing (#7231)
Univereaa67e79f075
diff --git a/packages/core/src/docs/data-model/index.ts b/packages/core/src/docs/data-model/index.tsindex e874345ed2..5c1d1cedba 100644--- a/packages/core/src/docs/data-model/index.ts+++ b/packages/core/src/docs/data-model/index.ts@@ -31,7 +31,7 @@ export {} from './rich-text-builder';export { DEFAULT_DOCUMENT_SUB_COMPONENT_ID } from './subdocument';export { ActionIterator } from './text-x/action-iterator';-export { TextXActionType } from './text-x/action-types';+export { PRESERVE_INSERTED_PARAGRAPH_IDS, TextXActionType } from './text-x/action-types';export type { IDeleteAction, IInsertAction, IRetainAction, TextXAction } from './text-x/action-types';export { normalizeTextRuns, RESTORE_INSERTED_PARAGRAPH_IDS } from './text-x/apply-utils/common';export { updateAttributeByDelete } from './text-x/apply-utils/delete-apply';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.tsindex ed1be2eec2..d6217ca7bf 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@@ -19,8 +19,11 @@ import { DocumentBlockRangeType } from '@univerjs/core';import { describe, expect, it } from 'vitest';import { DataStreamTreeTokenType } from '../../types';import { deleteBlockRanges, insertBlockRanges } from '../apply-utils/common';+import { BuildTextUtils } from '../build-utils';import { getPlainText } from '../build-utils/parse';-import { getBodySlice, getBodySliceForTextXAction } from '../utils';+import { validateDocBodyStructure } from '../structure-validator';+import { TextX } from '../text-x';+import { getBodySlice, getBodySliceForTextXAction, getParagraphsSlice, SliceBodyType } from '../utils';describe('document block ranges', () => {it('moves following block ranges when text is inserted before them', () => {@@ -75,6 +78,23 @@ describe('document block ranges', () => {expect(slice.blockRanges).toBeUndefined();});+ it('does not treat a block end sentinel as text in the following paragraph', () => {+ const T = DataStreamTreeTokenType;+ const body: IDocumentBody = {+ dataStream: `${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_END}B${T.PARAGRAPH}${T.SECTION_BREAK}`,+ paragraphs: [+ { startIndex: 2, paragraphId: 'inside-block' },+ { startIndex: 5, paragraphId: 'after-block' },+ ],+ };++ expect(getParagraphsSlice(body, 3, 4, SliceBodyType.copy)).toBeUndefined();+ expect(getParagraphsSlice(body, 4, 5, SliceBodyType.copy)).toEqual([{+ startIndex: 1,+ paragraphId: 'after-block',+ }]);+ });+it('removes fully deleted block ranges', () => {const body: IDocumentBody = {dataStream: `${DataStreamTreeTokenType.BLOCK_START}A\r${DataStreamTreeTokenType.BLOCK_END}\n`,@@ -87,6 +107,65 @@ describe('document block ranges', () => {expect(body.blockRanges).toEqual([]);});+ it('keeps block sentinels and a paragraph when a deletion crosses one boundary', () => {+ const T = DataStreamTreeTokenType;+ const body: IDocumentBody = {+ dataStream: `${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_END}B${T.PARAGRAPH}${T.SECTION_BREAK}`,+ paragraphs: [+ { startIndex: 2, paragraphId: 'inside-block' },+ { startIndex: 5, paragraphId: 'after-block' },+ ],+ sectionBreaks: [{ startIndex: 6 }],+ blockRanges: [{+ blockId: 'code-1',+ blockType: DocumentBlockRangeType.CODE,+ startIndex: 0,+ endIndex: 3,+ }],+ };++ const actions = BuildTextUtils.selection.delete([+ { startOffset: 1, endOffset: 5, collapsed: false },+ ], body);+ TextX.apply(body, actions);++ expect(body.dataStream).toBe(`${T.BLOCK_START}${T.PARAGRAPH}${T.BLOCK_END}${T.PARAGRAPH}${T.SECTION_BREAK}`);+ expect(body.blockRanges).toEqual([{+ blockId: 'code-1',+ blockType: DocumentBlockRangeType.CODE,+ startIndex: 0,+ endIndex: 2,+ }]);+ expect(validateDocBodyStructure(body)).toEqual([]);+ });++ it('allows deleting a fully selected block atomically', () => {+ const T = DataStreamTreeTokenType;+ const body: IDocumentBody = {+ dataStream: `${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_END}B${T.PARAGRAPH}${T.SECTION_BREAK}`,+ paragraphs: [+ { startIndex: 2, paragraphId: 'inside-block' },+ { startIndex: 5, paragraphId: 'after-block' },+ ],+ sectionBreaks: [{ startIndex: 6 }],+ blockRanges: [{+ blockId: 'code-1',+ blockType: DocumentBlockRangeType.CODE,+ startIndex: 0,+ endIndex: 3,+ }],+ };++ const actions = BuildTextUtils.selection.delete([+ { startOffset: 0, endOffset: 4, collapsed: false },+ ], body);+ TextX.apply(body, actions);++ expect(body.dataStream).toBe(`B${T.PARAGRAPH}${T.SECTION_BREAK}`);+ expect(body.blockRanges).toEqual([]);+ expect(validateDocBodyStructure(body)).toEqual([]);+ });+it('removes block tokens from plain text', () => {const stream = `${DataStreamTreeTokenType.BLOCK_START}Callout\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.tsindex 1c2352c30d..5cb9176407 100644--- 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@@ -16,6 +16,7 @@import type { IDocumentBody } from '../../../../types/interfaces';import { describe, expect, it } from 'vitest';+import { DocumentBlockRangeType } from '../../../../types/interfaces';import { DataStreamTreeTokenType } from '../../types';import { validateDocBodyStructure, validateDocumentStructure } from '../structure-validator';@@ -56,6 +57,23 @@ describe('validateDocBodyStructure', () => {]);});+ it('reports duplicate paragraph and section metadata', () => {+ const T = DataStreamTreeTokenType;+ const body: IDocumentBody = {+ dataStream: `A${T.PARAGRAPH}B${T.PARAGRAPH}${T.SECTION_BREAK}`,+ paragraphs: [+ { startIndex: 1, paragraphId: 'first' },+ { startIndex: 1, paragraphId: 'duplicate-first' },+ ],+ sectionBreaks: [{ startIndex: 4 }, { startIndex: 4 }],+ };++ expect(validateDocBodyStructure(body).map((issue) => issue.code)).toEqual([+ 'duplicate-paragraph-metadata',+ 'duplicate-section-break-metadata',+ ]);+ });+it('reports columns that have no paragraph or section child', () => {const T = DataStreamTreeTokenType;const body: IDocumentBody = {@@ -105,6 +123,152 @@ describe('validateDocBodyStructure', () => {expect(validateDocBodyStructure(body).map((issue) => issue.code)).toContain('table-end-token-mismatch');});+ it('reports table token ranges without metadata', () => {+ const T = DataStreamTreeTokenType;+ const body: IDocumentBody = {+ dataStream: `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.PARAGRAPH}${T.SECTION_BREAK}`,+ paragraphs: [+ { startIndex: 3, paragraphId: 'cell' },+ { startIndex: 8, paragraphId: 'after-table' },+ ],+ sectionBreaks: [{ startIndex: 4 }, { startIndex: 9 }],+ };++ expect(validateDocBodyStructure(body).map((issue) => issue.code)).toContain('missing-table-metadata');+ });++ it('reports block metadata that points to another block end sentinel', () => {+ const T = DataStreamTreeTokenType;+ const body: IDocumentBody = {+ dataStream: `${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_START}${T.BLOCK_END}${T.PARAGRAPH}${T.BLOCK_END}${T.SECTION_BREAK}`,+ paragraphs: [+ { startIndex: 2, paragraphId: 'outer' },+ { startIndex: 5, paragraphId: 'inner' },+ ],+ sectionBreaks: [{ startIndex: 7 }],+ blockRanges: [+ { startIndex: 0, endIndex: 6, blockId: 'outer', blockType: DocumentBlockRangeType.CODE },+ { startIndex: 3, endIndex: 6, blockId: 'inner', blockType: DocumentBlockRangeType.CALLOUT },+ ],+ };++ expect(validateDocBodyStructure(body).map((issue) => issue.code)).toEqual([+ 'block-range-token-mismatch',+ 'overlapping-block-range',+ ]);+ });++ it('accepts adjacent block ranges', () => {+ const T = DataStreamTreeTokenType;+ const body: IDocumentBody = {+ dataStream: `${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_END}${T.BLOCK_START}${T.PARAGRAPH}${T.BLOCK_END}${T.SECTION_BREAK}`,+ paragraphs: [+ { startIndex: 2, paragraphId: 'first' },+ { startIndex: 5, paragraphId: 'second' },+ ],+ sectionBreaks: [{ startIndex: 7 }],+ blockRanges: [+ { startIndex: 0, endIndex: 3, blockId: 'first', blockType: DocumentBlockRangeType.CODE },+ { startIndex: 4, endIndex: 6, blockId: 'second', blockType: DocumentBlockRangeType.CALLOUT },+ ],+ };++ expect(validateDocBodyStructure(body)).toEqual([]);+ });++ it('reports block token ranges without metadata and unbalanced block tokens', () => {+ const T = DataStreamTreeTokenType;+ const missingMetadata: IDocumentBody = {+ dataStream: `${T.BLOCK_START}${T.PARAGRAPH}${T.BLOCK_END}${T.PARAGRAPH}${T.SECTION_BREAK}`,+ paragraphs: [+ { startIndex: 1, paragraphId: 'inside' },+ { startIndex: 3, paragraphId: 'after' },+ ],+ sectionBreaks: [{ startIndex: 4 }],+ };+ const unbalanced: IDocumentBody = {+ dataStream: `${T.BLOCK_START}${T.PARAGRAPH}${T.SECTION_BREAK}`,+ paragraphs: [{ startIndex: 1, paragraphId: 'inside' }],+ sectionBreaks: [{ startIndex: 2 }],+ };++ expect(validateDocBodyStructure(missingMetadata).map((issue) => issue.code)).toContain('missing-block-range-metadata');+ expect(validateDocBodyStructure(unbalanced).map((issue) => issue.code)).toContain('unbalanced-block');+ });++ it('validates column group pairing, metadata presence, overlap, and column count', () => {+ const T = DataStreamTreeTokenType;+ const dataStream = `${T.COLUMN_GROUP_START}${T.COLUMN_START}${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_START}${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`;+ const baseBody: IDocumentBody = {+ dataStream,+ paragraphs: [+ { startIndex: 2, paragraphId: 'left' },+ { startIndex: 5, paragraphId: 'right' },+ ],+ sectionBreaks: [{ startIndex: 8 }],+ };++ expect(validateDocBodyStructure(baseBody).map((issue) => issue.code)).toContain('missing-column-group-metadata');++ const badCount: IDocumentBody = {+ ...baseBody,+ columnGroups: [{+ startIndex: 0,+ endIndex: 7,+ columnGroupId: 'columns-1',+ columns: [{ columnId: 'left', widthRatio: 1 }],+ }],+ };+ expect(validateDocBodyStructure(badCount).map((issue) => issue.code)).toContain('column-group-column-count-mismatch');++ const overlapping: IDocumentBody = {+ ...baseBody,+ columnGroups: [+ { startIndex: 0, endIndex: 7, columnGroupId: 'columns-1' },+ { startIndex: 0, endIndex: 7, columnGroupId: 'columns-2' },+ ],+ };+ expect(validateDocBodyStructure(overlapping).map((issue) => issue.code)).toContain('overlapping-column-group');++ const exclusiveEnd: IDocumentBody = {+ ...baseBody,+ columnGroups: [{+ startIndex: 0,+ endIndex: 8,+ columnGroupId: 'columns-exclusive',+ columns: [+ { columnId: 'left', widthRatio: 1 },+ { columnId: 'right', widthRatio: 1 },+ ],+ }],+ };+ expect(validateDocBodyStructure(exclusiveEnd).map((issue) => issue.code)).toContain('column-group-range-token-mismatch');+ });++ it('requires custom block metadata to point at exactly one custom block sentinel', () => {+ const T = DataStreamTreeTokenType;+ const valid: IDocumentBody = {+ dataStream: `${T.CUSTOM_BLOCK}${T.PARAGRAPH}${T.SECTION_BREAK}`,+ paragraphs: [{ startIndex: 1, paragraphId: 'after-custom-block' }],+ sectionBreaks: [{ startIndex: 2 }],+ customBlocks: [{ startIndex: 0, blockId: 'drawing-1' }],+ };++ expect(validateDocBodyStructure(valid)).toEqual([]);+ expect(validateDocBodyStructure({ ...valid, customBlocks: [] }).map((issue) => issue.code)).toContain('missing-custom-block-metadata');+ expect(validateDocBodyStructure({+ ...valid,+ customBlocks: [+ { startIndex: 0, blockId: 'drawing-1' },+ { startIndex: 0, blockId: 'drawing-2' },+ ],+ }).map((issue) => issue.code)).toContain('duplicate-custom-block-metadata');+ expect(validateDocBodyStructure({+ ...valid,+ dataStream: `${T.BLOCK_START}${T.PARAGRAPH}${T.SECTION_BREAK}`,+ }).map((issue) => issue.code)).toContain('custom-block-token-mismatch');+ });+it('reports unbalanced structural tokens', () => {const T = DataStreamTreeTokenType;const body: IDocumentBody = {diff --git a/packages/core/src/docs/data-model/text-x/__tests__/paragraph-id.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/paragraph-id.spec.tsindex 9ec6b930a0..0a955bdb42 100644--- a/packages/core/src/docs/data-model/text-x/__tests__/paragraph-id.spec.ts+++ b/packages/core/src/docs/data-model/text-x/__tests__/paragraph-id.spec.ts@@ -15,15 +15,49 @@*/import type { IDocumentBody } from '../../../../types/interfaces';-import type { TextXAction } from '../action-types';+import type { TextXAction } from '../../index';import { describe, expect, it } from 'vitest';import { UpdateDocsAttributeType } from '../../../../shared';-import { TextXActionType } from '../action-types';+import { DataStreamTreeTokenType } from '../../types';+import { PRESERVE_INSERTED_PARAGRAPH_IDS, TextXActionType } from '../action-types';import { TextX } from '../text-x';const PARAGRAPH_ID_PATTERN = /^para_.+/;describe('TextX paragraph ids', () => {+ it('does not treat a structural gap as part of the following paragraph', () => {+ const T = DataStreamTreeTokenType;+ const body: IDocumentBody = {+ dataStream: `${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_END}${T.BLOCK_START}B${T.PARAGRAPH}${T.BLOCK_END}${T.PARAGRAPH}${T.SECTION_BREAK}`,+ paragraphs: [+ { startIndex: 2, paragraphId: 'para_left' },+ { startIndex: 6, paragraphId: 'para_right', paragraphStyle: { indentStart: { v: 60 } } },+ { startIndex: 8, paragraphId: 'para_trailing' },+ ],+ };+ const actions: TextXAction[] = [{+ t: TextXActionType.RETAIN,+ len: 4,+ }, {+ t: TextXActionType.INSERT,+ len: 1,+ body: {+ dataStream: T.PARAGRAPH,+ paragraphs: [{ startIndex: 0, paragraphId: 'para_inserted' }],+ },+ }];++ TextX.makeInvertible(actions, body);+ TextX.apply(body, actions);++ expect(body.paragraphs?.find((paragraph) => paragraph.paragraphId === 'para_right')).toEqual({+ startIndex: 7,+ paragraphId: 'para_right',+ paragraphStyle: { indentStart: { v: 60 } },+ });+ expect(body.paragraphs?.find((paragraph) => paragraph.startIndex === 4)?.paragraphId).not.toBe('para_right');+ });+it('preserves paragraph ids when inserting text before paragraphs', () => {const body: IDocumentBody = {dataStream: 'A\rB\r\n',@@ -376,4 +410,77 @@ describe('TextX paragraph ids', () => {},});});++ it('preserves explicit paragraph ids during an atomic structural replacement', () => {+ const body: IDocumentBody = {+ dataStream: 'A\rB\r\n',+ paragraphs: [+ { startIndex: 1, paragraphId: 'para_first' },+ { startIndex: 3, paragraphId: 'para_second' },+ ],+ };+ const replacementBody = {+ dataStream: 'A\rB\r',+ paragraphs: [+ { startIndex: 1, paragraphId: 'para_first' },+ { startIndex: 3, paragraphId: 'para_second' },+ ],+ [PRESERVE_INSERTED_PARAGRAPH_IDS]: true,+ } as IDocumentBody;+ const textX = new TextX();++ textX.insert(4, replacementBody);+ textX.delete(4);+ const actions = textX.serialize();+ TextX.makeInvertible(actions, body);+ TextX.apply(body, actions);++ expect(body.dataStream).toBe('A\rB\r\n');+ expect(body.paragraphs).toEqual([+ { startIndex: 1, paragraphId: 'para_first' },+ { startIndex: 3, paragraphId: 'para_second' },+ ]);+ expect((actions[0].body as IDocumentBody & Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS]).toBe(true);+ expect((body as IDocumentBody & Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS]).toBeUndefined();+ });++ it('preserves the structural replacement marker when insert actions are split and composed', () => {+ const body: IDocumentBody = {+ dataStream: 'A\rB\r\n',+ paragraphs: [+ { startIndex: 1, paragraphId: 'para_first' },+ { startIndex: 3, paragraphId: 'para_second' },+ ],+ };+ const replacement = new TextX();+ replacement.insert(4, {+ dataStream: 'A\rB\r',+ paragraphs: [+ { startIndex: 1, paragraphId: 'para_first' },+ { startIndex: 3, paragraphId: 'para_second' },+ ],+ [PRESERVE_INSERTED_PARAGRAPH_IDS]: true,+ } as IDocumentBody);+ replacement.delete(4);++ const formatting = new TextX();+ formatting.retain(2, {+ dataStream: '',+ paragraphs: [{ startIndex: 1, paragraphId: 'para_first', paragraphStyle: { spaceAbove: { v: 8 } } }],+ });+ formatting.retain(2);++ const composed = TextX.compose(replacement.serialize(), formatting.serialize());+ const insertedBodies = composed+ .filter((action) => action.t === TextXActionType.INSERT)+ .map((action) => action.body as IDocumentBody & Record<string, unknown>);++ expect(insertedBodies.length).toBeGreaterThan(0);+ expect(insertedBodies.every((insertedBody) => insertedBody[PRESERVE_INSERTED_PARAGRAPH_IDS] === true)).toBe(true);++ TextX.makeInvertible(composed, body);+ TextX.apply(body, composed);++ expect(body.paragraphs?.map((paragraph) => paragraph.paragraphId)).toEqual(['para_first', 'para_second']);+ });});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.tsindex 5dbc47f6cf..d25b6ec981 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@@ -175,6 +175,31 @@ describe('TextX tables', () => {expect(body.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([7, 14]);});+ it('removes table metadata when exactly the half-open table token range is deleted', () => {+ 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}`;+ const body: IDocumentBody = {+ dataStream: `${tableStream}After${T.PARAGRAPH}${T.SECTION_BREAK}`,+ paragraphs: [+ { startIndex: 7, paragraphId: 'cell' },+ { startIndex: tableStream.length + 5, paragraphId: 'after' },+ ],+ sectionBreaks: [+ { startIndex: 8 },+ { startIndex: tableStream.length + 6 },+ ],+ tables: [{ startIndex: 0, endIndex: tableStream.length, tableId: 'table-1' }],+ };+ const actions: TextXAction[] = [{ t: TextXActionType.DELETE, len: tableStream.length }];++ TextX.makeInvertible(actions, body);+ TextX.apply(body, actions);++ expect(body.dataStream).toBe(`After${T.PARAGRAPH}${T.SECTION_BREAK}`);+ expect(body.tables).toEqual([]);+ expect(actions[0].body?.tables).toEqual([{ startIndex: 0, endIndex: tableStream.length, tableId: 'table-1' }]);+ });+it('keeps a following column group outside the table when typing at the table end', () => {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}`;diff --git a/packages/core/src/docs/data-model/text-x/action-types.ts b/packages/core/src/docs/data-model/text-x/action-types.tsindex 3d246255b1..4889aeaa58 100644--- a/packages/core/src/docs/data-model/text-x/action-types.ts+++ b/packages/core/src/docs/data-model/text-x/action-types.ts@@ -17,6 +17,10 @@import type { UpdateDocsAttributeType } from '../../../shared/command-enum';import type { IDocumentBody } from '../../../types/interfaces/i-document-data';+// Internal TextX structural-replacement marker. Inserted paragraphs replace the+// same logical paragraphs later in the operation, so their ids must stay stable.+export const PRESERVE_INSERTED_PARAGRAPH_IDS = '__textXPreserveParagraphIds';+export enum TextXActionType {RETAIN = 'r',INSERT = 'i',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.tsindex d889c46ebb..e9e40e21ac 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@@ -32,6 +32,13 @@ import { horizontalLineSegmentsSubtraction, sortRulesFactory, Tools } from '../.import { isSameStyleTextRun } from '../../../../shared/compare';import { cloneParagraphWithId } from '../../../paragraph-id';import { DataStreamTreeTokenType } from '../../types';+import { PRESERVE_INSERTED_PARAGRAPH_IDS } from '../action-types';+import {+ shiftExclusiveRangeOnDelete,+ shiftExclusiveRangeOnInsert,+ shiftInclusiveRangeOnDelete,+ shiftInclusiveRangeOnInsert,+} from '../build-utils/range-interval';import { getBodySlice } from '../utils';// Internal TextX undo marker: restored delete bodies keep their captured paragraph ids.@@ -174,7 +181,8 @@ export function insertParagraphs(insertBody: IDocumentBody,textLength: number,currentIndex: number,- preserveMissingParagraphIds = false+ preserveMissingParagraphIds = false,+ originalDataStream = body.dataStream) {if (!body.paragraphs && !insertBody.paragraphs?.length) {return;@@ -188,6 +196,8 @@ export function insertParagraphs(freshenSplitParagraph: true,preserveMissingParagraphIds,preserveExplicitSplitParagraphIds: Boolean((insertBody as unknown as Record<string, unknown>)[RESTORE_INSERTED_PARAGRAPH_IDS]),+ preserveExplicitParagraphIds: Boolean((insertBody as unknown as Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS]),+ dataStream: originalDataStream,});const paragraphIndexList = [];@@ -234,20 +244,23 @@ export function normalizeInsertedParagraphIdsForDocument(options: {freshenSplitParagraph: boolean;preserveExplicitSplitParagraphIds?: boolean;+ preserveExplicitParagraphIds?: boolean;preserveMissingParagraphIds?: boolean;reservedParagraphIds?: Set<string>;+ dataStream?: string;}) {if (!paragraphs || !insertParagraphs?.length) {return;}- const splitParagraph = getParagraphSplitByInsert(paragraphs, currentIndex);+ const splitParagraph = getParagraphSplitByInsert(paragraphs, currentIndex, options.dataStream);const firstSplitInsertIndex = splitParagraph ? getFirstInsertedParagraphIndex(insertParagraphs) : -1;const splitParagraphId = splitParagraph?.paragraphId;const firstInsertedParagraphId = firstSplitInsertIndex === -1 ? undefined : insertParagraphs[firstSplitInsertIndex].paragraphId;- const shouldPreserveExplicitSplitParagraphId = options.preserveExplicitSplitParagraphIds && firstInsertedParagraphId != null && firstInsertedParagraphId !== splitParagraphId;+ const shouldPreserveExplicitSplitParagraphId = (options.preserveExplicitSplitParagraphIds || options.preserveExplicitParagraphIds) && firstInsertedParagraphId != null && firstInsertedParagraphId !== splitParagraphId;const existingParagraphIds = collectParagraphIds(paragraphs);+ const preservedInsertedParagraphIds = new Set<string>();if (splitParagraphId) {existingParagraphIds.delete(splitParagraphId);@@ -271,6 +284,15 @@ export function normalizeInsertedParagraphIdsForDocument(}for (let i = 0, len = insertParagraphs.length; i < len; i++) {+ const explicitParagraphId = insertParagraphs[i].paragraphId;+ if (options.preserveExplicitParagraphIds && explicitParagraphId && !preservedInsertedParagraphIds.has(explicitParagraphId)) {+ // The corresponding old paragraph is deleted later in the same TextX+ // operation. A temporary id collision is therefore intentional.+ insertParagraphs[i] = { ...insertParagraphs[i] };+ preservedInsertedParagraphIds.add(explicitParagraphId);+ continue;+ }+if (i !== firstSplitInsertIndex || splitParagraphId == null || shouldPreserveExplicitSplitParagraphId) {insertParagraphs[i] = cloneInsertedParagraphWithId(insertParagraphs[i], existingParagraphIds, options.preserveMissingParagraphIds ?? false);continue;@@ -315,12 +337,35 @@ function cloneInsertedParagraphWithId(return cloneParagraphWithId(insertParagraph, existingParagraphIds);}-function getParagraphSplitByInsert(paragraphs: IParagraph[], currentIndex: number): IParagraph | undefined {+const PARAGRAPH_CONTAINER_TOKENS = new Set<string>([+ DataStreamTreeTokenType.SECTION_BREAK,+ DataStreamTreeTokenType.TABLE_START,+ DataStreamTreeTokenType.TABLE_ROW_START,+ DataStreamTreeTokenType.TABLE_CELL_START,+ DataStreamTreeTokenType.TABLE_CELL_END,+ DataStreamTreeTokenType.TABLE_ROW_END,+ DataStreamTreeTokenType.TABLE_END,+ DataStreamTreeTokenType.COLUMN_GROUP_START,+ DataStreamTreeTokenType.COLUMN_START,+ DataStreamTreeTokenType.COLUMN_END,+ DataStreamTreeTokenType.COLUMN_GROUP_END,+ DataStreamTreeTokenType.BLOCK_START,+ DataStreamTreeTokenType.BLOCK_END,+]);++function getParagraphSplitByInsert(paragraphs: IParagraph[], currentIndex: number, dataStream?: string): IParagraph | undefined {const sortedParagraphs = [...paragraphs].sort((left, right) => left.startIndex - right.startIndex);for (let i = 0; i < sortedParagraphs.length; i++) {const paragraph = sortedParagraphs[i];- const paragraphStart = i > 0 ? sortedParagraphs[i - 1].startIndex + 1 : 0;+ let paragraphStart = i > 0 ? sortedParagraphs[i - 1].startIndex + 1 : 0;+ while (paragraphStart < paragraph.startIndex) {+ const token = dataStream?.[paragraphStart];+ if (!token || !PARAGRAPH_CONTAINER_TOKENS.has(token)) {+ break;+ }+ paragraphStart++;+ }if (currentIndex > paragraphStart && currentIndex < paragraph.startIndex) {return paragraph;@@ -424,14 +469,7 @@ export function insertTables(body: IDocumentBody, insertBody: IDocumentBody, texconst { tables } = body;for (let i = 0, len = tables.length; i < len; i++) {const table = tables[i];- const { startIndex, endIndex } = table;-- if (startIndex >= currentIndex) {- table.startIndex += textLength;- table.endIndex += textLength;- } else if (endIndex > currentIndex) {- table.endIndex += textLength;- }+ Object.assign(table, shiftExclusiveRangeOnInsert(table, currentIndex, textLength));}const insertTables = insertBody.tables;@@ -459,14 +497,7 @@ export function insertColumnGroups(body: IDocumentBody, insertBody: IDocumentBodconst { columnGroups } = body;for (let i = 0, len = columnGroups.length; i < len; i++) {const columnGroup = columnGroups[i];- const { startIndex, endIndex } = columnGroup;-- if (startIndex >= currentIndex) {- columnGroup.startIndex += textLength;- columnGroup.endIndex += textLength;- } else if (endIndex > currentIndex || (endIndex === currentIndex && body.dataStream[currentIndex + textLength] === DataStreamTreeTokenType.COLUMN_GROUP_END)) {- columnGroup.endIndex += textLength;- }+ Object.assign(columnGroup, shiftInclusiveRangeOnInsert(columnGroup, currentIndex, textLength));}const insertColumnGroups = insertBody.columnGroups;@@ -494,14 +525,7 @@ export function insertBlockRanges(body: IDocumentBody, insertBody: IDocumentBodyconst { blockRanges } = body;for (let i = 0, len = blockRanges.length; i < len; i++) {const blockRange = blockRanges[i];- const { startIndex, endIndex } = blockRange;-- if (startIndex >= currentIndex) {- blockRange.startIndex += textLength;- blockRange.endIndex += textLength;- } else if (endIndex >= currentIndex) {- blockRange.endIndex += textLength;- }+ Object.assign(blockRange, shiftInclusiveRangeOnInsert(blockRange, currentIndex, textLength));}const insertBlockRanges = insertBody.blockRanges;@@ -991,43 +1015,22 @@ export function deleteCustomBlocks(body: IDocumentBody, textLength: number, currexport function deleteTables(body: IDocumentBody, textLength: number, currentIndex: number) {const { tables } = body;-- const startIndex = currentIndex;-- const endIndex = currentIndex + textLength - 1;const removeTables: ICustomTable[] = [];if (tables) {const newTables = [];for (let i = 0, len = tables.length; i < len; i++) {const table = tables[i];- const { startIndex: st, endIndex: ed } = table;-- if (startIndex <= st && endIndex >= ed) {+ const transformed = shiftExclusiveRangeOnDelete(table, currentIndex, textLength);+ if (!transformed) {removeTables.push({...table,- startIndex: st - currentIndex,- endIndex: ed - currentIndex,+ startIndex: table.startIndex - currentIndex,+ endIndex: table.endIndex - currentIndex,});continue;- } else if (st <= startIndex && ed >= endIndex) {- const segments = horizontalLineSegmentsSubtraction(st, ed, startIndex, endIndex);-- if (segments.length === 0) {- continue;- }-- table.startIndex = segments[0];- table.endIndex = segments[1];-- // FIXME: @JOCS, why startIndex will equal to endIndex here?- if (table.startIndex === table.endIndex) {- continue;- }- } else if (endIndex < st) {- table.startIndex -= textLength;- table.endIndex -= textLength;}+ Object.assign(table, transformed);newTables.push(table);}body.tables = newTables;@@ -1038,42 +1041,22 @@ export function deleteTables(body: IDocumentBody, textLength: number, currentIndexport function deleteColumnGroups(body: IDocumentBody, textLength: number, currentIndex: number) {const { columnGroups } = body;-- const startIndex = currentIndex;-- const endIndex = currentIndex + textLength - 1;const removeColumnGroups: ICustomColumnGroup[] = [];if (columnGroups) {const newColumnGroups = [];for (let i = 0, len = columnGroups.length; i < len; i++) {const columnGroup = columnGroups[i];- const { startIndex: st, endIndex: ed } = columnGroup;-- if (startIndex <= st && endIndex >= ed) {+ const transformed = shiftInclusiveRangeOnDelete(columnGroup, currentIndex, textLength);+ if (!transformed) {removeColumnGroups.push({...columnGroup,- startIndex: st - currentIndex,- endIndex: ed - currentIndex,+ startIndex: columnGroup.startIndex - currentIndex,+ endIndex: columnGroup.endIndex - currentIndex,});continue;- } else if (st <= startIndex && ed >= endIndex) {- const segments = horizontalLineSegmentsSubtraction(st, ed, startIndex, endIndex);-- if (segments.length === 0) {- continue;- }-- columnGroup.startIndex = segments[0];- columnGroup.endIndex = segments[1];-- if (columnGroup.startIndex === columnGroup.endIndex) {- continue;- }- } else if (endIndex < st) {- columnGroup.startIndex -= textLength;- columnGroup.endIndex -= textLength;}+ Object.assign(columnGroup, transformed);newColumnGroups.push(columnGroup);}body.columnGroups = newColumnGroups;@@ -1084,9 +1067,6 @@ export function deleteColumnGroups(body: IDocumentBody, textLength: number, currexport function deleteCustomRanges(body: IDocumentBody, textLength: number, currentIndex: number) {const { customRanges } = body;-- const startIndex = currentIndex;- const endIndex = currentIndex + textLength - 1;// TODO: @JOCS, removeCustomRanges is not used, should we remove it?const removeCustomRanges: ICustomRange[] = [];@@ -1094,24 +1074,12 @@ export function deleteCustomRanges(body: IDocumentBody, textLength: number, currconst newCustomRanges = [];for (let i = 0, len = customRanges.length; i < len; i++) {const customRange = customRanges[i];- const { startIndex: st, endIndex: ed } = customRange;- // delete decoration- if (st >= startIndex && ed <= endIndex) {+ const transformed = shiftInclusiveRangeOnDelete(customRange, currentIndex, textLength);+ if (!transformed) {removeCustomRanges.push(customRange);continue;- } else if (Math.max(startIndex, st) <= Math.min(endIndex, ed)) {- const segments = horizontalLineSegmentsSubtraction(st, ed, startIndex, endIndex);-- if (segments.length === 0) {- continue;- }-- customRange.startIndex = segments[0];- customRange.endIndex = segments[1];- } else if (endIndex < st) {- customRange.startIndex -= textLength;- customRange.endIndex -= textLength;}+ Object.assign(customRange, transformed);newCustomRanges.push(customRange);}@@ -1123,33 +1091,18 @@ export function deleteCustomRanges(body: IDocumentBody, textLength: number, currexport function deleteBlockRanges(body: IDocumentBody, textLength: number, currentIndex: number) {const { blockRanges } = body;-- const startIndex = currentIndex;- const endIndex = currentIndex + textLength - 1;const removeBlockRanges: IDocumentBlockRange[] = [];if (blockRanges) {const newBlockRanges = [];for (let i = 0, len = blockRanges.length; i < len; i++) {const blockRange = blockRanges[i];- const { startIndex: st, endIndex: ed } = blockRange;- if (st >= startIndex && ed <= endIndex) {+ const transformed = shiftInclusiveRangeOnDelete(blockRange, currentIndex, textLength);+ if (!transformed) {removeBlockRanges.push(blockRange);continue;- } else if (Math.max(startIndex, st) <= Math.min(endIndex, ed)) {- const segments = horizontalLineSegmentsSubtraction(st, ed, startIndex, endIndex);-- if (segments.length === 0) {- removeBlockRanges.push(blockRange);- continue;- }-- blockRange.startIndex = segments[0];- blockRange.endIndex = segments[1];- } else if (endIndex < st) {- blockRange.startIndex -= textLength;- blockRange.endIndex -= textLength;}+ Object.assign(blockRange, transformed);newBlockRanges.push(blockRange);}diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.tsindex 52eda0373e..15580dc158 100644--- a/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts+++ b/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts@@ -34,11 +34,12 @@ export function updateAttributeByInsert(textLength: number,currentIndex: number) {+ const originalDataStream = body.dataStream;body.dataStream = insertTextToContent(body.dataStream, currentIndex, insertBody.dataStream);insertTextRuns(body, insertBody, textLength, currentIndex);- insertParagraphs(body, insertBody, textLength, currentIndex);+ insertParagraphs(body, insertBody, textLength, currentIndex, false, originalDataStream);insertSectionBreaks(body, insertBody, textLength, currentIndex);diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/data-stream-change.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/data-stream-change.spec.tsnew file mode 100644index 0000000000..c3e7f9d185--- /dev/null+++ b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/data-stream-change.spec.ts@@ -0,0 +1,55 @@+/**+ * 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 { DocumentBlockRangeType } from '../../../../../types/interfaces';+import { DataStreamTreeTokenType } from '../../../types';+import { getSingleDataStreamChange } from '../data-stream-change';++describe('getSingleDataStreamChange', () => {+ it('anchors an inserted block before an adjacent identical start sentinel', () => {+ const T = DataStreamTreeTokenType;+ const previousBody: IDocumentBody = {+ dataStream: `${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_END}${T.BLOCK_START}B${T.PARAGRAPH}${T.BLOCK_END}`,+ blockRanges: [+ { blockId: 'code-1', blockType: DocumentBlockRangeType.CODE, startIndex: 0, endIndex: 3 },+ { blockId: 'quote-1', blockType: DocumentBlockRangeType.QUOTE, startIndex: 4, endIndex: 7 },+ ],+ };+ const nextBody: IDocumentBody = {+ dataStream: `${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_END}${T.BLOCK_START}${T.PARAGRAPH}${T.BLOCK_END}${T.BLOCK_START}B${T.PARAGRAPH}${T.BLOCK_END}`,+ blockRanges: [+ previousBody.blockRanges![0],+ { blockId: 'callout-1', blockType: DocumentBlockRangeType.CALLOUT, startIndex: 4, endIndex: 6 },+ { blockId: 'quote-1', blockType: DocumentBlockRangeType.QUOTE, startIndex: 7, endIndex: 10 },+ ],+ };++ expect(getSingleDataStreamChange(previousBody, nextBody)).toEqual({+ start: 4,+ deleteLength: 0,+ insertLength: 3,+ });+ });++ it('falls back to the minimal contiguous text change', () => {+ expect(getSingleDataStreamChange(+ { dataStream: 'Alpha\r' },+ { dataStream: 'AlXpha\r' }+ )).toEqual({ start: 2, deleteLength: 0, insertLength: 1 });+ });+});diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/paragraph.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/paragraph.spec.tsindex 1e1b6f8e74..b46f99497b 100644--- a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/paragraph.spec.ts+++ b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/paragraph.spec.ts@@ -17,11 +17,16 @@import type { IDocumentBody, IParagraph } from '../../../../../types/interfaces';import { describe, expect, it } from 'vitest';import { HorizontalAlign } from '../../../../../types/enum';+import { DocumentBlockRangeType } from '../../../../../types/interfaces';import { DocumentDataModel } from '../../../document-data-model';import { PresetListType } from '../../../preset-list-type';+import { DataStreamTreeTokenType } from '../../../types';import { TextX } from '../../text-x';import {changeParagraphBulletNestLevel,+ getParagraphContentStartOffset,+ getParagraphContentStartOffsets,+ getParagraphFollowingBlockOffset,hasParagraphInTable,setParagraphBullet,setParagraphStyle,@@ -86,6 +91,57 @@ function createDocModel() {}describe('paragraph build utils', () => {+ it('skips structural container sentinels when resolving paragraph content starts', () => {+ const T = DataStreamTreeTokenType;+ const cases = [+ `${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_END}${T.PARAGRAPH}`,+ `${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.PARAGRAPH}`,+ `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.SECTION_BREAK}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.PARAGRAPH}`,+ ];++ for (const dataStream of cases) {+ const firstParagraphIndex = dataStream.indexOf(T.PARAGRAPH);+ const paragraph = {+ startIndex: dataStream.lastIndexOf(T.PARAGRAPH),+ paragraphId: `para-structural-${dataStream.length}`,+ };+ const body: IDocumentBody = {+ dataStream,+ paragraphs: [+ { startIndex: firstParagraphIndex, paragraphId: 'para-before-structure' },+ paragraph,+ ],+ };++ expect(getParagraphContentStartOffset(body, paragraph)).toBe(paragraph.startIndex);+ }+ });++ it('resolves insert-below offsets after a containing document block', () => {+ expect(getParagraphFollowingBlockOffset({+ blockRanges: [{+ blockId: 'code-1',+ blockType: DocumentBlockRangeType.CODE,+ startIndex: 0,+ endIndex: 6,+ }],+ }, { startIndex: 5 })).toBe(7);+ expect(getParagraphFollowingBlockOffset({}, { startIndex: 5 })).toBe(6);+ });++ it('resolves all paragraph starts in one structural pass', () => {+ const T = DataStreamTreeTokenType;+ const body: IDocumentBody = {+ dataStream: `${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_END}B${T.PARAGRAPH}`,+ paragraphs: [+ { startIndex: 2, paragraphId: 'inside' },+ { startIndex: 5, paragraphId: 'after' },+ ],+ };++ expect([...getParagraphContentStartOffsets(body)]).toEqual([[2, 1], [5, 4]]);+ });+it('should switch bullets using adjacent paragraph context and remove an existing list when toggled again', () => {const doc = createDocModel();const body = doc.getBody()!;diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/range-interval.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/range-interval.spec.tsnew file mode 100644index 0000000000..9a95b841fb--- /dev/null+++ b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/range-interval.spec.ts@@ -0,0 +1,98 @@+/**+ * 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 { describe, expect, it } from 'vitest';+import { DataStreamTreeTokenType } from '../../../types';+import {+ containsInteriorInsertionOffset,+ containsStreamIndex,+ getBlockRangeInterval,+ getColumnGroupRangeInterval,+ getCustomBlockInterval,+ getCustomRangeInterval,+ getTableCellTokenInterval,+ getTableRangeInterval,+ getTableRowTokenInterval,+ intersectsOperationalIntervals,+ shiftExclusiveRangeOnDelete,+ shiftExclusiveRangeOnInsert,+ shiftInclusiveRangeOnDelete,+ shiftInclusiveRangeOnInsert,+} from '../range-interval';++describe('document operational intervals', () => {+ it('normalizes persisted range conventions to half-open intervals', () => {+ expect(getTableRangeInterval({ startIndex: 2, endIndex: 8 })).toEqual({ startOffset: 2, endOffset: 8 });+ expect(getBlockRangeInterval({ startIndex: 2, endIndex: 8 })).toEqual({ startOffset: 2, endOffset: 9 });+ expect(getColumnGroupRangeInterval({ startIndex: 2, endIndex: 8 })).toEqual({ startOffset: 2, endOffset: 9 });+ expect(getCustomRangeInterval({ startIndex: 2, endIndex: 8 })).toEqual({ startOffset: 2, endOffset: 9 });+ expect(getCustomBlockInterval({ startIndex: 2 })).toEqual({ startOffset: 2, endOffset: 3 });+ });++ it('keeps stream indexes and boundary insertion points distinct', () => {+ const interval = { startOffset: 2, endOffset: 8 };++ expect(containsStreamIndex(interval, 2)).toBe(true);+ expect(containsStreamIndex(interval, 7)).toBe(true);+ expect(containsStreamIndex(interval, 8)).toBe(false);+ expect(containsInteriorInsertionOffset(interval, 2)).toBe(false);+ expect(containsInteriorInsertionOffset(interval, 3)).toBe(true);+ expect(containsInteriorInsertionOffset(interval, 8)).toBe(false);+ });++ it('uses half-open overlap semantics for adjacent structures', () => {+ expect(intersectsOperationalIntervals(+ { startOffset: 0, endOffset: 4 },+ { startOffset: 4, endOffset: 8 }+ )).toBe(false);+ expect(intersectsOperationalIntervals(+ { startOffset: 0, endOffset: 5 },+ { startOffset: 4, endOffset: 8 }+ )).toBe(true);+ });++ it('applies insertion affinity according to persisted range semantics', () => {+ const inclusive = { startIndex: 2, endIndex: 5, id: 'inclusive' };+ const exclusive = { startIndex: 2, endIndex: 6, id: 'exclusive' };++ expect(shiftInclusiveRangeOnInsert(inclusive, 5, 2)).toEqual({ ...inclusive, endIndex: 7 });+ expect(shiftInclusiveRangeOnInsert(inclusive, 6, 2)).toBe(inclusive);+ expect(shiftExclusiveRangeOnInsert(exclusive, 5, 2)).toEqual({ ...exclusive, endIndex: 8 });+ expect(shiftExclusiveRangeOnInsert(exclusive, 6, 2)).toBe(exclusive);+ });++ it('removes or shrinks ranges using their persisted end convention', () => {+ const inclusive = { startIndex: 2, endIndex: 5, id: 'inclusive' };+ const exclusive = { startIndex: 2, endIndex: 6, id: 'exclusive' };++ expect(shiftInclusiveRangeOnDelete(inclusive, 5, 1)).toEqual({ ...inclusive, endIndex: 4 });+ expect(shiftExclusiveRangeOnDelete(exclusive, 5, 1)).toEqual({ ...exclusive, endIndex: 5 });+ expect(shiftInclusiveRangeOnDelete(inclusive, 2, 4)).toBeNull();+ expect(shiftExclusiveRangeOnDelete(exclusive, 2, 4)).toBeNull();+ expect(shiftInclusiveRangeOnDelete(inclusive, 3, 2)).toEqual({ ...inclusive, endIndex: 3 });+ expect(shiftExclusiveRangeOnDelete(exclusive, 3, 2)).toEqual({ ...exclusive, endIndex: 4 });+ });++ it('derives row and cell intervals from paired stream tokens', () => {+ const T = DataStreamTreeTokenType;+ const 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}`;++ expect(getTableRowTokenInterval(dataStream, 1)).toEqual({ startOffset: 1, endOffset: 8 });+ expect(getTableCellTokenInterval(dataStream, 2)).toEqual({ startOffset: 2, endOffset: 7 });+ expect(getTableCellTokenInterval(dataStream, 3)).toBeNull();+ expect(getTableRowTokenInterval(`${T.TABLE_ROW_START}A`, 0)).toBeNull();+ });+});diff --git a/packages/core/src/docs/data-model/text-x/build-utils/custom-range.ts b/packages/core/src/docs/data-model/text-x/build-utils/custom-range.tsindex 88c4886617..d4a0f7cb63 100644--- a/packages/core/src/docs/data-model/text-x/build-utils/custom-range.ts+++ b/packages/core/src/docs/data-model/text-x/build-utils/custom-range.ts@@ -18,6 +18,12 @@ import type { ITextRange } from '../../../../sheets/typedef';import type { CustomRangeType, ICustomRange, IDocumentBody } from '../../../../types/interfaces';import { Tools } from '../../../../shared';import { generateRandomId } from '../../../../shared/random-id';+import {+ containsInteriorInsertionOffset,+ getCustomRangeInterval,+ getInclusiveRangeInterval,+ intersectsOperationalIntervals,+} from './range-interval';/*** Check if two ranges intersect@@ -40,11 +46,14 @@ export function getCustomRangesInterestsWithSelection(range: ITextRange, customRfor (let i = 0, len = customRanges.length; i < len; i++) {const customRange = customRanges[i];if (range.collapsed) {- if (customRange.startIndex < range.startOffset && range.startOffset <= customRange.endIndex) {+ if (containsInteriorInsertionOffset(getCustomRangeInterval(customRange), range.startOffset)) {result.push(customRange);}} else {- if (isIntersecting(range.startOffset, range.endOffset - 1, customRange.startIndex, customRange.endIndex)) {+ if (intersectsOperationalIntervals(+ { startOffset: range.startOffset, endOffset: range.endOffset },+ getCustomRangeInterval(customRange)+ )) {result.push(customRange);}}@@ -85,11 +94,15 @@ export function excludePointsFromRange(range: [number, number], points: number[]export function getIntersectingCustomRanges(startIndex: number, endIndex: number, customRanges: ICustomRange[], rangeType?: CustomRangeType) {const relativeCustomRanges = [];+ const queryInterval = getInclusiveRangeInterval({ startIndex, endIndex });for (let i = 0, len = customRanges.length; i < len; i++) {const customRange = customRanges[i];// intersect- if ((rangeType === undefined || customRange.rangeType === rangeType) && Math.max(customRange.startIndex, startIndex) <= Math.min(customRange.endIndex, endIndex)) {+ if (+ (rangeType === undefined || customRange.rangeType === rangeType) &&+ intersectsOperationalIntervals(queryInterval, getCustomRangeInterval(customRange))+ ) {relativeCustomRanges.push({ ...customRange });}diff --git a/packages/core/src/docs/data-model/text-x/build-utils/data-stream-change.ts b/packages/core/src/docs/data-model/text-x/build-utils/data-stream-change.tsnew file mode 100644index 0000000000..3a3458f0ac--- /dev/null+++ b/packages/core/src/docs/data-model/text-x/build-utils/data-stream-change.ts@@ -0,0 +1,125 @@+/**+ * 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';++export interface IDataStreamChange {+ start: number;+ deleteLength: number;+ insertLength: number;+}++/**+ * Finds one contiguous dataStream change. Pure structural insertions are+ * anchored by their new stable ids before falling back to string comparison.+ * This prevents an adjacent identical sentinel from being mistaken for an+ * unchanged prefix and keeps the inserted structure metadata in the TextX body.+ */+export function getSingleDataStreamChange(+ previousBody: IDocumentBody | undefined,+ nextBody: IDocumentBody | undefined+): IDataStreamChange | null {+ if (previousBody == null || nextBody == null) {+ return null;+ }++ const previousDataStream = previousBody.dataStream;+ const nextDataStream = nextBody.dataStream;+ if (previousDataStream === nextDataStream) {+ return null;+ }++ const insertedLength = nextDataStream.length - previousDataStream.length;+ if (insertedLength > 0) {+ const structuralInsertion = findStructuralInsertion(+ previousBody,+ nextBody,+ previousDataStream,+ nextDataStream,+ insertedLength+ );+ if (structuralInsertion) {+ return structuralInsertion;+ }+ }++ 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 findStructuralInsertion(+ previousBody: IDocumentBody,+ nextBody: IDocumentBody,+ previousDataStream: string,+ nextDataStream: string,+ insertedLength: number+): IDataStreamChange | null {+ for (const start of collectNewStructuralStartOffsets(previousBody, nextBody)) {+ if (+ previousDataStream.slice(0, start) === nextDataStream.slice(0, start) &&+ previousDataStream.slice(start) === nextDataStream.slice(start + insertedLength)+ ) {+ return { start, deleteLength: 0, insertLength: insertedLength };+ }+ }++ return null;+}++function collectNewStructuralStartOffsets(previousBody: IDocumentBody, nextBody: IDocumentBody): number[] {+ const offsets = [+ ...collectNewStartOffsets(previousBody.blockRanges, nextBody.blockRanges, (item) => item.blockId),+ ...collectNewStartOffsets(previousBody.tables, nextBody.tables, (item) => item.tableId),+ ...collectNewStartOffsets(previousBody.columnGroups, nextBody.columnGroups, (item) => item.columnGroupId),+ ...collectNewStartOffsets(previousBody.customBlocks, nextBody.customBlocks, (item) => item.blockId),+ ];++ return Array.from(new Set(offsets)).sort((left, right) => left - right);+}++function collectNewStartOffsets<T extends { startIndex: number }>(+ previousItems: T[] | undefined,+ nextItems: T[] | undefined,+ getId: (item: T) => string+): number[] {+ const previousIds = new Set((previousItems ?? []).map(getId));+ return (nextItems ?? [])+ .filter((item) => !previousIds.has(getId(item)))+ .map((item) => item.startIndex);+}diff --git a/packages/core/src/docs/data-model/text-x/build-utils/index.ts b/packages/core/src/docs/data-model/text-x/build-utils/index.tsindex 53022ece0a..c2cbad0661 100644--- a/packages/core/src/docs/data-model/text-x/build-utils/index.ts+++ b/packages/core/src/docs/data-model/text-x/build-utils/index.ts@@ -79,4 +79,26 @@ export class BuildTextUtils {};}+export { getSingleDataStreamChange } from './data-stream-change';+export type { IDataStreamChange } from './data-stream-change';+export { getParagraphContentStartOffset, getParagraphContentStartOffsets, getParagraphFollowingBlockOffset } from './paragraph';+export {+ containsInteriorInsertionOffset,+ containsStreamIndex,+ getBlockRangeInterval,+ getColumnGroupRangeInterval,+ getCustomBlockInterval,+ getCustomRangeInterval,+ getExclusiveRangeInterval,+ getInclusiveRangeInterval,+ getTableCellTokenInterval,+ getTableRangeInterval,+ getTableRowTokenInterval,+ intersectsOperationalIntervals,+ shiftExclusiveRangeOnDelete,+ shiftExclusiveRangeOnInsert,+ shiftInclusiveRangeOnDelete,+ shiftInclusiveRangeOnInsert,+} from './range-interval';+export type { IDocOperationalInterval } from './range-interval';export type { IAddCustomRangeTextXParam, IDeleteCustomRangeParam, IReplaceSelectionTextXParams } from './text-x-utils';diff --git a/packages/core/src/docs/data-model/text-x/build-utils/paragraph.ts b/packages/core/src/docs/data-model/text-x/build-utils/paragraph.tsindex e594ae1cfb..0700da9bfd 100644--- a/packages/core/src/docs/data-model/text-x/build-utils/paragraph.ts+++ b/packages/core/src/docs/data-model/text-x/build-utils/paragraph.ts@@ -15,14 +15,16 @@*/import type { ITextRange } from '../../../../sheets/typedef';-import type { ICustomTable, IParagraph, IParagraphStyle, ITextStyle } from '../../../../types/interfaces';+import type { ICustomTable, IDocumentBody, IParagraph, IParagraphStyle, ITextStyle } from '../../../../types/interfaces';import type { DocumentDataModel } from '../../document-data-model';import { MemoryCursor } from '../../../../common/memory-cursor';import { UpdateDocsAttributeType } from '../../../../shared';import { generateRandomId } from '../../../../shared/random-id';import { PRESET_LIST_TYPE, PresetListType } from '../../preset-list-type';+import { DataStreamTreeTokenType } from '../../types';import { TextXActionType } from '../action-types';import { TextX } from '../text-x';+import { containsStreamIndex, getBlockRangeInterval, getTableRangeInterval } from './range-interval';import { getParagraphsInRanges } from './selection';export interface ISwitchParagraphBulletParams {@@ -244,7 +246,84 @@ export interface IChangeParagraphBulletNestLevelParams {}export function hasParagraphInTable(paragraph: IParagraph, tables: ICustomTable[]) {- return tables.some((table) => paragraph.startIndex > table.startIndex && paragraph.startIndex < table.endIndex);+ return tables.some((table) => {+ const interval = getTableRangeInterval(table);+ return paragraph.startIndex > interval.startOffset && containsStreamIndex(interval, paragraph.startIndex);+ });+}++const PARAGRAPH_CONTAINER_TOKENS = new Set<string>([+ DataStreamTreeTokenType.SECTION_BREAK,+ DataStreamTreeTokenType.TABLE_START,+ DataStreamTreeTokenType.TABLE_ROW_START,+ DataStreamTreeTokenType.TABLE_CELL_START,+ DataStreamTreeTokenType.TABLE_CELL_END,+ DataStreamTreeTokenType.TABLE_ROW_END,+ DataStreamTreeTokenType.TABLE_END,+ DataStreamTreeTokenType.COLUMN_GROUP_START,+ DataStreamTreeTokenType.COLUMN_START,+ DataStreamTreeTokenType.COLUMN_END,+ DataStreamTreeTokenType.COLUMN_GROUP_END,+ DataStreamTreeTokenType.BLOCK_START,+ DataStreamTreeTokenType.BLOCK_END,+]);++export function getParagraphContentStartOffset(+ body: Pick<IDocumentBody, 'dataStream' | 'paragraphs'>,+ paragraph: Pick<IParagraph, 'startIndex'>+): number {+ let previousParagraph: IParagraph | undefined;+ for (const candidate of body.paragraphs ?? []) {+ if (+ candidate.startIndex < paragraph.startIndex &&+ (!previousParagraph || candidate.startIndex > previousParagraph.startIndex)+ ) {+ previousParagraph = candidate;+ }+ }+ let startOffset = previousParagraph ? previousParagraph.startIndex + 1 : 0;++ while (+ startOffset < paragraph.startIndex &&+ PARAGRAPH_CONTAINER_TOKENS.has(body.dataStream[startOffset])+ ) {+ startOffset++;+ }++ return startOffset;+}++export function getParagraphContentStartOffsets(+ body: Pick<IDocumentBody, 'dataStream' | 'paragraphs'>+): Map<number, number> {+ const startOffsets = new Map<number, number>();+ const paragraphs = [...(body.paragraphs ?? [])].sort((left, right) => left.startIndex - right.startIndex);++ for (let index = 0; index < paragraphs.length; index++) {+ const paragraph = paragraphs[index];+ let startOffset = index > 0 ? paragraphs[index - 1].startIndex + 1 : 0;+ while (+ startOffset < paragraph.startIndex &&+ PARAGRAPH_CONTAINER_TOKENS.has(body.dataStream[startOffset])+ ) {+ startOffset++;+ }+ startOffsets.set(paragraph.startIndex, startOffset);+ }++ return startOffsets;+}++export function getParagraphFollowingBlockOffset(+ body: Pick<IDocumentBody, 'blockRanges'>,+ paragraph: Pick<IParagraph, 'startIndex'>+): number {+ const containingBlock = (body.blockRanges ?? []).find((blockRange) => {+ const interval = getBlockRangeInterval(blockRange);+ return paragraph.startIndex > interval.startOffset && paragraph.startIndex < interval.endOffset - 1;+ });++ return containingBlock ? getBlockRangeInterval(containingBlock).endOffset : paragraph.startIndex + 1;}export const changeParagraphBulletNestLevel = (params: IChangeParagraphBulletNestLevelParams) => {diff --git a/packages/core/src/docs/data-model/text-x/build-utils/range-interval.ts b/packages/core/src/docs/data-model/text-x/build-utils/range-interval.tsnew file mode 100644index 0000000000..50170216a2--- /dev/null+++ b/packages/core/src/docs/data-model/text-x/build-utils/range-interval.ts@@ -0,0 +1,230 @@+/**+ * 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 {+ ICustomBlock,+ ICustomColumnGroup,+ ICustomRange,+ ICustomTable,+ IDocumentBlockRange,+} from '../../../../types/interfaces/i-document-data';+import { DataStreamTreeTokenType } from '../../types';++/**+ * A canonical half-open interval used by document editing algorithms.+ * `startOffset` is included and `endOffset` is excluded.+ */+export interface IDocOperationalInterval {+ startOffset: number;+ endOffset: number;+}++type IInclusiveDocumentRange = Pick<IDocumentBlockRange, 'startIndex' | 'endIndex'>;+type IExclusiveDocumentRange = Pick<ICustomTable, 'startIndex' | 'endIndex'>;++/** Converts persisted inclusive indexes `[startIndex, endIndex]` to `[startOffset, endOffset)`. */+export function getInclusiveRangeInterval(range: IInclusiveDocumentRange): IDocOperationalInterval {+ return {+ startOffset: range.startIndex,+ endOffset: range.endIndex + 1,+ };+}++/** Converts persisted half-open indexes `[startIndex, endIndex)` to the operational representation. */+export function getExclusiveRangeInterval(range: IExclusiveDocumentRange): IDocOperationalInterval {+ return {+ startOffset: range.startIndex,+ endOffset: range.endIndex,+ };+}++/** A table stores an exclusive end immediately after `TABLE_END`. */+export function getTableRangeInterval(table: Pick<ICustomTable, 'startIndex' | 'endIndex'>): IDocOperationalInterval {+ return getExclusiveRangeInterval(table);+}++/** A document block stores an inclusive end that points at `BLOCK_END`. */+export function getBlockRangeInterval(blockRange: Pick<IDocumentBlockRange, 'startIndex' | 'endIndex'>): IDocOperationalInterval {+ return getInclusiveRangeInterval(blockRange);+}++/** A column group stores an inclusive end that points at `COLUMN_GROUP_END`. */+export function getColumnGroupRangeInterval(columnGroup: Pick<ICustomColumnGroup, 'startIndex' | 'endIndex'>): IDocOperationalInterval {+ return getInclusiveRangeInterval(columnGroup);+}++/** A custom range stores inclusive character indexes. */+export function getCustomRangeInterval(customRange: Pick<ICustomRange, 'startIndex' | 'endIndex'>): IDocOperationalInterval {+ return getInclusiveRangeInterval(customRange);+}++/** A custom block occupies exactly one `CUSTOM_BLOCK` sentinel. */+export function getCustomBlockInterval(customBlock: Pick<ICustomBlock, 'startIndex'>): IDocOperationalInterval {+ return {+ startOffset: customBlock.startIndex,+ endOffset: customBlock.startIndex + 1,+ };+}++/** Returns the half-open token interval for a row that starts at `startOffset`. */+export function getTableRowTokenInterval(dataStream: string, startOffset: number): IDocOperationalInterval | null {+ return getPairedTokenInterval(+ dataStream,+ startOffset,+ DataStreamTreeTokenType.TABLE_ROW_START,+ DataStreamTreeTokenType.TABLE_ROW_END+ );+}++/** Returns the half-open token interval for a cell that starts at `startOffset`. */+export function getTableCellTokenInterval(dataStream: string, startOffset: number): IDocOperationalInterval | null {+ return getPairedTokenInterval(+ dataStream,+ startOffset,+ DataStreamTreeTokenType.TABLE_CELL_START,+ DataStreamTreeTokenType.TABLE_CELL_END+ );+}++/** Tests whether a stream index belongs to a half-open operational interval. */+export function containsStreamIndex(interval: IDocOperationalInterval, index: number): boolean {+ return interval.startOffset <= index && index < interval.endOffset;+}++/**+ * Tests whether an insertion point is strictly inside a container.+ * Boundary insertion affinity must be decided by the caller.+ */+export function containsInteriorInsertionOffset(interval: IDocOperationalInterval, offset: number): boolean {+ return interval.startOffset < offset && offset < interval.endOffset;+}++/** Tests whether two half-open operational intervals overlap. */+export function intersectsOperationalIntervals(left: IDocOperationalInterval, right: IDocOperationalInterval): boolean {+ return Math.max(left.startOffset, right.startOffset) < Math.min(left.endOffset, right.endOffset);+}++/** Shifts or expands an inclusive persisted range for an insertion at `offset`. */+export function shiftInclusiveRangeOnInsert<T extends { startIndex: number; endIndex: number }>(+ range: T,+ offset: number,+ length: number+): T {+ if (range.startIndex >= offset) {+ return { ...range, startIndex: range.startIndex + length, endIndex: range.endIndex + length };+ }++ if (range.endIndex >= offset) {+ return { ...range, endIndex: range.endIndex + length };+ }++ return range;+}++/** Shifts or expands a half-open persisted range for an insertion at `offset`. */+export function shiftExclusiveRangeOnInsert<T extends { startIndex: number; endIndex: number }>(+ range: T,+ offset: number,+ length: number+): T {+ if (range.startIndex >= offset) {+ return { ...range, startIndex: range.startIndex + length, endIndex: range.endIndex + length };+ }++ if (range.endIndex > offset) {+ return { ...range, endIndex: range.endIndex + length };+ }++ return range;+}++/** Transforms an inclusive persisted range after deleting `[offset, offset + length)`. */+export function shiftInclusiveRangeOnDelete<T extends { startIndex: number; endIndex: number }>(+ range: T,+ offset: number,+ length: number+): T | null {+ if (length <= 0 || range.endIndex < offset) {+ return range;+ }++ const deleteEnd = offset + length;+ if (range.startIndex >= deleteEnd) {+ return { ...range, startIndex: range.startIndex - length, endIndex: range.endIndex - length };+ }++ const keepsLeft = range.startIndex < offset;+ const keepsRight = range.endIndex >= deleteEnd;+ if (!keepsLeft && !keepsRight) {+ return null;+ }++ const startIndex = keepsLeft ? range.startIndex : offset;+ const endIndex = keepsRight ? range.endIndex - length : offset - 1;+ return endIndex >= startIndex ? { ...range, startIndex, endIndex } : null;+}++/** Transforms a half-open persisted range after deleting `[offset, offset + length)`. */+export function shiftExclusiveRangeOnDelete<T extends { startIndex: number; endIndex: number }>(+ range: T,+ offset: number,+ length: number+): T | null {+ if (length <= 0 || range.endIndex <= offset) {+ return range;+ }++ const deleteEnd = offset + length;+ if (range.startIndex >= deleteEnd) {+ return { ...range, startIndex: range.startIndex - length, endIndex: range.endIndex - length };+ }++ const keepsLeft = range.startIndex < offset;+ const keepsRight = range.endIndex > deleteEnd;+ if (!keepsLeft && !keepsRight) {+ return null;+ }++ const startIndex = keepsLeft ? range.startIndex : offset;+ const endIndex = keepsRight ? range.endIndex - length : offset;+ return endIndex > startIndex ? { ...range, startIndex, endIndex } : null;+}++function getPairedTokenInterval(+ dataStream: string,+ startOffset: number,+ startToken: string,+ endToken: string+): IDocOperationalInterval | null {+ if (!Number.isInteger(startOffset) || startOffset < 0 || dataStream[startOffset] !== startToken) {+ return null;+ }++ let depth = 0;+ for (let offset = startOffset; offset < dataStream.length; offset++) {+ const token = dataStream[offset];+ if (token === startToken) {+ depth++;+ } else if (token === endToken) {+ depth--;+ if (depth === 0) {+ return { startOffset, endOffset: offset + 1 };+ }+ }+ }++ return null;+}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.tsindex 566c0d8a7d..7a5e45fd6c 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@@ -28,6 +28,7 @@ import { TextXActionType } from '../action-types';import { TextX } from '../text-x';import { getBodySlice, getBodySliceForTextXAction, getTextRunSlice } from '../utils';import { excludePointsFromRange, getIntersectingCustomRanges, getSelectionForAddCustomRange } from './custom-range';+import { getBlockRangeInterval } from './range-interval';export interface IDeleteCustomRangeParam {rangeId: string;@@ -163,6 +164,7 @@ export function addCustomRangeTextX(param: IAddCustomRangeTextXParam) {// paragraph information needs to be preserved when performing the CUT operationinterface IStructuralTextContainer {+ atomicRange?: { endOffset: number; startOffset: number };startOffset: number;endOffset: number;paragraphs: number[];@@ -170,6 +172,13 @@ interface IStructuralTextContainer {require: 'paragraph-or-section' | 'paragraph-and-section';}+function isAtomicContainerDeleted(container: IStructuralTextContainer, selections: ITextRange[]): boolean {+ return Boolean(container.atomicRange && selections.some((selection) =>+ selection.startOffset <= container.atomicRange!.startOffset &&+ selection.endOffset >= container.atomicRange!.endOffset+ ));+}+function isOffsetDeleted(offset: number, selections: ITextRange[]) {return selections.some((selection) => offset >= selection.startOffset && offset < selection.endOffset);}@@ -202,6 +211,66 @@ function protectDeletedColumnBoundaryTokens(body: IDocumentBody, selections: ITe}}+function protectPartiallyDeletedBlockBoundaryTokens(body: IDocumentBody, selections: ITextRange[], protectedOffsets: Set<number>) {+ for (const blockRange of body.blockRanges ?? []) {+ const blockInterval = getBlockRangeInterval(blockRange);+ const fullyDeleted = selections.some((selection) =>+ selection.startOffset <= blockInterval.startOffset &&+ selection.endOffset >= blockInterval.endOffset+ );+ if (fullyDeleted) {+ continue;+ }++ if (isOffsetDeleted(blockRange.startIndex, selections)) {+ protectedOffsets.add(blockRange.startIndex);+ }+ if (isOffsetDeleted(blockRange.endIndex, selections)) {+ protectedOffsets.add(blockRange.endIndex);+ }+ }+}++function collectBlockTextContainers(body: IDocumentBody): IStructuralTextContainer[] {+ const blockRanges = [...(body.blockRanges ?? [])].sort((left, right) => left.startIndex - right.startIndex);+ const containers = blockRanges.map((blockRange) => {+ const atomicRange = getBlockRangeInterval(blockRange);+ return {+ atomicRange,+ startOffset: atomicRange.startOffset + 1,+ endOffset: atomicRange.endOffset - 1,+ paragraphs: [] as number[],+ sectionBreaks: [] as number[],+ require: 'paragraph-or-section' as const,+ };+ });++ const assignPoint = (offset: number, key: 'paragraphs' | 'sectionBreaks') => {+ let low = 0;+ let high = blockRanges.length - 1;+ let index = -1;+ while (low <= high) {+ const middle = Math.floor((low + high) / 2);+ const blockRange = blockRanges[middle];+ if (offset <= blockRange.startIndex) {+ high = middle - 1;+ } else if (offset >= blockRange.endIndex) {+ low = middle + 1;+ } else {+ index = middle;+ break;+ }+ }+ if (index >= 0) {+ containers[index][key].push(offset);+ }+ };+ (body.paragraphs ?? []).forEach((paragraph) => assignPoint(paragraph.startIndex, 'paragraphs'));+ (body.sectionBreaks ?? []).forEach((sectionBreak) => assignPoint(sectionBreak.startIndex, 'sectionBreaks'));++ return containers;+}+function collectStructuralTextContainers(body: IDocumentBody): IStructuralTextContainer[] {const containers: IStructuralTextContainer[] = [{startOffset: 0,@@ -263,9 +332,42 @@ function collectStructuralTextContainers(body: IDocumentBody): IStructuralTextCo}}+ containers.push(...collectBlockTextContainers(body));+return containers;}+function protectRequiredContainerChildren(+ container: IStructuralTextContainer,+ selections: ITextRange[],+ insertBody: Nullable<IDocumentBody>,+ insertOffset: number,+ protectedOffsets: Set<number>+): void {+ if (isAtomicContainerDeleted(container, selections)) {+ return;+ }++ const insertAppliesToContainer = insertBody && isInsertInContainer(insertOffset, container);+ const insertDataStream = insertBody?.dataStream ?? '';+ const insertHasParagraph = insertDataStream.includes(DataStreamTreeTokenType.PARAGRAPH);+ const insertHasSectionBreak = insertDataStream.includes(DataStreamTreeTokenType.SECTION_BREAK);+ 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);+ }+}+function normalizeSelectionsForStructuralSentinels(selections: ITextRange[],body: IDocumentBody,@@ -276,32 +378,14 @@ function normalizeSelectionsForStructuralSentinels(}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);- }+ protectRequiredContainerChildren(container, selections, insertBody, insertOffset, protectedOffsets);});protectDeletedColumnBoundaryTokens(body, selections, protectedOffsets);+ protectPartiallyDeletedBlockBoundaryTokens(body, selections, protectedOffsets);if (!protectedOffsets.size) {return selections;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.tsindex b8ebb7233a..2ae598e7f2 100644--- a/packages/core/src/docs/data-model/text-x/structure-validator.ts+++ b/packages/core/src/docs/data-model/text-x/structure-validator.ts@@ -14,16 +14,37 @@* limitations under the License.*/-import type { IDocumentBody, IDocumentData } from '../../../types/interfaces/i-document-data';+import type { ICustomTable, IDocumentBody, IDocumentData } from '../../../types/interfaces/i-document-data';import { DataStreamTreeTokenType } from '../types';+import {+ getBlockRangeInterval,+ getColumnGroupRangeInterval,+ getTableRangeInterval,+ intersectsOperationalIntervals,+} from './build-utils/range-interval';export type DocStructureIssueCode =| 'missing-root-paragraph'| 'missing-root-section-break'| 'paragraph-token-mismatch'+ | 'duplicate-paragraph-metadata'| 'section-break-token-mismatch'+ | 'duplicate-section-break-metadata'| 'table-start-token-mismatch'| 'table-end-token-mismatch'+ | 'missing-table-metadata'+ | 'overlapping-table'+ | 'block-range-token-mismatch'+ | 'missing-block-range-metadata'+ | 'overlapping-block-range'+ | 'unbalanced-block'+ | 'column-group-range-token-mismatch'+ | 'missing-column-group-metadata'+ | 'overlapping-column-group'+ | 'column-group-column-count-mismatch'+ | 'custom-block-token-mismatch'+ | 'missing-custom-block-metadata'+ | 'duplicate-custom-block-metadata'| 'empty-column'| 'empty-table-cell'| 'unbalanced-column-group'@@ -67,6 +88,7 @@ function validateMinimumRootSentinels(body: IDocumentBody, issues: IDocStructure}function validateParagraphMetadata(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {+ const metadataCounts = new Map<number, number>();for (const paragraph of body.paragraphs ?? []) {if (body.dataStream[paragraph.startIndex] !== DataStreamTreeTokenType.PARAGRAPH) {issues.push(createIssue(@@ -75,11 +97,20 @@ function validateParagraphMetadata(body: IDocumentBody, issues: IDocStructureIss'Paragraph metadata must point to a paragraph sentinel.',paragraph.startIndex));+ } else {+ metadataCounts.set(paragraph.startIndex, (metadataCounts.get(paragraph.startIndex) ?? 0) + 1);}}++ validatePointMetadataDuplicates(metadataCounts, {+ context,+ duplicateCode: 'duplicate-paragraph-metadata',+ duplicateMessage: 'Paragraph sentinel must have exactly one paragraph metadata entry.',+ }, issues);}function validateSectionBreakMetadata(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {+ const metadataCounts = new Map<number, number>();for (const sectionBreak of body.sectionBreaks ?? []) {if (body.dataStream[sectionBreak.startIndex] !== DataStreamTreeTokenType.SECTION_BREAK) {issues.push(createIssue(@@ -88,12 +119,73 @@ function validateSectionBreakMetadata(body: IDocumentBody, issues: IDocStructure'Section break metadata must point to a section break sentinel.',sectionBreak.startIndex));+ } else {+ metadataCounts.set(sectionBreak.startIndex, (metadataCounts.get(sectionBreak.startIndex) ?? 0) + 1);}}++ validatePointMetadataDuplicates(metadataCounts, {+ context,+ duplicateCode: 'duplicate-section-break-metadata',+ duplicateMessage: 'Section break sentinel must have exactly one section break metadata entry.',+ }, issues);+}++function validatePointMetadataDuplicates(+ metadataCounts: Map<number, number>,+ options: {+ context: IValidationContext;+ duplicateCode: DocStructureIssueCode;+ duplicateMessage: string;+ },+ issues: IDocStructureIssue[]+): void {+ for (const [index, count] of metadataCounts) {+ if (count > 1) {+ issues.push(createIssue(options.context, options.duplicateCode, options.duplicateMessage, index));+ }+ }+}++function collectPairedTokenRanges(+ dataStream: string,+ startToken: string,+ endToken: string,+ exclusiveEnd: boolean+) {+ const pairs = new Map<number, number>();+ const stack: number[] = [];+ const unmatchedEnds: number[] = [];++ for (let index = 0; index < dataStream.length; index++) {+ if (dataStream[index] === startToken) {+ stack.push(index);+ } else if (dataStream[index] === endToken) {+ const startIndex = stack.pop();+ if (startIndex === undefined) {+ unmatchedEnds.push(index);+ } else {+ pairs.set(startIndex, exclusiveEnd ? index + 1 : index);+ }+ }+ }++ return { pairs, unmatchedEnds, unmatchedStarts: stack };}function validateTableMetadata(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {- for (const table of body.tables ?? []) {+ const pairedTables = collectPairedTokenRanges(+ body.dataStream,+ DataStreamTreeTokenType.TABLE_START,+ DataStreamTreeTokenType.TABLE_END,+ true+ ).pairs;+ const metadataStarts = new Set<number>();+ let previousTable: ICustomTable | undefined;++ const tables = [...(body.tables ?? [])].sort((a, b) => a.startIndex - b.startIndex || a.endIndex - b.endIndex);+ for (const table of tables) {+ metadataStarts.add(table.startIndex);if (!Number.isInteger(table.startIndex) || body.dataStream[table.startIndex] !== DataStreamTreeTokenType.TABLE_START) {issues.push(createIssue(context,@@ -107,7 +199,8 @@ function validateTableMetadata(body: IDocumentBody, issues: IDocStructureIssue[]!Number.isInteger(table.endIndex) ||table.endIndex <= table.startIndex ||table.endIndex > body.dataStream.length ||- body.dataStream[table.endIndex - 1] !== DataStreamTreeTokenType.TABLE_END+ body.dataStream[table.endIndex - 1] !== DataStreamTreeTokenType.TABLE_END ||+ pairedTables.get(table.startIndex) !== table.endIndex) {issues.push(createIssue(context,@@ -116,6 +209,155 @@ function validateTableMetadata(body: IDocumentBody, issues: IDocStructureIssue[]table.endIndex));}++ if (previousTable && intersectsOperationalIntervals(getTableRangeInterval(previousTable), getTableRangeInterval(table))) {+ issues.push(createIssue(context, 'overlapping-table', 'Table ranges must not overlap.', table.startIndex));+ }+ previousTable = table;+ }++ for (const startIndex of pairedTables.keys()) {+ if (!metadataStarts.has(startIndex)) {+ issues.push(createIssue(context, 'missing-table-metadata', 'Table token range must have a table metadata entry.', startIndex));+ }+ }+}++function validateBlockRangeMetadata(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {+ const pairedBlocks = collectPairedTokenRanges(+ body.dataStream,+ DataStreamTreeTokenType.BLOCK_START,+ DataStreamTreeTokenType.BLOCK_END,+ false+ );+ for (const index of [...pairedBlocks.unmatchedStarts, ...pairedBlocks.unmatchedEnds]) {+ issues.push(createIssue(context, 'unbalanced-block', 'Block sentinel has no matching boundary.', index));+ }++ const blockRanges = [...(body.blockRanges ?? [])].sort((a, b) => a.startIndex - b.startIndex || a.endIndex - b.endIndex);+ const metadataStarts = new Set<number>();+ let previousBlockRange: (typeof blockRanges)[number] | undefined;+ for (let i = 0; i < blockRanges.length; i++) {+ const blockRange = blockRanges[i];+ metadataStarts.add(blockRange.startIndex);+ if (pairedBlocks.pairs.get(blockRange.startIndex) !== blockRange.endIndex) {+ issues.push(createIssue(+ context,+ 'block-range-token-mismatch',+ 'Block range must point to its matching block start and end sentinels.',+ blockRange.startIndex+ ));+ }++ if (previousBlockRange && intersectsOperationalIntervals(+ getBlockRangeInterval(previousBlockRange),+ getBlockRangeInterval(blockRange)+ )) {+ issues.push(createIssue(+ context,+ 'overlapping-block-range',+ 'Block ranges must not overlap or share structural sentinels.',+ blockRange.startIndex+ ));+ }+ previousBlockRange = blockRange;+ }++ for (const startIndex of pairedBlocks.pairs.keys()) {+ if (!metadataStarts.has(startIndex)) {+ issues.push(createIssue(context, 'missing-block-range-metadata', 'Block token range must have a block metadata entry.', startIndex));+ }+ }+}++function validateColumnGroupMetadata(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {+ const pairedColumnGroups = collectPairedTokenRanges(+ body.dataStream,+ DataStreamTreeTokenType.COLUMN_GROUP_START,+ DataStreamTreeTokenType.COLUMN_GROUP_END,+ false+ ).pairs;+ const metadataStarts = new Set<number>();+ const columnGroups = [...(body.columnGroups ?? [])].sort((a, b) => a.startIndex - b.startIndex || a.endIndex - b.endIndex);+ let previousColumnGroup: (typeof columnGroups)[number] | undefined;++ for (const columnGroup of columnGroups) {+ metadataStarts.add(columnGroup.startIndex);+ const pairedEndIndex = pairedColumnGroups.get(columnGroup.startIndex);+ if (pairedEndIndex !== columnGroup.endIndex) {+ issues.push(createIssue(+ context,+ 'column-group-range-token-mismatch',+ 'Column group range must point to its matching start and end sentinels.',+ columnGroup.startIndex+ ));+ }+ if (previousColumnGroup && intersectsOperationalIntervals(+ getColumnGroupRangeInterval(previousColumnGroup),+ getColumnGroupRangeInterval(columnGroup)+ )) {+ issues.push(createIssue(context, 'overlapping-column-group', 'Column group ranges must not overlap.', columnGroup.startIndex));+ }+ previousColumnGroup = columnGroup;++ if (Array.isArray(columnGroup.columns)) {+ let streamColumnCount = 0;+ const scanEnd = pairedEndIndex ?? columnGroup.endIndex;+ for (let index = columnGroup.startIndex + 1; index < scanEnd; index++) {+ if (body.dataStream[index] === DataStreamTreeTokenType.COLUMN_START) {+ streamColumnCount++;+ }+ }+ if (streamColumnCount !== columnGroup.columns.length) {+ issues.push(createIssue(+ context,+ 'column-group-column-count-mismatch',+ 'Column group metadata column count must match the data stream.',+ columnGroup.startIndex+ ));+ }+ }+ }++ for (const startIndex of pairedColumnGroups.keys()) {+ if (!metadataStarts.has(startIndex)) {+ issues.push(createIssue(context, 'missing-column-group-metadata', 'Column group token range must have a metadata entry.', startIndex));+ }+ }+}++function validateCustomBlockMetadata(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {+ const metadataCounts = new Map<number, number>();+ for (const customBlock of body.customBlocks ?? []) {+ const { startIndex } = customBlock;+ if (!Number.isInteger(startIndex) || body.dataStream[startIndex] !== DataStreamTreeTokenType.CUSTOM_BLOCK) {+ issues.push(createIssue(+ context,+ 'custom-block-token-mismatch',+ 'Custom block startIndex must point to a custom block sentinel.',+ startIndex+ ));+ continue;+ }++ metadataCounts.set(startIndex, (metadataCounts.get(startIndex) ?? 0) + 1);+ }++ validatePointMetadataDuplicates(metadataCounts, {+ context,+ duplicateCode: 'duplicate-custom-block-metadata',+ duplicateMessage: 'Custom block sentinel must have exactly one custom block metadata entry.',+ }, issues);++ for (let index = 0; index < body.dataStream.length; index++) {+ if (body.dataStream[index] === DataStreamTreeTokenType.CUSTOM_BLOCK && !metadataCounts.has(index)) {+ issues.push(createIssue(+ context,+ 'missing-custom-block-metadata',+ 'Custom block sentinel must have a custom block metadata entry.',+ index+ ));+ }}}@@ -215,6 +457,9 @@ export function validateDocBodyStructure(validateParagraphMetadata(body, issues, context);validateSectionBreakMetadata(body, issues, context);validateTableMetadata(body, issues, context);+ validateBlockRangeMetadata(body, issues, context);+ validateColumnGroupMetadata(body, issues, context);+ validateCustomBlockMetadata(body, issues, context);validateStructuralContainers(body, issues, context);return issues;diff --git a/packages/core/src/docs/data-model/text-x/text-x.ts b/packages/core/src/docs/data-model/text-x/text-x.tsindex 90ce8f23f7..00a8fbad6c 100644--- a/packages/core/src/docs/data-model/text-x/text-x.ts+++ b/packages/core/src/docs/data-model/text-x/text-x.ts@@ -20,7 +20,7 @@ import type { IDeleteAction, IInsertAction, IRetainAction, TextXAction } from '.import { UpdateDocsAttributeType } from '../../../shared/command-enum';import { Tools } from '../../../shared/tools';import { ActionIterator } from './action-iterator';-import { TextXActionType } from './action-types';+import { PRESERVE_INSERTED_PARAGRAPH_IDS, TextXActionType } from './action-types';import { textXApply } from './apply';import { normalizeInsertedParagraphIdsForDocument, RESTORE_INSERTED_PARAGRAPH_IDS } from './apply-utils/common';import { transformBody } from './transform-utils';@@ -38,7 +38,9 @@ function normalizeInsertActionParagraphIds() {normalizeInsertedParagraphIdsForDocument(doc.paragraphs, body.paragraphs, currentIndex, {freshenSplitParagraph: false,+ preserveExplicitParagraphIds: Boolean((body as IDocumentBody & Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS]),reservedParagraphIds,+ dataStream: doc.dataStream,});}diff --git a/packages/core/src/docs/data-model/text-x/utils.ts b/packages/core/src/docs/data-model/text-x/utils.tsindex 828f34f2df..9820ff36a8 100644--- a/packages/core/src/docs/data-model/text-x/utils.ts+++ b/packages/core/src/docs/data-model/text-x/utils.ts@@ -19,8 +19,10 @@ import type { DocumentDataModel } from '../../data-model';import type { IRetainAction } from './action-types';import { UpdateDocsAttributeType } from '../../../shared/command-enum';import { Tools } from '../../../shared/tools';+import { PRESERVE_INSERTED_PARAGRAPH_IDS } from './action-types';import { normalizeTextRuns } from './apply-utils/common';import { coverTextRuns } from './apply-utils/update-apply';+import { getParagraphContentStartOffsets } from './build-utils/paragraph';export enum SliceBodyType {copy,@@ -215,10 +217,10 @@ export function getParagraphsSlice(}const sortedParagraphs = [...paragraphs].sort((a, b) => a.startIndex - b.startIndex);+ const paragraphStartOffsets = getParagraphContentStartOffsets(body);- for (let index = 0; index < sortedParagraphs.length; index++) {- const paragraph = sortedParagraphs[index];- const paragraphStart = index > 0 ? sortedParagraphs[index - 1].startIndex + 1 : 0;+ for (const paragraph of sortedParagraphs) {+ const paragraphStart = paragraphStartOffsets.get(paragraph.startIndex) ?? 0;const paragraphEnd = paragraph.startIndex;const paragraphMarkInRange = paragraphEnd >= startOffset && paragraphEnd < endOffset;const paragraphTextIntersectsRange = Math.max(paragraphStart, startOffset) < Math.min(paragraphEnd, endOffset);@@ -298,6 +300,10 @@ export function getBodySlice(dataStream: dataStream.slice(startOffset, endOffset),};+ if ((body as IDocumentBody & Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS]) {+ (docBody as IDocumentBody & Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS] = true;+ }+docBody.textRuns = getTextRunSlice(body, startOffset, endOffset, returnEmptyArray);const newTables = getTableSlice(body, startOffset, endOffset, structuralRangeMode);@@ -553,6 +559,13 @@ export function composeBody(dataStream: thisBody.dataStream,};+ if (+ (thisBody as IDocumentBody & Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS] ||+ (otherBody as IDocumentBody & Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS]+ ) {+ (retBody as IDocumentBody & Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS] = true;+ }+const {textRuns: thisTextRuns,paragraphs: thisParagraphs = [],diff --git a/packages/core/src/sheets/typedef.ts b/packages/core/src/sheets/typedef.tsindex 6f1ddf6b55..3d6ccaebe4 100644--- a/packages/core/src/sheets/typedef.ts+++ b/packages/core/src/sheets/typedef.ts@@ -705,6 +705,7 @@ export interface ISelection {primary: Nullable<ISelectionCell>;}export interface ITextRangeStart {+ /** Inclusive insertion offset at the start of the selection. */startOffset: number;}@@ -715,6 +716,7 @@ export enum RANGE_DIRECTION {}export interface ITextRange extends ITextRangeStart {+ /** Exclusive insertion offset at the end of a non-collapsed selection. */endOffset: number;collapsed: boolean;direction?: RANGE_DIRECTION;diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.tsindex 60524928f3..e7204ccd3e 100644--- a/packages/core/src/types/interfaces/i-document-data.ts+++ b/packages/core/src/types/interfaces/i-document-data.ts@@ -351,7 +351,9 @@ export interface IHyperlink {export interface ITextRun {// ct?: string; // content// len: number;+ /** Inclusive character index of the first styled character. */st: number;+ /** Exclusive character boundary after the last styled character. */ed: number;sId?: string; // styleIDts?: ITextStyle; // textStyle@@ -362,7 +364,9 @@ export interface ITextRun {* Block element, link like, disabled to self nested*/export interface ICustomRange<T extends Record<string, any> = Record<string, any>> {+ /** Inclusive index of the first character covered by this annotation. */startIndex: number;+ /** Inclusive index of the last character covered by this annotation. */endIndex: number;rangeId: string;rangeType: CustomRangeType | number;@@ -388,7 +392,9 @@ export enum DocumentBlockRangeType {}export interface IDocumentBlockRange {+ /** Inclusive index that must point at a `BLOCK_START` sentinel. */startIndex: number;+ /** Inclusive index that must point at the matching `BLOCK_END` sentinel. */endIndex: number;blockId: string;blockType: DocumentBlockRangeType;@@ -411,6 +417,7 @@ export enum CustomRangeType {* Custom Block*/export interface ICustomBlock {+ /** Index that must point at exactly one `CUSTOM_BLOCK` sentinel. */startIndex: number;blockType?: BlockType;// A unique ID associated with a custom block.@@ -423,7 +430,9 @@ export enum CustomDecorationType {}export interface ICustomDecoration {+ /** Inclusive index of the first decorated character. */startIndex: number;+ /** Inclusive index of the last decorated character. */endIndex: number;id: string;type: CustomDecorationType;@@ -959,14 +968,18 @@ export enum TableTextWrapType {}export interface ICustomTable {+ /** Inclusive index that must point at a `TABLE_START` sentinel. */startIndex: number;+ /** Exclusive boundary immediately after the matching `TABLE_END` sentinel. */endIndex: number;// A unique ID associated with a table.tableId: string;}export interface ICustomColumnGroup {+ /** Inclusive index that must point at a `COLUMN_GROUP_START` sentinel. */startIndex: number;+ /** Inclusive index that must point at the matching `COLUMN_GROUP_END` sentinel. */endIndex: number;// A unique ID associated with a column group.columnGroupId: string;@@ -1049,6 +1062,10 @@ export interface ITableRowSize {* Properties of row of table*/export interface ITableRow {+ /**+ * Rows do not persist stream offsets. Their ordinal position must match the+ * corresponding `TABLE_ROW_START`/`TABLE_ROW_END` pair in `dataStream`.+ */tableCells: ITableCell[]; // tableCells// If omitted, then the table row shall automatically resize its height to the height required by its contents// (the equivalent of an hRule value of auto)@@ -1062,6 +1079,10 @@ export interface ITableRow {* Properties of table cell*/export interface ITableCell {+ /**+ * Cells do not persist stream offsets. Their ordinal position must match the+ * corresponding `TABLE_CELL_START`/`TABLE_CELL_END` pair in the row stream.+ */margin?: ITableCellMargin; // marginrowSpan?: number; // rowSpancolumnSpan?: number; // columnSpandiff --git a/packages/docs-ui/src/commands/commands/__tests__/break-line.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/break-line.command.spec.tsindex b472b026de..2c3cd7d8c1 100644--- a/packages/docs-ui/src/commands/commands/__tests__/break-line.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/break-line.command.spec.ts@@ -15,7 +15,7 @@*/import type { DocumentDataModel, ICommand, IDocumentData, Injector, Univer } from '@univerjs/core';-import { awaitTime, DataStreamTreeTokenType, ICommandService, IUniverInstanceService, NamedStyleType, UniverInstanceType } from '@univerjs/core';+import { awaitTime, DataStreamTreeTokenType, DocumentBlockRangeType, ICommandService, IUniverInstanceService, NamedStyleType, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { BreakLineCommand } from '../break-line.command';@@ -80,6 +80,34 @@ function getDocumentDataWithColumnGroup(): IDocumentData {};}+function getDocumentDataWithAdjacentBlocks(): IDocumentData {+ const T = DataStreamTreeTokenType;++ return {+ id: 'test-doc',+ body: {+ dataStream: `${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_END}${T.BLOCK_START}B${T.PARAGRAPH}${T.BLOCK_END}${T.PARAGRAPH}${T.SECTION_BREAK}`,+ paragraphs: [+ { paragraphId: 'code-paragraph', startIndex: 2 },+ { paragraphId: 'callout-paragraph', startIndex: 6, paragraphStyle: { indentStart: { v: 60 } } },+ { paragraphId: 'trailing-paragraph', startIndex: 8 },+ ],+ sectionBreaks: [{ startIndex: 9 }],+ blockRanges: [+ { blockId: 'code-1', blockType: DocumentBlockRangeType.CODE, startIndex: 0, endIndex: 3 },+ { blockId: 'callout-1', blockType: DocumentBlockRangeType.CALLOUT, startIndex: 4, endIndex: 7 },+ ],+ },+ documentStyle: {+ pageSize: { width: 594.3, height: 840.51 },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}+describe('break line command', () => {let univer: Univer;let get: Injector['get'];@@ -114,6 +142,25 @@ describe('break line command', () => {return selectionManager;}+ function setupWithAdjacentBlocks() {+ univer.dispose();+ const testBed = createCommandTestBed(getDocumentDataWithAdjacentBlocks());+ univer = testBed.univer;+ get = testBed.get;+ commandService = get(ICommandService);+ commandService.registerCommand(BreakLineCommand);+ commandService.registerCommand(SetTextSelectionsOperation);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ const selectionManager = get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ });++ return selectionManager;+ }+beforeEach(() => {const testBed = createCommandTestBed(getDocumentData());univer = testBed.univer;@@ -166,4 +213,24 @@ describe('break line command', () => {expect(getBody()?.columnGroups).toEqual([{ columnGroupId: 'cg-1', startIndex: 7, endIndex: 17 }]);expect(getBody()?.dataStream[17]).toBe(DataStreamTreeTokenType.COLUMN_GROUP_END);});++ it('inserts a paragraph between adjacent block ranges without corrupting either range', async () => {+ const selectionManager = setupWithAdjacentBlocks();+ selectionManager.__TEST_ONLY_add([{ startOffset: 4, endOffset: 4, collapsed: true, isActive: true, segmentId: '', style: null as never }]);++ await commandService.executeCommand(BreakLineCommand.id, {+ textRange: { startOffset: 4, endOffset: 4, collapsed: true, segmentId: '' },+ });+ await awaitTime(0);++ const T = DataStreamTreeTokenType;+ expect(getBody()?.dataStream).toBe(`${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_END}${T.PARAGRAPH}${T.BLOCK_START}B${T.PARAGRAPH}${T.BLOCK_END}${T.PARAGRAPH}${T.SECTION_BREAK}`);+ expect(getBody()?.blockRanges).toEqual([+ { blockId: 'code-1', blockType: DocumentBlockRangeType.CODE, startIndex: 0, endIndex: 3 },+ { blockId: 'callout-1', blockType: DocumentBlockRangeType.CALLOUT, startIndex: 5, endIndex: 8 },+ ]);+ expect(getBody()?.paragraphs?.find((paragraph) => paragraph.startIndex === 4)?.paragraphStyle).toBeUndefined();+ expect(getBody()?.paragraphs?.find((paragraph) => paragraph.paragraphId === 'callout-paragraph')?.paragraphStyle).toEqual({ indentStart: { v: 60 } });+ expect(selectionManager.getActiveTextRange()?.startOffset).toBe(4);+ });});diff --git a/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.tsindex 09125da5f9..9fd1cc8eb5 100644--- a/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts@@ -253,7 +253,7 @@ describe('test cases in clipboard', () => {}function createCustomBlockDocumentData(): IDocumentData {- const dataStream = `${DataStreamTreeTokenType.BLOCK_START}\rBody\r\n`;+ const dataStream = `${DataStreamTreeTokenType.CUSTOM_BLOCK}\rBody\r\n`;return {id: 'test-doc',@@ -486,7 +486,7 @@ describe('test cases in clipboard', () => {});it('Should paste custom block drawings with new ids for internal clipboard content', async () => {- const blockDataStream = `${DataStreamTreeTokenType.BLOCK_START}\r`;+ const blockDataStream = `${DataStreamTreeTokenType.CUSTOM_BLOCK}\r`;const commandParams: IInnerPasteCommandParams = {segmentId: '',doc: {@@ -563,7 +563,7 @@ describe('test cases in clipboard', () => {const snapshot = getDocumentSnapshot();- expect(snapshot?.body?.dataStream.startsWith(DataStreamTreeTokenType.BLOCK_START)).toBe(false);+ expect(snapshot?.body?.dataStream.startsWith(DataStreamTreeTokenType.CUSTOM_BLOCK)).toBe(false);expect(snapshot?.body?.customBlocks ?? []).toHaveLength(0);expect(snapshot?.drawings?.['drawing-1']).toBeUndefined();expect(snapshot?.drawingsOrder ?? []).toHaveLength(0);diff --git a/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.tsindex 156d804659..f294e192b1 100644--- a/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.ts@@ -367,7 +367,7 @@ describe('core editing commands', () => {expect(isDeleteOffsetInsideBlockRange(body, 3)).toBe(false);});- it('detects block ranges whose endIndex points before the block end token', () => {+ it('does not reinterpret a malformed block range endIndex', () => {const dataStream = `${DataStreamTreeTokenType.BLOCK_START}A${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.BLOCK_END}\n`;const body = {dataStream,@@ -380,7 +380,7 @@ describe('core editing commands', () => {};expect(isDeleteOffsetInsideBlockRange(body, 1)).toBe(true);- expect(isDeleteOffsetInsideBlockRange(body, 2)).toBe(true);+ expect(isDeleteOffsetInsideBlockRange(body, 2)).toBe(false);expect(isDeleteOffsetInsideBlockRange(body, 3)).toBe(false);});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.tsindex 5d9d6f1a8a..58b60d3b2a 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@@ -187,10 +187,10 @@ describe('buildMoveDocBlockActions', () => {{ paragraphId: 'para_docs_ui_fixture_32', startIndex: 1 },{ paragraphId: 'para_docs_ui_fixture_33', startIndex: 5 },{ paragraphId: 'para_docs_ui_fixture_34', startIndex: 9 },- { paragraphId: 'para_docs_ui_fixture_35', startIndex: 12 },+ { paragraphId: 'para_docs_ui_fixture_35', startIndex: 13 },],- sectionBreaks: [{ startIndex: 13 }],- columnGroups: [{ columnGroupId: 'column-group-1', startIndex: 2, endIndex: 12 }],+ sectionBreaks: [{ startIndex: 14 }],+ columnGroups: [{ columnGroupId: 'column-group-1', startIndex: 2, endIndex: 11 }],});const { nextDocumentData } = buildMoveDocBlockActions({@@ -203,7 +203,7 @@ describe('buildMoveDocBlockActions', () => {expect(nextDocumentData.body?.columnGroups).toEqual([{columnGroupId: 'column-group-1',startIndex: 0,- endIndex: 10,+ endIndex: 9,}]);});});@@ -247,7 +247,7 @@ describe('MoveDocBlockCommand', () => {{ paragraphId: 'para_docs_ui_fixture_39', startIndex: 13 },],sectionBreaks: [{ startIndex: 14 }],- columnGroups: [{ columnGroupId: 'column-group-1', startIndex: 2, endIndex: 12 }],+ columnGroups: [{ columnGroupId: 'column-group-1', startIndex: 2, endIndex: 11 }],}));const commandService = testBed.get(ICommandService);commandService.registerCommand(MoveDocBlockCommand);@@ -263,7 +263,7 @@ describe('MoveDocBlockCommand', () => {expect(testBed.doc.getSnapshot().body?.columnGroups).toEqual([{columnGroupId: 'column-group-1',startIndex: 0,- endIndex: 10,+ endIndex: 9,}]);});diff --git a/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.tsindex c003ab51ed..3f73a9f115 100644--- a/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts@@ -683,6 +683,19 @@ describe('doc table create command helpers', () => {expect(canInsertTableAtOffset(fixture.documentData.body!, tableEndOffset)).toBe(true);});+ it('allows insertion immediately before table and block start boundaries', () => {+ const fixture = createTableFixture(1, 1);+ const blockBody = {+ blockRanges: [{ blockId: 'block-1', blockType: DocumentBlockRangeType.CALLOUT, startIndex: 1, endIndex: 3 }],+ customBlocks: [],+ tables: [],+ };++ expect(canInsertTableAtOffset(fixture.documentData.body!, fixture.tableRange.startIndex)).toBe(true);+ expect(canInsertTableAtOffset(blockBody, 1)).toBe(true);+ expect(canInsertTableAtOffset(blockBody, 2)).toBe(false);+ });+it('does not create a table on a custom block', async () => {const testBed = createTableCreationBed({...createParagraphDocument('A\b\r\n'),diff --git a/packages/docs-ui/src/commands/commands/__tests__/list.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/list.command.spec.tsindex 5e89b33a35..99126e4322 100644--- a/packages/docs-ui/src/commands/commands/__tests__/list.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/list.command.spec.ts@@ -22,8 +22,9 @@ import {PRESET_LIST_TYPE,PresetListType,UniverInstanceType,+ validateDocBodyStructure,} from '@univerjs/core';-import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';+import { DocContentInsertService, DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { InsertBulletBelowCommand } from '../insert-below/insert-bullet-below.command';import {@@ -94,7 +95,7 @@ describe('list commands', () => {}beforeEach(() => {- const testBed = createCommandTestBed(getDocumentData());+ const testBed = createCommandTestBed(getDocumentData(), [[DocContentInsertService]]);univer = testBed.univer;get = testBed.get;selectionId = 0;@@ -260,6 +261,24 @@ describe('list commands', () => {});});+ it('inserts a list at an explicit paragraph gap without inheriting or converting the right paragraph', async () => {+ const bodyBefore = getBody()!;+ bodyBefore.paragraphs![1].paragraphStyle = { indentStart: { v: 60 } };+ get(DocContentInsertService).setInsertRange({+ unitId: 'test-doc',+ startOffset: 6,+ endOffset: 6,+ });++ expect(await commandService.executeCommand(InsertBulletListBellowCommand.id)).toBe(true);+ await awaitTime(0);++ const body = getBody()!;+ expect(body.paragraphs?.find((paragraph) => paragraph.startIndex === 6)?.bullet?.listType).toBe(PresetListType.BULLET_LIST);+ expect(body.paragraphs?.find((paragraph) => paragraph.paragraphId === 'para_docs_ui_fixture_21')?.paragraphStyle).toEqual({ indentStart: { v: 60 } });+ expect(validateDocBodyStructure(body)).toEqual([]);+ });+it('inserts a bullet below the focused list item and keeps the active list identity', async () => {setSelections([{ startOffset: 0, endOffset: 4, collapsed: false }]);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.tsindex d09a7d2f6c..fbbe6879e7 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@@ -46,6 +46,7 @@ import {import {CreateHeaderFooterCommand,DeleteTextCommand,+ DocContentInsertService,DocSelectionManagerService,DocSkeletonManagerService,HeaderFooterType,@@ -56,7 +57,7 @@ import {import { DocumentEditArea, GlyphType, IRenderManagerService } from '@univerjs/engine-render';import { ISidebarService } from '@univerjs/ui';import { Subject } from 'rxjs';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { DocParagraphSettingController } from '../../../controllers/doc-paragraph-setting.controller';import { DocAutoFormatService } from '../../../services/doc-auto-format.service';import { DocIMEInputManagerService } from '../../../services/doc-ime-input-manager.service';@@ -945,6 +946,24 @@ describe('misc document commands', () => {}));});+ it('uses gap insertion mode for a paragraph-menu horizontal line', () => {+ const syncExecuteCommand = vi.fn(() => true);+ const accessor = {+ get: (token: unknown) => {+ if (token === ICommandService) return { syncExecuteCommand };+ if (token === IUniverInstanceService) return { getCurrentUnitOfType: () => ({ getUnitId: () => 'test-doc' }) };+ if (token === DocContentInsertService) return { consumeInsertRange: () => ({ unitId: 'test-doc', startOffset: 7, endOffset: 7 }) };+ throw new Error('unexpected dependency');+ },+ };++ expect(InsertHorizontalLineBellowCommand.handler(accessor as never)).toBe(true);+ expect(syncExecuteCommand).toHaveBeenCalledWith(HorizontalLineCommand.id, {+ insertionMode: 'insert-gap',+ insertRange: { startOffset: 7, endOffset: 7 },+ });+ });+it('removes a horizontal line from the paragraph before the cursor', async () => {({ univer, get } = createCommandTestBed(createHorizontalLineDoc()));commandService = get(ICommandService);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.tsindex b569de2b6e..a054304299 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@@ -15,7 +15,7 @@*/import type { DocumentDataModel, ICommand, IDocumentData, Injector, Univer } from '@univerjs/core';-import { ICommandService, IUniverInstanceService, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';+import { DataStreamTreeTokenType, ICommandService, IUniverInstanceService, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import {@@ -153,6 +153,8 @@ describe('replace or cover content of document', () => {describe('replace selected document content', () => {it('replaces the document snapshot including style and table metadata', async () => {+ const T = DataStreamTreeTokenType;+ const columnDataStream = `${T.COLUMN_GROUP_START}${T.COLUMN_START}Left${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_START}Right${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.PARAGRAPH}${T.SECTION_BREAK}`;const tableSource = {table_1: {tableId: 'table_1',@@ -162,7 +164,7 @@ describe('replace or cover content of document', () => {};const columnGroups = [{startIndex: 0,- endIndex: 9,+ endIndex: 16,columnGroupId: 'column_group_1',columns: [{ columnId: 'column_1', widthRatio: 1 },@@ -175,16 +177,14 @@ describe('replace or cover content of document', () => {const nextSnapshot = {...getDocumentData(),body: {- dataStream: 'Snapshot\r\n',- textRuns: [{- st: 0,- ed: 8,- ts: {- fs: 16,- },- }],- paragraphs: [{ paragraphId: 'para_replace_snapshot', startIndex: 8 }],- sectionBreaks: [{ startIndex: 9 }],+ dataStream: columnDataStream,+ textRuns: [],+ paragraphs: [+ { paragraphId: 'para_replace_left', startIndex: 6 },+ { paragraphId: 'para_replace_right', startIndex: 14 },+ { paragraphId: 'para_replace_after', startIndex: 17 },+ ],+ sectionBreaks: [{ startIndex: 18 }],customBlocks: [],columnGroups,},@@ -215,8 +215,8 @@ describe('replace or cover content of document', () => {unitId: 'test-doc',snapshot: nextSnapshot,textRanges: [{- startOffset: 8,- endOffset: 8,+ startOffset: 17,+ endOffset: 17,collapsed: true,}],options: {@@ -226,7 +226,7 @@ describe('replace or cover content of document', () => {const univerInstanceService = get(IUniverInstanceService);const docsModel = univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC);- expect(docsModel?.getBody()?.dataStream).toBe('Snapshot\r\n');+ expect(docsModel?.getBody()?.dataStream).toBe(columnDataStream);expect(docsModel?.getDocumentStyle().pageSize).toEqual({ width: 500, height: 700 });expect(docsModel?.getSnapshot().tableSource).toEqual(tableSource);expect(docsModel?.getBody()?.columnGroups).toEqual(columnGroups);diff --git a/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.tsindex 1849cfd377..fc0ac766be 100644--- a/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.ts@@ -15,7 +15,7 @@*/import type { DocumentDataModel, ICommand, IDocumentData, Injector, Univer } from '@univerjs/core';-import { awaitTime, ICommandService, IUniverInstanceService, NamedStyleType, UniverInstanceType } from '@univerjs/core';+import { awaitTime, DataStreamTreeTokenType, DocumentBlockRangeType, ICommandService, IUniverInstanceService, NamedStyleType, UniverInstanceType, validateDocBodyStructure } from '@univerjs/core';import {DocContentInsertService,DocSelectionManagerService,@@ -77,6 +77,66 @@ function getQuickHeadingDocumentData(): IDocumentData {};}+type BoundaryNodeType = 'blockRange' | 'paragraph' | 'table';++function getBoundaryDocumentData(leftType: BoundaryNodeType, rightType: BoundaryNodeType): { documentData: IDocumentData; insertOffset: number; rightParagraphId: string } {+ const T = DataStreamTreeTokenType;+ const body: NonNullable<IDocumentData['body']> = {+ dataStream: '',+ paragraphs: [],+ sectionBreaks: [],+ blockRanges: [],+ tables: [],+ };+ let nextId = 0;++ const append = (type: BoundaryNodeType, side: 'left' | 'right') => {+ const startIndex = body.dataStream.length;+ const paragraphId = `${side}-${type}-${nextId++}`;+ const paragraphStyle = side === 'right'+ ? { indentStart: { v: 60 }, textStyle: { ff: 'monospace' } }+ : undefined;++ if (type === 'paragraph') {+ body.dataStream += `${side}${T.PARAGRAPH}`;+ body.paragraphs!.push({ paragraphId, paragraphStyle, startIndex: body.dataStream.length - 1 });+ } else if (type === 'blockRange') {+ body.dataStream += `${T.BLOCK_START}${side}${T.PARAGRAPH}${T.BLOCK_END}`;+ body.paragraphs!.push({ paragraphId, paragraphStyle, startIndex: body.dataStream.length - 2 });+ body.blockRanges!.push({+ blockId: `${side}-block`,+ blockType: DocumentBlockRangeType.CALLOUT,+ startIndex,+ endIndex: body.dataStream.length - 1,+ });+ } else {+ body.dataStream += `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${side}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;+ body.paragraphs!.push({ paragraphId, paragraphStyle, startIndex: body.dataStream.length - 5 });+ body.sectionBreaks!.push({ startIndex: body.dataStream.length - 4 });+ body.tables!.push({ tableId: `${side}-table`, startIndex, endIndex: body.dataStream.length });+ }++ return paragraphId;+ };++ append(leftType, 'left');+ const insertOffset = body.dataStream.length;+ const rightParagraphId = append(rightType, 'right');+ body.dataStream += `${T.PARAGRAPH}${T.SECTION_BREAK}`;+ body.paragraphs!.push({ paragraphId: 'trailing', startIndex: body.dataStream.length - 2 });+ body.sectionBreaks!.push({ startIndex: body.dataStream.length - 1 });++ return {+ documentData: {+ id: 'test-doc',+ body,+ documentStyle: getHeadingDocumentData().documentStyle,+ },+ insertOffset,+ rightParagraphId,+ };+}+describe('set heading commands', () => {let univer: Univer;let get: Injector['get'];@@ -87,6 +147,22 @@ describe('set heading commands', () => {return univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)?.getBody();}+ function resetDocument(documentData: IDocumentData) {+ univer.dispose();+ const testBed = createCommandTestBed(documentData, [[DocContentInsertService]]);+ univer = testBed.univer;+ get = testBed.get;+ commandService = get(ICommandService);+ commandService.registerCommand(SetParagraphNamedStyleCommand);+ commandService.registerCommand(H1HeadingCommand);+ commandService.registerCommand(SetTextSelectionsOperation);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ get(DocSelectionManagerService).__TEST_ONLY_setCurrentSelection({+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ });+ }+beforeEach(() => {const testBed = createCommandTestBed(getHeadingDocumentData());univer = testBed.univer;@@ -186,6 +262,45 @@ describe('set heading commands', () => {expect(getBody()?.paragraphs?.[0].paragraphStyle?.headingId?.length).toBe(6);});+ it.each([+ ['paragraph', 'paragraph'],+ ['paragraph', 'blockRange'],+ ['paragraph', 'table'],+ ['blockRange', 'paragraph'],+ ['blockRange', 'blockRange'],+ ['blockRange', 'table'],+ ['table', 'paragraph'],+ ['table', 'blockRange'],+ ['table', 'table'],+ ] as Array<[BoundaryNodeType, BoundaryNodeType]>)('inserts an isolated H1 at the %s -> %s gap', async (leftType, rightType) => {+ const { documentData, insertOffset, rightParagraphId } = getBoundaryDocumentData(leftType, rightType);+ const rightStyle = documentData.body!.paragraphs!.find((paragraph) => paragraph.paragraphId === rightParagraphId)!.paragraphStyle;+ resetDocument(documentData);+ const selectionManager = get(DocSelectionManagerService);+ let latestSelectionOffset: number | undefined;+ const selectionSubscription = selectionManager.refreshSelection$.subscribe((event) => {+ latestSelectionOffset = event?.docRanges[0]?.startOffset;+ });+ get(DocContentInsertService).setInsertRange({+ unitId: 'test-doc',+ startOffset: insertOffset,+ endOffset: insertOffset,+ });++ expect(await commandService.executeCommand(H1HeadingCommand.id)).toBe(true);+ await awaitTime(0);++ const body = getBody()!;+ const insertedParagraph = body.paragraphs?.find((paragraph) => paragraph.startIndex === insertOffset);+ const rightParagraph = body.paragraphs?.find((paragraph) => paragraph.paragraphId === rightParagraphId);+ expect(insertedParagraph?.paragraphStyle).toMatchObject({ namedStyleType: NamedStyleType.HEADING_1 });+ expect(insertedParagraph?.paragraphStyle?.indentStart).toBeUndefined();+ expect(rightParagraph?.paragraphStyle).toEqual(rightStyle);+ expect(latestSelectionOffset).toBe(insertOffset);+ expect(validateDocBodyStructure(body)).toEqual([]);+ selectionSubscription.unsubscribe();+ });+it('converts markdown-like quick headings through the real command chain', async () => {univer.dispose();diff --git a/packages/docs-ui/src/commands/commands/break-line.command.ts b/packages/docs-ui/src/commands/commands/break-line.command.tsindex 099ca80ff7..faf66416f0 100644--- a/packages/docs-ui/src/commands/commands/break-line.command.ts+++ b/packages/docs-ui/src/commands/commands/break-line.command.ts@@ -72,6 +72,7 @@ export function generateParagraphs(interface IBreakLineCommandParams {horizontalLine?: IParagraphBorder;+ insertionMode?: 'split-paragraph' | 'insert-gap';textRange?: ITextRangeParam;}@@ -104,7 +105,7 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {return true;}- const { horizontalLine } = params ?? {};+ const { horizontalLine, insertionMode = 'split-paragraph' } = params ?? {};const { segmentId } = activeTextRange;const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);const originBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId ?? '')?.getBody();@@ -118,13 +119,16 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {const { startOffset, endOffset } = activeTextRange;const paragraphs = originBody.paragraphs ?? [];- const prevParagraph = paragraphs.find((p) => p.startIndex >= startOffset);+ const insertsAtStructuralGap = insertionMode === 'insert-gap' || isTopLevelStructuralGap(originBody.dataStream, startOffset);+ const prevParagraph = insertsAtStructuralGap+ ? undefined+ : paragraphs.find((p) => p.startIndex >= startOffset);- if (!prevParagraph) {+ if (!prevParagraph && !insertsAtStructuralGap) {return false;}- const isAtParagraphEnd = startOffset === prevParagraph.startIndex;- const prevParagraphIndex = prevParagraph.startIndex;+ const isAtParagraphEnd = startOffset === prevParagraph?.startIndex;+ const prevParagraphIndex = prevParagraph?.startIndex;const defaultTextStyle = docMenuStyleService.getDefaultStyle();const styleCache = docMenuStyleService.getStyleCache();const curTextRun = getTextRunAtPosition(originBody, endOffset, defaultTextStyle, styleCache);@@ -154,7 +158,7 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {return false;}const { collapsed } = activeTextRange;- const cursorMove = insertBody.dataStream.length;+ const cursorMove = insertsAtStructuralGap ? 0 : insertBody.dataStream.length;const textRanges = [{startOffset: startOffset + cursorMove,@@ -171,6 +175,7 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {actions: [],textRanges,debounce: true,+ trigger: BreakLineCommand.id,},};@@ -195,8 +200,8 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {textX.push(...dos);}- if (prevParagraph.bullet?.listType === PresetListType.CHECK_LIST_CHECKED || prevParagraph.paragraphStyle?.headingId) {- if (activeTextRange.endOffset < prevParagraphIndex) {+ if (prevParagraph && (prevParagraph.bullet?.listType === PresetListType.CHECK_LIST_CHECKED || prevParagraph.paragraphStyle?.headingId)) {+ if (prevParagraphIndex != null && activeTextRange.endOffset < prevParagraphIndex) {textX.push({t: TextXActionType.RETAIN,len: prevParagraphIndex - activeTextRange.endOffset,@@ -250,3 +255,15 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {return Boolean(result);},};++function isTopLevelStructuralGap(dataStream: string, offset: number): boolean {+ const previousToken = dataStream[offset - 1];+ const nextToken = dataStream[offset];++ return previousToken === DataStreamTreeTokenType.BLOCK_END ||+ previousToken === DataStreamTreeTokenType.TABLE_END ||+ previousToken === DataStreamTreeTokenType.COLUMN_GROUP_END ||+ nextToken === DataStreamTreeTokenType.BLOCK_START ||+ nextToken === DataStreamTreeTokenType.TABLE_START ||+ nextToken === DataStreamTreeTokenType.COLUMN_GROUP_START;+}diff --git a/packages/docs-ui/src/commands/commands/doc-delete.command.ts b/packages/docs-ui/src/commands/commands/doc-delete.command.tsindex 4a1607f209..657e95bc0a 100644--- a/packages/docs-ui/src/commands/commands/doc-delete.command.ts+++ b/packages/docs-ui/src/commands/commands/doc-delete.command.ts@@ -23,6 +23,7 @@ import {CommandType,DataStreamTreeTokenType,DeleteDirection,+ getBlockRangeInterval,getRichTextEditPath,HorizontalAlign,ICommandService,@@ -407,18 +408,10 @@ export function getCursorWhenDelete(textRanges: Readonly<Nullable<ITextRangeWithreturn cursor;}-function getBlockRangeEndTokenOffset(body: IDocumentBody, blockRange: Pick<IDocumentBlockRange, 'endIndex'>): number {- return body.dataStream[blockRange.endIndex] === DataStreamTreeTokenType.BLOCK_END- ? blockRange.endIndex- : body.dataStream[blockRange.endIndex + 1] === DataStreamTreeTokenType.BLOCK_END- ? blockRange.endIndex + 1- : blockRange.endIndex;-}-export function isDeleteOffsetInsideBlockRange(body: IDocumentBody, offset: number): boolean {return body.blockRanges?.some((blockRange) => {- const endTokenOffset = getBlockRangeEndTokenOffset(body, blockRange);- return blockRange.startIndex < offset && offset < endTokenOffset;+ const interval = getBlockRangeInterval(blockRange);+ return interval.startOffset < offset && offset < interval.endOffset - 1;}) ?? false;}diff --git a/packages/docs-ui/src/commands/commands/doc-horizontal-line.command.ts b/packages/docs-ui/src/commands/commands/doc-horizontal-line.command.tsindex 81269f0559..a4903f7cf5 100644--- a/packages/docs-ui/src/commands/commands/doc-horizontal-line.command.ts+++ b/packages/docs-ui/src/commands/commands/doc-horizontal-line.command.ts@@ -21,6 +21,7 @@ import { BreakLineCommand } from './break-line.command';import { getCurrentParagraph } from './util';interface IHorizontalCommandParams {+ insertionMode?: 'split-paragraph' | 'insert-gap';insertRange?: ITextRangeParam;}@@ -41,6 +42,7 @@ export const HorizontalLineCommand: ICommand<IHorizontalCommandParams> = {width: 1,dashStyle: DashStyleType.SOLID,},+ insertionMode: params?.insertionMode,textRange: params?.insertRange,});},@@ -60,6 +62,7 @@ export const InsertHorizontalLineBellowCommand: ICommand<IHorizontalCommandParam}if (contentInsertRange) {return commandService.syncExecuteCommand(HorizontalLineCommand.id, {+ insertionMode: 'insert-gap',insertRange: {startOffset: contentInsertRange.startOffset,endOffset: contentInsertRange.endOffset,diff --git a/packages/docs-ui/src/commands/commands/doc-select-all.command.ts b/packages/docs-ui/src/commands/commands/doc-select-all.command.tsindex 82f69a60e0..3521202d02 100644--- a/packages/docs-ui/src/commands/commands/doc-select-all.command.ts+++ b/packages/docs-ui/src/commands/commands/doc-select-all.command.ts@@ -14,9 +14,9 @@* limitations under the License.*/-import type { DocumentDataModel, ICommand, ICustomTable, IDocumentBody, IParagraph } from '@univerjs/core';+import type { DocumentDataModel, ICommand, ICustomTable, IDocumentBody } from '@univerjs/core';import type { ISuccinctDocRangeParam } from '@univerjs/engine-render';-import { CommandType, DOC_RANGE_TYPE, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { CommandType, DOC_RANGE_TYPE, getParagraphContentStartOffsets, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';interface ISelectAllCommandParams { }@@ -147,7 +147,7 @@ function getScopedSelectAllRange(body: IDocumentBody, activeRange: ISuccinctDocR}];}- const paragraphRange = clampParagraphRangeByTables(getParagraphRangeAtOffset(body.paragraphs ?? [], startOffset), body.tables ?? [], startOffset);+ const paragraphRange = clampParagraphRangeByTables(getParagraphRangeAtOffset(body, startOffset), body.tables ?? [], startOffset);return paragraphRange? [{...paragraphRange,@@ -185,11 +185,11 @@ function getTableRectRange(table: ICustomTable): ISuccinctDocRangeParam {};}-function getParagraphRangeAtOffset(paragraphs: IParagraph[], offset: number): Pick<ISuccinctDocRangeParam, 'endOffset' | 'startOffset'> | null {- const sortedParagraphs = [...paragraphs].sort((left, right) => left.startIndex - right.startIndex);- for (let index = 0; index < sortedParagraphs.length; index++) {- const paragraph = sortedParagraphs[index];- const startOffset = index === 0 ? 0 : sortedParagraphs[index - 1].startIndex + 1;+function getParagraphRangeAtOffset(body: IDocumentBody, offset: number): Pick<ISuccinctDocRangeParam, 'endOffset' | 'startOffset'> | null {+ const sortedParagraphs = [...(body.paragraphs ?? [])].sort((left, right) => left.startIndex - right.startIndex);+ const paragraphStartOffsets = getParagraphContentStartOffsets(body);+ for (const paragraph of sortedParagraphs) {+ const startOffset = paragraphStartOffsets.get(paragraph.startIndex) ?? 0;if (startOffset <= offset && offset <= paragraph.startIndex) {return {endOffset: paragraph.startIndex,diff --git a/packages/docs-ui/src/commands/commands/list.command.ts b/packages/docs-ui/src/commands/commands/list.command.tsindex e5423c07c3..eb3f69aab4 100644--- a/packages/docs-ui/src/commands/commands/list.command.ts+++ b/packages/docs-ui/src/commands/commands/list.command.ts@@ -486,7 +486,7 @@ export const QuickListCommand: ICommand<IQuickListCommandParams> = {},};-function insertList(accessor: IAccessor, listType: PresetListType) {+function insertList(accessor: IAccessor, listType: PresetListType, trigger: string) {const commandService = accessor.get(ICommandService);const docDataModel = accessor.get(IUniverInstanceService).getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);if (!docDataModel) {@@ -545,6 +545,7 @@ function insertList(accessor: IAccessor, listType: PresetListType) {collapsed: true,}],isEditing: false,+ trigger,},};const jsonX = JSONX.getInstance();@@ -559,7 +560,7 @@ export const InsertBulletListBellowCommand: ICommand<IQuickListCommandParams> =id: 'doc.command.insert-bullet-list-bellow',type: CommandType.COMMAND,handler: (accessor) => {- return insertList(accessor, PresetListType.BULLET_LIST);+ return insertList(accessor, PresetListType.BULLET_LIST, InsertBulletListBellowCommand.id);},};@@ -567,7 +568,7 @@ export const InsertOrderListBellowCommand: ICommand<IQuickListCommandParams> = {id: 'doc.command.insert-order-list-bellow',type: CommandType.COMMAND,handler: (accessor) => {- return insertList(accessor, PresetListType.ORDER_LIST);+ return insertList(accessor, PresetListType.ORDER_LIST, InsertOrderListBellowCommand.id);},};@@ -575,7 +576,7 @@ export const InsertCheckListBellowCommand: ICommand<IQuickListCommandParams> = {id: 'doc.command.insert-check-list-bellow',type: CommandType.COMMAND,handler: (accessor) => {- return insertList(accessor, PresetListType.CHECK_LIST);+ return insertList(accessor, PresetListType.CHECK_LIST, InsertCheckListBellowCommand.id);},};diff --git a/packages/docs-ui/src/commands/commands/set-heading.command.ts b/packages/docs-ui/src/commands/commands/set-heading.command.tsindex 5cf01adde0..b8a0e56cda 100644--- a/packages/docs-ui/src/commands/commands/set-heading.command.ts+++ b/packages/docs-ui/src/commands/commands/set-heading.command.ts@@ -55,7 +55,14 @@ export const SetParagraphNamedStyleCommand: ICommand<ISetParagraphNamedStyleCommconst selectionService = accessor.get(DocSelectionManagerService);const contentInsertRange = params.textRanges ? null : consumeContentInsertRange(accessor, unitId);if (contentInsertRange) {- return insertNamedStyleParagraph(accessor, doc, params.value, contentInsertRange.startOffset, contentInsertRange.endOffset);+ return insertNamedStyleParagraph(+ accessor,+ doc,+ params.value,+ contentInsertRange.startOffset,+ contentInsertRange.endOffset,+ contentInsertRange.segmentId+ );}const selections = params.textRanges ?? selectionService.getTextRanges({ unitId, subUnitId: unitId });@@ -107,7 +114,8 @@ function insertNamedStyleParagraph(doc: DocumentDataModel,namedStyleType: NamedStyleType,startOffset: number,- endOffset: number+ endOffset: number,+ segmentId = ''): boolean {const textX = BuildTextUtils.selection.replace({doc,@@ -115,6 +123,7 @@ function insertNamedStyleParagraph(startOffset,endOffset,collapsed: startOffset === endOffset,+ segmentId,},body: {dataStream: '\r',@@ -135,16 +144,26 @@ function insertNamedStyleParagraph(const jsonX = JSONX.getInstance();const commandService = accessor.get(ICommandService);- return Boolean(commandService.syncExecuteCommand<IRichTextEditingMutationParams>(RichTextEditingMutation.id, {- actions: jsonX.editOp(textX.serialize(), getRichTextEditPath(doc)),+ const success = Boolean(commandService.syncExecuteCommand<IRichTextEditingMutationParams>(RichTextEditingMutation.id, {+ actions: jsonX.editOp(textX.serialize(), getRichTextEditPath(doc, segmentId)),isEditing: false,textRanges: [{startOffset,endOffset: startOffset,collapsed: true,}],+ segmentId,unitId: doc.getUnitId(),}));++ if (success) {+ accessor.get(DocSelectionManagerService).replaceTextRanges([{+ startOffset,+ endOffset: startOffset,+ }], false);+ }++ return success;}export const QuickHeadingCommand: ICommand<ISetParagraphNamedStyleCommandParams> = {diff --git a/packages/docs-ui/src/commands/commands/table/doc-table-create.command.ts b/packages/docs-ui/src/commands/commands/table/doc-table-create.command.tsindex fc4720e0d4..d3218a82d9 100644--- a/packages/docs-ui/src/commands/commands/table/doc-table-create.command.ts+++ b/packages/docs-ui/src/commands/commands/table/doc-table-create.command.ts@@ -17,7 +17,7 @@import type { DocumentDataModel, ICommand, IDocumentBody, IMutationInfo, IParagraph, ISectionBreak, ITextRun, JSONXActions } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';import type { ITextRangeWithStyle } from '@univerjs/engine-render';-import { CommandType, createParagraphId, DataStreamTreeTokenType, getRichTextEditPath, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';+import { CommandType, containsInteriorInsertionOffset, createParagraphId, DataStreamTreeTokenType, getBlockRangeInterval, getParagraphContentStartOffset, getRichTextEditPath, getTableRangeInterval, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';import { DocContentInsertService, DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';import { getTextRunAtPosition } from '../../../basics/paragraph';import { DocMenuStyleService } from '../../../services/doc-menu-style.service';@@ -87,11 +87,11 @@ export function canInsertTableAtOffset(body: Pick<IDocumentBody, 'tables' | 'blo}function isOffsetInTableRange(ranges: Array<{ startIndex: number; endIndex: number }> | undefined, offset: number): boolean {- return Boolean(ranges?.some((range) => range.startIndex <= offset && offset < range.endIndex));+ return Boolean(ranges?.some((range) => containsInteriorInsertionOffset(getTableRangeInterval(range), offset)));}function isOffsetInIndexRange(ranges: Array<{ startIndex: number; endIndex: number }> | undefined, offset: number): boolean {- return Boolean(ranges?.some((range) => range.startIndex <= offset && offset <= range.endIndex));+ return Boolean(ranges?.some((range) => containsInteriorInsertionOffset(getBlockRangeInterval(range), offset)));}function isOffsetOnPointRange(ranges: Array<{ startIndex: number }> | undefined, offset: number): boolean {@@ -148,7 +148,10 @@ export const CreateDocTableCommand: ICommand<ICreateDocTableCommandParams> = {}const paragraphs = body.paragraphs ?? [];- const prevParagraph = paragraphs.find((p) => p.startIndex >= startOffset);+ const prevParagraph = paragraphs.find((paragraph) => {+ const paragraphStartOffset = getParagraphContentStartOffset(body, paragraph);+ return paragraphStartOffset < startOffset && startOffset <= paragraph.startIndex;+ });const curGlyph = skeleton.findNodeByCharIndex(startOffset, segmentId, segmentPage);// const line = curGlyph?.parent?.parent;// const preGlyph = skeleton.findNodeByCharIndex(startOffset - 1, segmentId, segmentPage);diff --git a/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.tsindex 73a3794c1c..e90662d327 100644--- a/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts+++ b/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts@@ -280,6 +280,30 @@ describe('DocMoveCursorController movement helpers', () => {expect(skeleton.findPositionByGlyph).toHaveBeenCalledWith(beforeGlyph, -1);});+ it('stops safely at a terminal column group when no following body line exists', () => {+ const controller = createControllerHarness();+ const columnGlyph = createGlyph('C', 12);+ const blockLine = createBlockLine(11, 40);+ const bodyColumn = createColumn([blockLine]);+ const bodyPage = createPage([bodyColumn], DocumentSkeletonPageType.BODY);+ const columnPage = createPage([createColumn([createLine([columnGlyph], 30, 0)])], DocumentSkeletonPageType.CELL);+ const columnGroupColumn = { columnId: 'b', left: 100, top: 0, width: 80, height: 20, st: 30, ed: 35, page: columnPage };+ const columnGroup = createColumnGroup([columnGroupColumn], bodyPage);+ bodyPage.skeColumnGroups.set('cg-1', columnGroup as never);++ const skeleton = {+ findPositionByGlyph: vi.fn(),+ };++ expect(controller._getTopOrBottomPosition(+ skeleton,+ columnGlyph,+ { segmentPage: -1 },+ true+ )).toBeUndefined();+ expect(skeleton.findPositionByGlyph).not.toHaveBeenCalled();+ });+it('enters the nearest docs table cell when moving vertically from a body line', () => {const controller = createControllerHarness();const bodyGlyph = createGlyph('A', 118);diff --git a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts b/packages/docs-ui/src/controllers/doc-move-cursor.controller.tsindex b87d47aaeb..b6e7dc497d 100644--- a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts+++ b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts@@ -1066,10 +1066,9 @@ export class DocMoveCursorController extends Disposable {}if (this._isColumnGroupContentPage(page)) {- const exitTarget = this._getColumnGroupExitLineTarget(page, direction, offsetLeft);- if (exitTarget != null) {- return exitTarget;- }+ // A column page is nested under a column-group column, not under the+ // document skeleton. Stop here even when the host has no adjacent line.+ return this._getColumnGroupExitLineTarget(page, direction, offsetLeft);}if (this._isTableCellContentPage(page)) {@@ -1078,7 +1077,7 @@ export class DocMoveCursorController extends Disposable {const skeleton: Nullable<IDocumentSkeletonCached> = page.parent as IDocumentSkeletonCached;- if (skeleton == null) {+ if (skeleton?.pages == null) {return;}diff --git a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.tsindex ec1012d629..81d6ae9a0b 100644--- a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts+++ b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts@@ -612,6 +612,29 @@ describe('DocParagraphMenuService', () => {});});+ it('does not include a preceding block end token in a paragraph move range', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const T = DataStreamTreeTokenType;+ const dataStream = `${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_END}B${T.PARAGRAPH}${T.SECTION_BREAK}`;+ const service = createService({+ attachPopupToRect,+ blockRanges: [{ blockId: 'code-1', blockType: DocumentBlockRangeType.CODE, startIndex: 0, endIndex: 3 }],+ dataStream,+ paragraphs: [{ startIndex: 2 }, { startIndex: 5 }],+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 4,+ paragraphEnd: 5,+ startIndex: 5,+ }));++ expect(service.activeTarget?.moveRange).toEqual({+ startOffset: 4,+ endOffset: 6,+ });+ });+it('keeps a hover bridge between the table and its top-left block menu', () => {expect(getTableBlockMenuHoverRect({bottom: 170,diff --git a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts b/packages/docs-ui/src/services/doc-paragraph-menu.service.tsindex 8f367dedd1..ae2605aa19 100644--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts@@ -18,7 +18,7 @@ import type { DocumentDataModel, ICustomBlock, ICustomTable, IDocumentBlockRangeimport type { IBoundRectNoAngle, IRenderContext, IRenderModule, ITextRangeWithStyle } from '@univerjs/engine-render';import type { IMutiPageParagraphBound, ITableBound, ITableParagraphBound } from './doc-event-manager.service';import type { IEditorInputConfig } from './selection/doc-selection-render.service';-import { BlockType, DataStreamTreeTokenType, Disposable, DOC_RANGE_TYPE, DocumentBlockType, Inject, isInternalEditorID, PresetListType } from '@univerjs/core';+import { BlockType, DataStreamTreeTokenType, Disposable, DOC_RANGE_TYPE, DocumentBlockType, getParagraphContentStartOffset, Inject, isInternalEditorID, PresetListType } from '@univerjs/core';import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';import { DocumentEditArea } from '@univerjs/engine-render';import { BehaviorSubject, combineLatest, first, throttleTime } from 'rxjs';@@ -891,20 +891,15 @@ function isParagraphInTable(documentDataModel: DocumentDataModel, paragraphStart}function getParagraphMoveRange(documentDataModel: DocumentDataModel, paragraph: IMutiPageParagraphBound, cellRange?: { startOffset: number; endOffset: number } | null) {- const paragraphs = [...(documentDataModel.getBody()?.paragraphs ?? [])].sort((left, right) => left.startIndex - right.startIndex);- const index = paragraphs.findIndex((item) => item.startIndex === paragraph.startIndex);- const previousParagraph = index > 0- ? paragraphs.slice(0, index).reverse().find((item) => {- if (!cellRange) {- return true;- }-- return item.startIndex > cellRange.startOffset && item.startIndex < cellRange.endOffset;- })- : null;+ const body = documentDataModel.getBody();+ const paragraphStartOffset = body+ ? getParagraphContentStartOffset(body, paragraph)+ : 0;return {- startOffset: previousParagraph ? previousParagraph.startIndex + 1 : (cellRange ? cellRange.startOffset + 1 : 0),+ startOffset: cellRange+ ? Math.max(paragraphStartOffset, cellRange.startOffset + 1)+ : paragraphStartOffset,endOffset: paragraph.startIndex + 1,};}diff --git a/packages/docs-ui/src/views/ParagraphMenu.tsx b/packages/docs-ui/src/views/ParagraphMenu.tsxindex fd0d655c64..de83cf745e 100644--- a/packages/docs-ui/src/views/ParagraphMenu.tsx+++ b/packages/docs-ui/src/views/ParagraphMenu.tsx@@ -48,7 +48,6 @@ import {} from '@univerjs/ui';import { useEffect, useMemo, useRef, useState } from 'react';import { BehaviorSubject } from 'rxjs';-import { BreakLineCommand } from '../commands/commands/break-line.command';import {DocCopyCommand,DocCopyCurrentParagraphCommand,@@ -1090,15 +1089,11 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; treturn;}- const insertRange = {+ docContentInsertService.setInsertRange({+ unitId: popup.unitId,startOffset: latestTarget.moveRange.endOffset,endOffset: latestTarget.moveRange.endOffset,- collapsed: true,segmentId: activeParagraphBound?.segmentId,- };- replaceSelection(insertRange);- await commandService.executeCommand(BreakLineCommand.id, {- textRange: insertRange,});const wrappedCommandId = typeof commandParams?.commandId === 'string' ? commandParams.commandId : undefined;if (wrappedCommandId) {diff --git a/packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts b/packages/docs/src/facade/__tests__/f-document-paragraph.spec.tsindex 758f936669..33d8548891 100644--- a/packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts+++ b/packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts@@ -16,7 +16,7 @@import type { IDocumentData, Univer } from '@univerjs/core';import type { FDocument } from '../f-document';-import { PresetListType } from '@univerjs/core';+import { DataStreamTreeTokenType, DocumentBlockRangeType, PresetListType } from '@univerjs/core';import { afterEach, describe, expect, it } from 'vitest';import {createBulletDocument,@@ -124,6 +124,40 @@ describe('FDocumentParagraph', () => {]);});+ it('keeps a paragraph after a block scoped outside the block end token', () => {+ const T = DataStreamTreeTokenType;+ createDocumentFacade(createDocumentData('doc-after-block', {+ dataStream: `${T.BLOCK_START}Code${T.PARAGRAPH}${T.BLOCK_END}After${T.PARAGRAPH}${T.SECTION_BREAK}`,+ paragraphs: [+ { startIndex: 5, paragraphId: 'para_code' },+ { startIndex: 12, paragraphId: 'para_after' },+ ],+ sectionBreaks: [{ startIndex: 13 }],+ blockRanges: [{+ blockId: 'code-1',+ blockType: DocumentBlockRangeType.CODE,+ startIndex: 0,+ endIndex: 6,+ }],+ }));++ const paragraph = document.getParagraphs()[1];++ expect(paragraph.getInfo()).toMatchObject({ startOffset: 7, endOffset: 12 });+ expect(paragraph.getText()).toBe('After');+ expect(document.insertParagraph(1, 'Between').getText()).toBe('Between');+ expect(document.save().body).toMatchObject({+ dataStream: `${T.BLOCK_START}Code${T.PARAGRAPH}${T.BLOCK_END}Between${T.PARAGRAPH}After${T.PARAGRAPH}${T.SECTION_BREAK}`,+ blockRanges: [{ startIndex: 0, endIndex: 6 }],+ });+ const paragraphAfterInsert = document.getParagraphs().find((item) => item.getText() === 'After');+ expect(paragraphAfterInsert?.setText('Changed')).toBe(true);+ expect(document.save().body).toMatchObject({+ dataStream: `${T.BLOCK_START}Code${T.PARAGRAPH}${T.BLOCK_END}Between${T.PARAGRAPH}Changed${T.PARAGRAPH}${T.SECTION_BREAK}`,+ blockRanges: [{ startIndex: 0, endIndex: 6 }],+ });+ });+it('keeps paragraph edits scoped to their header segment', () => {const headerId = 'header-1';createDocumentFacade({diff --git a/packages/docs/src/facade/f-document-paragraph.ts b/packages/docs/src/facade/f-document-paragraph.tsindex 89ae22b012..11d798e109 100644--- a/packages/docs/src/facade/f-document-paragraph.ts+++ b/packages/docs/src/facade/f-document-paragraph.ts@@ -17,7 +17,7 @@import type { IDocumentBody, Injector, IParagraph, IParagraphStyle } from '@univerjs/core';import type { FDocument } from './f-document';import type { IFDocumentTextRange } from './utils';-import { PresetListType, RESTORE_INSERTED_PARAGRAPH_IDS, UpdateDocsAttributeType } from '@univerjs/core';+import { getParagraphContentStartOffset, PresetListType, RESTORE_INSERTED_PARAGRAPH_IDS, UpdateDocsAttributeType } from '@univerjs/core';import { buildPlainTextInsertBody, replaceBodyRange, retainBodyRange } from './utils';/**@@ -92,7 +92,8 @@ export class FDocumentParagraph {* ```*/getInfo(): IFDocumentParagraphInfo {- const { paragraphs = [] } = this._document.getBody(this._segmentId);+ const body = this._document.getBody(this._segmentId);+ const { paragraphs = [] } = body;const matches = paragraphs.map((paragraph, paragraphIndex) => ({ paragraph, paragraphIndex })).filter(({ paragraph }) => paragraph.paragraphId === this._paragraphId);@@ -106,7 +107,7 @@ export class FDocumentParagraph {}const { paragraph, paragraphIndex } = matches[0];- const startOffset = paragraphIndex > 0 ? paragraphs[paragraphIndex - 1].startIndex + 1 : 0;+ const startOffset = getParagraphContentStartOffset(body, paragraph);return {paragraph,diff --git a/packages/docs/src/facade/f-document.ts b/packages/docs/src/facade/f-document.tsindex 08288d8d40..cde1e4aee9 100644--- a/packages/docs/src/facade/f-document.ts+++ b/packages/docs/src/facade/f-document.ts@@ -20,6 +20,7 @@ import {BooleanNumber,DocumentFlavor,generateRandomId,+ getParagraphContentStartOffset,ICommandService,Inject,Injector,@@ -469,7 +470,8 @@ export class FDocument extends FBaseInitialable {return 0;}- const { dataStream, paragraphs = [] } = this.getBody(segmentId);+ const body = this.getBody(segmentId);+ const { dataStream, paragraphs = [] } = body;if (paragraphs.length === 0) {return Math.max(0, dataStream.length - 1);@@ -479,7 +481,7 @@ export class FDocument extends FBaseInitialable {return paragraphs[paragraphs.length - 1].startIndex + 1;}- return paragraphs[index - 1].startIndex + 1;+ return getParagraphContentStartOffset(body, paragraphs[index]);}private _ensureHeaderFooter(kind: 'header' | 'footer', pageIndex: number): string {