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): render images inserted at table cell tail (#7387)

Univer46991c5230d8
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/drawings.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/drawings.spec.ts
index 5011022cc3..fd2a6c0413 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/drawings.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/drawings.spec.ts
@@ -15,12 +15,62 @@
*/
import { describe, expect, it } from 'vitest';
+import { DrawingTypeEnum } from '../../../../../types/interfaces/i-drawing';
import { DocumentDataModel } from '../../../document-data-model';
import { DataStreamTreeTokenType } from '../../../types';
import { getRichTextEditPath } from '../../utils';
import { addDrawing, getCustomBlockIdsInSelections } from '../drawings';
describe('drawing build utils', () => {
+ it('anchors a drawing in the current table-cell paragraph at the cell structural tail', () => {
+ 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 doc = new DocumentDataModel({
+ id: 'doc-table-cell-drawing',
+ body: {
+ dataStream: `${tableStream}${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 7, paragraphId: 'cell-paragraph' },
+ { startIndex: 12, paragraphId: 'body-paragraph' },
+ ],
+ sectionBreaks: [
+ { startIndex: 8, sectionId: 'cell-section' },
+ { startIndex: 13, sectionId: 'body-section' },
+ ],
+ customBlocks: [],
+ tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
+ },
+ drawings: {},
+ drawingsOrder: [],
+ });
+
+ const actions = addDrawing({
+ selection: { startOffset: 8, endOffset: 8, collapsed: true },
+ documentDataModel: doc,
+ drawings: [{
+ unitId: 'doc-table-cell-drawing',
+ subUnitId: '',
+ drawingId: 'drawing-new',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ }],
+ });
+
+ expect(actions).toBeTruthy();
+ if (!actions) {
+ throw new Error('Expected addDrawing to return JSONX actions');
+ }
+ doc.apply(actions);
+
+ expect(doc.getBody()?.dataStream).toBe(
+ `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.CUSTOM_BLOCK}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.PARAGRAPH}${T.SECTION_BREAK}`
+ );
+ expect(doc.getBody()?.customBlocks).toEqual([{ startIndex: 7, blockId: 'drawing-new' }]);
+ expect(doc.getBody()?.paragraphs).toEqual([
+ { startIndex: 8, paragraphId: 'cell-paragraph' },
+ { startIndex: 13, paragraphId: 'body-paragraph' },
+ ]);
+ });
+
it('keeps the initial empty paragraph above a drawing inserted at offset zero', () => {
const doc = new DocumentDataModel({
id: 'doc-empty-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 b02c2d7135..9c6baca4b3 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
@@ -144,7 +144,33 @@ export const addDrawing = (param: IAddDrawingParam) => {
};
function normalizeDrawingInsertOffset(body: IDocumentBody, offset: number): number {
- return offset === 0 && body.dataStream[0] === DataStreamTreeTokenType.PARAGRAPH ? 1 : offset;
+ const { dataStream } = body;
+ if (offset === 0 && dataStream[0] === DataStreamTreeTokenType.PARAGRAPH) {
+ return 1;
+ }
+
+ if (
+ dataStream[offset] === DataStreamTreeTokenType.SECTION_BREAK &&
+ dataStream[offset - 1] === DataStreamTreeTokenType.PARAGRAPH &&
+ isInsideTableCell(dataStream, offset)
+ ) {
+ return offset - 1;
+ }
+
+ return offset;
+}
+
+function isInsideTableCell(dataStream: string, offset: number): boolean {
+ let cellDepth = 0;
+ for (let index = 0; index < offset; index++) {
+ if (dataStream[index] === DataStreamTreeTokenType.TABLE_CELL_START) {
+ cellDepth++;
+ } else if (dataStream[index] === DataStreamTreeTokenType.TABLE_CELL_END) {
+ cellDepth = Math.max(0, cellDepth - 1);
+ }
+ }
+
+ return cellDepth > 0;
}
function buildDrawingInsertBody(body: IDocumentBody, drawings: IDrawingParam[], insertOffset: number): IDocumentBody {
diff --git a/packages/docs-drawing/src/commands/commands/insert-doc-drawing.command.ts b/packages/docs-drawing/src/commands/commands/insert-doc-drawing.command.ts
index 903a05e987..05f099eff8 100644
--- a/packages/docs-drawing/src/commands/commands/insert-doc-drawing.command.ts
+++ b/packages/docs-drawing/src/commands/commands/insert-doc-drawing.command.ts
@@ -14,23 +14,23 @@
* limitations under the License.
*/
-import type { DocumentDataModel, IAccessor, ICommand, IMutationInfo, ITextRangeParam, JSONXActions } from '@univerjs/core';
+import type { DocumentDataModel, IAccessor, ICommand, IMutationInfo, ITextRangeParam } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { IDocDrawing } from '../../services/doc-drawing.service';
import {
BooleanNumber,
BuildTextUtils,
CommandType,
- getCustomBlockIdsInSelections,
- getRichTextEditPath,
ICommandService,
IUniverInstanceService,
- JSONX,
- TextX,
- TextXActionType,
UniverInstanceType,
} from '@univerjs/core';
-import { DocSelectionManagerService, getContentInsertRange, normalizeTextRange, RichTextEditingMutation } from '@univerjs/docs';
+import {
+ DocSelectionManagerService,
+ getContentInsertRange,
+ normalizeTextRange,
+ RichTextEditingMutation,
+} from '@univerjs/docs';
export interface IInsertDocDrawingCommandParams {
unitId: string;
@@ -46,7 +46,6 @@ export const InsertDocDrawingCommand: ICommand = {
type: CommandType.COMMAND,
- // eslint-disable-next-line max-lines-per-function
handler: (accessor: IAccessor, params?: IInsertDocDrawingCommandParams) => {
if (!params) {
return false;
@@ -61,22 +60,19 @@ export const InsertDocDrawingCommand: ICommand = {
return false;
}
- const targetTextRange = resolveDocDrawingInsertTextRange(accessor, unitId, textRange);
+ const resolvedTextRange = resolveDocDrawingInsertTextRange(accessor, unitId, textRange);
- if (!targetTextRange) {
+ if (!resolvedTextRange) {
return false;
}
- const { collapsed, startOffset, segmentId = '' } = targetTextRange;
+ const { segmentId = '' } = resolvedTextRange;
const body = documentDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (!body) {
return false;
}
- const textX = new TextX();
- const jsonX = JSONX.getInstance();
- const rawActions: JSONXActions = [];
const snapshot = documentDataModel.getSnapshot();
const isHeaderFooter = !!snapshot.headers?.[segmentId] || !!snapshot.footers?.[segmentId];
const targetDrawings = isHeaderFooter
@@ -86,78 +82,14 @@ export const InsertDocDrawingCommand: ICommand = {
transforms: drawing.transforms ?? (drawing.transform ? [drawing.transform] : null),
}))
: drawings;
- const drawingOrderLength = snapshot.drawingsOrder?.length ?? 0;
- let removeDrawingLen = 0;
-
- // Step 1: Insert placeholder `\b` in dataStream and add drawing to customBlocks.
- if (collapsed) {
- if (startOffset > 0) {
- textX.push({
- t: TextXActionType.RETAIN,
- len: startOffset,
- });
- }
- } else {
- const dos = BuildTextUtils.selection.delete([targetTextRange], body, 0, null, false);
- textX.push(...dos);
-
- const removedCustomBlockIds = getCustomBlockIdsInSelections(body, [targetTextRange]);
- const drawings = documentDataModel.getDrawings() ?? {};
- const drawingOrder = documentDataModel.getDrawingsOrder() ?? [];
- const sortedRemovedCustomBlockIds = removedCustomBlockIds.sort((a, b) => {
- if (drawingOrder.indexOf(a) > drawingOrder.indexOf(b)) {
- return -1;
- } else if (drawingOrder.indexOf(a) < drawingOrder.indexOf(b)) {
- return 1;
- }
-
- return 0;
- });
-
- if (sortedRemovedCustomBlockIds.length > 0) {
- for (const blockId of sortedRemovedCustomBlockIds) {
- const drawing = drawings[blockId];
- const drawingIndex = drawingOrder.indexOf(blockId);
- if (drawing == null || drawingIndex < 0) {
- continue;
- }
-
- const removeDrawingAction = jsonX.removeOp(['drawings', blockId], drawing);
- const removeDrawingOrderAction = jsonX.removeOp(['drawingsOrder', drawingIndex], blockId);
-
- rawActions.push(removeDrawingAction!);
- rawActions.push(removeDrawingOrderAction!);
-
- removeDrawingLen++;
- }
- }
- }
-
- textX.push({
- t: TextXActionType.INSERT,
- body: {
- dataStream: '\b'.repeat(targetDrawings.length),
- customBlocks: targetDrawings.map((drawing, i) => ({
- startIndex: i,
- blockId: drawing.drawingId,
- })),
- },
- len: targetDrawings.length,
+ const actions = BuildTextUtils.drawing.add({
+ selection: resolvedTextRange,
+ documentDataModel,
+ drawings: targetDrawings,
});
- const path = getRichTextEditPath(documentDataModel, segmentId);
- const placeHolderAction = jsonX.editOp(textX.serialize(), path);
-
- rawActions.push(placeHolderAction!);
-
- // Step 2: add drawing to drawings and drawingsOrder fields.
- for (const drawing of targetDrawings) {
- const { drawingId } = drawing;
- const addDrawingAction = jsonX.insertOp(['drawings', drawingId], drawing);
- const addDrawingOrderAction = jsonX.insertOp(['drawingsOrder', drawingOrderLength - removeDrawingLen], drawingId);
-
- rawActions.push(addDrawingAction!);
- rawActions.push(addDrawingOrderAction!);
+ if (!actions) {
+ return false;
}
const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
@@ -169,9 +101,7 @@ export const InsertDocDrawingCommand: ICommand = {
},
};
- doMutation.params.actions = rawActions.reduce((acc, cur) => {
- return JSONX.compose(acc, cur as JSONXActions);
- }, null as JSONXActions);
+ doMutation.params.actions = actions;
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
diff --git a/packages/docs-drawing/src/facade/__tests__/create-test-bed.ts b/packages/docs-drawing/src/facade/__tests__/create-test-bed.ts
index 9ccbcebddb..02c37bfcb6 100644
--- a/packages/docs-drawing/src/facade/__tests__/create-test-bed.ts
+++ b/packages/docs-drawing/src/facade/__tests__/create-test-bed.ts
@@ -15,7 +15,14 @@
*/
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
-import { DocumentFlavor, ILogService, IUniverInstanceService, LogLevel, Univer, UniverInstanceType } from '@univerjs/core';
+import {
+ DocumentFlavor,
+ ILogService,
+ IUniverInstanceService,
+ LogLevel,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
import { FUniver } from '@univerjs/core/facade';
import { UniverDocsPlugin } from '@univerjs/docs';
import { UniverDrawingPlugin } from '@univerjs/drawing';
@@ -36,7 +43,7 @@ const DEFAULT_DOC_DATA: IDocumentData = {
drawingsOrder: [],
};
-export function createFacadeTestBed() {
+export function createFacadeTestBed(data: IDocumentData = DEFAULT_DOC_DATA) {
const univer = new Univer();
const injector = univer.__getInjector();
@@ -47,7 +54,7 @@ export function createFacadeTestBed() {
const documentDataModel = univer.createUnit<IDocumentData, DocumentDataModel>(
UniverInstanceType.UNIVER_DOC,
- DEFAULT_DOC_DATA
+ structuredClone(data)
);
injector.get(IUniverInstanceService).focusUnit(documentDataModel.getUnitId());
injector.get(ILogService).setLogLevel(LogLevel.SILENT);
diff --git a/packages/docs-drawing/src/facade/__tests__/f-document-image.spec.ts b/packages/docs-drawing/src/facade/__tests__/f-document-image.spec.ts
index aba453b249..6136112e97 100644
--- a/packages/docs-drawing/src/facade/__tests__/f-document-image.spec.ts
+++ b/packages/docs-drawing/src/facade/__tests__/f-document-image.spec.ts
@@ -14,10 +14,11 @@
* limitations under the License.
*/
-import type { IObjectPositionH, IObjectPositionV } from '@univerjs/core';
+import type { IDocumentData, IObjectPositionH, IObjectPositionV } from '@univerjs/core';
import {
ArrangeTypeEnum,
BooleanNumber,
+ DataStreamTreeTokenType,
ICommandService,
ImageSourceType,
ObjectRelativeFromH,
@@ -155,6 +156,94 @@ describe('FDocument image facade', () => {
expect(image?.getSize()).toEqual({ width: 160, height: 90 });
});
+ it('creates a renderable image paragraph when the range points to the document structural tail', async () => {
+ const image = await testBed.document.insertImage({
+ source: 'data:image/png;base64,image',
+ imageSourceType: ImageSourceType.BASE64,
+ width: 160,
+ height: 90,
+ textRange: {
+ startOffset: 12,
+ endOffset: 12,
+ collapsed: true,
+ segmentId: '',
+ },
+ });
+
+ const snapshot = testBed.document.save();
+
+ expect(image).not.toBeNull();
+ expect(snapshot.body?.dataStream).toBe('Hello world\r\b\r\n');
+ expect(snapshot.body?.customBlocks).toEqual([
+ {
+ startIndex: 12,
+ blockId: image?.getId(),
+ },
+ ]);
+ expect(snapshot.body?.paragraphs).toEqual([
+ { startIndex: 11, paragraphId: 'paragraph-1' },
+ expect.objectContaining({ startIndex: 13 }),
+ ]);
+ });
+
+ it('anchors an image inside the current table-cell paragraph when the range points to the cell structural tail', async () => {
+ 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 documentData: IDocumentData = {
+ id: 'test-doc',
+ documentStyle: {},
+ body: {
+ dataStream: `${tableStream}${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 7, paragraphId: 'cell-paragraph' },
+ { startIndex: 12, paragraphId: 'body-paragraph' },
+ ],
+ sectionBreaks: [
+ { startIndex: 8, sectionId: 'cell-section' },
+ { startIndex: 13, sectionId: 'body-section' },
+ ],
+ customBlocks: [],
+ tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
+ },
+ drawings: {},
+ drawingsOrder: [],
+ };
+ testBed.univer.dispose();
+ testBed = createFacadeTestBed(documentData);
+
+ const image = await testBed.document.insertImage({
+ source: 'data:image/png;base64,image',
+ imageSourceType: ImageSourceType.BASE64,
+ width: 160,
+ height: 90,
+ textRange: {
+ startOffset: 8,
+ endOffset: 8,
+ collapsed: true,
+ segmentId: '',
+ },
+ });
+
+ const snapshot = testBed.document.save();
+ const expectedDataStream = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.CUSTOM_BLOCK}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+
+ expect(image).not.toBeNull();
+ expect(snapshot.body?.dataStream).toBe(expectedDataStream);
+ expect(snapshot.body?.customBlocks).toEqual([{ startIndex: 7, blockId: image?.getId() }]);
+ expect(snapshot.body?.paragraphs).toEqual([
+ { startIndex: 8, paragraphId: 'cell-paragraph' },
+ { startIndex: 13, paragraphId: 'body-paragraph' },
+ ]);
+
+ expect(testBed.document.undo()).toBe(true);
+ expect(testBed.document.save().body?.dataStream).toBe(documentData.body?.dataStream);
+ expect(testBed.document.save().drawingsOrder).toEqual([]);
+
+ expect(testBed.document.redo()).toBe(true);
+ expect(testBed.document.save().body?.dataStream).toBe(expectedDataStream);
+ expect(testBed.document.save().drawingsOrder).toEqual([image?.getId()]);
+ });
+
it('inserts an image with a non-inline wrapping style', async () => {
const image = await testBed.document.insertImage({
source: 'data:image/png;base64,image',
@@ -190,7 +279,7 @@ describe('FDocument image facade', () => {
});
const imageData = image?.getImageData();
- expect(testBed.document.save().headers?.[segmentId].body.dataStream).toBe('\b\r\n');
+ expect(testBed.document.save().headers?.[segmentId].body.dataStream).toBe('\r\b\r\n');
expect(imageData?.isMultiTransform).toBe(BooleanNumber.TRUE);
expect(imageData?.transforms).toEqual(imageData?.transform ? [imageData.transform] : null);
});
diff --git a/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.ts b/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.ts
index 657ce1cae1..d36e275f70 100644
--- a/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.ts
+++ b/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.ts
@@ -15,6 +15,7 @@
*/
import type { Nullable } from '@univerjs/core';
+import type { DataStreamTreeNode } from '../data-stream-tree-node';
import { DataStreamTreeNodeType, DataStreamTreeTokenType } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
import { DocumentEditArea, DocumentViewModel, parseDataStreamToTree } from '../document-view-model';
@@ -88,6 +89,26 @@ describe('DocumentViewModel', () => {
expect(sectionList[1].children[0].content).toBe('');
});
+ it('projects legacy custom blocks after a paragraph terminator into a renderable paragraph', () => {
+ const T = DataStreamTreeTokenType;
+ const dataStream = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${T.PARAGRAPH}${T.CUSTOM_BLOCK}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const { sectionList } = parseDataStreamToTree(dataStream);
+ const tableCell = findFirstNodeByType(sectionList[0], DataStreamTreeNodeType.TABLE_CELL);
+ expect(tableCell).not.toBeNull();
+ if (!tableCell) {
+ throw new Error('Expected a table-cell node');
+ }
+ const paragraphs = tableCell.children[0].children;
+
+ expect(paragraphs.map((paragraph: DataStreamTreeNode) => paragraph.content)).toEqual([
+ T.PARAGRAPH,
+ `${T.CUSTOM_BLOCK}${T.SECTION_BREAK}`,
+ ]);
+ expect(paragraphs[1].startIndex).toBe(4);
+ expect(paragraphs[1].endIndex).toBe(4);
+ expect(paragraphs[1].blocks).toEqual([4]);
+ });
+
it('should parse table/custom-block and build table node cache', () => {
const ds = [
'A',
diff --git a/packages/engine-render/src/components/docs/view-model/document-view-model.ts b/packages/engine-render/src/components/docs/view-model/document-view-model.ts
index 92c4fa6556..d8adbf4eb8 100644
--- a/packages/engine-render/src/components/docs/view-model/document-view-model.ts
+++ b/packages/engine-render/src/components/docs/view-model/document-view-model.ts
@@ -157,6 +157,21 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[
? columnParagraphList
: paragraphList;
+ if (
+ tempParagraphList.length > 0 &&
+ currentBlocks.length > 0 &&
+ content === DataStreamTreeTokenType.CUSTOM_BLOCK.repeat(currentBlocks.length)
+ ) {
+ // Older drawing insertion could leave custom blocks between a paragraph terminator and section break.
+ // Project them as a synthetic paragraph without changing the persisted snapshot.
+ const blockParagraph = DataStreamTreeNode.create(DataStreamTreeNodeType.PARAGRAPH, content);
+ blockParagraph.setIndexRange(i - content.length, i - 1);
+ blockParagraph.addBlocks(currentBlocks);
+ tempParagraphList.push(blockParagraph);
+ currentBlocks.length = 0;
+ content = '';
+ }
+
if (tempParagraphList.length === 0) {
const emptyParagraph = DataStreamTreeNode.create(DataStreamTreeNodeType.PARAGRAPH, '');
emptyParagraph.setIndexRange(i, i - 1);