Skip to content

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

fix(docs): normalize block insert paragraphs (#7082)

Univera810ccbb253e
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__test__/drawings.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__test__/drawings.spec.ts
index c10536396c..a4dedd9cb4 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/__test__/drawings.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__test__/drawings.spec.ts
@@ -16,10 +16,58 @@
import { describe, expect, it } from 'vitest';
import { DocumentDataModel } from '../../../document-data-model';
+import { DataStreamTreeTokenType } from '../../../types';
import { getRichTextEditPath } from '../../utils';
import { addDrawing, getCustomBlockIdsInSelections } from '../drawings';
describe('drawing build utils', () => {
+ it('keeps the initial empty paragraph above a drawing inserted at offset zero', () => {
+ const doc = new DocumentDataModel({
+ id: 'doc-empty-drawing',
+ body: {
+ dataStream: '\r\n',
+ paragraphs: [{ startIndex: 0, paragraphId: 'para_top' }],
+ sectionBreaks: [{ startIndex: 1 }],
+ customBlocks: [],
+ },
+ drawings: {},
+ drawingsOrder: [],
+ });
+
+ const actions = addDrawing({
+ selection: { startOffset: 0, endOffset: 0, collapsed: true },
+ documentDataModel: doc,
+ drawings: [{
+ unitId: 'doc-empty-drawing',
+ subUnitId: '',
+ drawingId: 'drawing-new',
+ drawingType: 0,
+ title: 'New drawing',
+ description: 'New drawing',
+ docTransform: {
+ size: { width: 20, height: 20 },
+ positionH: { relativeFrom: 0, posOffset: 0 },
+ positionV: { relativeFrom: 0, posOffset: 0 },
+ },
+ layoutType: 0,
+ } as never],
+ });
+
+ expect(actions).toBeTruthy();
+ if (!actions) {
+ throw new Error('Expected addDrawing to return JSONX actions');
+ }
+ doc.apply(actions);
+
+ expect(doc.getBody()?.dataStream).toBe(`\r${DataStreamTreeTokenType.CUSTOM_BLOCK}\r\n`);
+ expect(doc.getBody()?.paragraphs).toEqual([
+ { startIndex: 0, paragraphId: 'para_top' },
+ { startIndex: 2, paragraphId: expect.stringMatching(/^para_/) },
+ ]);
+ expect(doc.getBody()?.customBlocks).toEqual([{ startIndex: 1, blockId: 'drawing-new' }]);
+ expect(doc.getBody()?.sectionBreaks).toEqual([{ startIndex: 3 }]);
+ });
+
it('should resolve custom blocks and replace selected drawings in the document body', () => {
const doc = new DocumentDataModel({
id: 'doc-drawing',
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/drawings.ts b/packages/core/src/docs/data-model/text-x/build-utils/drawings.ts
index 8e29a9d37a..381cbc6a4a 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/drawings.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/drawings.ts
@@ -18,8 +18,10 @@ import type { ITextRange, ITextRangeParam } from '../../../../sheets/typedef';
import type { IDocumentBody } from '../../../../types/interfaces';
import type { DocumentDataModel } from '../../document-data-model';
import type { JSONXActions } from '../../json-x/json-x';
+import { createParagraphId } from '../../../paragraph-id';
import { JSONX } from '../../json-x/json-x';
import { TextXActionType } from '../action-types';
+import { DataStreamTreeTokenType } from '../../types';
import { TextX } from '../text-x';
import { getRichTextEditPath } from '../utils';
import { deleteSelectionTextX } from './text-x-utils';
@@ -68,13 +70,14 @@ export const addDrawing = (param: IAddDrawingParam) => {
const drawingOrderLength = documentDataModel.getSnapshot().drawingsOrder?.length ?? 0;
let removeDrawingLen = 0;
+ const insertOffset = collapsed ? normalizeDrawingInsertOffset(body, startOffset ?? 0) : (startOffset ?? 0);
// Step 1: Insert placeholder `\b` in dataStream and add drawing to customBlocks.
if (collapsed) {
- if (startOffset > 0) {
+ if (insertOffset > 0) {
textX.push({
t: TextXActionType.RETAIN,
- len: startOffset,
+ len: insertOffset,
});
}
} else {
@@ -113,16 +116,11 @@ export const addDrawing = (param: IAddDrawingParam) => {
}
}
+ const insertBody = buildDrawingInsertBody(body, drawings, insertOffset);
textX.push({
t: TextXActionType.INSERT,
- body: {
- dataStream: '\b'.repeat(drawings.length),
- customBlocks: drawings.map((drawing, i) => ({
- startIndex: i,
- blockId: drawing.drawingId,
- })),
- },
- len: drawings.length,
+ body: insertBody,
+ len: insertBody.dataStream.length,
});
const path = getRichTextEditPath(documentDataModel, segmentId);
@@ -144,3 +142,29 @@ export const addDrawing = (param: IAddDrawingParam) => {
return JSONX.compose(acc, cur as JSONXActions);
}, null as JSONXActions);
};
+
+function normalizeDrawingInsertOffset(body: IDocumentBody, offset: number): number {
+ return offset === 0 && body.dataStream[0] === DataStreamTreeTokenType.PARAGRAPH ? 1 : offset;
+}
+
+function buildDrawingInsertBody(body: IDocumentBody, drawings: any[], insertOffset: number): IDocumentBody {
+ const placeholders = DataStreamTreeTokenType.CUSTOM_BLOCK.repeat(drawings.length);
+ const needsTrailingParagraph = body.dataStream[insertOffset] === DataStreamTreeTokenType.SECTION_BREAK || body.dataStream[insertOffset] === undefined;
+ const dataStream = needsTrailingParagraph ? `${placeholders}${DataStreamTreeTokenType.PARAGRAPH}` : placeholders;
+
+ return {
+ dataStream,
+ customBlocks: drawings.map((drawing, i) => ({
+ startIndex: i,
+ blockId: drawing.drawingId,
+ })),
+ ...(needsTrailingParagraph
+ ? {
+ paragraphs: [{
+ startIndex: placeholders.length,
+ paragraphId: createParagraphId(new Set(body.paragraphs?.map((paragraph) => paragraph.paragraphId))),
+ }],
+ }
+ : {}),
+ };
+}
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.ts
new file mode 100644
index 0000000000..561ece38f5
--- /dev/null
+++ b/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts
@@ -0,0 +1,58 @@
+/**
+ * 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 { DataStreamTreeTokenType } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { buildDocTableInsertBody, normalizeTableInsertOffset, shouldCreateParagraphBeforeTable } from '../table/doc-table-create.command';
+import { genEmptyTable } from '../table/table';
+
+describe('doc table create command helpers', () => {
+ it('normalizes offset zero to keep the initial empty paragraph above the table', () => {
+ expect(normalizeTableInsertOffset({ dataStream: '\r\n' }, 0)).toBe(1);
+ expect(normalizeTableInsertOffset({ dataStream: 'Title\r\n' }, 0)).toBe(0);
+ });
+
+ it('does not create another before-table paragraph at an existing paragraph boundary', () => {
+ expect(shouldCreateParagraphBeforeTable({ dataStream: '\r\n' }, 1)).toBe(false);
+ expect(shouldCreateParagraphBeforeTable({ dataStream: 'Title\r\n' }, 6)).toBe(false);
+ });
+
+ it('creates a before-table paragraph when inserting inside paragraph text', () => {
+ expect(shouldCreateParagraphBeforeTable({ dataStream: 'Title\r\n' }, 2)).toBe(true);
+ });
+
+ it('builds inserted table body with a normal paragraph after the table', () => {
+ const tableData = genEmptyTable(1, 1);
+ const body = buildDocTableInsertBody({
+ tableDataStream: tableData.dataStream,
+ tableParagraphs: tableData.paragraphs,
+ sectionBreaks: tableData.sectionBreaks,
+ tableId: 'table-1',
+ textRun: { st: 0, ed: tableData.dataStream.length, ts: {} },
+ });
+
+ expect(body.dataStream).toBe(`${tableData.dataStream}${DataStreamTreeTokenType.PARAGRAPH}`);
+ expect(body.tables).toEqual([{
+ startIndex: 0,
+ endIndex: tableData.dataStream.length,
+ tableId: 'table-1',
+ }]);
+ expect(body.paragraphs.at(-1)).toMatchObject({
+ startIndex: tableData.dataStream.length,
+ paragraphId: expect.stringMatching(/^para_/),
+ });
+ });
+});
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.ts
index 2c80cffd42..ccc597eb68 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
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import type { ICommand, IMutationInfo, JSONXActions } from '@univerjs/core';
+import type { ICommand, IMutationInfo, IParagraph, ISectionBreak, ITextRun, JSONXActions } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
-import { CommandType, DataStreamTreeTokenType, getRichTextEditPath, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';
+import { CommandType, createParagraphId, DataStreamTreeTokenType, getRichTextEditPath, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';
import { DocContentInsertService, DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { getTextRunAtPosition } from '../../../basics/paragraph';
import { DocMenuStyleService } from '../../../services/doc-menu-style.service';
@@ -31,6 +31,53 @@ export interface ICreateDocTableCommandParams {
rowCount: number;
colCount: number;
}
+
+export interface IDocTableInsertBodyParams {
+ tableDataStream: string;
+ tableParagraphs: IParagraph[];
+ sectionBreaks: ISectionBreak[];
+ tableId: string;
+ textRun: ITextRun;
+ existingParagraphIds?: Set<string>;
+}
+
+export function buildDocTableInsertBody(params: IDocTableInsertBodyParams) {
+ const { tableDataStream, tableParagraphs, sectionBreaks, tableId, textRun } = params;
+ const existingParagraphIds = params.existingParagraphIds ?? new Set(tableParagraphs.map((paragraph) => paragraph.paragraphId));
+ const dataStream = `${tableDataStream}${DataStreamTreeTokenType.PARAGRAPH}`;
+ const tableEnd = tableDataStream.length;
+
+ return {
+ dataStream,
+ paragraphs: [
+ ...tableParagraphs,
+ {
+ startIndex: tableEnd,
+ paragraphId: createParagraphId(existingParagraphIds),
+ },
+ ],
+ sectionBreaks,
+ textRuns: [{
+ ...textRun,
+ st: 0,
+ ed: tableEnd,
+ }],
+ tables: [{
+ startIndex: 0,
+ endIndex: tableEnd,
+ tableId,
+ }],
+ };
+}
+
+export function shouldCreateParagraphBeforeTable(body: { dataStream: string }, startOffset: number): boolean {
+ return startOffset <= 0 || body.dataStream[startOffset - 1] !== DataStreamTreeTokenType.PARAGRAPH;
+}
+
+export function normalizeTableInsertOffset(body: { dataStream: string }, startOffset: number): number {
+ return startOffset === 0 && body.dataStream[0] === DataStreamTreeTokenType.PARAGRAPH ? 1 : startOffset;
+}
+
/**
* The command to create a table at cursor point.
*/
@@ -75,7 +122,7 @@ export const CreateDocTableCommand: ICommand<ICreateDocTableCommandParams> = {
if (skeleton == null) {
return false;
}
- const startOffset = contentInsertRange?.startOffset ?? activeRange!.startOffset;
+ const startOffset = normalizeTableInsertOffset(body, contentInsertRange?.startOffset ?? activeRange!.startOffset);
const paragraphs = body.paragraphs ?? [];
const prevParagraph = paragraphs.find((p) => p.startIndex >= startOffset);
@@ -88,9 +135,7 @@ export const CreateDocTableCommand: ICommand<ICreateDocTableCommandParams> = {
return false;
}
- // Also need to create new paragraph when there is already a table in paragraph.
- // Always inert a paragraph before table.
- const needCreateParagraph = true; // isInParagraph || line.isBehindTable;
+ const needCreateParagraph = shouldCreateParagraphBeforeTable(body, startOffset);
const textX = new TextX();
const jsonX = JSONX.getInstance();
@@ -149,27 +194,19 @@ export const CreateDocTableCommand: ICommand<ICreateDocTableCommandParams> = {
}
const { pageWidth, marginLeft, marginRight } = page;
const tableSource = genTableSource(rowCount, colCount, pageWidth - marginLeft - marginRight);
+ const tableInsertBody = buildDocTableInsertBody({
+ tableDataStream,
+ tableParagraphs,
+ sectionBreaks,
+ tableId: tableSource.tableId,
+ textRun: curTextRun,
+ existingParagraphIds: new Set(body.paragraphs?.map((paragraph) => paragraph.paragraphId)),
+ });
textX.push({
t: TextXActionType.INSERT,
- body: {
- dataStream: tableDataStream,
- paragraphs: tableParagraphs,
- sectionBreaks,
- textRuns: [{
- ...curTextRun,
- st: 0,
- ed: tableDataStream.length,
- }],
- tables: [
- {
- startIndex: 0,
- endIndex: tableDataStream.length,
- tableId: tableSource.tableId,
- },
- ],
- },
- len: tableDataStream.length,
+ body: tableInsertBody,
+ len: tableInsertBody.dataStream.length,
});
const path = getRichTextEditPath(docDataModel, segmentId);