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.

feat(docs): support column group document flow (#7134)

Univer570f5d59fba3
diff --git a/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.ts b/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.ts
index 0c80f2947a..deb233f0c6 100644
--- a/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.ts
+++ b/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.ts
@@ -29,6 +29,7 @@ describe('getEmptySnapshot', () => {
it('initializes optional body arrays for structured doc features', () => {
expect(getEmptySnapshot().body).toMatchObject({
blockRanges: [],
+ columnGroups: [],
customBlocks: [],
customDecorations: [],
customRanges: [],
diff --git a/packages/core/src/docs/data-model/empty-snapshot.ts b/packages/core/src/docs/data-model/empty-snapshot.ts
index a9e2f0c0d3..deb9db648f 100644
--- a/packages/core/src/docs/data-model/empty-snapshot.ts
+++ b/packages/core/src/docs/data-model/empty-snapshot.ts
@@ -41,6 +41,7 @@ export function getEmptySnapshot(
textRuns: [],
customBlocks: [],
tables: [],
+ columnGroups: [],
blockRanges: [],
customRanges: [],
customDecorations: [],
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/column-groups.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/column-groups.spec.ts
new file mode 100644
index 0000000000..9ade44c581
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/__tests__/column-groups.spec.ts
@@ -0,0 +1,112 @@
+/**
+ * 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 type { TextXAction } from '../action-types';
+import { describe, expect, it } from 'vitest';
+import { DataStreamTreeTokenType } from '../../types';
+import { TextXActionType } from '../action-types';
+import { TextX } from '../text-x';
+
+describe('TextX column groups', () => {
+ it('adds inserted column group metadata to documents without existing column groups', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `A${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 1, paragraphId: 'before' }],
+ sectionBreaks: [{ startIndex: 2 }],
+ };
+
+ TextX.apply(body, [
+ { t: TextXActionType.RETAIN, len: 2 },
+ {
+ t: TextXActionType.INSERT,
+ len: 5,
+ body: {
+ dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}`,
+ paragraphs: [{ startIndex: 2, paragraphId: 'column' }],
+ columnGroups: [{ startIndex: 0, endIndex: 4, columnGroupId: 'cg-1' }],
+ },
+ },
+ ]);
+
+ expect(body.columnGroups).toEqual([{ startIndex: 2, endIndex: 6, columnGroupId: 'cg-1' }]);
+ });
+
+ it('expands a containing column group when text is inserted into a column', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ 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}`,
+ paragraphs: [
+ { startIndex: 2, paragraphId: 'left' },
+ { startIndex: 5, paragraphId: 'right' },
+ ],
+ sectionBreaks: [{ startIndex: 8 }],
+ columnGroups: [{ startIndex: 0, endIndex: 7, columnGroupId: 'cg-1' }],
+ };
+
+ TextX.apply(body, [
+ { t: TextXActionType.RETAIN, len: 2 },
+ { t: TextXActionType.INSERT, body: { dataStream: 'Alpha' }, len: 5 },
+ ]);
+
+ expect(body.dataStream).toBe(`${T.COLUMN_GROUP_START}${T.COLUMN_START}Alpha${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_START}${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`);
+ expect(body.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([7, 10]);
+ expect(body.sectionBreaks?.[0].startIndex).toBe(13);
+ expect(body.columnGroups).toEqual([{ startIndex: 0, endIndex: 12, columnGroupId: 'cg-1' }]);
+ });
+
+ it('keeps a column group wrapped when text is inserted before the closing boundary token', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_START}B${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 3, paragraphId: 'left' },
+ { startIndex: 7, paragraphId: 'right' },
+ { startIndex: 9, paragraphId: 'after' },
+ ],
+ sectionBreaks: [{ startIndex: 10 }],
+ columnGroups: [{ startIndex: 0, endIndex: 9, columnGroupId: 'cg-1' }],
+ };
+
+ TextX.apply(body, [
+ { t: TextXActionType.RETAIN, len: 9 },
+ { t: TextXActionType.INSERT, body: { dataStream: T.PARAGRAPH, paragraphs: [{ startIndex: 0, paragraphId: 'inserted' }] }, len: 1 },
+ ]);
+
+ expect(body.dataStream).toBe(`${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_START}B${T.PARAGRAPH}${T.COLUMN_END}${T.PARAGRAPH}${T.COLUMN_GROUP_END}${T.PARAGRAPH}${T.SECTION_BREAK}`);
+ expect(body.columnGroups).toEqual([{ startIndex: 0, endIndex: 10, columnGroupId: 'cg-1' }]);
+ });
+
+ it('returns deleted column groups in delete undo bodies', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 3, paragraphId: 'left' }],
+ sectionBreaks: [{ startIndex: 5 }],
+ columnGroups: [{ startIndex: 0, endIndex: 4, columnGroupId: 'cg-1' }],
+ };
+ const actions: TextXAction[] = [
+ { t: TextXActionType.DELETE, len: 5 },
+ ];
+
+ TextX.makeInvertible(actions, body);
+ TextX.apply(body, actions);
+
+ expect(body.columnGroups).toEqual([]);
+ expect(actions[0].body?.columnGroups).toEqual([{ startIndex: 0, endIndex: 4, columnGroupId: 'cg-1' }]);
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/tables.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/tables.spec.ts
new file mode 100644
index 0000000000..3a84a42447
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/__tests__/tables.spec.ts
@@ -0,0 +1,51 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentBody } from '../../../../types/interfaces';
+import { describe, expect, it } from 'vitest';
+import { DataStreamTreeTokenType } from '../../types';
+import { TextXActionType } from '../action-types';
+import { TextX } from '../text-x';
+
+describe('TextX tables', () => {
+ it('shifts table metadata when content is inserted at the table start boundary', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `A${T.PARAGRAPH}${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}B${T.PARAGRAPH}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 1, paragraphId: 'before' },
+ { startIndex: 6, paragraphId: 'cell' },
+ ],
+ sectionBreaks: [{ startIndex: 10 }],
+ tables: [{ startIndex: 2, endIndex: 9, tableId: 'table-1' }],
+ };
+
+ TextX.apply(body, [
+ { t: TextXActionType.RETAIN, len: 2 },
+ {
+ t: TextXActionType.INSERT,
+ body: {
+ dataStream: T.PARAGRAPH,
+ paragraphs: [{ startIndex: 0, paragraphId: 'inserted' }],
+ },
+ len: 1,
+ },
+ ]);
+
+ expect(body.dataStream).toBe(`A${T.PARAGRAPH}${T.PARAGRAPH}${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}B${T.PARAGRAPH}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.SECTION_BREAK}`);
+ expect(body.tables).toEqual([{ startIndex: 3, endIndex: 10, tableId: 'table-1' }]);
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
index 36a13c41f4..dee3bd3bb0 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
@@ -17,6 +17,7 @@
import type { Nullable } from '../../../../shared/types';
import type {
ICustomBlock,
+ ICustomColumnGroup,
ICustomDecoration,
ICustomRange,
ICustomTable,
@@ -418,7 +419,7 @@ export function insertTables(body: IDocumentBody, insertBody: IDocumentBody, tex
const table = tables[i];
const { startIndex, endIndex } = table;
- if (startIndex > currentIndex) {
+ if (startIndex >= currentIndex) {
table.startIndex += textLength;
table.endIndex += textLength;
} else if (endIndex > currentIndex) {
@@ -439,6 +440,41 @@ export function insertTables(body: IDocumentBody, insertBody: IDocumentBody, tex
}
}
+export function insertColumnGroups(body: IDocumentBody, insertBody: IDocumentBody, textLength: number, currentIndex: number) {
+ if (!body.columnGroups && !insertBody.columnGroups?.length) {
+ return;
+ }
+
+ if (!body.columnGroups) {
+ body.columnGroups = [];
+ }
+
+ const { 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) {
+ columnGroup.endIndex += textLength;
+ }
+ }
+
+ const insertColumnGroups = insertBody.columnGroups;
+ if (insertColumnGroups) {
+ for (let i = 0, len = insertColumnGroups.length; i < len; i++) {
+ const columnGroup = insertColumnGroups[i];
+ columnGroup.startIndex += currentIndex;
+ columnGroup.endIndex += currentIndex;
+ }
+
+ columnGroups.push(...insertColumnGroups);
+ columnGroups.sort(sortRulesFactory('startIndex'));
+ }
+}
+
export function insertBlockRanges(body: IDocumentBody, insertBody: IDocumentBody, textLength: number, currentIndex: number) {
if (!body.blockRanges && !insertBody.blockRanges?.length) {
return;
@@ -993,6 +1029,52 @@ export function deleteTables(body: IDocumentBody, textLength: number, currentInd
return removeTables;
}
+export 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) {
+ removeColumnGroups.push({
+ ...columnGroup,
+ startIndex: st - currentIndex,
+ endIndex: ed - 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;
+ }
+ newColumnGroups.push(columnGroup);
+ }
+ body.columnGroups = newColumnGroups;
+ }
+
+ return removeColumnGroups;
+}
+
export function deleteCustomRanges(body: IDocumentBody, textLength: number, currentIndex: number) {
const { customRanges } = body;
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts
index edb18112f2..e601e55b63 100644
--- a/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts
@@ -18,6 +18,7 @@ import type { IDocumentBody } from '../../../../types/interfaces';
import { deleteContent } from '../../../../shared';
import {
deleteBlockRanges,
+ deleteColumnGroups,
deleteCustomBlocks,
deleteCustomDecorations,
deleteCustomRanges,
@@ -43,6 +44,8 @@ export function updateAttributeByDelete(body: IDocumentBody, textLength: number,
const removeTables = deleteTables(body, textLength, currentIndex);
+ const removeColumnGroups = deleteColumnGroups(body, textLength, currentIndex);
+
const removeBlockRanges = deleteBlockRanges(body, textLength, currentIndex);
const removeCustomRanges = deleteCustomRanges(body, textLength, currentIndex);
@@ -62,6 +65,7 @@ export function updateAttributeByDelete(body: IDocumentBody, textLength: number,
sectionBreaks: removeSectionBreaks,
customBlocks: removeCustomBlocks,
tables: removeTables,
+ columnGroups: removeColumnGroups,
blockRanges: removeBlockRanges,
customRanges: removeCustomRanges,
customDecorations: removeCustomDecorations,
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.ts
index 357439963a..52eda0373e 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
@@ -18,6 +18,7 @@ import type { IDocumentBody } from '../../../../types/interfaces';
import { insertTextToContent } from '../../../../shared';
import {
insertBlockRanges,
+ insertColumnGroups,
insertCustomBlocks,
insertCustomDecorations,
insertCustomRanges,
@@ -45,6 +46,8 @@ export function updateAttributeByInsert(
insertTables(body, insertBody, textLength, currentIndex);
+ insertColumnGroups(body, insertBody, textLength, currentIndex);
+
insertBlockRanges(body, insertBody, textLength, currentIndex);
insertCustomRanges(body, insertBody, textLength, currentIndex);
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts
index 0c6dc9762c..ee3d94d68b 100644
--- a/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts
@@ -15,18 +15,20 @@
*/
import type { Nullable } from '../../../../shared';
-import type { ICustomBlock, ICustomDecoration, ICustomRange, ICustomTable, IDocumentBody, IParagraph, ISectionBreak, ITextRun } from '../../../../types/interfaces';
+import type { ICustomBlock, ICustomColumnGroup, ICustomDecoration, ICustomRange, ICustomTable, IDocumentBody, IParagraph, ISectionBreak, ITextRun } from '../../../../types/interfaces';
import { Tools, UpdateDocsAttributeType } from '../../../../shared';
import { CustomDecorationType } from '../../../../types/interfaces';
import { PresetListType } from '../../preset-list-type';
import {
deleteBlockRanges,
+ deleteColumnGroups,
deleteCustomBlocks,
deleteParagraphs,
deleteSectionBreaks,
deleteTables,
deleteTextRuns,
insertBlockRanges,
+ insertColumnGroups,
insertCustomBlocks,
insertParagraphs,
insertSectionBreaks,
@@ -51,6 +53,7 @@ export function updateAttribute(
const removeSectionBreaks = updateSectionBreaks(body, updateBody, textLength, currentIndex, coverType);
const removeCustomBlocks = updateCustomBlocks(body, updateBody, textLength, currentIndex, coverType);
const removeTables = updateTables(body, updateBody, textLength, currentIndex, coverType);
+ const removeColumnGroups = updateColumnGroups(body, updateBody, textLength, currentIndex, coverType);
const removeBlockRanges = updateBlockRanges(body, updateBody, textLength, currentIndex, coverType);
const removeCustomRanges = updateCustomRanges(body, updateBody, textLength, currentIndex, coverType);
const removeCustomDecorations = updateCustomDecorations(body, updateBody, textLength, currentIndex, coverType);
@@ -62,6 +65,7 @@ export function updateAttribute(
sectionBreaks: removeSectionBreaks,
customBlocks: removeCustomBlocks,
tables: removeTables,
+ columnGroups: removeColumnGroups,
blockRanges: removeBlockRanges,
customRanges: removeCustomRanges,
customDecorations: removeCustomDecorations,
@@ -448,6 +452,54 @@ function updateTables(
return removeTables;
}
+function updateColumnGroups(
+ body: IDocumentBody,
+ updateBody: IDocumentBody,
+ textLength: number,
+ currentIndex: number,
+ coverType: UpdateDocsAttributeType
+) {
+ const { columnGroups } = body;
+
+ const { columnGroups: updateDataColumnGroups } = updateBody;
+
+ if (columnGroups == null || updateDataColumnGroups == null) {
+ return;
+ }
+
+ const removeColumnGroups = deleteColumnGroups(body, textLength, currentIndex);
+ if (coverType !== UpdateDocsAttributeType.REPLACE) {
+ const newUpdateColumnGroups: ICustomColumnGroup[] = [];
+ for (const updateColumnGroup of updateDataColumnGroups) {
+ const { startIndex: updateStartIndex, endIndex: updateEndIndex } = updateColumnGroup;
+ let splitUpdateColumnGroups: ICustomColumnGroup[] = [];
+ for (const removeColumnGroup of removeColumnGroups) {
+ const { startIndex: removeStartIndex, endIndex: removeEndIndex } = removeColumnGroup;
+ if (removeStartIndex >= updateStartIndex && removeEndIndex <= updateEndIndex) {
+ if (coverType === UpdateDocsAttributeType.COVER) {
+ splitUpdateColumnGroups.push({
+ ...removeColumnGroup,
+ ...updateColumnGroup,
+ });
+ } else {
+ splitUpdateColumnGroups.push({
+ ...updateColumnGroup,
+ ...removeColumnGroup,
+ });
+ }
+ break;
+ }
+ }
+ newUpdateColumnGroups.push(...splitUpdateColumnGroups);
+ splitUpdateColumnGroups = [];
+ }
+ updateBody.columnGroups = newUpdateColumnGroups;
+ }
+ insertColumnGroups(body, updateBody, textLength, currentIndex);
+
+ return removeColumnGroups;
+}
+
function updateBlockRanges(
body: IDocumentBody,
updateBody: IDocumentBody,
diff --git a/packages/core/src/docs/data-model/text-x/utils.ts b/packages/core/src/docs/data-model/text-x/utils.ts
index 2599c44a81..b944a94fe3 100644
--- a/packages/core/src/docs/data-model/text-x/utils.ts
+++ b/packages/core/src/docs/data-model/text-x/utils.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICustomBlock, ICustomDecoration, ICustomRange, IDocumentBlockRange, IDocumentBody, IParagraph, ISectionBreak, ITextRun } from '../../../types/interfaces/i-document-data';
+import type { ICustomBlock, ICustomColumnGroup, ICustomDecoration, ICustomRange, IDocumentBlockRange, IDocumentBody, IParagraph, ISectionBreak, ITextRun } from '../../../types/interfaces/i-document-data';
import type { DocumentDataModel } from '../../data-model';
import type { IRetainAction } from './action-types';
import { UpdateDocsAttributeType } from '../../../shared/command-enum';
@@ -128,6 +128,30 @@ export function getBlockRangeSlice(
return newBlockRanges;
}
+export function getColumnGroupSlice(
+ body: IDocumentBody,
+ startOffset: number,
+ endOffset: number
+) {
+ const { columnGroups = [] } = body;
+ const newColumnGroups: ICustomColumnGroup[] = [];
+
+ for (const columnGroup of columnGroups) {
+ const clonedColumnGroup = Tools.deepClone(columnGroup);
+ const { startIndex, endIndex } = clonedColumnGroup;
+
+ if (startIndex >= startOffset && endIndex < endOffset) {
+ newColumnGroups.push({
+ ...clonedColumnGroup,
+ startIndex: startIndex - startOffset,
+ endIndex: endIndex - startOffset,
+ });
+ }
+ }
+
+ return newColumnGroups;
+}
+
export function getParagraphsSlice(
body: IDocumentBody,
startOffset: number,
@@ -250,6 +274,11 @@ export function getBodySlice(
docBody.blockRanges = newBlockRanges;
}
+ const newColumnGroups = getColumnGroupSlice(body, startOffset, endOffset);
+ if (newColumnGroups.length) {
+ docBody.columnGroups = newColumnGroups;
+ }
+
docBody.paragraphs = getParagraphsSlice(body, startOffset, endOffset, type);
if (type === SliceBodyType.cut) {
@@ -273,7 +302,7 @@ export function getBodySlice(
}
export function normalizeBody(body: IDocumentBody): IDocumentBody {
- const { dataStream, textRuns, paragraphs, customRanges, customDecorations, tables, blockRanges } = body;
+ const { dataStream, textRuns, paragraphs, customRanges, customDecorations, tables, columnGroups, blockRanges } = body;
let leftOffset = 0;
let rightOffset = 0;
@@ -323,6 +352,11 @@ export function normalizeBody(body: IDocumentBody): IDocumentBody {
table.endIndex += rightOffset;
});
+ columnGroups?.forEach((columnGroup) => {
+ columnGroup.startIndex += leftOffset;
+ columnGroup.endIndex += rightOffset;
+ });
+
return {
...body,
dataStream: newData,
@@ -331,6 +365,7 @@ export function normalizeBody(body: IDocumentBody): IDocumentBody {
customRanges,
customDecorations,
tables,
+ columnGroups,
blockRanges,
};
}
@@ -467,6 +502,7 @@ export function composeBody(
paragraphs: thisParagraphs = [],
customRanges: thisCustomRanges,
customDecorations: thisCustomDecorations = [],
+ columnGroups: thisColumnGroups = [],
blockRanges: thisBlockRanges = [],
} = thisBody;
const {
@@ -474,6 +510,7 @@ export function composeBody(
paragraphs: otherParagraphs = [],
customRanges: otherCustomRanges,
customDecorations: otherCustomDecorations = [],
+ columnGroups: otherColumnGroups = [],
blockRanges: otherBlockRanges = [],
} = otherBody;
@@ -528,6 +565,11 @@ export function composeBody(
retBody.blockRanges = blockRanges;
}
+ const columnGroups = composeColumnGroups(thisColumnGroups, otherColumnGroups);
+ if (columnGroups.length) {
+ retBody.columnGroups = columnGroups;
+ }
+
return retBody;
}
@@ -549,6 +591,24 @@ function composeDocumentBlockRanges(
return Array.from(byId.values()).sort((left, right) => left.startIndex - right.startIndex);
}
+function composeColumnGroups(
+ thisRanges: ICustomColumnGroup[],
+ otherRanges: ICustomColumnGroup[]
+): ICustomColumnGroup[] {
+ if (!thisRanges.length) {
+ return otherRanges;
+ }
+
+ if (!otherRanges.length) {
+ return thisRanges;
+ }
+
+ const byId = new Map(thisRanges.map((range) => [range.columnGroupId, Tools.deepClone(range)]));
+ otherRanges.forEach((range) => byId.set(range.columnGroupId, Tools.deepClone(range)));
+
+ return Array.from(byId.values()).sort((left, right) => left.startIndex - right.startIndex);
+}
+
export function isUselessRetainAction(action: IRetainAction): boolean {
const { body } = action;
@@ -556,9 +616,9 @@ export function isUselessRetainAction(action: IRetainAction): boolean {
return true;
}
- const { textRuns, paragraphs, customRanges, customBlocks, customDecorations, tables, blockRanges } = body;
+ const { textRuns, paragraphs, customRanges, customBlocks, customDecorations, tables, columnGroups, blockRanges } = body;
- if (textRuns == null && paragraphs == null && customRanges == null && customBlocks == null && customDecorations == null && tables == null && blockRanges == null) {
+ if (textRuns == null && paragraphs == null && customRanges == null && customBlocks == null && customDecorations == null && tables == null && columnGroups == null && blockRanges == null) {
return true;
}
diff --git a/packages/core/src/docs/data-model/types.ts b/packages/core/src/docs/data-model/types.ts
index 8836e2b3cd..847968a232 100644
--- a/packages/core/src/docs/data-model/types.ts
+++ b/packages/core/src/docs/data-model/types.ts
@@ -24,6 +24,8 @@ export enum DataStreamTreeNodeType {
TABLE = 'TABLE',
TABLE_ROW = 'TABLE_ROW',
TABLE_CELL = 'TABLE_CELL',
+ COLUMN_GROUP = 'COLUMN_GROUP',
+ COLUMN = 'COLUMN',
BLOCK = 'BLOCK',
CUSTOM_BLOCK = 'CUSTOM_BLOCK', // \b images, mentions, etc. that do not participate in document flow
}
@@ -38,6 +40,11 @@ export enum DataStreamTreeTokenType {
TABLE_CELL_END = '\x1D', // table cell end
TABLE_ROW_END = '\x0E', // table row end
TABLE_END = '\x0F', // table end
+ // column group.
+ COLUMN_GROUP_START = '\x12', // column group start
+ COLUMN_START = '\x13', // column start
+ COLUMN_END = '\x14', // column end
+ COLUMN_GROUP_END = '\x15', // column group end
// block.
BLOCK_START = '\x10', // block start
BLOCK_END = '\x11', // block end
diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.ts
index ea455f4092..16f1eb2c99 100644
--- a/packages/core/src/types/interfaces/i-document-data.ts
+++ b/packages/core/src/types/interfaces/i-document-data.ts
@@ -133,6 +133,8 @@ export interface IDocumentBody {
tables?: ICustomTable[]; // Table
+ columnGroups?: ICustomColumnGroup[]; // ColumnGroup
+
blockRanges?: IDocumentBlockRange[]; // Generic structured block range, e.g. callout, quote, code.
// tableOfContents?: { [index: number]: ITableOfContent }; // tableOfContents
@@ -951,6 +953,43 @@ export interface ICustomTable {
tableId: string;
}
+export interface ICustomColumnGroup {
+ startIndex: number;
+ endIndex: number;
+ // A unique ID associated with a column group.
+ columnGroupId: string;
+ columns?: IColumn[];
+ gap?: INumberUnit;
+ layout?: ColumnLayoutType;
+ responsive?: ColumnResponsiveType;
+ version?: number;
+}
+
+export enum ColumnLayoutType {
+ FIXED = 'fixed',
+ AUTO = 'auto',
+}
+
+export enum ColumnResponsiveType {
+ STACK = 'stack',
+ SHRINK = 'shrink',
+}
+
+export interface IColumnGroup {
+ columnGroupId: string;
+ columns: IColumn[];
+ gap: INumberUnit;
+ layout: ColumnLayoutType;
+ responsive: ColumnResponsiveType;
+ version?: number;
+}
+
+export interface IColumn {
+ columnId: string;
+ widthRatio: number;
+ minWidth?: INumberUnit;
+}
+
/**
* Properties of table
*/
diff --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.ts
index b6743e9bf8..b472b026de 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, ICommandService, IUniverInstanceService, NamedStyleType, UniverInstanceType } from '@univerjs/core';
+import { awaitTime, DataStreamTreeTokenType, 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';
@@ -49,6 +49,37 @@ function getDocumentData(): IDocumentData {
};
}
+function getDocumentDataWithColumnGroup(): IDocumentData {
+ const T = DataStreamTreeTokenType;
+ const columnGroupStream = `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_START}B${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}`;
+
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: `Before${T.PARAGRAPH}${columnGroupStream}${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ textRuns: [],
+ paragraphs: [
+ { paragraphId: 'before', startIndex: 6 },
+ { paragraphId: 'left', startIndex: 10 },
+ { paragraphId: 'right', startIndex: 14 },
+ { paragraphId: 'after', startIndex: 17 },
+ ],
+ sectionBreaks: [{ startIndex: 18 }],
+ columnGroups: [{ columnGroupId: 'cg-1', startIndex: 7, endIndex: 16 }],
+ },
+ 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'];
@@ -59,6 +90,30 @@ describe('break line command', () => {
return univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)?.getBody()?.paragraphs ?? [];
}
+ function getBody() {
+ const univerInstanceService = get(IUniverInstanceService);
+ return univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)?.getBody();
+ }
+
+ function setupWithColumnGroup() {
+ univer.dispose();
+ const testBed = createCommandTestBed(getDocumentDataWithColumnGroup());
+ 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;
@@ -89,4 +144,26 @@ describe('break line command', () => {
expect(getParagraphs()[1].paragraphStyle?.namedStyleType).toBeUndefined();
expect(getParagraphs()[1].paragraphStyle?.headingId).toBeUndefined();
});
+
+ it('keeps column groups when breaking a blank paragraph below a column group', async () => {
+ const selectionManager = setupWithColumnGroup();
+ selectionManager.__TEST_ONLY_add([{ startOffset: 17, endOffset: 17, collapsed: true, isActive: true, segmentId: '', style: null as never }]);
+
+ await commandService.executeCommand(BreakLineCommand.id);
+ await awaitTime(0);
+
+ expect(getBody()?.columnGroups).toEqual([{ columnGroupId: 'cg-1', startIndex: 7, endIndex: 16 }]);
+ expect(getBody()?.dataStream).toContain(DataStreamTreeTokenType.COLUMN_GROUP_END);
+ });
+
+ it('keeps column groups wrapped when breaking at the closing column boundary', async () => {
+ const selectionManager = setupWithColumnGroup();
+ selectionManager.__TEST_ONLY_add([{ startOffset: 16, endOffset: 16, collapsed: true, isActive: true, segmentId: '', style: null as never }]);
+
+ await commandService.executeCommand(BreakLineCommand.id);
+ await awaitTime(0);
+
+ expect(getBody()?.columnGroups).toEqual([{ columnGroupId: 'cg-1', startIndex: 7, endIndex: 17 }]);
+ expect(getBody()?.dataStream[17]).toBe(DataStreamTreeTokenType.COLUMN_GROUP_END);
+ });
});
diff --git a/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts
index b4d405ec70..0f5c0b9706 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts
@@ -34,6 +34,7 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import {
+ DocBlockMoveValidatorService,
DocSelectionManagerService,
DocSkeletonManagerService,
DocStateChangeManagerService,
@@ -41,6 +42,7 @@ import {
} from '@univerjs/docs';
import { DocumentViewModel, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { BehaviorSubject, takeUntil } from 'rxjs';
+import { DocHtmlExportService } from '../../../services/clipboard/udm-to-html/doc-html-export.service';
import { DocIMEInputManagerService } from '../../../services/doc-ime-input-manager.service';
import { DocMenuStyleService } from '../../../services/doc-menu-style.service';
import { DocSelectionRenderService } from '../../../services/selection/doc-selection-render.service';
@@ -117,11 +119,13 @@ export function createCommandTestBed(docData?: IDocumentData, dependencies?: Dep
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
injector.add([DocSelectionManagerService]);
+ injector.add([DocBlockMoveValidatorService]);
injector.add([DocMenuStyleService]);
injector.add([DocStateEmitService]);
injector.add([DocStateChangeManagerService]);
injector.add([DocIMEInputManagerService]);
injector.add([DocSelectionRenderService]);
+ injector.add([DocHtmlExportService]);
dependencies?.forEach((d) => injector.add(d));
}
diff --git a/packages/docs-ui/src/commands/commands/__tests__/doc-block-move.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/doc-block-move.command.spec.ts
index a8209a26c6..f5d30063aa 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
@@ -19,10 +19,11 @@ import {
awaitTime,
BlockType,
CustomRangeType,
+ DataStreamTreeTokenType,
DocumentBlockRangeType,
ICommandService,
} from '@univerjs/core';
-import { RichTextEditingMutation } from '@univerjs/docs';
+import { DocBlockMoveValidatorService, RichTextEditingMutation } from '@univerjs/docs';
import { afterEach, describe, expect, it } from 'vitest';
import { buildMoveDocBlockActions, MoveDocBlockCommand } from '../doc-block-move.command';
import { createCommandTestBed } from './create-command-test-bed';
@@ -177,6 +178,34 @@ describe('buildMoveDocBlockActions', () => {
expect(collectStarts(nextDocumentData.body?.customDecorations)).toEqual([0, 6]);
expect(collectTextRunStarts(nextDocumentData.body?.textRuns)).toEqual([0, 6]);
});
+
+ it('remaps column group ranges when moving content before a column group', () => {
+ const T = DataStreamTreeTokenType;
+ const columnGroupStream = `${T.COLUMN_GROUP_START}${T.COLUMN_START}B${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_START}C${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}`;
+ const documentData = createDocument(`A${T.PARAGRAPH}${columnGroupStream}Z${T.PARAGRAPH}${T.SECTION_BREAK}`, {
+ paragraphs: [
+ { 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 },
+ ],
+ sectionBreaks: [{ startIndex: 13 }],
+ columnGroups: [{ columnGroupId: 'column-group-1', startIndex: 2, endIndex: 12 }],
+ });
+
+ const { nextDocumentData } = buildMoveDocBlockActions({
+ documentData,
+ sourceRange: { startOffset: 0, endOffset: 2 },
+ targetOffset: 12,
+ });
+
+ expect(nextDocumentData.body?.dataStream).toBe(`${columnGroupStream}A${T.PARAGRAPH}Z${T.PARAGRAPH}${T.SECTION_BREAK}`);
+ expect(nextDocumentData.body?.columnGroups).toEqual([{
+ columnGroupId: 'column-group-1',
+ startIndex: 0,
+ endIndex: 10,
+ }]);
+ });
});
describe('MoveDocBlockCommand', () => {
@@ -207,6 +236,68 @@ describe('MoveDocBlockCommand', () => {
expect(testBed.doc.getSnapshot().body?.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([1, 3, 5]);
});
+ it('writes remapped column group ranges through the real rich text mutation flow', async () => {
+ const T = DataStreamTreeTokenType;
+ const columnGroupStream = `${T.COLUMN_GROUP_START}${T.COLUMN_START}B${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_START}C${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}`;
+ testBed = createCommandTestBed(createDocument(`A${T.PARAGRAPH}${columnGroupStream}Z${T.PARAGRAPH}${T.SECTION_BREAK}`, {
+ paragraphs: [
+ { paragraphId: 'para_docs_ui_fixture_36', startIndex: 1 },
+ { paragraphId: 'para_docs_ui_fixture_37', startIndex: 5 },
+ { paragraphId: 'para_docs_ui_fixture_38', startIndex: 9 },
+ { paragraphId: 'para_docs_ui_fixture_39', startIndex: 12 },
+ ],
+ sectionBreaks: [{ startIndex: 13 }],
+ columnGroups: [{ columnGroupId: 'column-group-1', startIndex: 2, endIndex: 12 }],
+ }));
+ const commandService = testBed.get(ICommandService);
+ commandService.registerCommand(MoveDocBlockCommand);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+
+ await expect(commandService.executeCommand(MoveDocBlockCommand.id, {
+ unitId: 'test-doc',
+ sourceRange: { startOffset: 0, endOffset: 2 },
+ targetOffset: 12,
+ })).resolves.toBe(true);
+
+ await awaitTime(0);
+ expect(testBed.doc.getSnapshot().body?.columnGroups).toEqual([{
+ columnGroupId: 'column-group-1',
+ startIndex: 0,
+ endIndex: 10,
+ }]);
+ });
+
+ it('applies registered block move transformers through the real rich text mutation flow', async () => {
+ testBed = createCommandTestBed(createDocument('A\rB\r\n', {
+ paragraphs: [{ paragraphId: 'para_docs_ui_fixture_40', startIndex: 1 }, { paragraphId: 'para_docs_ui_fixture_41', startIndex: 3 }],
+ sectionBreaks: [{ startIndex: 4 }],
+ }));
+ const commandService = testBed.get(ICommandService);
+ const moveValidatorService = testBed.get(DocBlockMoveValidatorService);
+ commandService.registerCommand(MoveDocBlockCommand);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+
+ moveValidatorService.registerTransformer((context) => ({
+ ...context.result,
+ nextDocumentData: {
+ ...context.result.nextDocumentData,
+ body: {
+ ...context.result.nextDocumentData.body!,
+ dataStream: `${context.result.nextDocumentData.body?.dataStream}!`,
+ },
+ },
+ }));
+
+ await expect(commandService.executeCommand(MoveDocBlockCommand.id, {
+ unitId: 'test-doc',
+ sourceRange: { startOffset: 0, endOffset: 2 },
+ targetOffset: 4,
+ })).resolves.toBe(true);
+
+ await awaitTime(0);
+ expect(testBed.doc.getSnapshot().body?.dataStream).toBe('B\rA\r\n!');
+ });
+
it('does not mutate when the target document is missing', async () => {
testBed = createCommandTestBed(createDocument('A\r\n', {
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_28', startIndex: 1 }],
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
index 99e0a76272..59f063b0da 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
@@ -502,6 +502,23 @@ describe('doc table create command helpers', () => {
expect(tableSource?.tableColumns.map((column) => column.size.width.v)).toEqual([90, 90, 90, 90]);
});
+ it('preserves the current table width when inserting a column into a narrow table', async () => {
+ const fixture = createTableFixture();
+ fixture.documentData.tableSource![TABLE_ID].tableColumns.forEach((column) => {
+ column.size.width.v = 80;
+ });
+ const testBed = createTableCommandBed(fixture);
+ const commandService = testBed.get(ICommandService);
+ setActiveTableRange(testBed, fixture.cellRanges[1].startIndex + 1);
+
+ const result = await commandService.executeCommand(DocTableInsertColumnRightCommand.id);
+ await awaitTime(0);
+
+ const tableSource = testBed.doc.getSnapshot().tableSource?.[TABLE_ID];
+ expect(result).toBe(true);
+ expect(tableSource?.tableColumns.map((column) => column.size.width.v)).toEqual([60, 60, 60, 60]);
+ });
+
it('executes below-row and left-column insertion aliases', async () => {
const rowFixture = createTableFixture();
const rowTestBed = createTableCommandBed(rowFixture);
diff --git a/packages/docs-ui/src/commands/commands/__tests__/replace-content.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/replace-content.command.spec.ts
index ff00f1a9e1..ae68956499 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
@@ -159,6 +159,18 @@ describe('replace or cover content of document', () => {
tableColumns: [],
},
};
+ const columnGroups = [{
+ startIndex: 0,
+ endIndex: 9,
+ columnGroupId: 'column_group_1',
+ columns: [
+ { columnId: 'column_1', widthRatio: 1 },
+ { columnId: 'column_2', widthRatio: 1 },
+ ],
+ gap: { v: 12 },
+ layout: 'fixed',
+ responsive: 'stack',
+ }];
const nextSnapshot = {
...getDocumentData(),
body: {
@@ -173,6 +185,7 @@ describe('replace or cover content of document', () => {
paragraphs: [{ paragraphId: 'para_replace_snapshot', startIndex: 8 }],
sectionBreaks: [{ startIndex: 9 }],
customBlocks: [],
+ columnGroups,
},
documentStyle: {
pageSize: {
@@ -215,6 +228,7 @@ describe('replace or cover content of document', () => {
expect(docsModel?.getBody()?.dataStream).toBe('Snapshot\r\n');
expect(docsModel?.getDocumentStyle().pageSize).toEqual({ width: 500, height: 700 });
expect(docsModel?.getSnapshot().tableSource).toEqual(tableSource);
+ expect(docsModel?.getBody()?.columnGroups).toEqual(columnGroups);
});
it('updates only the selection when the replacement snapshot body is unchanged', async () => {
diff --git a/packages/docs-ui/src/commands/commands/doc-block-move.command.ts b/packages/docs-ui/src/commands/commands/doc-block-move.command.ts
index 753a376c62..a66c34545a 100644
--- a/packages/docs-ui/src/commands/commands/doc-block-move.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-block-move.command.ts
@@ -18,7 +18,7 @@ import type { DocumentDataModel, ICommand, IDocumentBody, IDocumentData, JSONXAc
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import { CommandType, ICommandService, IUniverInstanceService, JSONX, Tools, UniverInstanceType } from '@univerjs/core';
-import { RichTextEditingMutation } from '@univerjs/docs';
+import { DocBlockMoveValidatorService, RichTextEditingMutation } from '@univerjs/docs';
export interface IMoveDocBlockCommandParams {
unitId?: string;
@@ -56,11 +56,18 @@ export const MoveDocBlockCommand: ICommand<IMoveDocBlockCommandParams> = {
}
const previousDocumentData = doc.getSnapshot();
- const { nextDocumentData, movedRange } = buildMoveDocBlockActions({
+ const moveResult = buildMoveDocBlockActions({
documentData: previousDocumentData,
sourceRange: params.sourceRange,
targetOffset: params.targetOffset,
});
+ const { nextDocumentData, movedRange } = accessor.get(DocBlockMoveValidatorService).transformMoveResult({
+ unitId: doc.getUnitId(),
+ sourceRange: params.sourceRange,
+ targetOffset: params.targetOffset,
+ previousDocumentData,
+ result: moveResult,
+ });
const actions = buildReplaceDocumentBodyActions(previousDocumentData, nextDocumentData);
if (!actions) {
@@ -145,6 +152,7 @@ function buildReplaceDocumentBodyActions(previousDocumentData: IDocumentData, ne
jsonX.replaceOp(['body', 'paragraphs'], previousBody.paragraphs, nextBody.paragraphs),
jsonX.replaceOp(['body', 'sectionBreaks'], previousBody.sectionBreaks, nextBody.sectionBreaks),
jsonX.replaceOp(['body', 'tables'], previousBody.tables, nextBody.tables),
+ jsonX.replaceOp(['body', 'columnGroups'], previousBody.columnGroups, nextBody.columnGroups),
jsonX.replaceOp(['body', 'customBlocks'], previousBody.customBlocks, nextBody.customBlocks),
jsonX.replaceOp(['body', 'blockRanges'], previousBody.blockRanges, nextBody.blockRanges),
jsonX.replaceOp(['body', 'customRanges'], previousBody.customRanges, nextBody.customRanges),
@@ -181,6 +189,9 @@ function remapBodyIndexesAfterMove(
body.tables = body.tables?.map((table) => remapExclusiveRange(table, startOffset, endOffset, targetOffset, insertOffset, moveLength))
.sort((left, right) => left.startIndex - right.startIndex);
+ body.columnGroups = body.columnGroups?.map((columnGroup) => remapExclusiveRange(columnGroup, startOffset, endOffset, targetOffset, insertOffset, moveLength))
+ .sort((left, right) => left.startIndex - right.startIndex);
+
body.blockRanges = body.blockRanges?.map((blockRange) => remapInclusiveRange(blockRange, startOffset, endOffset, targetOffset, insertOffset, moveLength))
.sort((left, right) => left.startIndex - right.startIndex);
@@ -219,7 +230,7 @@ function remapExclusiveRange<T extends { startIndex: number; endIndex: number }>
return {
...range,
startIndex: remapIndexAfterMove(range.startIndex, startOffset, endOffset, targetOffset, insertOffset, moveLength),
- endIndex: remapIndexAfterMove(range.endIndex, startOffset, endOffset, targetOffset, insertOffset, moveLength),
+ endIndex: remapExclusiveEndIndexAfterMove(range.endIndex, startOffset, endOffset, targetOffset, insertOffset, moveLength),
};
}
@@ -262,6 +273,18 @@ function remapIndexAfterMove(index: number, startOffset: number, endOffset: numb
return index;
}
+function remapExclusiveEndIndexAfterMove(index: number, startOffset: number, endOffset: number, targetOffset: number, insertOffset: number, moveLength: number): number {
+ if (index > startOffset && index <= endOffset) {
+ return insertOffset + index - startOffset;
+ }
+
+ if (targetOffset > endOffset && index >= endOffset && index <= targetOffset) {
+ return index - moveLength;
+ }
+
+ return remapIndexAfterMove(index, startOffset, endOffset, targetOffset, insertOffset, moveLength);
+}
+
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
diff --git a/packages/docs-ui/src/commands/commands/table/doc-table-insert.command.ts b/packages/docs-ui/src/commands/commands/table/doc-table-insert.command.ts
index 23d0e7ed41..a1935a7bb4 100644
--- a/packages/docs-ui/src/commands/commands/table/doc-table-insert.command.ts
+++ b/packages/docs-ui/src/commands/commands/table/doc-table-insert.command.ts
@@ -316,15 +316,16 @@ export const DocTableInsertColumnCommand: ICommand<IDocTableInsertColumnCommandP
const { marginLeft = 0, marginRight = 0 } = documentStyle;
- const pageWidth = (documentStyle.pageSize?.width ?? 800) - marginLeft - marginRight;
-
const tableColumns = snapshot?.tableSource?.[tableId]?.tableColumns;
if (!tableColumns) {
return false;
}
- const { newColWidth, widths } = getColumnWidths(pageWidth, tableColumns, columnIndex);
+ const pageWidth = (documentStyle.pageSize?.width ?? 800) - marginLeft - marginRight;
+ const tableWidth = tableColumns.reduce((sum, column) => sum + column.size.width.v, 0);
+ const targetWidth = tableWidth > 0 ? tableWidth : pageWidth;
+ const { newColWidth, widths } = getColumnWidths(targetWidth, tableColumns, columnIndex);
// Update pre columns width.
for (let i = 0; i < widths.length; i++) {
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.ts
index c24304cc44..19051e6249 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
@@ -117,6 +117,38 @@ describe('DocMoveCursorController movement helpers', () => {
expect(skeleton.findPositionByGlyph).toHaveBeenCalledWith(lastTextGlyph, -1);
});
+ it('uses a paragraph glyph as the vertical cursor target for empty paragraph lines', () => {
+ const controller = createControllerHarness();
+ const paragraphGlyph = {
+ count: 1,
+ content: DataStreamTreeTokenType.PARAGRAPH,
+ left: 0,
+ streamType: DataStreamTreeTokenType.PARAGRAPH,
+ };
+ const line = { divides: [] as unknown[] };
+ const divide = { left: 0, glyphGroup: [paragraphGlyph], parent: line };
+ line.divides = [divide];
+ Object.assign(paragraphGlyph, { parent: divide });
+
+ const skeleton = {
+ findPositionByGlyph: vi.fn(() => ({ glyph: 0 })),
+ };
+
+ expect(controller._matchPositionByLeftOffset(skeleton, line, 0, { segmentPage: -1 })).toEqual({ glyph: 0 });
+ expect(skeleton.findPositionByGlyph).toHaveBeenCalledWith(paragraphGlyph, -1);
+ });
+
+ it('keeps column boundary tokens out of the default cursor skip list', () => {
+ const controller = createControllerHarness();
+
+ const skipTokens = controller._getCursorSkipTokens();
+
+ expect(skipTokens).not.toContain(DataStreamTreeTokenType.COLUMN_GROUP_START);
+ expect(skipTokens).not.toContain(DataStreamTreeTokenType.COLUMN_START);
+ expect(skipTokens).not.toContain(DataStreamTreeTokenType.COLUMN_END);
+ expect(skipTokens).not.toContain(DataStreamTreeTokenType.COLUMN_GROUP_END);
+ });
+
it('resolves document start and end offsets', () => {
const controller = createControllerHarness();
diff --git a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
index 969f65c2af..cf0279dd29 100644
--- a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
@@ -679,12 +679,28 @@ export class DocMoveCursorController extends Disposable {
} = {
distance: Number.POSITIVE_INFINITY,
};
+ const nearestEmptyParagraphNode: {
+ glyph?: IDocumentSkeletonGlyph;
+ distance: number;
+ } = {
+ distance: Number.POSITIVE_INFINITY,
+ };
for (const divide of line.divides) {
const divideLeft = divide.left;
for (const glyph of divide.glyphGroup) {
if (!this._isCursorAddressableGlyph(glyph)) {
+ if (glyph.streamType === DataStreamTreeTokenType.PARAGRAPH && glyph.count > 0) {
+ const { left } = glyph;
+ const leftSide = divideLeft + left;
+ const distance = Math.abs(offsetLeft - leftSide);
+
+ if (distance < nearestEmptyParagraphNode.distance) {
+ nearestEmptyParagraphNode.glyph = glyph;
+ nearestEmptyParagraphNode.distance = distance;
+ }
+ }
continue;
}
const { left } = glyph;
@@ -699,13 +715,15 @@ export class DocMoveCursorController extends Disposable {
}
}
- if (nearestNode.glyph == null) {
+ const nearestGlyph = nearestNode.glyph ?? nearestEmptyParagraphNode.glyph;
+
+ if (nearestGlyph == null) {
return;
}
const { segmentPage } = nodePosition;
- return docSkeleton.findPositionByGlyph(nearestNode.glyph, segmentPage);
+ return docSkeleton.findPositionByGlyph(nearestGlyph, segmentPage);
}
// eslint-disable-next-line max-lines-per-function, complexity
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index 79bd125fd8..a0eb4b8620 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -181,6 +181,8 @@ export { UniverDocsUIPlugin } from './plugin';
export * from './services';
export { IDocClipboardService } from './services/clipboard/clipboard.service';
export { convertBodyToHtml } from './services/clipboard/udm-to-html/convertor';
+export { DocHtmlExportService } from './services/clipboard/udm-to-html/doc-html-export.service';
+export type { DocHtmlExportTransformer } from './services/clipboard/udm-to-html/doc-html-export.service';
export { DocAutoFormatService } from './services/doc-auto-format.service';
export {
DocEventManagerService,
diff --git a/packages/docs-ui/src/menu/paragraph-menu.ts b/packages/docs-ui/src/menu/paragraph-menu.ts
index ef627280da..6b74441c8a 100644
--- a/packages/docs-ui/src/menu/paragraph-menu.ts
+++ b/packages/docs-ui/src/menu/paragraph-menu.ts
@@ -515,7 +515,7 @@ export function ParagraphMenuInsertBelowHeadingH1MenuItemFactory(accessor: IAcce
icon: 'H1Icon',
title: 'docs-ui.toolbar.heading.leading1',
tooltip: 'docs-ui.toolbar.heading.leading1',
- params: { commandId: H1HeadingCommand.id, paragraphMenuPlacement: 'below', paragraphMenuInsertMode: 'breakline' },
+ params: { commandId: H1HeadingCommand.id, paragraphMenuInsertMode: 'breakline' },
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
}
@@ -528,7 +528,7 @@ export function ParagraphMenuInsertBelowHeadingH2MenuItemFactory(accessor: IAcce
icon: 'H2Icon',
title: 'docs-ui.toolbar.heading.leading2',
tooltip: 'docs-ui.toolbar.heading.leading2',
- params: { commandId: H2HeadingCommand.id, paragraphMenuPlacement: 'below', paragraphMenuInsertMode: 'breakline' },
+ params: { commandId: H2HeadingCommand.id, paragraphMenuInsertMode: 'breakline' },
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
}
@@ -541,7 +541,7 @@ export function ParagraphMenuInsertBelowHeadingH3MenuItemFactory(accessor: IAcce
icon: 'H3Icon',
title: 'docs-ui.toolbar.heading.leading3',
tooltip: 'docs-ui.toolbar.heading.leading3',
- params: { commandId: H3HeadingCommand.id, paragraphMenuPlacement: 'below', paragraphMenuInsertMode: 'breakline' },
+ params: { commandId: H3HeadingCommand.id, paragraphMenuInsertMode: 'breakline' },
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
}
@@ -554,7 +554,7 @@ export function ParagraphMenuInsertBelowHeadingH4MenuItemFactory(accessor: IAcce
icon: 'H4Icon',
title: 'docs-ui.toolbar.heading.leading4',
tooltip: 'docs-ui.toolbar.heading.leading4',
- params: { commandId: H4HeadingCommand.id, paragraphMenuPlacement: 'below', paragraphMenuInsertMode: 'breakline' },
+ params: { commandId: H4HeadingCommand.id, paragraphMenuInsertMode: 'breakline' },
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
}
@@ -567,7 +567,7 @@ export function ParagraphMenuInsertBelowHeadingH5MenuItemFactory(accessor: IAcce
icon: 'H5Icon',
title: 'docs-ui.toolbar.heading.leading5',
tooltip: 'docs-ui.toolbar.heading.leading5',
- params: { commandId: H5HeadingCommand.id, paragraphMenuPlacement: 'below', paragraphMenuInsertMode: 'breakline' },
+ params: { commandId: H5HeadingCommand.id, paragraphMenuInsertMode: 'breakline' },
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
}
@@ -580,7 +580,7 @@ export function ParagraphMenuInsertBelowTableMenuItemFactory(accessor: IAccessor
icon: 'GridIcon',
title: 'docs-ui.toolbar.table.insert',
tooltip: 'docs-ui.toolbar.table.insert',
- params: { rowCount: 3, colCount: 5, paragraphMenuPlacement: 'below' },
+ params: { rowCount: 3, colCount: 5 },
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
}
diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.ts
index 447380c7cf..1c510e724d 100644
--- a/packages/docs-ui/src/plugin.ts
+++ b/packages/docs-ui/src/plugin.ts
@@ -117,6 +117,7 @@ import { DocRenderController } from './controllers/render-controllers/doc.render
import { DocZoomRenderController } from './controllers/render-controllers/zoom.render-controller';
import { DocUIController } from './controllers/ui.controller';
import { DocClipboardService, IDocClipboardService } from './services/clipboard/clipboard.service';
+import { DocHtmlExportService } from './services/clipboard/udm-to-html/doc-html-export.service';
import { DocAutoFormatService } from './services/doc-auto-format.service';
import { DocEventManagerService } from './services/doc-event-manager.service';
import { DocIMEInputManagerService } from './services/doc-ime-input-manager.service';
@@ -364,6 +365,7 @@ export class UniverDocsUIPlugin extends Plugin {
[DocParagraphSettingController],
[IEditorService, { useClass: EditorService }],
[IDocClipboardService, { useClass: DocClipboardService }],
+ [DocHtmlExportService],
[DocCanvasPopManagerService],
[DocsRenderService],
[IDocStateChangeInterceptorService, { useClass: DocIMEStateChangeInterceptorService }],
diff --git a/packages/docs-ui/src/services/__tests__/doc-event-manager.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-event-manager.service.spec.ts
index adad287135..bfa2b0d2f7 100644
--- a/packages/docs-ui/src/services/__tests__/doc-event-manager.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-event-manager.service.spec.ts
@@ -16,8 +16,8 @@
import { EventState, EventSubject, Injector, PresetListType } from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
-import { TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';
-import { describe, expect, it } from 'vitest';
+import { setDocsTableRenderViewportProvider, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';
+import { afterEach, describe, expect, it } from 'vitest';
import {
DocEventManagerService,
getListMarkerFallbackBound,
@@ -58,6 +58,16 @@ class TestDocSkeletonManagerService {
paddingTop: 3,
contentHeight: 10,
divides: [],
+ }, {
+ paragraphStart: true,
+ paragraphIndex: 60,
+ st: 40,
+ top: 140,
+ lineHeight: 72,
+ marginTop: 0,
+ paddingTop: 0,
+ contentHeight: 72,
+ divides: [],
}],
}],
}],
@@ -101,6 +111,122 @@ class TestDocSkeletonManagerService {
}],
},
]]),
+ skeColumnGroups: new Map([[
+ 'column-group-1',
+ {
+ columnGroupId: 'column-group-1',
+ left: 20,
+ top: 140,
+ width: 200,
+ height: 72,
+ columns: [{
+ columnId: 'column-1',
+ left: 0,
+ top: 0,
+ width: 94,
+ height: 72,
+ page: {
+ pageWidth: 94,
+ pageHeight: 72,
+ marginLeft: 0,
+ marginRight: 0,
+ marginTop: 0,
+ marginBottom: 0,
+ sections: [{
+ top: 0,
+ colCount: 1,
+ columns: [{
+ left: 0,
+ lines: [{
+ paragraphStart: true,
+ paragraphIndex: 44,
+ st: 40,
+ top: 4,
+ lineHeight: 16,
+ marginTop: 1,
+ paddingTop: 1,
+ contentHeight: 8,
+ divides: [],
+ }],
+ }],
+ }],
+ },
+ }, {
+ columnId: 'column-2',
+ left: 106,
+ top: 0,
+ width: 94,
+ height: 72,
+ page: {
+ pageWidth: 94,
+ pageHeight: 72,
+ marginLeft: 0,
+ marginRight: 0,
+ marginTop: 0,
+ marginBottom: 0,
+ sections: [{
+ top: 0,
+ colCount: 1,
+ columns: [{
+ left: 0,
+ lines: [{
+ paragraphStart: true,
+ paragraphIndex: 52,
+ st: 48,
+ top: 4,
+ lineHeight: 16,
+ marginTop: 1,
+ paddingTop: 1,
+ contentHeight: 8,
+ divides: [],
+ }],
+ }],
+ }],
+ skeTables: new Map([[
+ 'table-in-column',
+ {
+ tableId: 'table-in-column',
+ left: 4,
+ top: 20,
+ width: 80,
+ height: 30,
+ rows: [{
+ index: 0,
+ top: 0,
+ cells: [{
+ left: 0,
+ marginTop: 2,
+ marginLeft: 0,
+ marginRight: 0,
+ marginBottom: 2,
+ pageWidth: 80,
+ pageHeight: 30,
+ sections: [{
+ top: 0,
+ colCount: 1,
+ columns: [{
+ left: 0,
+ lines: [{
+ paragraphStart: true,
+ paragraphIndex: 70,
+ st: 70,
+ top: 4,
+ lineHeight: 16,
+ marginTop: 1,
+ paddingTop: 1,
+ contentHeight: 8,
+ divides: [],
+ }],
+ }],
+ }],
+ }],
+ }],
+ },
+ ]]),
+ },
+ }],
+ },
+ ]]),
}],
skeHeaders: new Map(),
skeFooters: new Map(),
@@ -134,6 +260,12 @@ function createDocEventManagerService() {
},
}, {
startIndex: 30,
+ }, {
+ startIndex: 44,
+ }, {
+ startIndex: 52,
+ }, {
+ startIndex: 70,
}],
customRanges: [],
};
@@ -177,6 +309,10 @@ function createDocEventManagerService() {
}
describe('DocEventManagerService list marker helpers', () => {
+ afterEach(() => {
+ setDocsTableRenderViewportProvider(null);
+ });
+
it('detects list marker fallback hits without treating body text as marker', () => {
const paragraph = {
startIndex: 12,
@@ -289,6 +425,74 @@ describe('DocEventManagerService list marker helpers', () => {
service.dispose();
});
+ it('finds paragraph bounds inside column group columns for paragraph menus', () => {
+ const { service } = createDocEventManagerService();
+
+ expect(service.paragraphBounds.get(44)?.rect).toEqual({
+ bottom: 222,
+ left: 20,
+ right: 114,
+ top: 154,
+ });
+ expect(service.paragraphBounds.get(52)?.rect).toEqual({
+ bottom: 222,
+ left: 126,
+ right: 220,
+ top: 154,
+ });
+ expect(service.findParagraphBoundByIndex(44)?.startIndex).toBe(44);
+ expect(service.findParagraphBoundsInRange(44, 44)[0].startIndex).toBe(44);
+
+ service.dispose();
+ });
+
+ it('finds table cell and paragraph bounds inside column group tables', () => {
+ const { service } = createDocEventManagerService();
+
+ expect(service.tableBounds.get('table-in-column')?.rect).toEqual({
+ bottom: 200,
+ left: 130,
+ right: 210,
+ top: 170,
+ });
+ expect(service.findTableCellBound('table-in-column', 0, 0)?.rect).toEqual({
+ bottom: 198,
+ left: 130,
+ right: 210,
+ top: 172,
+ });
+ expect(service.findParagraphBoundByIndex(70)?.rect).toEqual({
+ bottom: 192,
+ left: 130,
+ right: 210,
+ top: 176,
+ });
+
+ service.dispose();
+ });
+
+ it('rebuilds column nested table bounds when its horizontal viewport changes', () => {
+ const { service } = createDocEventManagerService();
+
+ expect(service.tableBounds.get('table-in-column')?.rect.right).toBe(210);
+
+ setDocsTableRenderViewportProvider((unitId, tableId) => {
+ if (unitId !== 'doc-event' || tableId !== 'table-in-column') {
+ return null;
+ }
+
+ return {
+ contentWidth: 160,
+ scrollLeft: 0,
+ viewportWidth: 40,
+ };
+ });
+
+ expect(service.tableBounds.get('table-in-column')?.rect.right).toBe(170);
+
+ service.dispose();
+ });
+
it('recalculates paragraph bounds after document layout invalidation events', () => {
const { context, service, skeletonManager } = createDocEventManagerService();
@@ -449,6 +653,55 @@ describe('DocEventManagerService list marker helpers', () => {
service.dispose();
});
+ it('publishes paragraph hover state from pointer movement inside a column group', async () => {
+ const { context, service } = createDocEventManagerService();
+ const hoveredParagraphs: Array<number | null> = [];
+ const hoveredLeftParagraphs: Array<number | null> = [];
+
+ const paragraphSub = service.hoverParagraphRealTime$.subscribe((bound) => {
+ hoveredParagraphs.push(bound?.startIndex ?? null);
+ });
+ const paragraphLeftSub = service.hoverParagraphLeftRealTime$.subscribe((bound) => {
+ hoveredLeftParagraphs.push(bound?.startIndex ?? null);
+ });
+
+ context.scene.onPointerMove$.emitEvent({
+ buttons: 0,
+ offsetX: 50,
+ offsetY: 160,
+ });
+
+ expect(service.paragraphBounds.get(60)?.rect).toEqual({
+ bottom: 222,
+ left: 20,
+ right: 260,
+ top: 150,
+ });
+ expect(hoveredParagraphs.at(-1)).toBe(44);
+
+ await new Promise((resolve) => setTimeout(resolve, 35));
+ context.scene.onPointerMove$.emitEvent({
+ buttons: 0,
+ offsetX: 50,
+ offsetY: 210,
+ });
+
+ expect(hoveredParagraphs.at(-1)).toBe(44);
+
+ await new Promise((resolve) => setTimeout(resolve, 35));
+ context.scene.onPointerMove$.emitEvent({
+ buttons: 0,
+ offsetX: 10,
+ offsetY: 210,
+ });
+
+ expect(hoveredLeftParagraphs.at(-1)).toBe(44);
+
+ paragraphSub.unsubscribe();
+ paragraphLeftSub.unsubscribe();
+ service.dispose();
+ });
+
it('clears hover state while dragging across the document', async () => {
const { context, service } = createDocEventManagerService();
const hoveredParagraphs: Array<number | null> = [];
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.ts
index 4251c32880..efc5f159e4 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
@@ -44,6 +44,29 @@ describe('DocParagraphMenuService', () => {
expect(attachPopupToRect).toHaveBeenCalledTimes(1);
});
+ it('treats empty column paragraphs as empty paragraph menu targets', () => {
+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));
+ const T = DataStreamTreeTokenType;
+ const service = createService({
+ attachPopupToRect,
+ dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 2 }],
+ });
+
+ service.showParagraphMenu(createParagraphBound({
+ paragraphStart: 2,
+ paragraphEnd: 2,
+ startIndex: 2,
+ }));
+
+ expect(attachPopupToRect).toHaveBeenCalledTimes(1);
+ expect(service.activeTarget).toMatchObject({
+ kind: 'paragraph',
+ key: 'paragraph:2',
+ emptyMode: true,
+ });
+ });
+
it('keeps hiding the paragraph menu for image-only paragraphs', () => {
const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));
const service = createService({
diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
index d2bc4b229e..ca980fb37f 100644
--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
@@ -68,6 +68,7 @@ import {
wrapClipboardHtml,
} from './internal-fragment';
import { UDMToHtmlService } from './udm-to-html/convertor';
+import { DocHtmlExportService } from './udm-to-html/doc-html-export.service';
HtmlToUDMService.use(LarkPastePlugin);
HtmlToUDMService.use(UniverPastePlugin);
@@ -145,16 +146,18 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
private _clipboardHooks: IDocClipboardHook[] = [];
private _htmlToUDM = new HtmlToUDMService();
- private _umdToHtml = new UDMToHtmlService();
+ private readonly _umdToHtml: UDMToHtmlService;
constructor(
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@ILogService private readonly _logService: ILogService,
@ICommandService private readonly _commandService: ICommandService,
@IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService,
+ @Inject(DocHtmlExportService) docHtmlExportService: DocHtmlExportService,
@Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService
) {
super();
+ this._umdToHtml = new UDMToHtmlService(docHtmlExportService);
}
async copy(sliceType: SliceBodyType = SliceBodyType.copy, ranges?: ITextRangeWithStyle[]): Promise<boolean> {
diff --git a/packages/docs-ui/src/services/clipboard/udm-to-html/__tests__/convertor.spec.ts b/packages/docs-ui/src/services/clipboard/udm-to-html/__tests__/convertor.spec.ts
index 3f5c81d44f..250117c832 100644
--- a/packages/docs-ui/src/services/clipboard/udm-to-html/__tests__/convertor.spec.ts
+++ b/packages/docs-ui/src/services/clipboard/udm-to-html/__tests__/convertor.spec.ts
@@ -88,6 +88,32 @@ describe('test case in html and udm convert', () => {
expect(html).toBe('<p class="UniverNormal" >=SUM(<span style="font-family: Arial; color: #9e6de3;">F15:G18</span>)</p>');
});
+ it('applies registered export transformers before converting UDM to HTML', () => {
+ const convertor = new UDMToHtmlService({
+ transformDocumentForHtmlExport: (doc) => ({
+ ...doc,
+ body: {
+ dataStream: 'Exported\r\n',
+ paragraphs: [{ paragraphId: 'para_docs_ui_fixture_73', startIndex: 'Exported'.length }],
+ sectionBreaks: [{ startIndex: 'Exported\r\n'.length - 1 }],
+ },
+ }),
+ });
+
+ const html = convertor.convert([{
+ id: '',
+ documentStyle: {},
+ body: {
+ dataStream: 'Original\r\n',
+ paragraphs: [{ paragraphId: 'para_docs_ui_fixture_74', startIndex: 'Original'.length }],
+ sectionBreaks: [{ startIndex: 'Original\r\n'.length - 1 }],
+ },
+ }]);
+
+ expect(html).toContain('Exported');
+ expect(html).not.toContain('Original');
+ });
+
it('Should convert textRun to Html', () => {
const documentBody = getTestBody();
const expectedHtml = '<span style="font-family: Microsoft YaHei; color: #000000; font-size: 24pt;"><strong>塘月</strong></span>';
diff --git a/packages/docs-ui/src/services/clipboard/udm-to-html/__tests__/doc-html-export.service.spec.ts b/packages/docs-ui/src/services/clipboard/udm-to-html/__tests__/doc-html-export.service.spec.ts
new file mode 100644
index 0000000000..368723d55e
--- /dev/null
+++ b/packages/docs-ui/src/services/clipboard/udm-to-html/__tests__/doc-html-export.service.spec.ts
@@ -0,0 +1,38 @@
+/**
+ * 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 { DocHtmlExportService } from '../doc-html-export.service';
+
+describe('DocHtmlExportService', () => {
+ it('applies registered document transformers in order and disposes them', () => {
+ const service = new DocHtmlExportService();
+ const first = service.registerTransformer((doc) => ({
+ ...doc,
+ id: `${doc.id}-first`,
+ }));
+ service.registerTransformer((doc) => ({
+ ...doc,
+ id: `${doc.id}-second`,
+ }));
+
+ expect(service.transformDocumentForHtmlExport({ id: 'doc', documentStyle: {} }).id).toBe('doc-first-second');
+
+ first.dispose();
+
+ expect(service.transformDocumentForHtmlExport({ id: 'doc', documentStyle: {} }).id).toBe('doc-second');
+ });
+});
diff --git a/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts b/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts
index 17755a0ff2..e6310c34ed 100644
--- a/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts
+++ b/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts
@@ -17,6 +17,7 @@
import type { IDocumentBody, IDocumentData, IParagraph, ITable, ITableCell, ITextRun, ITextStyle } from '@univerjs/core';
import type { IDocImage } from '@univerjs/docs-drawing';
import type { DataStreamTreeNode } from '@univerjs/engine-render';
+import type { DocHtmlExportService } from './doc-html-export.service';
import {
BaselineOffset,
BooleanNumber,
@@ -710,6 +711,11 @@ function hasVisibleHtml(html: string): boolean {
}
export class UDMToHtmlService {
+ constructor(
+ private readonly _docHtmlExportService?: Pick<DocHtmlExportService, 'transformDocumentForHtmlExport'>
+ ) {
+ }
+
convert(docList: IDocumentData[]): string {
if (docList.length === 0) {
throw new Error('The bodyList length at least to be 1');
@@ -718,7 +724,7 @@ export class UDMToHtmlService {
let html = '';
for (const doc of Tools.deepClone(docList)) {
- html += convertBodyToHtml(doc);
+ html += convertBodyToHtml(this._docHtmlExportService?.transformDocumentForHtmlExport(doc) ?? doc);
}
return html;
diff --git a/packages/docs-ui/src/services/clipboard/udm-to-html/doc-html-export.service.ts b/packages/docs-ui/src/services/clipboard/udm-to-html/doc-html-export.service.ts
new file mode 100644
index 0000000000..8a49fe14a7
--- /dev/null
+++ b/packages/docs-ui/src/services/clipboard/udm-to-html/doc-html-export.service.ts
@@ -0,0 +1,34 @@
+/**
+ * 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 { IDisposable, IDocumentData } from '@univerjs/core';
+import { Disposable, remove, toDisposable } from '@univerjs/core';
+
+export type DocHtmlExportTransformer = (documentData: IDocumentData) => IDocumentData;
+
+export class DocHtmlExportService extends Disposable {
+ private readonly _transformers: DocHtmlExportTransformer[] = [];
+
+ registerTransformer(transformer: DocHtmlExportTransformer): IDisposable {
+ this._transformers.push(transformer);
+
+ return this.disposeWithMe(toDisposable(() => remove(this._transformers, transformer)));
+ }
+
+ transformDocumentForHtmlExport(documentData: IDocumentData): IDocumentData {
+ return this._transformers.reduce((doc, transformer) => transformer(doc), documentData);
+ }
+}
diff --git a/packages/docs-ui/src/services/doc-event-manager.service.ts b/packages/docs-ui/src/services/doc-event-manager.service.ts
index d79a4446fa..e4ac30f642 100644
--- a/packages/docs-ui/src/services/doc-event-manager.service.ts
+++ b/packages/docs-ui/src/services/doc-event-manager.service.ts
@@ -21,6 +21,7 @@ import type {
IBoundRectNoAngle,
IDocsTableRenderViewport,
IDocumentSkeletonGlyph,
+ IDocumentSkeletonLineContext,
IDocumentSkeletonPage,
IDocumentSkeletonSection,
IRenderContext,
@@ -28,7 +29,7 @@ import type {
} from '@univerjs/engine-render';
import { Disposable, fromEventSubject, Inject, PresetListType } from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
-import { CURSOR_TYPE, getDocsTableRenderViewport, getTableIdAndSliceIndex, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';
+import { CURSOR_TYPE, documentSkeletonLineIterator, documentSkeletonTableIterator, getDocsTableRenderViewport, getTableIdAndSliceIndex, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';
import { BehaviorSubject, distinctUntilChanged, filter, map, Subject, switchMap, take, throttleTime } from 'rxjs';
import { DOC_VERTICAL_PADDING } from '../types/const/padding';
import { transformOffset2Bound } from './doc-popup-manager.service';
@@ -134,6 +135,68 @@ const calcDocParagraphPositions = (sections: IDocumentSkeletonSection[], top: nu
return paragraphBounds;
};
+const calcParagraphPositionsFromLineContexts = (
+ contexts: IDocumentSkeletonLineContext[],
+ docsLeft: number,
+ docsTop: number
+): ICustomRangeBoundBase[] => {
+ const paragraphBounds: ICustomRangeBoundBase[] = [];
+ const currentParagraphs = new Map<string, ICustomRangeBoundBase>();
+
+ for (const context of contexts) {
+ const { column, line, lineWidth, pageLeft, sectionTop } = context;
+ const startIndex = line.paragraphIndex;
+ const columnLeft = pageLeft + column.left + docsLeft;
+ const lineTop = sectionTop + line.top + docsTop;
+ const lineBottom = getParagraphLineBottom(context, lineTop);
+ const key = `${context.source}:${context.pageIndex}:${pageLeft}:${column.left}:${startIndex}`;
+
+ if (line.paragraphStart) {
+ const currentParagraph = currentParagraphs.get(key);
+ if (currentParagraph) {
+ paragraphBounds.push(currentParagraph);
+ }
+
+ currentParagraphs.set(key, {
+ paragraphStart: line.st,
+ paragraphEnd: startIndex,
+ startIndex,
+ rect: {
+ top: lineTop,
+ left: columnLeft,
+ right: columnLeft + lineWidth,
+ bottom: lineBottom,
+ },
+ fisrtLine: {
+ top: lineTop + line.marginTop + line.paddingTop,
+ left: columnLeft,
+ right: columnLeft + lineWidth,
+ bottom: lineTop + line.marginTop + line.paddingTop + line.contentHeight,
+ },
+ });
+ } else {
+ const currentParagraph = currentParagraphs.get(key);
+ if (currentParagraph) {
+ currentParagraph.rect.bottom = lineBottom;
+ }
+ }
+ }
+
+ paragraphBounds.push(...currentParagraphs.values());
+
+ return paragraphBounds;
+};
+
+function getParagraphLineBottom(context: IDocumentSkeletonLineContext, lineTop: number): number {
+ const lineBottom = lineTop + context.line.lineHeight;
+ if (context.source !== 'column' || context.line !== context.column.lines.at(-1) || !Number.isFinite(context.page.pageHeight)) {
+ return lineBottom;
+ }
+
+ const pageTop = lineTop - context.line.top - context.section.top;
+ return Math.max(lineBottom, pageTop + context.page.pageHeight);
+}
+
export const calcDocGlyphPosition = (glyph: IDocumentSkeletonGlyph, documents: Documents, skeleton: DocumentSkeleton, pageIndex = -1): IBoundRectNoAngle | undefined => {
const start = skeleton.findPositionByGlyph(glyph, pageIndex);
if (!start) {
@@ -270,6 +333,36 @@ function isPointInRect(x: number, y: number, rect: IBoundRectNoAngle) {
return false;
}
+function getRectArea(rect: IBoundRectNoAngle) {
+ return Math.max(0, rect.right - rect.left) * Math.max(0, rect.bottom - rect.top);
+}
+
+function isRectContainingRect(outer: IBoundRectNoAngle, inner: IBoundRectNoAngle) {
+ return outer.left <= inner.left &&
+ outer.right >= inner.right &&
+ outer.top <= inner.top &&
+ outer.bottom >= inner.bottom;
+}
+
+function getParagraphTextRangeLength(bound: Pick<IMutiPageParagraphBound, 'paragraphEnd' | 'paragraphStart'>) {
+ return Math.max(0, bound.paragraphEnd - bound.paragraphStart);
+}
+
+function getMostSpecificParagraphBound(bounds: IMutiPageParagraphBound[]) {
+ return bounds.sort((left, right) =>
+ getRectArea(left.rect) - getRectArea(right.rect) ||
+ getParagraphTextRangeLength(left) - getParagraphTextRangeLength(right)
+ )[0];
+}
+
+function removeContainerParagraphBounds<T extends Pick<IMutiPageParagraphBound, 'rect'>>(bounds: T[]) {
+ return bounds.filter((bound) => !bounds.some((other) => (
+ other !== bound &&
+ getRectArea(other.rect) < getRectArea(bound.rect) &&
+ isRectContainingRect(bound.rect, other.rect)
+ )));
+}
+
export function getTableBlockMenuHoverRect(tableRect: IBoundRectNoAngle): IBoundRectNoAngle {
return {
bottom: tableRect.bottom,
@@ -430,7 +523,7 @@ export class DocEventManagerService extends Disposable implements IRenderModule
}
private _initEvents() {
- this.disposeWithMe(fromEventSubject(this._context.scene.onPointerMove$).pipe(throttleTime(30)).subscribe((evt) => {
+ this.disposeWithMe(fromEventSubject(this._context.scene.onPointerMove$).pipe(throttleTime(30, undefined, { leading: true, trailing: true })).subscribe((evt) => {
if (evt.buttons > 0) {
this._hoverBullet$.next(null);
this._hoverCustomRanges$.next([]);
@@ -713,12 +806,16 @@ export class DocEventManagerService extends Disposable implements IRenderModule
// eslint-disable-next-line max-lines-per-function
const calc = (pages: IDocumentSkeletonPage[]) => {
const paragraphMap: Map<number, IMutiPageParagraphBound> = new Map();
- const handlePage = (page: IDocumentSkeletonPage, pageIndex: number, top: number, left: number) => {
- const bounds = calcDocParagraphPositions(page.sections, top, left, page.pageWidth - page.marginLeft - page.marginRight);
+ const addParagraphBoundsToMap = (
+ map: Map<number, IMutiPageParagraphBound>,
+ bounds: ICustomRangeBoundBase[],
+ pageIndex: number,
+ segmentId?: string
+ ) => {
bounds.forEach((bound) => {
- if (!paragraphMap.has(bound.startIndex)) {
- paragraphMap.set(bound.startIndex, {
+ if (!map.has(bound.startIndex)) {
+ map.set(bound.startIndex, {
rect: bound.rect,
paragraphStart: bound.paragraphStart,
paragraphEnd: bound.paragraphEnd,
@@ -729,7 +826,7 @@ export class DocEventManagerService extends Disposable implements IRenderModule
firstLine: bound.fisrtLine,
});
} else {
- const current = paragraphMap.get(bound.startIndex);
+ const current = map.get(bound.startIndex);
if (current) {
current.rect.bottom = bound.rect.bottom;
current.rects.push(bound.rect);
@@ -738,94 +835,93 @@ export class DocEventManagerService extends Disposable implements IRenderModule
});
};
- for (let i = 0; i < pages.length; i++) {
- const page = pages[i];
- const top = ((page.pageHeight === Infinity ? 0 : page.pageHeight) + documentOffsetConfig.pageMarginTop) * i + page.marginTop + documentOffsetConfig.docsTop;
- const left = page.marginLeft + documentOffsetConfig.docsLeft;
- if (page.skeTables) {
- Array.from(page.skeTables.values()).forEach((table) => {
- const tableLeft = table.left + left;
- const tableTop = table.top + top;
- const sourceTableId = getTableIdAndSliceIndex(table.tableId).tableId;
- const tableViewport = getTableHorizontalViewportGeometry(
- tableLeft,
- table.width,
- getDocsTableRenderViewport(this._context.unitId, sourceTableId)
- );
- const tableRight = tableViewport.visibleRight;
- const tableBottom = tableTop + table.height;
- const tableId = table.tableId;
- this._tableBounds.set(tableId, {
- rect: {
- left: tableLeft,
- top: tableTop,
- right: tableRight,
- bottom: tableBottom,
- },
- pageIndex: i,
- tableId,
- });
+ const lineContextsBySource = new Map<number, IDocumentSkeletonLineContext[]>();
+ documentSkeletonLineIterator(pages, {
+ docsLeft: documentOffsetConfig.docsLeft,
+ pageMarginTop: documentOffsetConfig.pageMarginTop,
+ unitId: this._context.unitId,
+ }, (context) => {
+ if (context.source === 'table-cell') {
+ return;
+ }
- table.rows.forEach((row, rowIndex) => {
- row.cells.forEach((cell, colIndex) => {
- const top = (((page.pageHeight === Infinity ? 0 : page.pageHeight) + documentOffsetConfig.pageMarginTop) * i) + table.top + documentOffsetConfig.docsTop + page.marginTop + row.top + cell.marginTop;
- const cellLeft = tableLeft + cell.left - tableViewport.scrollLeft + cell.marginLeft;
- const cellContentWidth = cell.pageWidth - cell.marginLeft - cell.marginRight;
- const cellRight = cellLeft + cellContentWidth;
- const visibleCellLeft = Math.max(cellLeft, tableViewport.visibleLeft);
- const visibleCellRight = Math.min(cellRight, tableViewport.visibleRight);
- if (visibleCellRight <= visibleCellLeft) {
- return;
- }
+ const lineContexts = lineContextsBySource.get(context.pageIndex) ?? [];
+ lineContexts.push(context);
+ lineContextsBySource.set(context.pageIndex, lineContexts);
+ });
- const bounds = calcDocParagraphPositions(cell.sections, top, cellLeft, cellContentWidth)
- .map((bound) => clipParagraphBoundHorizontally(bound, tableViewport.visibleLeft, tableViewport.visibleRight))
- .filter((bound): bound is ICustomRangeBoundBase => bound != null);
- let arr = this._tableParagraphBounds.get(tableId);
- if (!arr) {
- arr = [];
- this._tableParagraphBounds.set(tableId, arr);
- }
+ lineContextsBySource.forEach((contexts, pageIndex) => {
+ addParagraphBoundsToMap(
+ paragraphMap,
+ calcParagraphPositionsFromLineContexts(contexts, documentOffsetConfig.docsLeft, documentOffsetConfig.docsTop),
+ pageIndex,
+ segmentId
+ );
+ });
- arr.push(...bounds.map((bound) => ({
- rect: bound.rect,
- paragraphStart: bound.paragraphStart,
- paragraphEnd: bound.paragraphEnd,
- startIndex: bound.startIndex,
- pageIndex: i,
- segmentId,
- rowIndex,
- colIndex,
- firstLine: bound.fisrtLine,
- tableId,
- }))
- );
-
- let cellBounds = this._tableCellBounds.get(tableId);
-
- if (!cellBounds) {
- cellBounds = [];
- this._tableCellBounds.set(tableId, cellBounds);
- }
+ for (const tableContext of documentSkeletonTableIterator(pages, {
+ docsLeft: documentOffsetConfig.docsLeft,
+ docsTop: documentOffsetConfig.docsTop,
+ pageMarginTop: documentOffsetConfig.pageMarginTop,
+ unitId: this._context.unitId,
+ })) {
+ const tableId = tableContext.tableId;
+ const sourceTableId = getTableIdAndSliceIndex(tableId).tableId;
+ const tableViewport = getTableHorizontalViewportGeometry(
+ tableContext.tableRect.left,
+ tableContext.table.width,
+ getDocsTableRenderViewport(this._context.unitId, sourceTableId)
+ );
+ this._tableBounds.set(tableId, {
+ rect: {
+ ...tableContext.tableRect,
+ right: tableViewport.visibleRight,
+ },
+ pageIndex: tableContext.pageIndex,
+ tableId,
+ });
- cellBounds.push({
- rect: {
- top,
- left: visibleCellLeft,
- right: visibleCellRight,
- bottom: top + cell.pageHeight - cell.marginBottom - cell.marginTop,
- },
- pageIndex: i,
- rowIndex,
- colIndex,
- tableId,
- });
- });
- });
+ for (const cellGeometry of tableContext.cells) {
+ const cell = cellGeometry.cell;
+ const cellContentWidth = (cell.pageWidth ?? 0) - (cell.marginLeft ?? 0) - (cell.marginRight ?? 0);
+ const bounds = calcDocParagraphPositions(cell.sections, cellGeometry.pageTop, cellGeometry.pageLeft, cellContentWidth)
+ .map((bound) => clipParagraphBoundHorizontally(bound, cellGeometry.clipLeft, cellGeometry.clipRight))
+ .filter((bound): bound is ICustomRangeBoundBase => bound != null);
+ let arr = this._tableParagraphBounds.get(tableId);
+ if (!arr) {
+ arr = [];
+ this._tableParagraphBounds.set(tableId, arr);
+ }
+
+ arr.push(...bounds.map((bound) => ({
+ rect: bound.rect,
+ paragraphStart: bound.paragraphStart,
+ paragraphEnd: bound.paragraphEnd,
+ startIndex: bound.startIndex,
+ pageIndex: tableContext.pageIndex,
+ segmentId,
+ rowIndex: cellGeometry.rowIndex,
+ colIndex: cellGeometry.columnIndex,
+ firstLine: bound.fisrtLine,
+ tableId,
+ }))
+ );
+
+ let cellBounds = this._tableCellBounds.get(tableId);
+
+ if (!cellBounds) {
+ cellBounds = [];
+ this._tableCellBounds.set(tableId, cellBounds);
+ }
+
+ cellBounds.push({
+ rect: cellGeometry.cellRect,
+ pageIndex: tableContext.pageIndex,
+ rowIndex: cellGeometry.rowIndex,
+ colIndex: cellGeometry.columnIndex,
+ tableId,
});
}
-
- handlePage(page, i, top, left);
}
return paragraphMap;
@@ -901,23 +997,16 @@ export class DocEventManagerService extends Disposable implements IRenderModule
};
}
- let paragraph: IMutiPageParagraphBound | undefined;
- for (const bounds of this._paragraphBounds) {
- const bound = bounds[1];
- if (bound.rects.some((rect) => isPointInRect(x, y, rect))) {
- paragraph = bound;
- break;
- }
- }
- return paragraph;
+ return getMostSpecificParagraphBound([...this._paragraphBounds.values()].filter((bound) =>
+ bound.rects.some((rect) => isPointInRect(x, y, rect))
+ ));
}
private _calcActiveParagraphLeft(evt: { x: number; y: number }): Nullable<IMutiPageParagraphBound> {
this._buildParagraphBounds();
const { x, y } = evt;
- const paragraph = this._paragraphLeftBounds.find((bound) => isPointInRect(x, y, bound.rect));
- return paragraph;
+ return getMostSpecificParagraphBound(this._paragraphLeftBounds.filter((bound) => isPointInRect(x, y, bound.rect)));
}
get paragraphBounds() {
@@ -974,18 +1063,20 @@ export class DocEventManagerService extends Disposable implements IRenderModule
const pages = this._skeleton.getSkeletonData()?.pages ?? [];
const signatures: string[] = [];
- pages.forEach((page) => {
- page.skeTables?.forEach((table) => {
- const tableId = getTableIdAndSliceIndex(table.tableId).tableId;
- const viewport = getDocsTableRenderViewport(this._context.unitId, tableId);
- if (!viewport) {
- signatures.push(`${tableId}:none`);
- return;
- }
+ for (const tableContext of documentSkeletonTableIterator(pages, {
+ pageMarginTop: this._documents.getOffsetConfig().pageMarginTop,
+ resolveViewport: false,
+ unitId: this._context.unitId,
+ })) {
+ const tableId = getTableIdAndSliceIndex(tableContext.tableId).tableId;
+ const viewport = getDocsTableRenderViewport(this._context.unitId, tableId);
+ if (!viewport) {
+ signatures.push(`${tableId}:none`);
+ continue;
+ }
- signatures.push(`${tableId}:${viewport.contentWidth}:${viewport.viewportWidth}:${viewport.scrollLeft}`);
- });
- });
+ signatures.push(`${tableId}:${viewport.contentWidth}:${viewport.viewportWidth}:${viewport.scrollLeft}`);
+ }
return signatures.join('|');
}
@@ -1002,7 +1093,7 @@ export function getPreferredParagraphBoundsInRange(
return matchedTableBounds;
}
- return bodyBounds.filter((bound) => isRangeOverlappingParagraph(bound, startIndex, endIndex));
+ return removeContainerParagraphBounds(bodyBounds.filter((bound) => isRangeOverlappingParagraph(bound, startIndex, endIndex)));
}
function isRangeOverlappingParagraph(bound: Pick<IMutiPageParagraphBound, 'paragraphEnd' | 'paragraphStart'>, startIndex: number, endIndex: number): boolean {
diff --git a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
index 3d93a50d25..bced1d3cd3 100644
--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
@@ -301,7 +301,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
this._docEventManagerService.hoverParagraphLeft$,
this._docEventManagerService.hoverTableRealTime$ ?? new BehaviorSubject<Nullable<ITableBound>>(null),
])
- .pipe(throttleTime(16))
+ .pipe(throttleTime(16, undefined, { leading: true, trailing: true }))
.subscribe(([p, left, table]) => {
const paragraph = p ?? left;
handleHoverTarget(paragraph, table);
diff --git a/packages/docs-ui/src/services/selection/__tests__/convert-rect-range.spec.ts b/packages/docs-ui/src/services/selection/__tests__/convert-rect-range.spec.ts
index c0c0d830fe..ff2501c5cc 100644
--- a/packages/docs-ui/src/services/selection/__tests__/convert-rect-range.spec.ts
+++ b/packages/docs-ui/src/services/selection/__tests__/convert-rect-range.spec.ts
@@ -14,15 +14,18 @@
* limitations under the License.
*/
+import type { INodePosition } from '@univerjs/engine-render';
+import { DocumentSkeletonPageType } from '@univerjs/engine-render';
import { describe, expect, it } from 'vitest';
import {
compareNodePositionInTable,
isInSameTableCell,
isInSameTableCellData,
isValidRectRange,
+ NodePositionConvertToRectRange,
} from '../convert-rect-range';
-function createNodePosition(path: Array<string | number>) {
+function createNodePosition(path: Array<string | number>): INodePosition {
return {
page: 0,
section: 0,
@@ -31,7 +34,7 @@ function createNodePosition(path: Array<string | number>) {
divide: 0,
glyph: 0,
path,
- } as never;
+ } as INodePosition;
}
describe('selection rect range helpers', () => {
@@ -49,6 +52,128 @@ describe('selection rect range helpers', () => {
expect(isInSameTableCell(sameCell, otherCell)).toBe(false);
});
+ it('ignores column page paths when converting rect ranges', () => {
+ const columnPosition = createNodePosition(['pages', 0, 'skeColumnGroups', 'cg-1', 'columns', 0, 'page']);
+ const columnPage = { parent: { parent: { columnGroupId: 'cg-1' } } };
+ const skeleton = {
+ findCharIndexByPosition: () => 1,
+ getSkeletonData: () => ({
+ pages: [{
+ skeColumnGroups: new Map([
+ ['cg-1', { columns: [{ page: columnPage }] }],
+ ]),
+ }],
+ }),
+ };
+ const convertor = new NodePositionConvertToRectRange({} as never, skeleton as never);
+
+ expect(convertor.getNodePositionGroup(columnPosition, columnPosition)).toBeUndefined();
+ });
+
+ it('projects rect ranges for table cells inside column groups through column offsets', () => {
+ const firstCell = {
+ left: 0,
+ pageWidth: 50,
+ segmentId: 'table-in-column',
+ sections: [{ columns: [{ lines: [{}] }] }],
+ };
+ const secondCell = {
+ left: 50,
+ pageWidth: 50,
+ segmentId: 'table-in-column',
+ sections: [{ columns: [{ lines: [{}] }] }],
+ };
+ const row = {
+ cells: [firstCell, secondCell],
+ height: 20,
+ index: 0,
+ top: 0,
+ };
+ const table = {
+ left: 7,
+ rows: [row],
+ tableId: 'table-in-column',
+ top: 0,
+ };
+ const columnPage = {
+ marginLeft: 5,
+ marginTop: 0,
+ skeTables: new Map([['table-in-column', table]]),
+ };
+ const columnGroupColumn = {
+ left: 60,
+ page: columnPage,
+ top: 4,
+ };
+ const columnGroup = {
+ columnGroupId: 'cg-1',
+ columns: [columnGroupColumn],
+ left: 20,
+ top: 30,
+ };
+ const page = {
+ marginLeft: 0,
+ marginTop: 0,
+ pageHeight: 500,
+ pageWidth: 500,
+ skeColumnGroups: new Map([['cg-1', columnGroup]]),
+ skeTables: new Map(),
+ };
+
+ (firstCell as { parent?: unknown }).parent = row;
+ (secondCell as { parent?: unknown }).parent = row;
+ (row as { parent?: unknown }).parent = table;
+ (table as { parent?: unknown }).parent = columnPage;
+ (columnPage as { parent?: unknown }).parent = columnGroupColumn;
+ (columnGroupColumn as { parent?: unknown }).parent = columnGroup;
+ (columnGroup as { parent?: unknown }).parent = page;
+
+ const skeleton = {
+ getSkeletonData: () => ({
+ pages: [page],
+ skeFooters: new Map(),
+ skeHeaders: new Map(),
+ }),
+ getViewModel: () => ({
+ getDataModel: () => ({
+ getUnitId: () => 'unit-1',
+ }),
+ getSnapshot: () => ({
+ tableSource: {
+ 'table-in-column': {
+ tableRows: [{
+ tableCells: [{}, {}],
+ }],
+ },
+ },
+ }),
+ }),
+ };
+ const anchor = {
+ ...createNodePosition(['pages', 0, 'skeColumnGroups', 'cg-1', 'columns', 0, 'page', 'skeTables', 'table-in-column', 'rows', 0, 'cells', 0]),
+ pageType: DocumentSkeletonPageType.CELL,
+ } as never;
+ const focus = {
+ ...createNodePosition(['pages', 0, 'skeColumnGroups', 'cg-1', 'columns', 0, 'page', 'skeTables', 'table-in-column', 'rows', 0, 'cells', 1]),
+ pageType: DocumentSkeletonPageType.CELL,
+ } as never;
+ const convertor = new NodePositionConvertToRectRange({
+ pageLayoutType: 0,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ } as never, skeleton as never);
+
+ const result = convertor.getRangePointData(anchor, focus);
+
+ expect(result?.pointGroup[0]).toEqual([
+ { x: 92, y: 34 },
+ { x: 192, y: 34 },
+ { x: 192, y: 54 },
+ { x: 92, y: 54 },
+ { x: 92, y: 34 },
+ ]);
+ });
+
it('detects same table-cell data across pages and compares table order', () => {
const anchor = createNodePosition(['pages', 0, 'skeTables', 'table#-#0', 'rows', 1, 'cells', 2]);
const focus = createNodePosition(['pages', 1, 'skeTables', 'table#-#1', 'rows', 1, 'cells', 2]);
diff --git a/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts b/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts
index 7601cca9b5..5fd07e6ab5 100644
--- a/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts
+++ b/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts
@@ -44,6 +44,36 @@ describe('selection convert text range helpers', () => {
expect(compareNodePosition(end, start)).toEqual({ start, end });
});
+ it('orders positions in different document columns by their column-group path', () => {
+ const firstColumnEnd = {
+ page: 0,
+ pageType: DocumentSkeletonPageType.CELL,
+ section: 0,
+ column: 0,
+ line: 0,
+ divide: 0,
+ glyph: 2,
+ path: ['pages', 0, 'skeColumnGroups', 'cg-1', 'columns', 0, 'page'],
+ } as never;
+ const secondColumnStart = {
+ page: 0,
+ pageType: DocumentSkeletonPageType.CELL,
+ section: 0,
+ column: 0,
+ line: 0,
+ divide: 0,
+ glyph: 0,
+ path: ['pages', 0, 'skeColumnGroups', 'cg-1', 'columns', 1, 'page'],
+ } as never;
+
+ expect(compareNodePositionLogic(firstColumnEnd, secondColumnStart)).toBe(true);
+ expect(compareNodePositionLogic(secondColumnStart, firstColumnEnd)).toBe(false);
+ expect(compareNodePosition(secondColumnStart, firstColumnEnd)).toEqual({
+ start: firstColumnEnd,
+ end: secondColumnStart,
+ });
+ });
+
it('merges cursor fragments into one text range', () => {
expect(getOneTextSelectionRange([])).toBeUndefined();
expect(getOneTextSelectionRange([
@@ -198,6 +228,214 @@ describe('selection convert text range helpers', () => {
expect(getAnchorBounding(result.contentBoxPointGroup).left).toBe(70);
});
+ it('projects column page cursors through the column group offset', () => {
+ const glyph = {
+ bBox: { ba: 8, bd: 2 },
+ count: 1,
+ glyphType: 'LETTER',
+ left: 20,
+ width: 10,
+ };
+ const columnPage = {
+ marginLeft: 0,
+ marginTop: 0,
+ sections: [{
+ columns: [{
+ left: 0,
+ lines: [{
+ asc: 10,
+ divides: [{
+ glyphGroup: [glyph],
+ left: 0,
+ paddingLeft: 0,
+ }],
+ lineHeight: 20,
+ marginBottom: 0,
+ marginTop: 0,
+ paddingTop: 0,
+ top: 0,
+ }],
+ }],
+ top: 0,
+ }],
+ };
+ const columnGroupColumn = {
+ left: 60,
+ page: columnPage,
+ top: 4,
+ };
+ const columnGroup = {
+ columnGroupId: 'cg-1',
+ columns: [columnGroupColumn],
+ left: 20,
+ top: 30,
+ };
+ const page = {
+ marginLeft: 0,
+ marginTop: 0,
+ pageHeight: 500,
+ pageWidth: 500,
+ skeColumnGroups: new Map([['cg-1', columnGroup]]),
+ skeTables: new Map(),
+ };
+
+ (columnPage as { parent?: unknown }).parent = columnGroupColumn;
+ (columnGroupColumn as { parent?: unknown }).parent = columnGroup;
+ (columnGroup as { parent?: unknown }).parent = page;
+
+ const skeleton = {
+ getSkeletonData: () => ({
+ pages: [page],
+ skeFooters: new Map(),
+ skeHeaders: new Map(),
+ }),
+ getViewModel: () => ({
+ getDataModel: () => ({
+ getUnitId: () => 'unit-1',
+ }),
+ }),
+ };
+ const position: INodePosition = {
+ column: 0,
+ divide: 0,
+ glyph: 0,
+ isBack: false,
+ line: 0,
+ page: 0,
+ pageType: DocumentSkeletonPageType.CELL,
+ path: ['pages', 0, 'skeColumnGroups', 'cg-1', 'columns', 0, 'page'],
+ section: 0,
+ segmentPage: 0,
+ };
+
+ const convertor = new NodePositionConvertToCursor({
+ docsLeft: 0,
+ docsTop: 0,
+ pageLayoutType: 0,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ } as never, skeleton as never);
+
+ const result = convertor.getRangePointData(position, position);
+
+ expect(getAnchorBounding(result.contentBoxPointGroup).left).toBe(100);
+ });
+
+ it('projects table cell cursors inside column groups through the column and table offsets', () => {
+ const glyph = {
+ bBox: { ba: 8, bd: 2 },
+ count: 1,
+ glyphType: 'LETTER',
+ left: 20,
+ width: 10,
+ };
+ const cell = {
+ left: 30,
+ marginLeft: 3,
+ marginTop: 0,
+ sections: [{
+ columns: [{
+ left: 0,
+ lines: [{
+ asc: 10,
+ divides: [{
+ glyphGroup: [glyph],
+ left: 0,
+ paddingLeft: 0,
+ }],
+ lineHeight: 20,
+ marginBottom: 0,
+ marginTop: 0,
+ paddingTop: 0,
+ top: 0,
+ }],
+ }],
+ top: 0,
+ }],
+ };
+ const row = {
+ cells: [cell],
+ height: 20,
+ index: 0,
+ top: 0,
+ };
+ const table = {
+ left: 7,
+ rows: [row],
+ tableId: 'table-in-column',
+ top: 0,
+ };
+ const columnPage = {
+ marginLeft: 5,
+ marginTop: 0,
+ sections: [],
+ skeTables: new Map([['table-in-column', table]]),
+ };
+ const columnGroupColumn = {
+ left: 60,
+ page: columnPage,
+ top: 4,
+ };
+ const columnGroup = {
+ columnGroupId: 'cg-1',
+ columns: [columnGroupColumn],
+ left: 20,
+ top: 30,
+ };
+ const page = {
+ marginLeft: 0,
+ marginTop: 0,
+ pageHeight: 500,
+ pageWidth: 500,
+ skeColumnGroups: new Map([['cg-1', columnGroup]]),
+ skeTables: new Map(),
+ };
+
+ (cell as { parent?: unknown }).parent = row;
+ (row as { parent?: unknown }).parent = table;
+ (table as { parent?: unknown }).parent = columnPage;
+ (columnPage as { parent?: unknown }).parent = columnGroupColumn;
+ (columnGroupColumn as { parent?: unknown }).parent = columnGroup;
+ (columnGroup as { parent?: unknown }).parent = page;
+
+ const skeleton = {
+ getSkeletonData: () => ({
+ pages: [page],
+ skeFooters: new Map(),
+ skeHeaders: new Map(),
+ }),
+ getViewModel: () => ({
+ getDataModel: () => ({
+ getUnitId: () => 'unit-1',
+ }),
+ }),
+ };
+ const position: INodePosition = {
+ column: 0,
+ divide: 0,
+ glyph: 0,
+ isBack: false,
+ line: 0,
+ page: 0,
+ pageType: DocumentSkeletonPageType.CELL,
+ path: ['pages', 0, 'skeColumnGroups', 'cg-1', 'columns', 0, 'page', 'skeTables', 'table-in-column', 'rows', 0, 'cells', 0],
+ section: 0,
+ segmentPage: 0,
+ };
+
+ const convertor = new NodePositionConvertToCursor({
+ docsLeft: 0,
+ docsTop: 0,
+ pageLayoutType: 0,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ } as never, skeleton as never);
+
+ const result = convertor.getRangePointData(position, position);
+
+ expect(getAnchorBounding(result.contentBoxPointGroup).left).toBe(145);
+ });
+
it('excludes layout-only paragraph spacing from text selection height', () => {
const glyph = {
bBox: { ba: 10, bd: 3 },
diff --git a/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts b/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts
index 0f21576e04..3e8b608774 100644
--- a/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts
+++ b/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts
@@ -384,10 +384,10 @@ describe('selection utils', () => {
.mockReturnValueOnce(endPosition)
.mockReturnValueOnce(startPosition)
.mockReturnValueOnce(endPosition),
- } as never;
+ };
- const textRange = getTextRangeFromCharIndex(1, 2, {} as never, createDocument(), skeleton, {} as never, '', -1);
- const rectRange = getRectRangeFromCharIndex(1, 2, {} as never, createDocument(), skeleton, {} as never, '', -1);
+ const textRange = getTextRangeFromCharIndex(1, 2, {} as never, createDocument(), skeleton as never, {} as never, '', -1);
+ const rectRange = getRectRangeFromCharIndex(1, 2, {} as never, createDocument(), skeleton as never, {} as never, '', -1);
expect(textRange).toBeInstanceOf(TextRange);
expect(textRange?.anchorNodePosition).toEqual(startPosition);
@@ -400,12 +400,39 @@ describe('selection utils', () => {
it('does not create ranges when a character boundary cannot be resolved', () => {
const skeleton = {
findNodePositionByCharIndex: vi.fn(() => undefined),
- } as never;
+ };
const document = createDocument();
- expect(getTextRangeFromCharIndex(1, 2, {} as never, document, skeleton, {} as never, '', -1)).toBeUndefined();
- expect(getRectRangeFromCharIndex(1, 2, {} as never, document, skeleton, {} as never, '', -1)).toBeUndefined();
- expect(getRangeListFromCharIndex(1, 2, {} as never, document, skeleton, {} as never, '', -1)).toBeUndefined();
+ expect(getTextRangeFromCharIndex(1, 2, {} as never, document, skeleton as never, {} as never, '', -1)).toBeUndefined();
+ expect(getRectRangeFromCharIndex(1, 2, {} as never, document, skeleton as never, {} as never, '', -1)).toBeUndefined();
+ expect(getRangeListFromCharIndex(1, 2, {} as never, document, skeleton as never, {} as never, '', -1)).toBeUndefined();
+ });
+
+ it('resolves collapsed ranges from the backward character boundary', () => {
+ const position = createNodePosition(['pages', 0], 0);
+ const skeleton = {
+ findNodePositionByCharIndex: vi.fn(() => position),
+ findGlyphByPosition: vi.fn(() => null),
+ findCharIndexByPosition: vi.fn(() => 5),
+ getViewModel: () => ({
+ getSelfOrHeaderFooterViewModel: () => ({
+ getChildren: () => [{
+ children: [{
+ children: [],
+ endIndex: 8,
+ startIndex: 1,
+ }],
+ }],
+ }),
+ }),
+ };
+ const document = createDocument();
+
+ const ranges = getRangeListFromCharIndex(5, 5, {} as never, document, skeleton as never, {} as never, '', -1);
+
+ expect(skeleton.findNodePositionByCharIndex).toHaveBeenNthCalledWith(1, 5, true, '', -1);
+ expect(ranges?.textRanges[0].anchorNodePosition).toBe(position);
+ expect(ranges?.textRanges[0].focusNodePosition).toBe(position);
});
it('routes same-cell and rect selections into the expected range buckets', () => {
@@ -760,6 +787,64 @@ describe('selection utils', () => {
expect(missing).toBeUndefined();
});
+ it('collapses a first-column input boundary instead of turning it into a cross-column selection', () => {
+ const anchor = createNodePosition(['pages', 0, 'skeColumnGroups', 'column-group-1', 'columns', 0, 'page'], 1);
+ const focus = createNodePosition(['pages', 0, 'skeColumnGroups', 'column-group-1', 'columns', 1, 'page']);
+ const skeleton = {
+ findCharIndexByPosition: vi
+ .fn()
+ .mockReturnValueOnce(190)
+ .mockReturnValueOnce(189),
+ getViewModel: () => ({
+ getSelfOrHeaderFooterViewModel: () => ({
+ getChildren: () => [],
+ }),
+ }),
+ };
+
+ const result = getRangeListFromSelection(
+ anchor,
+ focus,
+ {} as never,
+ createDocument(),
+ skeleton as never,
+ {} as never,
+ '',
+ -1
+ );
+
+ expect(result?.textRanges).toHaveLength(1);
+ expect(result?.rectRanges).toHaveLength(0);
+ expect(result?.textRanges[0].anchorNodePosition).toBe(anchor);
+ expect(result?.textRanges[0].focusNodePosition).toBe(anchor);
+ });
+
+ it('resolves both endpoints for collapsed text ranges instead of reusing the start node', () => {
+ const startNode = createNodePosition(['body', 'collapsed-start'], 10);
+ const endNode = createNodePosition(['body', 'collapsed-end'], 11);
+ const skeleton = {
+ findNodePositionByCharIndex: vi
+ .fn()
+ .mockReturnValueOnce(startNode)
+ .mockReturnValueOnce(endNode),
+ findCharIndexByPosition: vi
+ .fn()
+ .mockReturnValueOnce(5)
+ .mockReturnValueOnce(5),
+ getViewModel: () => ({
+ getSelfOrHeaderFooterViewModel: () => ({
+ getChildren: () => [{ children: [{ startIndex: 0, endIndex: 10, children: [] }] }],
+ }),
+ }),
+ };
+
+ const result = getRangeListFromCharIndex(5, 5, {} as never, createDocument(), skeleton as never, {} as never, '', -1);
+
+ expect(result?.textRanges).toHaveLength(1);
+ expect(skeleton.findNodePositionByCharIndex).toHaveBeenNthCalledWith(1, 5, true, '', -1);
+ expect(skeleton.findNodePositionByCharIndex).toHaveBeenNthCalledWith(2, 5, true, '', -1);
+ });
+
it('falls back to original boundary positions when the first character index cannot be resolved back to a node', () => {
const focusPosition = createNodePosition(['body'], 0);
focusPosition.isBack = true;
@@ -784,14 +869,14 @@ describe('selection utils', () => {
getChildren: () => [{ children: [paragraph] }],
}),
}),
- } as never;
+ };
const result = getRangeListFromSelection(
anchorPosition,
focusPosition,
{} as never,
createDocument(),
- skeleton,
+ skeleton as never,
{} as never,
'',
-1
diff --git a/packages/docs-ui/src/services/selection/convert-rect-range.ts b/packages/docs-ui/src/services/selection/convert-rect-range.ts
index b0ba7af0fc..1c09696d55 100644
--- a/packages/docs-ui/src/services/selection/convert-rect-range.ts
+++ b/packages/docs-ui/src/services/selection/convert-rect-range.ts
@@ -17,7 +17,7 @@
import type { ITable, Nullable } from '@univerjs/core';
import type { DocumentSkeleton, IDocsTableRenderViewport, IDocumentOffsetConfig, IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonTable, INodePosition, IPoint } from '@univerjs/engine-render';
import { Tools } from '@univerjs/core';
-import { DocumentSkeletonPageType, getDocsTableRenderViewport, getPageFromPath, getTableIdAndSliceIndex, Liquid } from '@univerjs/engine-render';
+import { DocumentSkeletonPageType, documentSkeletonTableIterator, getDocsTableRenderViewport, getPageFromPath, getTableIdAndSliceIndex, Liquid } from '@univerjs/engine-render';
import { compareNodePositionLogic, pushToPoints } from './convert-text-range';
// The anchor and focus need to be in the same table,
@@ -278,6 +278,12 @@ export class NodePositionConvertToRectRange {
const { pageLayoutType, pageMarginLeft, pageMarginTop } = this._documentOffsetConfig;
const unitId = getDocumentUnitId(docSkeleton);
const sourceTableId = getTableIdAndSliceIndex(tableId).tableId;
+ const nestedTableContexts = documentSkeletonTableIterator(pages, {
+ docsLeft: this._documentOffsetConfig.docsLeft ?? 0,
+ docsTop: this._documentOffsetConfig.docsTop ?? 0,
+ pageMarginTop,
+ unitId,
+ });
const skipPageIndex = pageType === DocumentSkeletonPageType.BODY || pageType === DocumentSkeletonPageType.CELL ? startPage : startSegmentPage;
@@ -302,6 +308,64 @@ export class NodePositionConvertToRectRange {
}
if (table == null) {
+ const nestedTableContext = nestedTableContexts.find((context) => (
+ context.pageIndex === p &&
+ context.source === 'column' &&
+ context.tableId.startsWith(tableId)
+ ));
+ if (nestedTableContext) {
+ const nestedTable = nestedTableContext.table;
+ const viewport = getDocsTableRenderViewport(unitId, sourceTableId);
+ const nestedX = nestedTableContext.tableRect.left - nestedTable.left;
+ const nestedY = nestedTableContext.tableRect.top;
+
+ if (intersectsMergedCell) {
+ const rows = nestedTable.rows.filter((row) => row.index >= startRow && row.index <= endRow);
+ const firstRow = rows[0];
+ const lastRow = rows[rows.length - 1];
+ const startX = getColumnBoundary(nestedTable, startColumn);
+ const endX = getColumnBoundary(nestedTable, endColumn + 1);
+
+ if (firstRow && lastRow && startX != null && endX != null) {
+ pushViewportClippedPoints(pointGroup, {
+ startX: nestedX + nestedTable.left + startX,
+ startY: nestedY + firstRow.top,
+ endX: nestedX + nestedTable.left + endX,
+ endY: nestedY + lastRow.top + lastRow.height,
+ }, viewport, nestedX + nestedTable.left);
+ }
+
+ this._liquid.restorePagePadding(page);
+ this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
+ continue;
+ }
+
+ for (const row of nestedTable.rows) {
+ if (row.index >= startRow && row.index <= endRow) {
+ const cells = findNonEmptyCellPages(row.cells, startColumn, endColumn);
+
+ if (cells == null) {
+ continue;
+ }
+
+ const [rowStartCell, rowEndCell] = cells;
+
+ const position = {
+ startX: nestedX + rowStartCell.left + nestedTable.left,
+ startY: nestedY + row.top,
+ endX: nestedX + rowEndCell.left + rowEndCell.pageWidth + nestedTable.left,
+ endY: nestedY + row.top + row.height,
+ };
+
+ pushViewportClippedPoints(pointGroup, position, viewport, nestedX + nestedTable.left);
+ }
+ }
+
+ this._liquid.restorePagePadding(page);
+ this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
+ continue;
+ }
+
this._liquid.restorePagePadding(page);
this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
continue;
@@ -462,6 +526,10 @@ export class NodePositionConvertToRectRange {
const { path: anchorPath } = anchorPosition;
const { path: focusPath } = focusPosition;
+ if (anchorPath.indexOf('cells') === -1 || focusPath.indexOf('cells') === -1) {
+ return;
+ }
+
const anchorCell = getPageFromPath(skeletonData, anchorPath);
const focusCell = getPageFromPath(skeletonData, focusPath);
@@ -469,18 +537,24 @@ export class NodePositionConvertToRectRange {
return;
}
+ const anchorRow = anchorCell.parent as IDocumentSkeletonRow;
+ const focusRow = focusCell.parent as IDocumentSkeletonRow;
+ if (!Array.isArray(anchorRow?.cells) || !Array.isArray(focusRow?.cells)) {
+ return;
+ }
+
const tableId = anchorCell.segmentId;
- const anchorRow = (anchorCell.parent as IDocumentSkeletonRow).index;
- const anchorColumn = (anchorCell.parent as IDocumentSkeletonRow).cells.indexOf(anchorCell);
+ const anchorRowIndex = anchorRow.index;
+ const anchorColumn = anchorRow.cells.indexOf(anchorCell);
- const focusRow = (focusCell?.parent as IDocumentSkeletonRow).index;
- const focusColumn = (focusCell?.parent as IDocumentSkeletonRow).cells.indexOf(focusCell);
+ const focusRowIndex = focusRow.index;
+ const focusColumn = focusRow.cells.indexOf(focusCell);
const sourceTableId = getTableIdAndSliceIndex(tableId).tableId;
const tableSource = docSkeleton.getViewModel().getSnapshot().tableSource?.[sourceTableId];
const rawRange = {
- startRowIndex: Math.min(anchorRow, focusRow),
- endRowIndex: Math.max(anchorRow, focusRow),
+ startRowIndex: Math.min(anchorRowIndex, focusRowIndex),
+ endRowIndex: Math.max(anchorRowIndex, focusRowIndex),
startColumnIndex: Math.min(anchorColumn, focusColumn),
endColumnIndex: Math.max(anchorColumn, focusColumn),
};
diff --git a/packages/docs-ui/src/services/selection/convert-text-range.ts b/packages/docs-ui/src/services/selection/convert-text-range.ts
index 5c65d6af38..b9c067e974 100644
--- a/packages/docs-ui/src/services/selection/convert-text-range.ts
+++ b/packages/docs-ui/src/services/selection/convert-text-range.ts
@@ -30,8 +30,10 @@ import type {
IPoint,
} from '@univerjs/engine-render';
import {
+ compareDocumentSkeletonNestedPagePathOrder,
DocumentSkeletonPageType,
getDocsTableRenderViewport,
+ getDocumentSkeletonNestedPageOffset,
getPageFromPath,
getTableIdAndSliceIndex,
GlyphType,
@@ -72,6 +74,11 @@ export const NodePositionMap = {
};
export function compareNodePositionLogic(pos1: INodePosition, pos2: INodePosition) {
+ const nestedPagePathOrder = compareDocumentSkeletonNestedPagePathOrder(pos1, pos2);
+ if (nestedPagePathOrder != null) {
+ return nestedPagePathOrder;
+ }
+
if (pos1.page > pos2.page) {
return false;
}
@@ -585,9 +592,19 @@ export class NodePositionConvertToCursor {
break;
}
case DocumentSkeletonPageType.CELL: {
+ const nestedPageOffset = getDocumentSkeletonNestedPageOffset(segmentPage);
+ if (nestedPageOffset) {
+ this._liquid.translatePagePadding(page);
+ this._liquid.translate(nestedPageOffset.left, nestedPageOffset.top);
+ this._liquid.translatePagePadding(segmentPage);
+ break;
+ }
+
this._liquid.translatePagePadding(page);
const rowSke = segmentPage.parent as IDocumentSkeletonRow;
const tableSke = rowSke.parent!;
+ const tablePage = tableSke.parent as IDocumentSkeletonPage | undefined;
+ const tablePageNestedOffset = tablePage ? getDocumentSkeletonNestedPageOffset(tablePage) : undefined;
const { left: cellLeft } = segmentPage;
const { top: tableTop, left: tableLeft } = tableSke;
const { top: rowTop } = rowSke;
@@ -596,6 +613,11 @@ export class NodePositionConvertToCursor {
const hasHorizontalViewport = hasHorizontalTableViewport(viewport);
const scrollLeft = hasHorizontalViewport ? viewport.scrollLeft : 0;
+ if (tablePageNestedOffset) {
+ this._liquid.translate(tablePageNestedOffset.left, tablePageNestedOffset.top);
+ this._liquid.translatePagePadding(tablePage!);
+ }
+
if (hasHorizontalViewport) {
const visibleLeft = this._liquid.x + tableLeft - (viewport.leadingInsetLeft ?? 0);
this._horizontalClip = {
diff --git a/packages/docs-ui/src/services/selection/selection-utils.ts b/packages/docs-ui/src/services/selection/selection-utils.ts
index 508277f770..f3f40a06dd 100644
--- a/packages/docs-ui/src/services/selection/selection-utils.ts
+++ b/packages/docs-ui/src/services/selection/selection-utils.ts
@@ -28,7 +28,7 @@ import type {
} from '@univerjs/engine-render';
import type { IDocRange } from './range-interface';
import { RANGE_DIRECTION, Tools } from '@univerjs/core';
-import { getOffsetRectForDom } from '@univerjs/engine-render';
+import { getDocumentSkeletonColumnPagePathInfo, getOffsetRectForDom } from '@univerjs/engine-render';
import { isInSameTableCell, isInSameTableCellData, isValidRectRange } from './convert-rect-range';
import { compareNodePosition } from './convert-text-range';
import { convertPositionsToRectRanges, RectRange } from './rect-range';
@@ -39,6 +39,44 @@ interface IDocRangeList {
rectRanges: RectRange[];
}
+function isInSameColumnPage(anchorPosition: INodePosition, focusPosition: INodePosition): boolean {
+ const anchorColumnInfo = getDocumentSkeletonColumnPagePathInfo(anchorPosition);
+ const focusColumnInfo = getDocumentSkeletonColumnPagePathInfo(focusPosition);
+
+ return !!anchorColumnInfo && !!focusColumnInfo &&
+ anchorColumnInfo.pageIndex === focusColumnInfo.pageIndex &&
+ anchorColumnInfo.columnGroupId === focusColumnInfo.columnGroupId &&
+ anchorColumnInfo.columnIndex === focusColumnInfo.columnIndex;
+}
+
+function getColumnInputBoundaryCollapsedPosition(
+ anchorPosition: INodePosition,
+ focusPosition: INodePosition,
+ skeleton: DocumentSkeleton
+): Nullable<INodePosition> {
+ const anchorColumnInfo = getDocumentSkeletonColumnPagePathInfo(anchorPosition);
+ const focusColumnInfo = getDocumentSkeletonColumnPagePathInfo(focusPosition);
+
+ if (
+ !anchorColumnInfo ||
+ !focusColumnInfo ||
+ anchorColumnInfo.pageIndex !== focusColumnInfo.pageIndex ||
+ anchorColumnInfo.columnGroupId !== focusColumnInfo.columnGroupId ||
+ anchorColumnInfo.columnIndex + 1 !== focusColumnInfo.columnIndex
+ ) {
+ return;
+ }
+
+ const anchorOffset = skeleton.findCharIndexByPosition(anchorPosition);
+ const focusOffset = skeleton.findCharIndexByPosition(focusPosition);
+
+ if (anchorOffset == null || focusOffset == null || anchorOffset <= focusOffset) {
+ return;
+ }
+
+ return anchorPosition;
+}
+
export function getTextRangeFromCharIndex(
startOffset: number,
endOffset: number,
@@ -134,6 +172,26 @@ export function getRangeListFromSelection(
number
] = [scene, document, skeleton, anchorPosition, focusPosition, style, segmentId, segmentPage];
+ const collapsedColumnPosition = getColumnInputBoundaryCollapsedPosition(anchorPosition, focusPosition, skeleton);
+
+ if (collapsedColumnPosition) {
+ textRanges.push(new TextRange(scene, document, skeleton, collapsedColumnPosition, collapsedColumnPosition, style, segmentId, segmentPage));
+
+ return {
+ textRanges,
+ rectRanges,
+ };
+ }
+
+ if (isInSameColumnPage(anchorPosition, focusPosition)) {
+ textRanges.push(new TextRange(...rangeParams));
+
+ return {
+ textRanges,
+ rectRanges,
+ };
+ }
+
// TODO: @JOCS handle NEST table.
// Handle selection in same table cell.
if (isInSameTableCellData(skeleton, anchorPosition, focusPosition)) {
diff --git a/packages/docs-ui/src/views/ParagraphMenu.tsx b/packages/docs-ui/src/views/ParagraphMenu.tsx
index 5eaa50753c..948fac244a 100644
--- a/packages/docs-ui/src/views/ParagraphMenu.tsx
+++ b/packages/docs-ui/src/views/ParagraphMenu.tsx
@@ -15,6 +15,7 @@
*/
import type { DocumentDataModel, IDocumentBlockRange, IDocumentBody, IParagraph, ITextRun } from '@univerjs/core';
+import type { IDocBlockMoveValidationContext } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IPopup, IValueOption, RectPopupDirection } from '@univerjs/ui';
import type { CSSProperties } from 'react';
@@ -32,7 +33,7 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { clsx } from '@univerjs/design';
-import { DocContentInsertService, DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
+import { DocBlockMoveValidatorService, DocContentInsertService, DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { IRenderManagerService } from '@univerjs/engine-render';
import {
ContextMenuPanel,
@@ -121,6 +122,13 @@ function getParagraphMenuTriggerClassName(visible: boolean) {
});
}
+export function shouldExecuteParagraphMenuMove(
+ validatorService: Pick<DocBlockMoveValidatorService, 'canMoveBlock'>,
+ context: IDocBlockMoveValidationContext
+): boolean {
+ return validatorService.canMoveBlock(context);
+}
+
function getParagraphMenuTriggerIconKey(namedStyleType?: NamedStyleType): string {
switch (namedStyleType) {
case NamedStyleType.HEADING_1:
@@ -689,6 +697,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
const docSelectionManagerService = useDependency(DocSelectionManagerService);
const docClipboardService = useDependency(IDocClipboardService);
const docContentInsertService = useDependency(DocContentInsertService);
+ const docBlockMoveValidatorService = useDependency(DocBlockMoveValidatorService);
const clipboardInterfaceService = useDependency(IClipboardInterfaceService);
const layoutService = useDependency(ILayoutService);
const iconManager = useDependency(IconManager);
@@ -1064,6 +1073,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
}}
onMouseLeave={() => {
isMouseOver.current = false;
+ setParagraphMenuInteractionActive(docParagraphMenuService, false);
cancelOpenMenu();
scheduleHideMenu();
}}
@@ -1132,7 +1142,11 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
docParagraphMenuService?.setBlockMenuDragging(false);
setDropRect(null);
- if (shouldDrop && range && targetOffset != null) {
+ if (shouldDrop && range && targetOffset != null && shouldExecuteParagraphMenuMove(docBlockMoveValidatorService, {
+ unitId: popup.unitId,
+ sourceRange: range,
+ targetOffset,
+ })) {
commandService.executeCommand(MoveDocBlockCommand.id, {
unitId: popup.unitId,
sourceRange: range,
@@ -1183,6 +1197,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
}}
onMouseLeave={() => {
isMouseOver.current = false;
+ setParagraphMenuInteractionActive(docParagraphMenuService, false);
scheduleHideMenu();
}}
/>
@@ -1202,6 +1217,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
}}
onMouseLeave={() => {
isMouseOver.current = false;
+ setParagraphMenuInteractionActive(docParagraphMenuService, false);
scheduleHideMenu();
}}
>
@@ -1220,6 +1236,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
}}
onMenuPointerLeave={() => {
isMouseOver.current = false;
+ setParagraphMenuInteractionActive(docParagraphMenuService, false);
scheduleHideMenu();
}}
onCancel={() => {
@@ -1307,8 +1324,7 @@ export function shouldUseInsertBelowRange(commandId: string, params: IValueOptio
return true;
}
- const rawParams = typeof params.params === 'function' ? params.params() : params.params;
- if (rawParams && typeof rawParams === 'object' && 'paragraphMenuPlacement' in rawParams && rawParams.paragraphMenuPlacement === 'below') {
+ if (typeof params.id === 'string' && params.id.toLowerCase().includes('below')) {
return true;
}
diff --git a/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts b/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
index 91c6092c3d..c08a133c82 100644
--- a/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
+++ b/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
@@ -15,10 +15,12 @@
*/
import type { IDocumentBlockRange } from '@univerjs/core';
+import type { IDocBlockMoveValidationContext } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IMutiPageParagraphBound } from '../../services/doc-event-manager.service';
import type { IDocBlockMenuTarget } from '../../services/doc-paragraph-menu.service';
import { DocumentBlockRangeType, NamedStyleType } from '@univerjs/core';
+import { DocBlockMoveValidatorService } from '@univerjs/docs';
import { describe, expect, it } from 'vitest';
import { HorizontalLineCommand } from '../../commands/commands/doc-horizontal-line.command';
import { BulletListCommand } from '../../commands/commands/list.command';
@@ -30,6 +32,8 @@ import {
getParagraphMenuCommandTargetRange,
getParagraphMenuHiddenItemIds,
getParagraphMenuResolvedCommand,
+ isEmptyParagraphMenuTarget,
+ shouldExecuteParagraphMenuMove,
shouldUseInsertBelowRange,
} from '../ParagraphMenu';
@@ -151,13 +155,42 @@ describe('ParagraphMenu command behavior', () => {
it('routes explicit and declared insert actions below the active block', () => {
expect(shouldUseInsertBelowRange('doc.command.insert-image', { id: 'image' })).toBe(true);
- expect(shouldUseInsertBelowRange('docs.operation.insert-embed', {
- id: 'embed',
- params: {
- paragraphMenuPlacement: 'below',
- },
- })).toBe(true);
+ expect(shouldUseInsertBelowRange('docs.operation.insert-embed', { id: 'docs.operation.insert-embed.below' })).toBe(true);
expect(shouldUseInsertBelowRange('docs.operation.insert-divider', { id: INSERT_BELLOW_MENU_ID })).toBe(true);
expect(shouldUseInsertBelowRange(AlignCenterCommand.id, { id: AlignCenterCommand.id })).toBe(false);
});
+
+ it('does not treat a whitespace-only paragraph as an empty paragraph target', () => {
+ expect(isEmptyParagraphMenuTarget(' \r', {
+ paragraphStart: 0,
+ paragraphEnd: 4,
+ } as IMutiPageParagraphBound)).toBe(false);
+ });
+
+ it('consults registered move validators before executing a paragraph drag move', () => {
+ const validatorService = new DocBlockMoveValidatorService();
+ const seenContexts: IDocBlockMoveValidationContext[] = [];
+
+ validatorService.registerValidator((context) => {
+ seenContexts.push(context);
+ return false;
+ });
+
+ expect(shouldExecuteParagraphMenuMove(validatorService, {
+ unitId: 'doc-1',
+ sourceRange: {
+ startOffset: 10,
+ endOffset: 20,
+ },
+ targetOffset: 30,
+ })).toBe(false);
+ expect(seenContexts).toEqual([{
+ unitId: 'doc-1',
+ sourceRange: {
+ startOffset: 10,
+ endOffset: 20,
+ },
+ targetOffset: 30,
+ }]);
+ });
});
diff --git a/packages/docs/src/commands/commands/core-editing.command.ts b/packages/docs/src/commands/commands/core-editing.command.ts
index dfa668f3a6..57e027b3f4 100644
--- a/packages/docs/src/commands/commands/core-editing.command.ts
+++ b/packages/docs/src/commands/commands/core-editing.command.ts
@@ -72,6 +72,7 @@ export const InsertTextCommand: ICommand<IInsertTextCommandParams> = {
if (originBody == null) {
return false;
}
+
const { startOffset, collapsed } = range;
const cursorMove = cursorOffset ?? body.dataStream.length;
const textRanges = [
diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.ts
index be0bd163b4..5ac3189593 100644
--- a/packages/docs/src/index.ts
+++ b/packages/docs/src/index.ts
@@ -26,6 +26,8 @@ export { SetTextSelectionsOperation } from './commands/operations/text-selection
export type { ISetTextSelectionsOperationParams } from './commands/operations/text-selection.operation';
export type { IUniverDocsConfig } from './config/config';
export { UniverDocsPlugin } from './plugin';
+export { DocBlockMoveValidatorService } from './services/doc-block-move-validator.service';
+export type { DocBlockMoveTransformer, DocBlockMoveValidator, IDocBlockMoveResult, IDocBlockMoveTransformContext, IDocBlockMoveValidationContext } from './services/doc-block-move-validator.service';
export { DocContentInsertService } from './services/doc-content-insert.service';
export type { IDocContentInsertRange } from './services/doc-content-insert.service';
export { DocInterceptorService } from './services/doc-interceptor/doc-interceptor.service';
diff --git a/packages/docs/src/plugin.ts b/packages/docs/src/plugin.ts
index 9f7caeb088..a5f1c68db0 100644
--- a/packages/docs/src/plugin.ts
+++ b/packages/docs/src/plugin.ts
@@ -31,6 +31,7 @@ import { DocsRenameMutation } from './commands/mutations/docs-rename.mutation';
import { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';
import { defaultPluginConfig, DOCS_PLUGIN_CONFIG_KEY } from './config/config';
import { DocCustomRangeController } from './controllers/custom-range.controller';
+import { DocBlockMoveValidatorService } from './services/doc-block-move-validator.service';
import { DocContentInsertService } from './services/doc-content-insert.service';
import { DocSelectionManagerService } from './services/doc-selection-manager.service';
import { DocStateChangeManagerService } from './services/doc-state-change-manager.service';
@@ -84,6 +85,7 @@ export class UniverDocsPlugin extends Plugin {
[DocSelectionManagerService],
[DocStateEmitService],
[DocStateChangeManagerService],
+ [DocBlockMoveValidatorService],
[DocContentInsertService],
[DocCustomRangeController],
] as Dependency[]
diff --git a/packages/docs/src/services/__tests__/doc-block-move-validator.service.spec.ts b/packages/docs/src/services/__tests__/doc-block-move-validator.service.spec.ts
new file mode 100644
index 0000000000..7126bff88a
--- /dev/null
+++ b/packages/docs/src/services/__tests__/doc-block-move-validator.service.spec.ts
@@ -0,0 +1,169 @@
+/**
+ * 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 { DocBlockMoveValidatorService } from '../doc-block-move-validator.service';
+
+const DOCUMENT_STYLE = {
+ pageSize: {
+ width: 594,
+ height: 840,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginLeft: 90,
+ marginRight: 90,
+};
+
+describe('DocBlockMoveValidatorService', () => {
+ it('allows a move when no validator rejects it', () => {
+ const service = new DocBlockMoveValidatorService();
+
+ const first = service.registerValidator(() => true);
+ service.registerValidator(() => true);
+
+ expect(service.canMoveBlock({
+ unitId: 'doc-1',
+ sourceRange: {
+ startOffset: 2,
+ endOffset: 8,
+ },
+ targetOffset: 20,
+ })).toBe(true);
+
+ first.dispose();
+ expect(service.canMoveBlock({
+ unitId: 'doc-1',
+ sourceRange: {
+ startOffset: 2,
+ endOffset: 8,
+ },
+ targetOffset: 20,
+ })).toBe(true);
+ });
+
+ it('blocks a move when any validator rejects it and stops checking later validators', () => {
+ const service = new DocBlockMoveValidatorService();
+ let laterValidatorCalls = 0;
+
+ service.registerValidator(() => false);
+ service.registerValidator(() => {
+ laterValidatorCalls++;
+ return true;
+ });
+
+ expect(service.canMoveBlock({
+ unitId: 'doc-1',
+ sourceRange: {
+ startOffset: 2,
+ endOffset: 8,
+ },
+ targetOffset: 20,
+ })).toBe(false);
+ expect(laterValidatorCalls).toBe(0);
+ });
+
+ it('applies registered move transformers in order and supports disposal', () => {
+ const service = new DocBlockMoveValidatorService();
+ const first = service.registerTransformer((context) => ({
+ nextDocumentData: {
+ ...context.result.nextDocumentData,
+ body: {
+ dataStream: `${context.result.nextDocumentData.body?.dataStream ?? ''}!`,
+ },
+ },
+ movedRange: context.result.movedRange,
+ }));
+ service.registerTransformer((context) => ({
+ nextDocumentData: context.result.nextDocumentData,
+ movedRange: {
+ startOffset: context.result.movedRange.startOffset + 1,
+ endOffset: context.result.movedRange.endOffset + 1,
+ },
+ }));
+
+ const transformed = service.transformMoveResult({
+ unitId: 'doc-1',
+ sourceRange: {
+ startOffset: 0,
+ endOffset: 1,
+ },
+ targetOffset: 2,
+ previousDocumentData: {
+ id: 'doc-1',
+ body: {
+ dataStream: 'A',
+ },
+ documentStyle: DOCUMENT_STYLE,
+ },
+ result: {
+ nextDocumentData: {
+ id: 'doc-1',
+ body: {
+ dataStream: 'B',
+ },
+ documentStyle: DOCUMENT_STYLE,
+ },
+ movedRange: {
+ startOffset: 0,
+ endOffset: 1,
+ },
+ },
+ });
+
+ expect(transformed.nextDocumentData.body?.dataStream).toBe('B!');
+ expect(transformed.movedRange).toEqual({
+ startOffset: 1,
+ endOffset: 2,
+ });
+
+ first.dispose();
+ const transformedAfterDispose = service.transformMoveResult({
+ unitId: 'doc-1',
+ sourceRange: {
+ startOffset: 0,
+ endOffset: 1,
+ },
+ targetOffset: 2,
+ previousDocumentData: {
+ id: 'doc-1',
+ body: {
+ dataStream: 'A',
+ },
+ documentStyle: DOCUMENT_STYLE,
+ },
+ result: {
+ nextDocumentData: {
+ id: 'doc-1',
+ body: {
+ dataStream: 'B',
+ },
+ documentStyle: DOCUMENT_STYLE,
+ },
+ movedRange: {
+ startOffset: 0,
+ endOffset: 1,
+ },
+ },
+ });
+
+ expect(transformedAfterDispose.nextDocumentData.body?.dataStream).toBe('B');
+ expect(transformedAfterDispose.movedRange).toEqual({
+ startOffset: 1,
+ endOffset: 2,
+ });
+ });
+});
diff --git a/packages/docs/src/services/doc-block-move-validator.service.ts b/packages/docs/src/services/doc-block-move-validator.service.ts
new file mode 100644
index 0000000000..094e33fa9f
--- /dev/null
+++ b/packages/docs/src/services/doc-block-move-validator.service.ts
@@ -0,0 +1,72 @@
+/**
+ * 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 { IDisposable, IDocumentData } from '@univerjs/core';
+import { Disposable, remove, toDisposable } from '@univerjs/core';
+
+export interface IDocBlockMoveValidationContext {
+ unitId: string;
+ sourceRange: {
+ startOffset: number;
+ endOffset: number;
+ };
+ targetOffset: number;
+}
+
+export type DocBlockMoveValidator = (context: IDocBlockMoveValidationContext) => boolean;
+
+export interface IDocBlockMoveResult {
+ nextDocumentData: IDocumentData;
+ movedRange: {
+ startOffset: number;
+ endOffset: number;
+ };
+}
+
+export interface IDocBlockMoveTransformContext extends IDocBlockMoveValidationContext {
+ previousDocumentData: IDocumentData;
+ result: IDocBlockMoveResult;
+}
+
+export type DocBlockMoveTransformer = (context: IDocBlockMoveTransformContext) => IDocBlockMoveResult;
+
+export class DocBlockMoveValidatorService extends Disposable {
+ private readonly _validators: DocBlockMoveValidator[] = [];
+ private readonly _transformers: DocBlockMoveTransformer[] = [];
+
+ registerValidator(validator: DocBlockMoveValidator): IDisposable {
+ this._validators.push(validator);
+
+ return this.disposeWithMe(toDisposable(() => remove(this._validators, validator)));
+ }
+
+ registerTransformer(transformer: DocBlockMoveTransformer): IDisposable {
+ this._transformers.push(transformer);
+
+ return this.disposeWithMe(toDisposable(() => remove(this._transformers, transformer)));
+ }
+
+ canMoveBlock(context: IDocBlockMoveValidationContext): boolean {
+ return this._validators.every((validator) => validator(context));
+ }
+
+ transformMoveResult(context: IDocBlockMoveTransformContext): IDocBlockMoveResult {
+ return this._transformers.reduce((result, transformer) => transformer({
+ ...context,
+ result,
+ }), context.result);
+ }
+}
diff --git a/packages/engine-render/src/basics/i-document-skeleton-cached.ts b/packages/engine-render/src/basics/i-document-skeleton-cached.ts
index 5e74fd0448..3703110d7e 100644
--- a/packages/engine-render/src/basics/i-document-skeleton-cached.ts
+++ b/packages/engine-render/src/basics/i-document-skeleton-cached.ts
@@ -19,6 +19,7 @@ import type {
ColumnSeparatorType,
DataStreamTreeTokenType,
IColorStyle,
+ IColumnGroup,
IDocDrawingBase,
IDocumentRenderConfig,
INestingLevel,
@@ -105,6 +106,7 @@ export interface IDocumentSkeletonPage {
ed: number; // endIndex
skeDrawings: Map<string, IDocumentSkeletonDrawing>;
skeTables: Map<string, IDocumentSkeletonTable>; // table skeletons in the page
+ skeColumnGroups: Map<string, IDocumentSkeletonColumnGroup>; // column group skeletons in the page
segmentId: string; // header/footer id if header/footer, empty string if body page
type: DocumentSkeletonPageType; // page type: header, footer, body, or cell
renderConfig?: IDocumentRenderConfig;
@@ -149,6 +151,31 @@ export interface IDocumentSkeletonRow {
isRepeatRow: boolean; // whether it is a repeated header row
}
+export interface IDocumentSkeletonColumnGroup {
+ columns: IDocumentSkeletonColumnGroupColumn[];
+ width: number;
+ height: number;
+ top: number;
+ left: number;
+ st: number;
+ ed: number;
+ columnGroupId: string;
+ columnGroupSource: IColumnGroup;
+ parent?: IDocumentSkeletonPage;
+}
+
+export interface IDocumentSkeletonColumnGroupColumn {
+ columnId: string;
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ st: number;
+ ed: number;
+ page: IDocumentSkeletonPage;
+ parent?: IDocumentSkeletonColumnGroup;
+}
+
export interface IDocumentSkeletonColumn {
lines: IDocumentSkeletonLine[];
// column coordinate system relative to section
diff --git a/packages/engine-render/src/components/docs/__tests__/document.spec.ts b/packages/engine-render/src/components/docs/__tests__/document.spec.ts
index 89d0f5b383..295b1d9bcd 100644
--- a/packages/engine-render/src/components/docs/__tests__/document.spec.ts
+++ b/packages/engine-render/src/components/docs/__tests__/document.spec.ts
@@ -177,6 +177,7 @@ function createPage(pageType: DocumentSkeletonPageType, segmentId: string, backg
ed: 2,
skeDrawings: new Map(),
skeTables: new Map(),
+ skeColumnGroups: new Map(),
segmentId,
type: pageType,
renderConfig: {
@@ -243,6 +244,72 @@ function attachTable(page: any) {
page.skeTables.set('table-1', table);
}
+function setFirstTextGlyph(page: any, content: string) {
+ const glyph = page.sections[0].columns[0].lines[1].divides[0].glyphGroup[0];
+ glyph.content = content;
+ glyph.raw = content;
+ glyph.count = content.length;
+}
+
+function attachColumnGroup(page: any) {
+ const leftPage = createPage(DocumentSkeletonPageType.BODY, 'column-left');
+ const rightPage = createPage(DocumentSkeletonPageType.BODY, 'column-right');
+ leftPage.marginLeft = 0;
+ leftPage.marginTop = 0;
+ leftPage.marginRight = 0;
+ leftPage.marginBottom = 0;
+ rightPage.marginLeft = 0;
+ rightPage.marginTop = 0;
+ rightPage.marginRight = 0;
+ rightPage.marginBottom = 0;
+ setFirstTextGlyph(leftPage, 'L');
+ setFirstTextGlyph(rightPage, 'R');
+
+ const columnGroup = {
+ columns: [
+ {
+ columnId: 'column-left',
+ left: 0,
+ top: 0,
+ width: 70,
+ height: 80,
+ st: 0,
+ ed: 10,
+ page: leftPage,
+ },
+ {
+ columnId: 'column-right',
+ left: 90,
+ top: 0,
+ width: 70,
+ height: 80,
+ st: 11,
+ ed: 20,
+ page: rightPage,
+ },
+ ],
+ width: 160,
+ height: 80,
+ top: 20,
+ left: 12,
+ st: 0,
+ ed: 20,
+ columnGroupId: 'column-group-1',
+ columnGroupSource: {
+ columnGroupId: 'column-group-1',
+ gap: { v: 20 },
+ columns: [],
+ },
+ parent: page,
+ } as any;
+
+ columnGroup.columns.forEach((column: any) => {
+ column.parent = columnGroup;
+ column.page.parent = column;
+ });
+ page.skeColumnGroups.set(columnGroup.columnGroupId, columnGroup);
+}
+
describe('documents render', () => {
let restoreEnv: () => void;
let container: HTMLDivElement;
@@ -1153,6 +1220,286 @@ describe('documents render', () => {
documents.dispose();
});
+ it('draws column group child pages at their column offsets', () => {
+ const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');
+ bodyPage.sections[0].columns[0].lines = [];
+ bodyPage.marginLeft = 0;
+ bodyPage.marginTop = 0;
+ bodyPage.renderConfig.centerAngle = 0;
+ bodyPage.renderConfig.vertexAngle = 0;
+ attachColumnGroup(bodyPage);
+
+ const skeletonData = {
+ pages: [bodyPage],
+ skeHeaders: new Map(),
+ skeFooters: new Map(),
+ };
+ bodyPage.parent = skeletonData;
+
+ const documents = new Documents('docs-column-group', {
+ getSkeletonData: () => skeletonData,
+ } as any, {
+ pageLayoutType: PageLayoutType.VERTICAL,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ });
+ documents.transformByState({
+ left: 0,
+ top: 0,
+ width: 260,
+ height: 180,
+ });
+ scene.addObject(documents, 1);
+
+ const spanRecords: Array<{ content: string; x: number }> = [];
+ const spanExtension = {
+ uKey: 'DocsSpanExtension',
+ type: DOCS_EXTENSION_TYPE.SPAN,
+ extensionOffset: {},
+ clearCache: vi.fn(),
+ draw: vi.fn(function (this: any, _ctx: unknown, _parentScale: unknown, glyph: any) {
+ if (['L', 'R'].includes(glyph.content)) {
+ spanRecords.push({
+ content: glyph.content,
+ x: this.extensionOffset.spanStartPoint.x,
+ });
+ }
+ }),
+ };
+ vi.spyOn(documents as any, 'getExtensionsByOrder').mockReturnValue([
+ spanExtension,
+ ] as any);
+
+ documents.draw(canvas.getContext(), {
+ viewBound: { left: 0, top: 0, right: 900, bottom: 700 },
+ cacheBound: { left: 0, top: 0, right: 900, bottom: 700 },
+ } as any);
+
+ expect(spanRecords.map((record) => record.content)).toEqual(['L', 'R']);
+ expect(spanRecords[1].x - spanRecords[0].x).toBeGreaterThanOrEqual(90);
+
+ documents.dispose();
+ });
+
+ it('clips table cell content with parent page margins', () => {
+ const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');
+ bodyPage.marginLeft = 30;
+ bodyPage.marginTop = 40;
+ const cell = createPage(DocumentSkeletonPageType.CELL, 'cell-seg');
+ cell.marginLeft = 4;
+ cell.marginTop = 6;
+ cell.pageWidth = 120;
+ cell.pageHeight = 60;
+ cell.sections[0].columns[0].lines = [];
+
+ const documents = new Documents('docs-table-cell-clip');
+ (documents as any)._drawLiquid = {
+ x: 12,
+ y: 20,
+ translateSave: vi.fn(),
+ translateRestore: vi.fn(),
+ translateSection: vi.fn(),
+ translateColumn: vi.fn(),
+ };
+ const ctx = {
+ beginPath: vi.fn(),
+ clip: vi.fn(),
+ closePath: vi.fn(),
+ rectByPrecision: vi.fn(),
+ restore: vi.fn(),
+ save: vi.fn(),
+ } as any;
+
+ (documents as any)._drawNestedPageContent(
+ ctx,
+ bodyPage,
+ cell,
+ [],
+ null,
+ [],
+ { x: 0, y: 0 },
+ 0,
+ 0,
+ {},
+ { scaleX: 1, scaleY: 1 }
+ );
+
+ expect(ctx.rectByPrecision).toHaveBeenCalledWith(42, 60, 120, 60);
+
+ documents.dispose();
+ });
+
+ it('clips column group nested page content with the column align offset', () => {
+ const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');
+ bodyPage.marginLeft = 30;
+ bodyPage.marginTop = 40;
+ attachColumnGroup(bodyPage);
+ const columnGroup = bodyPage.skeColumnGroups.get('column-group-1')!;
+ const nestedPage = columnGroup.columns[0].page;
+ nestedPage.marginLeft = 4;
+ nestedPage.marginTop = 6;
+ nestedPage.sections[0].columns[0].lines = [];
+
+ const documents = new Documents('docs-column-group-clip');
+ (documents as any)._drawLiquid = {
+ x: 12,
+ y: 20,
+ translateSave: vi.fn(),
+ translateRestore: vi.fn(),
+ translateSection: vi.fn(),
+ translateColumn: vi.fn(),
+ };
+ const ctx = {
+ beginPath: vi.fn(),
+ clip: vi.fn(),
+ closePath: vi.fn(),
+ rectByPrecision: vi.fn(),
+ restore: vi.fn(),
+ save: vi.fn(),
+ } as any;
+
+ (documents as any)._drawNestedPageContent(
+ ctx,
+ bodyPage,
+ nestedPage,
+ [],
+ null,
+ [],
+ { x: 100, y: 200 },
+ 0,
+ 0,
+ {},
+ { scaleX: 1, scaleY: 1 }
+ );
+
+ expect(ctx.rectByPrecision).toHaveBeenCalledWith(116, 226, 200, 420);
+
+ documents.dispose();
+ });
+
+ it('draws tables inside column group nested pages', () => {
+ const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');
+ attachColumnGroup(bodyPage);
+ const nestedPage = bodyPage.skeColumnGroups.get('column-group-1')!.columns[0].page;
+ attachTable(nestedPage);
+ nestedPage.marginLeft = 4;
+ nestedPage.marginTop = 6;
+ nestedPage.sections[0].columns[0].lines = [];
+
+ const documents = new Documents('docs-column-group-table');
+ const translate = vi.fn();
+ (documents as any)._drawLiquid = {
+ x: 12,
+ y: 20,
+ translateSave: vi.fn(),
+ translateRestore: vi.fn(),
+ translate,
+ translateSection: vi.fn(),
+ translateColumn: vi.fn(),
+ };
+ const ctx = {
+ beginPath: vi.fn(),
+ clip: vi.fn(),
+ closePath: vi.fn(),
+ rectByPrecision: vi.fn(),
+ restore: vi.fn(),
+ save: vi.fn(),
+ } as any;
+ const drawTable = vi.spyOn(documents as any, '_drawTable').mockImplementation(() => undefined);
+
+ (documents as any)._drawNestedPageContent(
+ ctx,
+ bodyPage,
+ nestedPage,
+ [],
+ null,
+ [],
+ { x: 0, y: 0 },
+ 0,
+ 0,
+ {},
+ { scaleX: 1, scaleY: 1 }
+ );
+
+ expect(drawTable).toHaveBeenCalledWith(
+ ctx,
+ expect.objectContaining({
+ marginLeft: 0,
+ marginTop: 0,
+ }),
+ nestedPage.skeTables,
+ [],
+ null,
+ [],
+ { x: 0, y: 0 },
+ 0,
+ 0,
+ {},
+ { scaleX: 1, scaleY: 1 }
+ );
+ expect(translate).toHaveBeenCalledWith(4, 6);
+
+ documents.dispose();
+ });
+
+ it('does not draw persistent backgrounds behind column group columns', () => {
+ const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');
+ bodyPage.marginLeft = 3;
+ bodyPage.marginTop = 5;
+ attachColumnGroup(bodyPage);
+ const documents = new Documents('docs-column-group-background');
+ const translateSave = vi.fn();
+ const translateRestore = vi.fn();
+ const translate = vi.fn();
+ (documents as any)._drawLiquid = {
+ x: 10,
+ y: 20,
+ translateSave,
+ translateRestore,
+ translate,
+ };
+ const rects: Array<{ x: number; y: number; width: number; height: number }> = [];
+ const fillStyles: string[] = [];
+ const ctx = {
+ beginPath: vi.fn(),
+ closePath: vi.fn(),
+ fill: vi.fn(),
+ getScale: () => ({ scaleX: 1, scaleY: 1 }),
+ rect: vi.fn((x: number, y: number, width: number, height: number) => {
+ rects.push({ x, y, width, height });
+ }),
+ restore: vi.fn(),
+ save: vi.fn(),
+ set fillStyle(value: string) {
+ fillStyles.push(value);
+ },
+ } as any;
+ const drawNestedPageContent = vi
+ .spyOn(documents as any, '_drawNestedPageContent')
+ .mockImplementation(() => undefined);
+
+ (documents as any)._drawColumnGroups(
+ ctx,
+ bodyPage,
+ bodyPage.skeColumnGroups,
+ [],
+ null,
+ [],
+ { x: 0, y: 0 },
+ 0,
+ 0,
+ {},
+ { scaleX: 1, scaleY: 1 }
+ );
+
+ expect(fillStyles).toEqual([]);
+ expect(rects).toEqual([]);
+ expect(ctx.fill).not.toHaveBeenCalled();
+ expect(drawNestedPageContent).toHaveBeenCalledTimes(2);
+
+ documents.dispose();
+ });
+
it('draws body/header/footer/table flows with extension dispatch and page events', () => {
const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');
const headerPage = createPage(DocumentSkeletonPageType.HEADER, 'header-main');
diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.ts
index f4ba002571..6fa5c87e94 100644
--- a/packages/engine-render/src/components/docs/document.ts
+++ b/packages/engine-render/src/components/docs/document.ts
@@ -16,6 +16,8 @@
import type { DocumentFlavor, IDocumentRenderConfig, IScale, ITableCell, ITableCellBorder, Nullable } from '@univerjs/core';
import type {
+ IDocumentSkeletonColumnGroup,
+ IDocumentSkeletonColumnGroupColumn,
IDocumentSkeletonGlyph,
IDocumentSkeletonLine,
IDocumentSkeletonPage,
@@ -41,8 +43,8 @@ import { Vector2 } from '../../basics/vector2';
import { DocumentsSpanAndLineExtensionRegistry } from '../extension';
import { DocComponent } from './doc-component';
import { DOCS_EXTENSION_TYPE } from './doc-extension';
-import { collectBackgroundGlyphRuns } from './extensions/background-runs';
import { getDocumentCompatibilityPolicy, shouldAllowImportedTableMarginOverflow } from './document-compatibility';
+import { collectBackgroundGlyphRuns } from './extensions/background-runs';
import { getTableIdAndSliceIndex } from './layout/block/table';
import { Liquid } from './liquid';
import { getDocsTableRenderViewport, hasDocsTableHorizontalViewport } from './table-render-viewport';
@@ -169,6 +171,7 @@ export class Documents extends DocComponent {
footerId,
renderConfig = {},
skeTables,
+ skeColumnGroups = new Map(),
} = page;
const {
verticalAlign = VerticalAlign.TOP, // Do not make changes, otherwise the document will not render.
@@ -454,6 +457,22 @@ export class Documents extends DocComponent {
}
}
+ if (skeColumnGroups.size > 0) {
+ this._drawColumnGroups(
+ ctx,
+ page,
+ skeColumnGroups,
+ extensions,
+ backgroundExtension,
+ glyphExtensionsExcludeBackground,
+ alignOffsetNoAngle,
+ centerAngle,
+ vertexAngle,
+ renderConfig,
+ parentScale
+ );
+ }
+
this._resetRotation(ctx, finalAngle);
const footerSkeletonPage = skeFooters.get(footerId)?.get(pageWidth);
@@ -585,6 +604,51 @@ export class Documents extends DocComponent {
}
}
+ private _drawColumnGroups(
+ ctx: UniverRenderingContext,
+ page: IDocumentSkeletonPage,
+ skeColumnGroups: Map<string, IDocumentSkeletonColumnGroup>,
+ extensions: ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>[],
+ backgroundExtension: Nullable<ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>>,
+ glyphExtensionsExcludeBackground: ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>[],
+ alignOffsetNoAngle: Vector2,
+ centerAngle: number,
+ vertexAngle: number,
+ renderConfig: IDocumentRenderConfig,
+ parentScale: IScale
+ ) {
+ const drawLiquid = this._drawLiquid;
+ if (drawLiquid == null) {
+ return;
+ }
+
+ for (const columnGroup of skeColumnGroups.values()) {
+ drawLiquid.translateSave();
+ drawLiquid.translate(columnGroup.left, columnGroup.top);
+
+ for (const column of columnGroup.columns) {
+ drawLiquid.translateSave();
+ drawLiquid.translate(column.left, column.top);
+ this._drawNestedPageContent(
+ ctx,
+ page,
+ column.page,
+ extensions,
+ backgroundExtension,
+ glyphExtensionsExcludeBackground,
+ alignOffsetNoAngle,
+ centerAngle,
+ vertexAngle,
+ renderConfig,
+ parentScale
+ );
+ drawLiquid.translateRestore();
+ }
+
+ drawLiquid.translateRestore();
+ }
+ }
+
private _drawTableCellBackgrounds(
ctx: UniverRenderingContext,
page: IDocumentSkeletonPage,
@@ -814,19 +878,89 @@ export class Documents extends DocComponent {
return;
}
this._drawTableCellBordersAndBg(ctx, page, cell, false);
- const { sections, marginLeft, marginTop } = cell;
- // eslint-disable-next-line no-param-reassign
- alignOffsetNoAngle = Vector2.create(alignOffsetNoAngle.x + marginLeft, alignOffsetNoAngle.y + marginTop);
+ this._drawNestedPageContent(
+ ctx,
+ page,
+ cell,
+ extensions,
+ backgroundExtension,
+ glyphExtensionsExcludeBackground,
+ alignOffsetNoAngle,
+ centerAngle,
+ vertexAngle,
+ renderConfig,
+ parentScale
+ );
+ }
+
+ private _drawNestedPageContent(
+ ctx: UniverRenderingContext,
+ parentPage: IDocumentSkeletonPage,
+ nestedPage: IDocumentSkeletonPage,
+ extensions: ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>[],
+ backgroundExtension: Nullable<ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>>,
+ glyphExtensionsExcludeBackground: ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>[],
+ alignOffsetNoAngle: Vector2,
+ centerAngle: number,
+ vertexAngle: number,
+ renderConfig: IDocumentRenderConfig,
+ parentScale: IScale
+ ) {
+ if (this._drawLiquid == null) {
+ return;
+ }
+ const { sections, marginLeft, marginTop, skeTables } = nestedPage;
+ const alignOffset = Vector2.create(alignOffsetNoAngle.x + marginLeft, alignOffsetNoAngle.y + marginTop);
ctx.save();
const { x, y } = this._drawLiquid;
- const { pageWidth, pageHeight } = cell;
+ const { pageWidth, pageHeight } = nestedPage;
+ const clipOrigin = getNestedPageClipOrigin(parentPage, nestedPage, { x, y }, alignOffset);
ctx.beginPath();
- ctx.rectByPrecision(x + page.marginLeft, y + page.marginTop, pageWidth, pageHeight);
+ ctx.rectByPrecision(clipOrigin.x, clipOrigin.y, pageWidth, pageHeight);
ctx.closePath();
ctx.clip();
+ if (skeTables.size > 0) {
+ if (isColumnGroupNestedPage(nestedPage)) {
+ this._drawLiquid.translateSave();
+ this._drawLiquid.translate(alignOffset.x, alignOffset.y);
+ this._drawTable(
+ ctx,
+ {
+ ...nestedPage,
+ marginLeft: 0,
+ marginTop: 0,
+ },
+ skeTables,
+ extensions,
+ backgroundExtension,
+ glyphExtensionsExcludeBackground,
+ Vector2.create(0, 0),
+ centerAngle,
+ vertexAngle,
+ renderConfig,
+ parentScale
+ );
+ this._drawLiquid.translateRestore();
+ } else {
+ this._drawTable(
+ ctx,
+ nestedPage,
+ skeTables,
+ extensions,
+ backgroundExtension,
+ glyphExtensionsExcludeBackground,
+ alignOffset,
+ centerAngle,
+ vertexAngle,
+ renderConfig,
+ parentScale
+ );
+ }
+ }
+
for (const section of sections) {
const { columns } = section;
@@ -841,8 +975,6 @@ export class Documents extends DocComponent {
const linesCount = lines.length;
- const alignOffset = alignOffsetNoAngle;
-
for (let i = 0; i < linesCount; i++) {
const line = lines[i];
const { divides, asc = 0, type, lineHeight = 0 } = line;
@@ -865,7 +997,7 @@ export class Documents extends DocComponent {
} else {
this._drawLiquid.translateSave();
this._drawLiquid.translateLine(line, true, true);
- this._drawLineBackground(ctx, cell, line, page.marginLeft, page.marginTop);
+ this._drawLineBackground(ctx, nestedPage, line);
const divideLength = divides.length;
@@ -939,7 +1071,7 @@ export class Documents extends DocComponent {
}
if (line.borderBottom) {
- this._drawBorderBottom(ctx, cell, line, page.marginLeft, page.marginTop);
+ this._drawBorderBottom(ctx, nestedPage, line, parentPage.marginLeft, parentPage.marginTop);
}
this._drawLiquid.translateRestore();
@@ -1339,6 +1471,31 @@ function setTableCellBorderDash(ctx: UniverRenderingContext, dashStyle?: DashSty
ctx.setLineDash([0]);
}
+function isColumnGroupNestedPage(page: IDocumentSkeletonPage): boolean {
+ const parent = page.parent as IDocumentSkeletonColumnGroupColumn | undefined;
+
+ return parent?.columnId != null && parent.parent?.columnGroupId != null;
+}
+
+function getNestedPageClipOrigin(
+ parentPage: IDocumentSkeletonPage,
+ nestedPage: IDocumentSkeletonPage,
+ drawOrigin: { x: number; y: number },
+ alignOffset: Vector2
+): { x: number; y: number } {
+ if (isColumnGroupNestedPage(nestedPage)) {
+ return {
+ x: drawOrigin.x + alignOffset.x,
+ y: drawOrigin.y + alignOffset.y,
+ };
+ }
+
+ return {
+ x: drawOrigin.x + parentPage.marginLeft,
+ y: drawOrigin.y + parentPage.marginTop,
+ };
+}
+
function fillRectByPrecisionBounds(
ctx: UniverRenderingContext,
x: number,
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
index 4ca6c777e9..809b714cc0 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
@@ -17,6 +17,7 @@
import {
ColumnSeparatorType,
createDocumentModelWithStyle,
+ DataStreamTreeTokenType,
DocumentDataModel,
DocumentFlavor,
LocaleService,
@@ -80,6 +81,7 @@ function createPage(type: DocumentSkeletonPageType, st: number, tableId = '') {
tableId,
sections: [section],
skeTables: new Map(),
+ skeColumnGroups: new Map(),
} as any;
divide.parent = line;
@@ -101,6 +103,64 @@ function createPage(type: DocumentSkeletonPageType, st: number, tableId = '') {
}
describe('doc skeleton', () => {
+ it('uses empty paragraph glyphs as mouse hit-test targets', () => {
+ const body = createPage(DocumentSkeletonPageType.BODY, 0);
+ const emptyParagraphGlyph = {
+ st: 4,
+ ed: 4,
+ count: 1,
+ width: 0,
+ left: 0,
+ xOffset: 0,
+ content: '',
+ raw: DataStreamTreeTokenType.PARAGRAPH,
+ streamType: DataStreamTreeTokenType.PARAGRAPH,
+ glyphType: GlyphType.WORD,
+ } as any;
+ const emptyDivide = {
+ st: 4,
+ ed: 4,
+ left: 0,
+ glyphGroup: [emptyParagraphGlyph],
+ } as any;
+ const emptyLine = {
+ st: 4,
+ ed: 4,
+ top: 30,
+ lineHeight: 20,
+ divides: [emptyDivide],
+ } as any;
+
+ emptyParagraphGlyph.parent = emptyDivide;
+ emptyDivide.parent = emptyLine;
+ emptyLine.parent = body.column;
+ body.column.lines.push(emptyLine);
+ body.column.ed = 4;
+ body.section.ed = 4;
+ body.page.ed = 4;
+
+ const docViewModel = {
+ getDataModel: () => ({
+ documentStyle: {
+ pageSize: { width: 210, height: 297 },
+ },
+ }),
+ dispose: vi.fn(),
+ } as any;
+ const skeleton = new DocumentSkeleton(docViewModel, {} as any);
+ const skeletonData = {
+ pages: [body.page],
+ skeHeaders: new Map(),
+ skeFooters: new Map(),
+ };
+ (skeleton as any)._skeletonData = skeletonData;
+ body.page.parent = skeletonData;
+
+ const node = skeleton.findNodeByCoord(new Vector2(20, 50), PageLayoutType.VERTICAL, 0, 0);
+
+ expect(node?.node).toBe(emptyParagraphGlyph);
+ });
+
it('covers size and position search for body/header/footer/cell pages', () => {
const body = createPage(DocumentSkeletonPageType.BODY, 0);
const header = createPage(DocumentSkeletonPageType.HEADER, 200);
@@ -323,6 +383,258 @@ describe('doc skeleton', () => {
expect((skeleton as any)._findLiquid.x).toBeGreaterThanOrEqual(0);
});
+ it('finds nodes by coordinate inside column group columns', () => {
+ const body = createPage(DocumentSkeletonPageType.BODY, 0);
+ const columnPage = createPage(DocumentSkeletonPageType.CELL, 100);
+ body.column.lines = [];
+ body.page.ed = 110;
+ body.section.ed = 110;
+ body.column.ed = 110;
+ columnPage.page.pageWidth = 100;
+ columnPage.page.pageHeight = 80;
+ columnPage.page.marginLeft = 0;
+ columnPage.page.marginTop = 0;
+ columnPage.page.marginRight = 0;
+ columnPage.page.marginBottom = 0;
+ columnPage.glyphs.glyphA.left = 0;
+ columnPage.glyphs.glyphA.width = 10;
+ columnPage.divide.glyphGroup = [columnPage.glyphs.glyphA];
+
+ const columnGroup = {
+ columns: [
+ {
+ columnId: 'col-1',
+ left: 60,
+ top: 0,
+ width: 100,
+ height: 80,
+ st: 100,
+ ed: 110,
+ page: columnPage.page,
+ },
+ ],
+ width: 180,
+ height: 80,
+ top: 30,
+ left: 20,
+ st: 90,
+ ed: 110,
+ columnGroupId: 'cg-1',
+ parent: body.page,
+ } as any;
+ columnGroup.columns[0].parent = columnGroup;
+ columnPage.page.parent = columnGroup.columns[0];
+ body.page.skeColumnGroups.set('cg-1', columnGroup);
+
+ const docViewModel = {
+ getDataModel: () => ({
+ documentStyle: {
+ pageSize: { width: 210, height: 297 },
+ },
+ }),
+ getHeaderFooterTreeMap: () => ({
+ headerTreeMap: new Map(),
+ footerTreeMap: new Map(),
+ }),
+ dispose: vi.fn(),
+ } as any;
+ const skeleton = new DocumentSkeleton(docViewModel, {} as any);
+ const skeletonData = {
+ pages: [body.page],
+ skeHeaders: new Map(),
+ skeFooters: new Map(),
+ };
+ body.page.parent = skeletonData as any;
+ (skeleton as any)._skeletonData = skeletonData;
+
+ const node = skeleton.findNodeByCoord(
+ Vector2.FromArray([90, 45]),
+ PageLayoutType.VERTICAL,
+ 0,
+ 0
+ );
+
+ expect(node?.node).toBe(columnPage.glyphs.glyphA);
+ expect(skeleton.findNodeByCharIndex(100)).toBe(columnPage.glyphs.glyphA);
+ expect(skeleton.findNodePositionByCharIndex(110)?.path).toEqual([
+ 'pages',
+ 0,
+ 'skeColumnGroups',
+ 'cg-1',
+ 'columns',
+ 0,
+ 'page',
+ ]);
+ });
+
+ it('resolves char positions inside tables nested in column group columns', () => {
+ const body = createPage(DocumentSkeletonPageType.BODY, 0);
+ const columnPage = createPage(DocumentSkeletonPageType.CELL, 100);
+ const cellPage = createPage(DocumentSkeletonPageType.CELL, 130, 'nested-table');
+ body.column.lines = [];
+ body.page.ed = 150;
+ body.section.ed = 150;
+ body.column.ed = 150;
+ columnPage.page.st = 100;
+ columnPage.page.ed = 150;
+ columnPage.section.ed = 150;
+ columnPage.column.ed = 150;
+ cellPage.glyphs.glyphA.left = 0;
+ cellPage.glyphs.glyphA.width = 10;
+ cellPage.divide.glyphGroup = [cellPage.glyphs.glyphA];
+
+ const row = {
+ cells: [cellPage.page],
+ index: 0,
+ top: 0,
+ } as any;
+ const table = {
+ rows: [row],
+ tableId: 'nested-table',
+ parent: columnPage.page,
+ } as any;
+ row.parent = table;
+ cellPage.page.parent = row;
+ columnPage.page.skeTables = new Map([['nested-table', table]]);
+
+ const columnGroup = {
+ columns: [{
+ columnId: 'col-1',
+ left: 60,
+ top: 0,
+ width: 100,
+ height: 80,
+ st: 100,
+ ed: 150,
+ page: columnPage.page,
+ }],
+ width: 180,
+ height: 80,
+ top: 30,
+ left: 20,
+ st: 90,
+ ed: 150,
+ columnGroupId: 'cg-1',
+ parent: body.page,
+ } as any;
+ columnGroup.columns[0].parent = columnGroup;
+ columnPage.page.parent = columnGroup.columns[0];
+ body.page.skeColumnGroups.set('cg-1', columnGroup);
+
+ const docViewModel = {
+ getDataModel: () => ({
+ documentStyle: {
+ pageSize: { width: 210, height: 297 },
+ },
+ }),
+ getHeaderFooterTreeMap: () => ({
+ headerTreeMap: new Map(),
+ footerTreeMap: new Map(),
+ }),
+ dispose: vi.fn(),
+ } as any;
+ const skeleton = new DocumentSkeleton(docViewModel, {} as any);
+ const skeletonData = {
+ pages: [body.page],
+ skeHeaders: new Map(),
+ skeFooters: new Map(),
+ };
+ body.page.parent = skeletonData as any;
+ (skeleton as any)._skeletonData = skeletonData;
+
+ expect(skeleton.findNodeByCharIndex(130)).toBe(cellPage.glyphs.glyphA);
+ expect(skeleton.findNodePositionByCharIndex(130)?.path).toEqual([
+ 'pages',
+ 0,
+ 'skeColumnGroups',
+ 'cg-1',
+ 'columns',
+ 0,
+ 'page',
+ 'skeTables',
+ 'nested-table',
+ 'rows',
+ 0,
+ 'cells',
+ 0,
+ ]);
+ });
+
+ it('does not search column content when the coordinate is below the column group bounds', () => {
+ const body = createPage(DocumentSkeletonPageType.BODY, 0);
+ const columnPage = createPage(DocumentSkeletonPageType.CELL, 100);
+ body.line.top = 130;
+ body.page.height = 260;
+ body.page.pageHeight = 260;
+ body.page.ed = 110;
+ body.section.ed = 110;
+ body.column.ed = 110;
+ columnPage.page.pageWidth = 100;
+ columnPage.page.pageHeight = 500;
+ columnPage.page.marginLeft = 0;
+ columnPage.page.marginTop = 0;
+ columnPage.page.marginRight = 0;
+ columnPage.page.marginBottom = 0;
+ columnPage.glyphs.glyphA.left = 0;
+ columnPage.glyphs.glyphA.width = 10;
+ columnPage.divide.glyphGroup = [columnPage.glyphs.glyphA];
+
+ const columnGroup = {
+ columns: [{
+ columnId: 'col-1',
+ left: 60,
+ top: 0,
+ width: 100,
+ height: 80,
+ st: 100,
+ ed: 110,
+ page: columnPage.page,
+ }],
+ width: 180,
+ height: 80,
+ top: 30,
+ left: 20,
+ st: 90,
+ ed: 110,
+ columnGroupId: 'cg-1',
+ parent: body.page,
+ } as any;
+ columnGroup.columns[0].parent = columnGroup;
+ columnPage.page.parent = columnGroup.columns[0];
+ body.page.skeColumnGroups.set('cg-1', columnGroup);
+
+ const docViewModel = {
+ getDataModel: () => ({
+ documentStyle: {
+ pageSize: { width: 210, height: 297 },
+ },
+ }),
+ getHeaderFooterTreeMap: () => ({
+ headerTreeMap: new Map(),
+ footerTreeMap: new Map(),
+ }),
+ dispose: vi.fn(),
+ } as any;
+ const skeleton = new DocumentSkeleton(docViewModel, {} as any);
+ const skeletonData = {
+ pages: [body.page],
+ skeHeaders: new Map(),
+ skeFooters: new Map(),
+ };
+ body.page.parent = skeletonData as any;
+ (skeleton as any)._skeletonData = skeletonData;
+
+ const node = skeleton.findNodeByCoord(
+ Vector2.FromArray([170, 145]),
+ PageLayoutType.VERTICAL,
+ 0,
+ 0
+ );
+
+ expect(Object.values(body.glyphs)).toContain(node?.node);
+ expect(node?.node).not.toBe(columnPage.glyphs.glyphA);
+ });
+
it('covers continuous-section helper and index lookup fallback branches', () => {
const body = createPage(DocumentSkeletonPageType.BODY, 0);
const docViewModel = {
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts
index e8b768d88d..566f6b1d9d 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts
@@ -32,9 +32,14 @@ import { GlyphType } from '../../../../basics/i-document-skeleton-cached';
import {
clearFontCreateConfigCache,
columnIterator,
+ compareDocumentSkeletonNestedPagePathOrder,
+ documentSkeletonLineIterator,
+ documentSkeletonTableIterator,
getCharSpaceApply,
getCharSpaceConfig,
getColumnByDivide,
+ getDocumentSkeletonColumnPagePathInfo,
+ getDocumentSkeletonNestedPageOffset,
getFontConfigFromLastGlyph,
getFontCreateConfig,
getGlyphGroupWidth,
@@ -467,6 +472,7 @@ describe('docs layout tools extra', () => {
expect((mergedMin as any).a.v).toBe(3);
const pageCell = { id: 'cell-page' };
+ const columnPage = { id: 'column-page' };
const root = {
pages: [
{
@@ -474,10 +480,311 @@ describe('docs layout tools extra', () => {
skeTables: new Map([
['t1', { rows: [{ cells: [pageCell] }] }],
]),
+ skeColumnGroups: new Map([
+ ['cg1', { columns: [{ page: columnPage }] }],
+ ]),
},
],
};
expect(getPageFromPath(root as any, ['pages', 0])).toBe(root.pages[0]);
expect(getPageFromPath(root as any, ['pages', 0, 'skeTables', 't1', 'rows', 0, 'cells', 0])).toBe(pageCell);
+ expect(getPageFromPath(root as any, ['pages', 0, 'skeColumnGroups', 'cg1', 'columns', 0, 'page'])).toBe(columnPage);
+ });
+
+ it('iterates document skeleton lines with nested table and column layout context', () => {
+ const page = {
+ marginLeft: 60,
+ marginRight: 40,
+ marginTop: 10,
+ pageHeight: 800,
+ pageWidth: 600,
+ sections: [createLineSection(1, 5, 100)],
+ skeTables: new Map([['table-1', {
+ tableId: 'table-1',
+ left: 100,
+ top: 40,
+ width: 300,
+ rows: [{
+ top: 0,
+ cells: [{
+ left: 20,
+ marginLeft: 3,
+ marginRight: 2,
+ marginTop: 4,
+ pageWidth: 200,
+ sections: [createLineSection(2, 7, 80)],
+ }],
+ }],
+ }]]),
+ skeColumnGroups: new Map([['column-group-1', {
+ columnGroupId: 'column-group-1',
+ left: 20,
+ top: 120,
+ columns: [{
+ left: 200,
+ top: 0,
+ width: 300,
+ page: {
+ marginLeft: 0,
+ marginRight: 0,
+ marginTop: 0,
+ pageHeight: 80,
+ pageWidth: 160,
+ sections: [createLineSection(3, 10, 120)],
+ },
+ }],
+ }]]),
+ };
+
+ const contexts: unknown[] = [];
+ documentSkeletonLineIterator([page as any], {
+ docsLeft: 0,
+ pageMarginTop: 30,
+ tableCellInsetX: 6,
+ unitId: 'doc-1',
+ }, (context) => contexts.push({
+ paragraphIndex: context.line.paragraphIndex,
+ pageIndex: context.pageIndex,
+ pageLeft: context.pageLeft,
+ sectionTop: context.sectionTop,
+ source: context.source,
+ visualLeft: context.visualLeft,
+ visualWidth: context.visualWidth,
+ clipLeft: context.clipLeft,
+ clipRight: context.clipRight,
+ }));
+
+ expect(contexts).toEqual([
+ {
+ clipLeft: undefined,
+ clipRight: undefined,
+ pageIndex: 0,
+ pageLeft: 60,
+ paragraphIndex: 1,
+ sectionTop: 10,
+ source: 'page',
+ visualLeft: 65,
+ visualWidth: 495,
+ },
+ {
+ clipLeft: 160,
+ clipRight: 378,
+ pageIndex: 0,
+ pageLeft: 183,
+ paragraphIndex: 2,
+ sectionTop: 54,
+ source: 'table-cell',
+ visualLeft: 189,
+ visualWidth: 183,
+ },
+ {
+ clipLeft: undefined,
+ clipRight: undefined,
+ pageIndex: 0,
+ pageLeft: 280,
+ paragraphIndex: 3,
+ sectionTop: 130,
+ source: 'column',
+ visualLeft: 290,
+ visualWidth: 290,
+ },
+ ]);
+ });
+
+ it('iterates top-level and column nested tables with document geometry', () => {
+ const page = {
+ marginLeft: 60,
+ marginRight: 40,
+ marginTop: 10,
+ pageHeight: 800,
+ pageWidth: 600,
+ sections: [createLineSection(1, 5, 100)],
+ skeTables: new Map([['table-1', {
+ tableId: 'table-1',
+ left: 100,
+ top: 40,
+ width: 300,
+ height: 44,
+ rows: [{
+ top: 0,
+ height: 44,
+ index: 0,
+ cells: [{
+ left: 20,
+ marginLeft: 3,
+ marginRight: 2,
+ marginTop: 4,
+ marginBottom: 5,
+ pageWidth: 200,
+ pageHeight: 44,
+ sections: [createLineSection(2, 7, 80)],
+ }],
+ }],
+ }]]),
+ skeColumnGroups: new Map([['column-group-1', {
+ columnGroupId: 'column-group-1',
+ left: 20,
+ top: 120,
+ columns: [{
+ left: 200,
+ top: 8,
+ width: 300,
+ page: {
+ marginLeft: 4,
+ marginRight: 6,
+ marginTop: 6,
+ pageHeight: 80,
+ pageWidth: 160,
+ sections: [createLineSection(3, 10, 120)],
+ skeTables: new Map([['nested-table-1', {
+ tableId: 'nested-table-1',
+ left: 12,
+ top: 14,
+ width: 120,
+ height: 36,
+ rows: [{
+ top: 0,
+ height: 36,
+ index: 0,
+ cells: [{
+ left: 10,
+ marginLeft: 2,
+ marginRight: 3,
+ marginTop: 5,
+ marginBottom: 4,
+ pageWidth: 60,
+ pageHeight: 36,
+ sections: [createLineSection(4, 9, 50)],
+ }],
+ }],
+ }]]),
+ },
+ }],
+ }]]),
+ };
+
+ const tables = Array.from(documentSkeletonTableIterator([page as any], {
+ docsLeft: 7,
+ docsTop: 9,
+ pageMarginTop: 30,
+ tableCellInsetX: 6,
+ unitId: 'doc-1',
+ }));
+
+ expect(tables.map((context) => ({
+ cells: context.cells.map((cell) => ({
+ cellRect: cell.cellRect,
+ clipLeft: cell.clipLeft,
+ clipRight: cell.clipRight,
+ visualLeft: cell.visualLeft,
+ visualWidth: cell.visualWidth,
+ })),
+ pageIndex: context.pageIndex,
+ source: context.source,
+ tableId: context.table.tableId,
+ tableRect: context.tableRect,
+ }))).toEqual([
+ {
+ cells: [{
+ cellRect: { bottom: 98, left: 190, right: 385, top: 63 },
+ clipLeft: 167,
+ clipRight: 385,
+ visualLeft: 196,
+ visualWidth: 183,
+ }],
+ pageIndex: 0,
+ source: 'page',
+ tableId: 'table-1',
+ tableRect: { bottom: 103, left: 167, right: 467, top: 59 },
+ },
+ {
+ cells: [{
+ cellRect: { bottom: 199, left: 315, right: 370, top: 172 },
+ clipLeft: 303,
+ clipRight: 370,
+ visualLeft: 321,
+ visualWidth: 43,
+ }],
+ pageIndex: 0,
+ source: 'column',
+ tableId: 'nested-table-1',
+ tableRect: { bottom: 203, left: 303, right: 423, top: 167 },
+ },
+ ]);
+ });
+
+ it('resolves column child page offsets from skeleton parents', () => {
+ const columnPage = {};
+ const column = {
+ left: 60,
+ page: columnPage,
+ top: 4,
+ };
+ const columnGroup = {
+ columnGroupId: 'cg-1',
+ columns: [column],
+ left: 20,
+ top: 30,
+ };
+ (columnPage as { parent?: unknown }).parent = column;
+ (column as { parent?: unknown }).parent = columnGroup;
+
+ expect(getDocumentSkeletonNestedPageOffset(columnPage as never)).toEqual({
+ left: 80,
+ top: 34,
+ });
+ expect(getDocumentSkeletonNestedPageOffset({ parent: { cells: [] } } as never)).toBeUndefined();
+ });
+
+ it('compares nested column page paths within the same column group', () => {
+ const firstColumn = {
+ path: ['pages', 0, 'skeColumnGroups', 'cg-1', 'columns', 0, 'page'],
+ };
+ const secondColumn = {
+ path: ['pages', 0, 'skeColumnGroups', 'cg-1', 'columns', 1, 'page'],
+ };
+ const otherGroup = {
+ path: ['pages', 0, 'skeColumnGroups', 'cg-2', 'columns', 0, 'page'],
+ };
+ const body = {
+ path: ['pages', 0],
+ };
+
+ expect(compareDocumentSkeletonNestedPagePathOrder(firstColumn as never, secondColumn as never)).toBe(true);
+ expect(compareDocumentSkeletonNestedPagePathOrder(secondColumn as never, firstColumn as never)).toBe(false);
+ expect(compareDocumentSkeletonNestedPagePathOrder(firstColumn as never, otherGroup as never)).toBeUndefined();
+ expect(compareDocumentSkeletonNestedPagePathOrder(firstColumn as never, body as never)).toBeUndefined();
+ });
+
+ it('parses nested column page paths through one shared helper', () => {
+ expect(getDocumentSkeletonColumnPagePathInfo({
+ path: ['pages', 2, 'skeColumnGroups', 'cg-1', 'columns', 3, 'page'],
+ })).toEqual({
+ columnGroupId: 'cg-1',
+ columnIndex: 3,
+ pageIndex: 2,
+ });
+ expect(getDocumentSkeletonColumnPagePathInfo({
+ path: ['pages', 2, 'skeTables', 'table-1', 'rows', 0, 'cells', 0],
+ })).toBeUndefined();
});
});
+
+function createLineSection(paragraphIndex: number, columnLeft: number, columnWidth: number) {
+ return {
+ top: 0,
+ columns: [{
+ left: columnLeft,
+ width: columnWidth,
+ lines: [{
+ lineHeight: 24,
+ marginBottom: 0,
+ marginTop: 0,
+ paddingBottom: 0,
+ paddingTop: 0,
+ paragraphIndex,
+ top: 0,
+ }],
+ }],
+ };
+}
diff --git a/packages/engine-render/src/components/docs/layout/block/__tests__/section.spec.ts b/packages/engine-render/src/components/docs/layout/block/__tests__/section.spec.ts
index 35deef61eb..31ae7901b3 100644
--- a/packages/engine-render/src/components/docs/layout/block/__tests__/section.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/__tests__/section.spec.ts
@@ -15,9 +15,10 @@
*/
import type { IDocumentSkeletonPage } from '../../../../../basics/i-document-skeleton-cached';
-import { DataStreamTreeNodeType } from '@univerjs/core';
+import { BooleanNumber, ColumnLayoutType, ColumnResponsiveType, DataStreamTreeNodeType, DataStreamTreeTokenType, DocumentBlockRangeType, TableAlignmentType, TableRowHeightRule, TableSizeType, TableTextWrapType, VerticalAlignmentType } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
import { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';
+import { updateBlockIndex } from '../../tools';
import { createSectionLayoutTestBed } from '../paragraph/__tests__/create-paragraph-layout-test-bed';
import { dealWithSection } from '../section';
@@ -118,6 +119,323 @@ describe('section', () => {
expect(result.pages.length).toBeGreaterThanOrEqual(2);
});
+ it('lays out column group blocks into page skeleton columns', () => {
+ const dataStream = [
+ DataStreamTreeTokenType.COLUMN_GROUP_START,
+ DataStreamTreeTokenType.COLUMN_START,
+ 'Left',
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_START,
+ 'Right',
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_END,
+ DataStreamTreeTokenType.SECTION_BREAK,
+ ].join('');
+ const { ctx, viewModel, sectionNode, curPage, sectionBreakConfig } =
+ createSectionLayoutTestBed(['unused'], {
+ body: {
+ dataStream,
+ paragraphs: [
+ { startIndex: 5, paragraphId: 'left' },
+ { startIndex: 12, paragraphId: 'right' },
+ ],
+ sectionBreaks: [{ startIndex: dataStream.length - 1 }],
+ columnGroups: [{
+ startIndex: 0,
+ endIndex: dataStream.length - 1,
+ columnGroupId: 'cg-1',
+ gap: { v: 12 },
+ layout: ColumnLayoutType.FIXED,
+ responsive: ColumnResponsiveType.SHRINK,
+ columns: [
+ { columnId: 'left-col', widthRatio: 1, minWidth: { v: 40 } },
+ { columnId: 'right-col', widthRatio: 1, minWidth: { v: 40 } },
+ ],
+ }],
+ },
+ });
+
+ const result = dealWithSection(ctx, viewModel, sectionNode, curPage, sectionBreakConfig, null);
+ const page = result.pages[0];
+ const columnGroup = page.skeColumnGroups.get('cg-1');
+
+ expect(columnGroup).toBeTruthy();
+ if (columnGroup == null) {
+ throw new Error('Expected column group skeleton to be created');
+ }
+
+ expect(columnGroup).toMatchObject({
+ columnGroupId: 'cg-1',
+ left: 0,
+ width: 266.66666666666663,
+ columns: [
+ { columnId: 'left-col', left: 0, width: 127.33333333333331 },
+ { columnId: 'right-col', left: 139.33333333333331, width: 127.33333333333331 },
+ ],
+ });
+ expect(columnGroup.height).toBeGreaterThan(0);
+ expect(columnGroup.columns[0].page.sections[0].columns[0].lines.length).toBeGreaterThan(0);
+ expect(page.sections[0].columns[0].lines.at(-1)).toMatchObject({
+ paragraphIndex: columnGroup.ed,
+ lineHeight: columnGroup.height,
+ });
+ });
+
+ it('reserves visible height for empty column group blocks', () => {
+ const dataStream = [
+ DataStreamTreeTokenType.COLUMN_GROUP_START,
+ DataStreamTreeTokenType.COLUMN_START,
+ ' ',
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_START,
+ ' ',
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_END,
+ DataStreamTreeTokenType.SECTION_BREAK,
+ ].join('');
+ const { ctx, viewModel, sectionNode, curPage, sectionBreakConfig } =
+ createSectionLayoutTestBed(['unused'], {
+ body: {
+ dataStream,
+ paragraphs: [
+ { startIndex: 3, paragraphId: 'left' },
+ { startIndex: 7, paragraphId: 'right' },
+ ],
+ sectionBreaks: [{ startIndex: dataStream.length - 1 }],
+ columnGroups: [{
+ startIndex: 0,
+ endIndex: dataStream.length - 1,
+ columnGroupId: 'cg-empty',
+ gap: { v: 12 },
+ layout: ColumnLayoutType.FIXED,
+ responsive: ColumnResponsiveType.SHRINK,
+ columns: [
+ { columnId: 'left-col', widthRatio: 1, minWidth: { v: 40 } },
+ { columnId: 'right-col', widthRatio: 1, minWidth: { v: 40 } },
+ ],
+ }],
+ },
+ });
+
+ const result = dealWithSection(ctx, viewModel, sectionNode, curPage, sectionBreakConfig, null);
+ const page = result.pages[0];
+ const columnGroup = page.skeColumnGroups.get('cg-empty');
+
+ expect(columnGroup?.height).toBe(72);
+ expect(columnGroup?.columns.map((column) => column.height)).toEqual([72, 72]);
+ expect(columnGroup?.columns.map((column) => column.page.sections[0].columns[0].lines.length)).toEqual([1, 1]);
+ expect(columnGroup?.columns.map((column) =>
+ column.page.sections[0].columns[0].lines[0].divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content))
+ )).toEqual([[' ', DataStreamTreeTokenType.PARAGRAPH], [' ', DataStreamTreeTokenType.PARAGRAPH]]);
+ expect(page.sections[0].columns[0].lines.at(-1)).toMatchObject({
+ lineHeight: 72,
+ paragraphIndex: columnGroup?.ed,
+ });
+ });
+
+ it('pushes following paragraph lines below an empty column group block', () => {
+ const dataStream = [
+ DataStreamTreeTokenType.COLUMN_GROUP_START,
+ DataStreamTreeTokenType.COLUMN_START,
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_START,
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_END,
+ 'After',
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.SECTION_BREAK,
+ ].join('');
+ const { ctx, viewModel, sectionNode, curPage, sectionBreakConfig } =
+ createSectionLayoutTestBed(['unused'], {
+ body: {
+ dataStream,
+ paragraphs: [
+ { startIndex: 2, paragraphId: 'left' },
+ { startIndex: 5, paragraphId: 'right' },
+ { startIndex: 13, paragraphId: 'after' },
+ ],
+ sectionBreaks: [{ startIndex: dataStream.length - 1 }],
+ columnGroups: [{
+ startIndex: 0,
+ endIndex: 7,
+ columnGroupId: 'cg-empty-flow',
+ gap: { v: 12 },
+ layout: ColumnLayoutType.FIXED,
+ responsive: ColumnResponsiveType.SHRINK,
+ columns: [
+ { columnId: 'left-col', widthRatio: 1, minWidth: { v: 40 } },
+ { columnId: 'right-col', widthRatio: 1, minWidth: { v: 40 } },
+ ],
+ }],
+ },
+ });
+
+ const result = dealWithSection(ctx, viewModel, sectionNode, curPage, sectionBreakConfig, null);
+ updateBlockIndex(result.pages);
+ const page = result.pages[0];
+ const columnGroup = page.skeColumnGroups.get('cg-empty-flow');
+ const lines = page.sections[0].columns[0].lines;
+ const columnGroupLine = lines.find((line) => line.paragraphIndex === columnGroup?.ed);
+ const followingParagraphLine = lines.find((line) => line.paragraphIndex === 13);
+
+ expect(columnGroup?.height).toBe(72);
+ expect(columnGroupLine).toMatchObject({
+ top: columnGroup?.top,
+ lineHeight: 72,
+ st: 0,
+ ed: 7,
+ });
+ expect(followingParagraphLine).toMatchObject({
+ st: 8,
+ ed: 14,
+ });
+ expect(followingParagraphLine?.top).toBeGreaterThanOrEqual(columnGroupLine!.top + columnGroupLine!.lineHeight);
+ });
+
+ it('lays out tables inside column content pages', () => {
+ const T = DataStreamTreeTokenType;
+ const dataStream = [
+ T.COLUMN_GROUP_START,
+ T.COLUMN_START,
+ T.TABLE_START,
+ T.TABLE_ROW_START,
+ T.TABLE_CELL_START,
+ 'H',
+ T.PARAGRAPH,
+ T.SECTION_BREAK,
+ T.TABLE_CELL_END,
+ T.TABLE_ROW_END,
+ T.TABLE_END,
+ T.PARAGRAPH,
+ T.COLUMN_END,
+ T.COLUMN_START,
+ T.PARAGRAPH,
+ T.COLUMN_END,
+ T.COLUMN_GROUP_END,
+ T.SECTION_BREAK,
+ ].join('');
+ const { ctx, viewModel, sectionNode, curPage, sectionBreakConfig } =
+ createSectionLayoutTestBed(['unused'], {
+ body: {
+ dataStream,
+ paragraphs: [
+ { startIndex: 6, paragraphId: 'table-cell-para' },
+ { startIndex: 11, paragraphId: 'after-table-para' },
+ { startIndex: 14, paragraphId: 'right-column-para' },
+ ],
+ sectionBreaks: [
+ { startIndex: 7 },
+ { startIndex: dataStream.length - 1 },
+ ],
+ tables: [{ startIndex: 2, endIndex: 11, tableId: 'table-in-column' }],
+ columnGroups: [{
+ startIndex: 0,
+ endIndex: 16,
+ columnGroupId: 'cg-table',
+ gap: { v: 12 },
+ layout: ColumnLayoutType.FIXED,
+ responsive: ColumnResponsiveType.SHRINK,
+ columns: [
+ { columnId: 'left-col', widthRatio: 1, minWidth: { v: 40 } },
+ { columnId: 'right-col', widthRatio: 1, minWidth: { v: 40 } },
+ ],
+ }],
+ },
+ tableSource: {
+ 'table-in-column': {
+ tableId: 'table-in-column',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: {} as never,
+ dist: {} as never,
+ size: { type: TableSizeType.SPECIFIED, width: { v: 120 } },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 120 } } }],
+ tableRows: [{
+ repeatHeaderRow: BooleanNumber.FALSE,
+ trHeight: {
+ hRule: TableRowHeightRule.AT_LEAST,
+ val: { v: 30 },
+ },
+ tableCells: [{ vAlign: VerticalAlignmentType.TOP }],
+ }],
+ },
+ },
+ });
+
+ const result = dealWithSection(ctx, viewModel, sectionNode, curPage, sectionBreakConfig, null);
+ const columnGroup = result.pages[0].skeColumnGroups.get('cg-table');
+ const table = columnGroup?.columns[0].page.skeTables.get('table-in-column');
+
+ expect(columnGroup).toBeTruthy();
+ expect(table).toBeTruthy();
+ expect(table?.rows).toHaveLength(1);
+ expect(table?.left).toBe(0);
+ expect(columnGroup?.height).toBeGreaterThanOrEqual(table?.height ?? 0);
+ });
+
+ it('adds trailing block range spacing to the column page when the block range is the last column element', () => {
+ const dataStream = [
+ DataStreamTreeTokenType.COLUMN_GROUP_START,
+ DataStreamTreeTokenType.COLUMN_START,
+ 'Column block range line one',
+ DataStreamTreeTokenType.PARAGRAPH,
+ 'Column block range line two',
+ DataStreamTreeTokenType.PARAGRAPH,
+ 'Column block range line three',
+ DataStreamTreeTokenType.PARAGRAPH,
+ 'Column block range line four',
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_END,
+ DataStreamTreeTokenType.SECTION_BREAK,
+ ].join('');
+ const { ctx, viewModel, sectionNode, curPage, sectionBreakConfig } =
+ createSectionLayoutTestBed(['unused'], {
+ body: {
+ dataStream,
+ paragraphs: [
+ { startIndex: 30, paragraphId: 'column-block-1' },
+ { startIndex: 58, paragraphId: 'column-block-2' },
+ { startIndex: 88, paragraphId: 'column-block-3' },
+ { startIndex: 117, paragraphId: 'column-block-4' },
+ ],
+ sectionBreaks: [{ startIndex: dataStream.length - 1 }],
+ blockRanges: [{
+ blockId: 'callout-column-1',
+ blockType: DocumentBlockRangeType.CALLOUT,
+ startIndex: 1,
+ endIndex: dataStream.length - 3,
+ }],
+ columnGroups: [{
+ startIndex: 0,
+ endIndex: dataStream.length - 1,
+ columnGroupId: 'cg-block-range',
+ gap: { v: 12 },
+ layout: ColumnLayoutType.FIXED,
+ responsive: ColumnResponsiveType.SHRINK,
+ columns: [
+ { columnId: 'left-col', widthRatio: 1, minWidth: { v: 40 } },
+ ],
+ }],
+ },
+ });
+
+ const result = dealWithSection(ctx, viewModel, sectionNode, curPage, sectionBreakConfig, null);
+ const columnPage = result.pages[0].skeColumnGroups.get('cg-block-range')?.columns[0].page;
+ const lastLine = columnPage?.sections[0].columns[0].lines.at(-1);
+
+ expect(lastLine?.paragraphIndex).toBeGreaterThan(1);
+ expect(lastLine?.paragraphIndex).toBeLessThan(dataStream.length - 3);
+ expect(columnPage?.height).toBeGreaterThan((lastLine?.top ?? 0) + (lastLine?.lineHeight ?? 0));
+ });
+
it('handles an empty section', () => {
const { ctx, viewModel, curPage, sectionBreakConfig } =
createSectionLayoutTestBed(['Hello']);
diff --git a/packages/engine-render/src/components/docs/layout/block/column.ts b/packages/engine-render/src/components/docs/layout/block/column.ts
new file mode 100644
index 0000000000..db5e723271
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/block/column.ts
@@ -0,0 +1,322 @@
+/**
+ * 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 { IColumn, IColumnGroup, Nullable } from '@univerjs/core';
+import type { IDocumentSkeletonColumnGroup, IDocumentSkeletonColumnGroupColumn, IDocumentSkeletonLine, IDocumentSkeletonPage } from '../../../../basics/i-document-skeleton-cached';
+import type { ISectionBreakConfig } from '../../../../basics/interfaces';
+import type { DataStreamTreeNode } from '../../view-model/data-stream-tree-node';
+import type { DocumentViewModel } from '../../view-model/document-view-model';
+import type { ILayoutContext } from '../tools';
+import { ColumnResponsiveType, DataStreamTreeNodeType } from '@univerjs/core';
+import { DocumentSkeletonPageType, LineType } from '../../../../basics/i-document-skeleton-cached';
+import { applyTrailingBlockRangeSpaceBelow, createSkeletonPage } from '../model/page';
+import { getLastNotFullColumnInfo, updateBlockIndex } from '../tools';
+import { dealWidthParagraph } from './paragraph/paragraph-layout';
+
+interface IColumnGroupLayoutColumn {
+ columnId: string;
+ left: number;
+ top: number;
+ width: number;
+}
+
+interface IColumnGroupLayout {
+ mode: 'horizontal' | 'stack';
+ width: number;
+ height: number;
+ columns: IColumnGroupLayoutColumn[];
+}
+
+const EMPTY_COLUMN_GROUP_MIN_HEIGHT = 72;
+
+export function createColumnGroupSkeleton(
+ ctx: ILayoutContext,
+ curPage: IDocumentSkeletonPage,
+ viewModel: DocumentViewModel,
+ columnGroupNode: DataStreamTreeNode,
+ sectionBreakConfig: ISectionBreakConfig
+): Nullable<IDocumentSkeletonColumnGroup> {
+ const columnGroupSource = viewModel.getColumnGroupByStartIndex(columnGroupNode.startIndex)?.columnGroupSource;
+ if (columnGroupSource == null) {
+ console.warn('Column group not found when creating column group skeleton');
+ return null;
+ }
+
+ const hostColumn = getLastNotFullColumnInfo(curPage)?.column;
+ if (hostColumn == null) {
+ return null;
+ }
+
+ const columnPages = columnGroupNode.children.map((columnNode, index) => {
+ const sourceColumn = columnGroupSource.columns[index];
+ const width = Math.max(0, getInitialColumnWidth(columnGroupSource, sourceColumn, hostColumn.width));
+
+ return createColumnContentPage(ctx, viewModel, columnNode, sectionBreakConfig, width);
+ });
+ const columnHeights = columnPages.map((page) => Math.max(page.height, EMPTY_COLUMN_GROUP_MIN_HEIGHT));
+ const layout = calculateColumnGroupLayout(columnGroupSource, hostColumn.width, columnHeights);
+ const columns = layout.columns.map((layoutColumn, index): IDocumentSkeletonColumnGroupColumn => {
+ const page = columnPages[index];
+ page.pageHeight = columnHeights[index];
+
+ return {
+ columnId: layoutColumn.columnId,
+ left: layoutColumn.left,
+ top: layoutColumn.top,
+ width: layoutColumn.width,
+ height: columnHeights[index],
+ st: columnGroupNode.children[index].startIndex,
+ ed: columnGroupNode.children[index].endIndex,
+ page,
+ };
+ });
+
+ const columnGroupSkeleton: IDocumentSkeletonColumnGroup = {
+ columns,
+ width: layout.width,
+ height: layout.height,
+ top: getNextBlockTop(hostColumn.lines),
+ left: hostColumn.left,
+ st: columnGroupNode.startIndex,
+ ed: columnGroupNode.endIndex,
+ columnGroupId: columnGroupSource.columnGroupId,
+ columnGroupSource,
+ };
+
+ columns.forEach((column) => {
+ column.parent = columnGroupSkeleton;
+ column.page.parent = column as never;
+ });
+
+ return columnGroupSkeleton;
+}
+
+export function appendColumnGroupBlockLine(page: IDocumentSkeletonPage, columnGroup: IDocumentSkeletonColumnGroup): boolean {
+ const columnInfo = getLastNotFullColumnInfo(page);
+ if (columnInfo == null) {
+ return false;
+ }
+
+ const { column } = columnInfo;
+ const line = createColumnGroupBlockLine(columnGroup, column.lines.length);
+ line.parent = column;
+ column.lines.push(line);
+
+ page.skeColumnGroups.set(columnGroup.columnGroupId, columnGroup);
+ columnGroup.parent = page;
+
+ return true;
+}
+
+function createColumnContentPage(
+ ctx: ILayoutContext,
+ viewModel: DocumentViewModel,
+ columnNode: DataStreamTreeNode,
+ sectionBreakConfig: ISectionBreakConfig,
+ width: number
+): IDocumentSkeletonPage {
+ const columnSectionBreakConfig: ISectionBreakConfig = {
+ ...sectionBreakConfig,
+ pageSize: {
+ width,
+ height: Number.POSITIVE_INFINITY,
+ },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ columnProperties: [],
+ };
+ const page = createSkeletonPage(ctx, columnSectionBreakConfig, ctx.skeletonResourceReference);
+ page.type = DocumentSkeletonPageType.CELL;
+
+ for (const paragraphNode of getColumnParagraphNodes(columnNode)) {
+ dealWidthParagraph(ctx, viewModel, paragraphNode, page, columnSectionBreakConfig);
+ }
+
+ updateBlockIndex([page], columnNode.startIndex);
+ applyTrailingBlockRangeSpaceBelow([page], ctx.dataModel?.getBody?.(), columnNode.endIndex);
+
+ return page;
+}
+
+function getColumnParagraphNodes(columnNode: DataStreamTreeNode): DataStreamTreeNode[] {
+ const firstChild = columnNode.children[0];
+ if (firstChild?.nodeType === DataStreamTreeNodeType.SECTION_BREAK) {
+ return firstChild.children;
+ }
+
+ return columnNode.children;
+}
+
+function createColumnGroupBlockLine(columnGroup: IDocumentSkeletonColumnGroup, lineIndex: number): IDocumentSkeletonLine {
+ const top = columnGroup.top;
+
+ return {
+ paragraphIndex: columnGroup.ed,
+ type: LineType.BLOCK,
+ divides: [],
+ divideLen: 0,
+ lineHeight: columnGroup.height,
+ contentHeight: columnGroup.height,
+ top,
+ asc: 0,
+ dsc: 0,
+ paddingTop: 0,
+ paddingBottom: 0,
+ marginTop: 0,
+ marginBottom: 0,
+ spaceBelowApply: 0,
+ st: columnGroup.st,
+ ed: columnGroup.ed,
+ lineIndex,
+ paragraphStart: true,
+ isBehindTable: false,
+ tableId: '',
+ };
+}
+
+function getNextBlockTop(lines: IDocumentSkeletonLine[]) {
+ const lastLine = lines[lines.length - 1];
+ if (lastLine == null) {
+ return 0;
+ }
+
+ return lastLine.top + lastLine.lineHeight;
+}
+
+function calculateColumnGroupLayout(source: IColumnGroup, availableWidth: number, columnHeights: number[]): IColumnGroupLayout {
+ const width = Math.max(0, availableWidth);
+ const gap = Math.max(0, source.gap?.v ?? 0);
+ const columns = source.columns;
+ if (columns.length === 0) {
+ return {
+ mode: 'horizontal',
+ width,
+ height: 0,
+ columns: [],
+ };
+ }
+
+ if (shouldStack(columns, width, gap, source.responsive)) {
+ let top = 0;
+
+ return {
+ mode: 'stack',
+ width,
+ height: sumHeights(columnHeights),
+ columns: columns.map((column, index) => {
+ const layoutColumn = {
+ columnId: column.columnId,
+ left: 0,
+ top,
+ width,
+ };
+ top += Math.max(0, columnHeights[index] ?? 0);
+
+ return layoutColumn;
+ }),
+ };
+ }
+
+ const contentWidth = Math.max(0, width - gap * (columns.length - 1));
+ const widths = allocateHorizontalWidths(columns, contentWidth);
+ let left = 0;
+
+ return {
+ mode: 'horizontal',
+ width,
+ height: Math.max(0, ...columnHeights),
+ columns: columns.map((column, index) => {
+ const layoutColumn = {
+ columnId: column.columnId,
+ left,
+ top: 0,
+ width: widths[index],
+ };
+ left += widths[index] + gap;
+
+ return layoutColumn;
+ }),
+ };
+}
+
+function shouldStack(columns: IColumn[], availableWidth: number, gap: number, responsive: ColumnResponsiveType): boolean {
+ if (responsive !== ColumnResponsiveType.STACK) {
+ return false;
+ }
+
+ const totalMinWidth = columns.reduce((sum, column) => sum + getMinWidth(column), 0) + gap * Math.max(0, columns.length - 1);
+
+ return totalMinWidth > availableWidth;
+}
+
+function getInitialColumnWidth(source: IColumnGroup, column: IColumn | undefined, availableWidth: number): number {
+ if (column == null) {
+ return availableWidth;
+ }
+
+ const contentWidth = Math.max(0, availableWidth - Math.max(0, source.gap?.v ?? 0) * Math.max(0, source.columns.length - 1));
+ const ratioSum = source.columns.reduce((sum, item) => sum + Math.max(0, item.widthRatio || 0), 0) || source.columns.length;
+
+ return Math.max(getMinWidth(column), contentWidth * (Math.max(0, column.widthRatio || 0) || 1) / ratioSum);
+}
+
+function allocateHorizontalWidths(columns: IColumn[], contentWidth: number): number[] {
+ const ratioSum = columns.reduce((sum, column) => sum + Math.max(0, column.widthRatio || 0), 0) || columns.length;
+ const idealWidths = columns.map((column) => contentWidth * (Math.max(0, column.widthRatio || 0) || 1) / ratioSum);
+ const minWidths = columns.map(getMinWidth);
+ const widths = idealWidths.map((width, index) => Math.max(width, minWidths[index]));
+ const overflow = widths.reduce((sum, width) => sum + width, 0) - contentWidth;
+
+ if (overflow <= 0) {
+ return widths;
+ }
+
+ return compressToFit(widths, minWidths, overflow);
+}
+
+function compressToFit(widths: number[], minWidths: number[], overflow: number): number[] {
+ const nextWidths = [...widths];
+ let remainingOverflow = overflow;
+ let flexibleIndexes = getFlexibleIndexes(nextWidths, minWidths);
+
+ while (remainingOverflow > 0 && flexibleIndexes.length > 0) {
+ const totalShrink = flexibleIndexes.reduce((sum, item) => sum + item.shrink, 0);
+ for (const item of flexibleIndexes) {
+ const shrink = Math.min(item.shrink, remainingOverflow * item.shrink / totalShrink);
+ nextWidths[item.index] -= shrink;
+ remainingOverflow -= shrink;
+ }
+ flexibleIndexes = getFlexibleIndexes(nextWidths, minWidths);
+ }
+
+ return nextWidths;
+}
+
+function getFlexibleIndexes(widths: number[], minWidths: number[]) {
+ return widths
+ .map((width, index) => ({ index, shrink: Math.max(0, width - minWidths[index]) }))
+ .filter((item) => item.shrink > 0);
+}
+
+function getMinWidth(column: IColumn): number {
+ return Math.max(0, column.minWidth?.v ?? 0);
+}
+
+function sumHeights(heights: number[]): number {
+ return heights.reduce((sum, height) => sum + Math.max(0, height), 0);
+}
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts
index a8fa6e8ba0..233c84063f 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts
@@ -17,6 +17,7 @@
import { BooleanNumber, DataStreamTreeTokenType, PositionedObjectLayoutType } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
import { Lang } from '../../../hyphenation/lang';
+import { createSkeletonLetterGlyph } from '../../../model/glyph';
import { fontLibrary } from '../../../shaping-engine/font-library';
import * as textShapingModule from '../../../shaping-engine/text-shaping';
import { shaping } from '../shaping';
@@ -253,6 +254,26 @@ describe('shaping', () => {
expect(customBlockGlyph!.width).toBe(0);
});
+ it('shapes column group tokens as zero-width placeholders', () => {
+ const columnTokens = [
+ DataStreamTreeTokenType.COLUMN_GROUP_START,
+ DataStreamTreeTokenType.COLUMN_START,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_END,
+ ];
+ for (const token of columnTokens) {
+ const glyph = createSkeletonLetterGlyph(token, {
+ fontStyle: {},
+ textStyle: {},
+ } as any);
+
+ expect(glyph.raw).toBe(token);
+ expect(glyph.streamType).toBe(token);
+ expect(glyph.width).toBe(0);
+ expect(glyph.content).toBe('');
+ }
+ });
+
it('shapes text with useOpenType when font library is ready', () => {
const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('Hello');
const originalIsReady = fontLibrary.isReady;
diff --git a/packages/engine-render/src/components/docs/layout/block/section.ts b/packages/engine-render/src/components/docs/layout/block/section.ts
index bcbf415a61..d35b3fd606 100644
--- a/packages/engine-render/src/components/docs/layout/block/section.ts
+++ b/packages/engine-render/src/components/docs/layout/block/section.ts
@@ -23,6 +23,7 @@ import type { ILayoutContext } from '../tools';
import { DataStreamTreeNodeType } from '@univerjs/core';
import { createSkeletonPage } from '../model/page';
import { dealWithBlockError } from './block-error';
+import { appendColumnGroupBlockLine, createColumnGroupSkeleton } from './column';
import { dealWidthParagraph } from './paragraph/paragraph-layout';
export function dealWithSection(
@@ -82,6 +83,20 @@ export function dealWithSection(
);
}
+ if (paragraphNode.nodeType === DataStreamTreeNodeType.COLUMN_GROUP) {
+ const columnGroupSkeleton = createColumnGroupSkeleton(
+ ctx,
+ currentPageCache,
+ viewModel,
+ paragraphNode,
+ sectionBreakConfig
+ );
+
+ if (columnGroupSkeleton && appendColumnGroupBlockLine(currentPageCache, columnGroupSkeleton)) {
+ skeletonPages = [currentPageCache];
+ }
+ }
+
if (skeletonPages.length === 0) {
skeletonPages = dealWithBlockError();
}
diff --git a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
index 0dd2eec96b..670b032e91 100644
--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
@@ -25,7 +25,7 @@ import type { IDocsConfig, INodeInfo, INodePosition, INodeSearch } from '../../.
import type { IViewportInfo, Vector2 } from '../../../basics/vector2';
import type { DocumentViewModel } from '../view-model/document-view-model';
import type { ILayoutContext } from './tools';
-import { PRESET_LIST_TYPE, SectionType, Skeleton } from '@univerjs/core';
+import { DataStreamTreeTokenType, PRESET_LIST_TYPE, SectionType, Skeleton } from '@univerjs/core';
import { Subject } from 'rxjs';
import {
DocumentSkeletonPageType,
@@ -33,12 +33,12 @@ import {
LineType,
PageLayoutType,
} from '../../../basics/i-document-skeleton-cached';
+import { getDocumentCompatibilityPolicy } from '../document-compatibility';
import { Liquid } from '../liquid';
import { getDocsTableRenderViewport, hasDocsTableHorizontalViewport } from '../table-render-viewport';
import { DocumentEditArea } from '../view-model/document-view-model';
import { dealWithSection } from './block/section';
import { getTableIdAndSliceIndex } from './block/table';
-import { getDocumentCompatibilityPolicy } from '../document-compatibility';
import { Hyphen } from './hyphenation/hyphen';
import { LanguageDetector } from './hyphenation/language-detector';
import { createSkeletonPage } from './model/page';
@@ -97,6 +97,18 @@ function getPagePath(page: IDocumentSkeletonPage) {
// eslint-disable-next-line ts/no-explicit-any
let parent: any = skeNode.parent;
while (parent) {
+ if (parent.page === skeNode && parent.parent?.columns) {
+ const index = parent.parent.columns.indexOf(parent);
+
+ if (index !== -1) {
+ path.unshift('columns', index, 'page');
+ }
+
+ skeNode = parent.parent;
+ parent = skeNode?.parent;
+ continue;
+ }
+
if (parent.pages) {
const index = parent.pages.indexOf(skeNode);
@@ -117,6 +129,8 @@ function getPagePath(page: IDocumentSkeletonPage) {
}
} else if (parent.skeTables && parent.skeTables.has(skeNode.tableId)) {
path.unshift('skeTables', skeNode.tableId);
+ } else if (parent.skeColumnGroups && parent.skeColumnGroups.has(skeNode.columnGroupId)) {
+ path.unshift('skeColumnGroups', skeNode.columnGroupId);
}
skeNode = parent;
@@ -126,6 +140,65 @@ function getPagePath(page: IDocumentSkeletonPage) {
return path;
}
+function getBoundaryGlyphInPage(page: IDocumentSkeletonPage, useLast: boolean) {
+ const sections = useLast ? [...page.sections].reverse() : page.sections;
+
+ for (const section of sections) {
+ const columns = useLast ? [...section.columns].reverse() : section.columns;
+ for (const column of columns) {
+ const lines = useLast ? [...column.lines].reverse() : column.lines;
+ for (const line of lines) {
+ const divides = useLast ? [...line.divides].reverse() : line.divides;
+ for (const divide of divides) {
+ const glyphGroup = useLast ? [...divide.glyphGroup].reverse() : divide.glyphGroup;
+ const glyph = glyphGroup.find((item) => item.content?.length);
+
+ if (glyph) {
+ return {
+ section,
+ column,
+ line,
+ divide,
+ glyph,
+ };
+ }
+ }
+ }
+ }
+ }
+}
+
+function isHitTestAddressableGlyph(glyph: IDocumentSkeletonGlyph): boolean {
+ return Boolean(glyph.content?.length) ||
+ (glyph.streamType === DataStreamTreeTokenType.PARAGRAPH && glyph.count > 0);
+}
+
+function resolveMostSpecificPageByCharIndex(page: IDocumentSkeletonPage, charIndex: number): IDocumentSkeletonPage {
+ for (const table of page.skeTables?.values() ?? []) {
+ for (const row of table.rows) {
+ for (const cell of row.cells) {
+ const { st, ed } = cell;
+
+ if (charIndex >= st && charIndex <= ed) {
+ return resolveMostSpecificPageByCharIndex(cell, charIndex);
+ }
+ }
+ }
+ }
+
+ for (const columnGroup of page.skeColumnGroups?.values() ?? []) {
+ for (const column of columnGroup.columns) {
+ const { st, ed } = column;
+
+ if (charIndex >= st && charIndex <= ed) {
+ return resolveMostSpecificPageByCharIndex(column.page, charIndex);
+ }
+ }
+ }
+
+ return page;
+}
+
export class DocumentSkeleton extends Skeleton {
private _dirty$ = new Subject<boolean>();
readonly dirty$ = this._dirty$.asObservable();
@@ -724,7 +797,7 @@ export class DocumentSkeleton extends Skeleton {
nestLevel: number = 0
// eslint-disable-next-line ts/no-explicit-any
): any {
- const { sections, skeTables } = segmentPage;
+ const { sections, skeTables, skeColumnGroups = new Map() } = segmentPage;
this._findLiquid.translateSave();
const pageLeft = this._findLiquid.x;
@@ -821,7 +894,7 @@ export class DocumentSkeleton extends Skeleton {
const { x: startX } = this._findLiquid;
for (const glyph of glyphGroup) {
- if (!glyph.content || glyph.content.length === 0) {
+ if (!isHitTestAddressableGlyph(glyph)) {
continue;
}
@@ -960,6 +1033,65 @@ export class DocumentSkeleton extends Skeleton {
}
}
+ if (skeColumnGroups.size > 0) {
+ for (const columnGroup of skeColumnGroups.values()) {
+ const { top: columnGroupTop, left: columnGroupLeft, width: columnGroupWidth, height: columnGroupHeight, columns } = columnGroup;
+ const absoluteColumnGroupLeft = this._findLiquid.x + columnGroupLeft;
+ const absoluteColumnGroupTop = this._findLiquid.y + columnGroupTop;
+
+ if (
+ x < absoluteColumnGroupLeft ||
+ x > absoluteColumnGroupLeft + columnGroupWidth ||
+ y < absoluteColumnGroupTop ||
+ y > absoluteColumnGroupTop + columnGroupHeight
+ ) {
+ continue;
+ }
+
+ this._findLiquid?.translateSave();
+ this._findLiquid?.translate(columnGroupLeft, columnGroupTop);
+
+ for (const column of columns) {
+ const absoluteColumnLeft = absoluteColumnGroupLeft + column.left;
+ const absoluteColumnTop = absoluteColumnGroupTop + column.top;
+
+ if (
+ x < absoluteColumnLeft ||
+ x > absoluteColumnLeft + column.width ||
+ y < absoluteColumnTop ||
+ y > absoluteColumnTop + column.height
+ ) {
+ continue;
+ }
+
+ const nestedCache: INearestCache = {
+ nearestNodeList: [],
+ nearestNodeDistanceList: [],
+ };
+
+ this._findLiquid?.translateSave();
+ this._findLiquid?.translate(column.left, column.top);
+
+ exactMatch = exactMatch ?? this._collectNearestNode(
+ column.page,
+ DocumentSkeletonPageType.CELL,
+ column.page,
+ segmentId,
+ pi,
+ nestedCache,
+ x,
+ y,
+ pageLength,
+ nestLevel + 1
+ ) ?? this._getNearestNode(nestedCache.nearestNodeList, nestedCache.nearestNodeDistanceList);
+
+ this._findLiquid?.translateRestore();
+ }
+
+ this._findLiquid?.translateRestore();
+ }
+ }
+
if (exactMatch) {
this._findLiquid.translateRestore();
return exactMatch;
@@ -1273,7 +1405,7 @@ export class DocumentSkeleton extends Skeleton {
continue;
}
- const { pageWidth, skeTables } = page;
+ const { pageWidth } = page;
let segmentPage = page;
if (segmentId) {
@@ -1288,39 +1420,30 @@ export class DocumentSkeleton extends Skeleton {
}
}
- // Find node from tables.
if (segmentId === '') {
- let foundCell = false;
- for (const table of skeTables.values()) {
- const { rows } = table;
-
- for (const row of rows) {
- const { cells } = row;
-
- for (const cell of cells) {
- const { st, ed } = cell;
-
- if (charIndex >= st && charIndex <= ed) {
- segmentPage = cell;
- foundCell = true;
- break;
- }
- }
-
- if (foundCell) {
- break;
- }
- }
-
- if (foundCell) {
- break;
- }
- }
+ segmentPage = resolveMostSpecificPageByCharIndex(page, charIndex);
}
const { sections, st, ed } = segmentPage;
+ const segmentPageParent = segmentPage.parent as { page?: IDocumentSkeletonPage; parent?: { columnGroupId?: string } } | undefined;
+ const isColumnSegmentPage = segmentId === '' &&
+ segmentPageParent?.page === segmentPage &&
+ segmentPageParent.parent?.columnGroupId;
if (charIndex < st || charIndex > ed) {
+ if (isColumnSegmentPage) {
+ const boundary = getBoundaryGlyphInPage(segmentPage, charIndex >= ed);
+
+ if (boundary) {
+ return {
+ page: segmentPage,
+ pageType: segmentPage.type,
+ segmentPageIndex,
+ ...boundary,
+ };
+ }
+ }
+
continue;
}
@@ -1377,6 +1500,19 @@ export class DocumentSkeleton extends Skeleton {
}
}
}
+
+ if (isColumnSegmentPage) {
+ const boundary = getBoundaryGlyphInPage(segmentPage, charIndex >= segmentPage.ed);
+
+ if (boundary) {
+ return {
+ page: segmentPage,
+ pageType: segmentPage.type,
+ segmentPageIndex,
+ ...boundary,
+ };
+ }
+ }
}
}
}
diff --git a/packages/engine-render/src/components/docs/layout/model/glyph.ts b/packages/engine-render/src/components/docs/layout/model/glyph.ts
index b56ad91fc5..d84dd037f9 100644
--- a/packages/engine-render/src/components/docs/layout/model/glyph.ts
+++ b/packages/engine-render/src/components/docs/layout/model/glyph.ts
@@ -33,9 +33,9 @@ import {
isCjkRightAlignedPunctuation,
ptToPixel,
} from '../../../../basics/tools';
+import { applyFontMetricCompatibility, getDocumentCompatibilityPolicy } from '../../document-compatibility';
import { FontCache } from '../shaping-engine/font-cache';
import { validationGrid } from '../tools';
-import { applyFontMetricCompatibility, getDocumentCompatibilityPolicy } from '../../document-compatibility';
export function isSpace(char: string) {
const SPACE_CHARS = [' ', '\u{00A0}', ' '];
@@ -162,6 +162,10 @@ export function _createSkeletonWordOrLetter(
DT.TABLE_ROW_END,
DT.TABLE_CELL_START,
DT.TABLE_CELL_END,
+ DT.COLUMN_GROUP_START,
+ DT.COLUMN_START,
+ DT.COLUMN_END,
+ DT.COLUMN_GROUP_END,
DT.BLOCK_START,
DT.BLOCK_END,
DT.CUSTOM_RANGE_START,
diff --git a/packages/engine-render/src/components/docs/layout/model/page.ts b/packages/engine-render/src/components/docs/layout/model/page.ts
index 8983cb8256..f443b74cf6 100644
--- a/packages/engine-render/src/components/docs/layout/model/page.ts
+++ b/packages/engine-render/src/components/docs/layout/model/page.ts
@@ -193,6 +193,7 @@ function _getNullPage(
ed: 0,
skeDrawings: new Map(),
skeTables: new Map(),
+ skeColumnGroups: new Map(),
type,
segmentId,
};
@@ -394,7 +395,7 @@ export function createSkeletonCellPages(
updateBlockIndex(pages, cellNode.startIndex);
- applyTrailingCellBlockRangeSpaceBelow(pages, ctx.dataModel?.getBody?.(), cellNode.endIndex);
+ applyTrailingBlockRangeSpaceBelow(pages, ctx.dataModel?.getBody?.(), cellNode.endIndex);
updateInlineDrawingCoordsAndBorder(ctx, pages);
expandCellPageHeightForInlineDrawings(pages);
@@ -417,7 +418,7 @@ export function expandCellPageHeightForInlineDrawings(pages: IDocumentSkeletonPa
}
}
-function applyTrailingCellBlockRangeSpaceBelow(pages: IDocumentSkeletonPage[], body: Nullable<IDocumentBody>, cellEndIndex: number) {
+export function applyTrailingBlockRangeSpaceBelow(pages: IDocumentSkeletonPage[], body: Nullable<IDocumentBody>, containerEndIndex: number) {
const blockRanges = body?.blockRanges;
const trailingBlockRangeSpace = 28;
if (!blockRanges?.length) {
@@ -436,8 +437,8 @@ function applyTrailingCellBlockRangeSpaceBelow(pages: IDocumentSkeletonPage[], b
continue;
}
- const hasLaterParagraphInCell = body?.paragraphs?.some((paragraph) => paragraph.startIndex > paragraphIndex && paragraph.startIndex < cellEndIndex);
- if (hasLaterParagraphInCell) {
+ const hasLaterParagraphInContainer = body?.paragraphs?.some((paragraph) => paragraph.startIndex > paragraphIndex && paragraph.startIndex < containerEndIndex);
+ if (hasLaterParagraphInContainer) {
continue;
}
diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.ts
index cebd93471e..b3db0eb912 100644
--- a/packages/engine-render/src/components/docs/layout/tools.ts
+++ b/packages/engine-render/src/components/docs/layout/tools.ts
@@ -36,10 +36,13 @@ import type {
IDocumentSkeletonGlyph,
IDocumentSkeletonLine,
IDocumentSkeletonPage,
+ IDocumentSkeletonRow,
IDocumentSkeletonSection,
+ IDocumentSkeletonTable,
ISkeletonResourceReference,
} from '../../../basics/i-document-skeleton-cached';
import type { IDocsConfig, IParagraphConfig, ISectionBreakConfig } from '../../../basics/interfaces';
+import type { IBoundRectNoAngle } from '../../../basics/vector2';
import type { DataStreamTreeNode } from '../view-model/data-stream-tree-node';
import type { DocumentViewModel } from '../view-model/document-view-model';
import type { Hyphen } from './hyphenation/hyphen';
@@ -69,9 +72,10 @@ import {
WrapStrategy,
} from '@univerjs/core';
import { DEFAULT_DOCUMENT_FONTSIZE } from '../../../basics/const';
-import { GlyphType } from '../../../basics/i-document-skeleton-cached';
+import { GlyphType, LineType } from '../../../basics/i-document-skeleton-cached';
import { getFontStyleString, isFunction } from '../../../basics/tools';
import { getDocumentCompatibilityPolicy } from '../document-compatibility';
+import { getDocsTableRenderViewport, hasDocsTableHorizontalViewport } from '../table-render-viewport';
import { updateInlineDrawingPosition } from './block/paragraph/layout-ruler';
import { getCustomDecorationStyle } from './style/custom-decoration';
import { getCustomRangeStyle } from './style/custom-range';
@@ -345,7 +349,7 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =
let prePageStartIndex = start;
for (const page of pages) {
- const { sections, skeTables } = page;
+ const { sections, skeTables, skeColumnGroups = new Map() } = page;
const pageStartIndex = prePageStartIndex;
const pageEndIndex = pageStartIndex;
let preSectionStartIndex = pageStartIndex;
@@ -378,6 +382,18 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =
lineStartIndex = table.ed;
}
}
+
+ if (line.type === LineType.BLOCK && divides.length === 0) {
+ line.st = Math.max(line.st, lineStartIndex + 1);
+ line.ed = Math.max(line.ed, line.st);
+ line.width = 0;
+ line.asc = 0;
+ line.dsc = 0;
+ columnHeight = top + lineHeight;
+ preLineStartIndex = Math.max(preLineStartIndex, line.ed);
+ continue;
+ }
+
const lineEndIndex = lineStartIndex;
let preDivideStartIndex = lineStartIndex;
let actualWidth = 0;
@@ -478,6 +494,12 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =
preSectionStartIndex = Math.max(preSectionStartIndex, ed);
}
+ for (const columnGroup of skeColumnGroups.values()) {
+ const { ed } = columnGroup;
+
+ preSectionStartIndex = Math.max(preSectionStartIndex, ed);
+ }
+
page.st = pageStartIndex + 1;
page.ed = preSectionStartIndex >= page.st ? preSectionStartIndex : page.st;
page.height = contentHeight;
@@ -584,6 +606,475 @@ export function lineIterator(
}
}
+export type DocumentSkeletonLineSource = 'page' | 'table-cell' | 'column';
+
+export interface IDocumentSkeletonLineIteratorOptions {
+ docsLeft?: number;
+ pageMarginTop?: number;
+ tableCellInsetX?: number;
+ unitId?: string;
+}
+
+export interface IDocumentSkeletonLineContext {
+ clipLeft?: number;
+ clipRight?: number;
+ column: IDocumentSkeletonColumn;
+ line: IDocumentSkeletonLine;
+ lineWidth: number;
+ page: IDocumentSkeletonPage;
+ pageIndex: number;
+ pageLeft: number;
+ section: IDocumentSkeletonSection;
+ sectionTop: number;
+ source: DocumentSkeletonLineSource;
+ visualLeft?: number;
+ visualWidth?: number;
+}
+
+export type DocumentSkeletonTableSource = 'page' | 'column';
+
+export interface IDocumentSkeletonTableCellGeometry {
+ cell: IDocumentSkeletonPage;
+ cellRect: IBoundRectNoAngle;
+ clipLeft: number;
+ clipRight: number;
+ columnIndex: number;
+ pageLeft: number;
+ pageTop: number;
+ row: IDocumentSkeletonRow;
+ rowIndex: number;
+ visualLeft: number;
+ visualWidth: number;
+}
+
+export interface IDocumentSkeletonTableContext {
+ cells: IDocumentSkeletonTableCellGeometry[];
+ page: IDocumentSkeletonPage;
+ pageIndex: number;
+ pageLeft: number;
+ pageTop: number;
+ rootPage: IDocumentSkeletonPage;
+ source: DocumentSkeletonTableSource;
+ table: IDocumentSkeletonTable;
+ tableId: string;
+ tableRect: IBoundRectNoAngle;
+}
+
+export interface IDocumentSkeletonTableIteratorOptions {
+ docsLeft?: number;
+ docsTop?: number;
+ pageMarginTop?: number;
+ resolveViewport?: boolean;
+ tableCellInsetX?: number;
+ unitId?: string;
+}
+
+export function documentSkeletonTableIterator(
+ pages: IDocumentSkeletonPage[],
+ options: IDocumentSkeletonTableIteratorOptions = {}
+): IDocumentSkeletonTableContext[] {
+ const {
+ docsLeft = 0,
+ docsTop = 0,
+ pageMarginTop = 0,
+ resolveViewport = true,
+ tableCellInsetX = 0,
+ unitId = '',
+ } = options;
+ const contexts: IDocumentSkeletonTableContext[] = [];
+
+ pages.forEach((rootPage, pageIndex) => {
+ const rootPageHeight = rootPage.pageHeight === Infinity ? 0 : rootPage.pageHeight;
+ const rootPageTop = (rootPageHeight + pageMarginTop) * pageIndex + rootPage.marginTop + docsTop;
+ const rootPageLeft = rootPage.marginLeft + docsLeft;
+
+ collectPageTables({
+ contexts,
+ docsLeft,
+ page: rootPage,
+ pageIndex,
+ pageLeft: rootPageLeft,
+ pageTop: rootPageTop,
+ rootPage,
+ source: 'page',
+ resolveViewport,
+ tableCellInsetX,
+ unitId,
+ });
+
+ rootPage.skeColumnGroups?.forEach((columnGroup) => {
+ columnGroup.columns.forEach((columnGroupColumn) => {
+ const nestedPage = columnGroupColumn.page;
+ const nestedPageLeft = rootPageLeft + columnGroup.left + columnGroupColumn.left + nestedPage.marginLeft;
+ const nestedPageTop = rootPageTop + columnGroup.top + columnGroupColumn.top + nestedPage.marginTop;
+
+ collectPageTables({
+ contexts,
+ docsLeft,
+ page: nestedPage,
+ pageIndex,
+ pageLeft: nestedPageLeft,
+ pageTop: nestedPageTop,
+ rootPage,
+ source: 'column',
+ resolveViewport,
+ tableCellInsetX,
+ unitId,
+ });
+ });
+ });
+ });
+
+ return contexts;
+}
+
+export function documentSkeletonLineIterator(
+ pages: IDocumentSkeletonPage[],
+ options: IDocumentSkeletonLineIteratorOptions,
+ cb: (context: IDocumentSkeletonLineContext) => void
+) {
+ const {
+ docsLeft = 0,
+ pageMarginTop = 0,
+ tableCellInsetX = 0,
+ unitId = '',
+ } = options;
+
+ pages.forEach((page, pageIndex) => {
+ const pageHeight = page.pageHeight === Infinity ? 0 : page.pageHeight;
+ const pageTop = (pageHeight + pageMarginTop) * pageIndex + page.marginTop;
+ const pageLeft = page.marginLeft;
+
+ visitPageLines(page, {
+ pageIndex,
+ pageLeft,
+ pageTop,
+ source: 'page',
+ getBounds: (linePage, column, section) => getPageLineBounds(linePage, column, section.columns.length, pageLeft),
+ }, cb);
+
+ page.skeTables?.forEach((table) => {
+ const sourceTableId = getSourceTableId(table.tableId);
+ const viewport = getDocsTableRenderViewport(unitId, sourceTableId);
+ const hasHorizontalViewport = hasDocsTableHorizontalViewport(viewport);
+ const tableViewportLeft = getTableViewportLeft(pageLeft, table.left, viewport, docsLeft);
+ const tableViewportRight = tableViewportLeft + (hasHorizontalViewport ? viewport.viewportWidth : table.width);
+ const tableScrollLeft = hasHorizontalViewport ? viewport.scrollLeft : 0;
+
+ table.rows.forEach((row) => {
+ row.cells.forEach((cell) => {
+ const cellTop = pageTop + table.top + row.top + cell.marginTop;
+ const cellLeft = pageLeft + table.left + cell.left - tableScrollLeft + cell.marginLeft;
+ const cellContentRight = cellLeft + cell.pageWidth - cell.marginLeft - cell.marginRight;
+ const visualLeft = cellLeft + tableCellInsetX;
+ const visualRight = cellContentRight - tableCellInsetX;
+ const visualWidth = Math.max(0, visualRight - visualLeft);
+ const clipLeft = tableViewportLeft;
+ const clipRight = Math.min(cellContentRight, tableViewportRight);
+
+ if (visualWidth <= 0 || Math.min(visualRight, clipRight) <= Math.max(visualLeft, clipLeft)) {
+ return;
+ }
+
+ visitPageLines(cell, {
+ clipLeft,
+ clipRight,
+ pageIndex,
+ pageLeft: cellLeft,
+ pageTop: cellTop,
+ source: 'table-cell',
+ visualLeft,
+ visualWidth,
+ }, cb);
+ });
+ });
+ });
+
+ page.skeColumnGroups?.forEach((columnGroup) => {
+ columnGroup.columns.forEach((columnGroupColumn) => {
+ const nestedPage = columnGroupColumn.page;
+ const nestedPageLeft = pageLeft + columnGroup.left + columnGroupColumn.left + nestedPage.marginLeft;
+ const nestedPageTop = pageTop + columnGroup.top + columnGroupColumn.top + nestedPage.marginTop;
+ const visualWidth = Math.max(0, columnGroupColumn.width - nestedPage.marginLeft - nestedPage.marginRight);
+
+ visitPageLines(nestedPage, {
+ pageIndex,
+ pageLeft: nestedPageLeft,
+ pageTop: nestedPageTop,
+ source: 'column',
+ getBounds: (_linePage, column) => ({
+ lineWidth: Math.max(getFiniteWidth(column.width), visualWidth - column.left),
+ visualLeft: nestedPageLeft + column.left,
+ visualWidth: Math.max(getFiniteWidth(column.width), visualWidth - column.left),
+ }),
+ }, cb);
+ });
+ });
+ });
+}
+
+export function getDocumentSkeletonNestedPageOffset(page: IDocumentSkeletonPage): { left: number; top: number } | undefined {
+ const parent = page.parent as {
+ left?: number;
+ page?: IDocumentSkeletonPage;
+ parent?: {
+ columnGroupId?: string;
+ columns?: unknown[];
+ left?: number;
+ top?: number;
+ };
+ top?: number;
+ } | undefined;
+
+ if (parent?.page === page && parent.parent?.columnGroupId && parent.parent.columns?.includes(parent)) {
+ return {
+ left: (parent.parent.left ?? 0) + (parent.left ?? 0),
+ top: (parent.parent.top ?? 0) + (parent.top ?? 0),
+ };
+ }
+}
+
+export interface IDocumentSkeletonColumnPagePathInfo {
+ columnGroupId: string;
+ columnIndex: number;
+ pageIndex: number;
+}
+
+export function getDocumentSkeletonColumnPagePathInfo(
+ position: { path?: (string | number)[] }
+): IDocumentSkeletonColumnPagePathInfo | undefined {
+ const { path } = position;
+ const pagesIndex = path?.indexOf('pages') ?? -1;
+ const columnGroupIndex = path?.indexOf('skeColumnGroups') ?? -1;
+ const columnsIndex = path?.indexOf('columns') ?? -1;
+
+ if (
+ pagesIndex === -1 ||
+ columnGroupIndex === -1 ||
+ columnsIndex === -1 ||
+ path?.[columnsIndex + 2] !== 'page'
+ ) {
+ return;
+ }
+
+ const pageIndex = path?.[pagesIndex + 1];
+ const columnGroupId = path?.[columnGroupIndex + 1];
+ const columnIndex = path?.[columnsIndex + 1];
+
+ if (typeof pageIndex !== 'number' || typeof columnGroupId !== 'string' || typeof columnIndex !== 'number') {
+ return;
+ }
+
+ return {
+ columnGroupId,
+ columnIndex,
+ pageIndex,
+ };
+}
+
+export function compareDocumentSkeletonNestedPagePathOrder(
+ pos1: { path?: (string | number)[] },
+ pos2: { path?: (string | number)[] }
+): boolean | undefined {
+ const columnGroupOrder1 = getDocumentSkeletonColumnPagePathInfo(pos1);
+ const columnGroupOrder2 = getDocumentSkeletonColumnPagePathInfo(pos2);
+
+ if (
+ columnGroupOrder1 &&
+ columnGroupOrder2 &&
+ columnGroupOrder1.pageIndex === columnGroupOrder2.pageIndex &&
+ columnGroupOrder1.columnGroupId === columnGroupOrder2.columnGroupId &&
+ columnGroupOrder1.columnIndex !== columnGroupOrder2.columnIndex
+ ) {
+ return columnGroupOrder1.columnIndex < columnGroupOrder2.columnIndex;
+ }
+}
+
+interface IVisitPageLineOptions {
+ clipLeft?: number;
+ clipRight?: number;
+ getBounds?: (
+ page: IDocumentSkeletonPage,
+ column: IDocumentSkeletonColumn,
+ section: IDocumentSkeletonSection
+ ) => Partial<Pick<IDocumentSkeletonLineContext, 'lineWidth' | 'visualLeft' | 'visualWidth'>> | undefined;
+ pageIndex: number;
+ pageLeft: number;
+ pageTop: number;
+ source: DocumentSkeletonLineSource;
+ visualLeft?: number;
+ visualWidth?: number;
+}
+
+function visitPageLines(
+ page: IDocumentSkeletonPage,
+ options: IVisitPageLineOptions,
+ cb: (context: IDocumentSkeletonLineContext) => void
+) {
+ page.sections.forEach((section) => {
+ section.columns.forEach((column) => {
+ column.lines.forEach((line) => {
+ const bounds = options.getBounds?.(page, column, section);
+
+ cb({
+ clipLeft: options.clipLeft,
+ clipRight: options.clipRight,
+ column,
+ line,
+ lineWidth: bounds?.lineWidth ?? bounds?.visualWidth ?? getFiniteWidth(column.width),
+ page,
+ pageIndex: options.pageIndex,
+ pageLeft: options.pageLeft,
+ section,
+ sectionTop: options.pageTop + section.top,
+ source: options.source,
+ visualLeft: bounds?.visualLeft ?? options.visualLeft,
+ visualWidth: bounds?.visualWidth ?? options.visualWidth,
+ });
+ });
+ });
+ });
+}
+
+function getPageLineBounds(
+ page: IDocumentSkeletonPage,
+ column: IDocumentSkeletonColumn,
+ columnCount: number,
+ pageLeft: number
+): Pick<IDocumentSkeletonLineContext, 'lineWidth' | 'visualLeft' | 'visualWidth'> | undefined {
+ if (columnCount !== 1 || !Number.isFinite(page.pageWidth)) {
+ return;
+ }
+
+ const visualLeft = pageLeft + column.left;
+ const visualRight = page.pageWidth - page.marginRight;
+ const visualWidth = Math.max(0, visualRight - visualLeft);
+ const lineWidth = Math.max(0, page.pageWidth - page.marginLeft - page.marginRight);
+ return visualWidth > 0 ? { lineWidth, visualLeft, visualWidth } : undefined;
+}
+
+interface ICollectPageTablesOptions {
+ contexts: IDocumentSkeletonTableContext[];
+ docsLeft: number;
+ page: IDocumentSkeletonPage;
+ pageIndex: number;
+ pageLeft: number;
+ pageTop: number;
+ rootPage: IDocumentSkeletonPage;
+ resolveViewport: boolean;
+ source: DocumentSkeletonTableSource;
+ tableCellInsetX: number;
+ unitId: string;
+}
+
+function collectPageTables(options: ICollectPageTablesOptions): void {
+ const {
+ contexts,
+ docsLeft,
+ page,
+ pageIndex,
+ pageLeft,
+ pageTop,
+ resolveViewport,
+ rootPage,
+ source,
+ tableCellInsetX,
+ unitId,
+ } = options;
+
+ page.skeTables?.forEach((table, tableId) => {
+ const effectiveTableId = table.tableId ?? tableId;
+ const tableLeft = pageLeft + table.left;
+ const tableTop = pageTop + table.top;
+ const sourceTableId = getSourceTableId(effectiveTableId);
+ const viewport = resolveViewport ? getDocsTableRenderViewport(unitId, sourceTableId) : null;
+ const hasHorizontalViewport = hasDocsTableHorizontalViewport(viewport);
+ const tableViewportLeft = getTableViewportLeft(pageLeft, table.left, viewport, docsLeft);
+ const tableViewportRight = tableViewportLeft + (hasHorizontalViewport ? viewport.viewportWidth : table.width);
+ const tableScrollLeft = hasHorizontalViewport ? viewport.scrollLeft : 0;
+ const cells: IDocumentSkeletonTableCellGeometry[] = [];
+
+ table.rows.forEach((row, rowIndex) => {
+ row.cells.forEach((cell, columnIndex) => {
+ if ((cell as IDocumentSkeletonPage & { isMergedCellCovered?: boolean }).isMergedCellCovered) {
+ return;
+ }
+
+ const cellMarginLeft = cell.marginLeft ?? 0;
+ const cellMarginRight = cell.marginRight ?? 0;
+ const cellMarginTop = cell.marginTop ?? 0;
+ const cellMarginBottom = cell.marginBottom ?? 0;
+ const cellPageWidth = cell.pageWidth ?? 0;
+ const cellPageHeight = cell.pageHeight ?? 0;
+ const cellTop = tableTop + (row.top ?? 0) + cellMarginTop;
+ const cellLeft = tableLeft + (cell.left ?? 0) - tableScrollLeft + cellMarginLeft;
+ const cellContentRight = cellLeft + cellPageWidth - cellMarginLeft - cellMarginRight;
+ const visualLeft = cellLeft + tableCellInsetX;
+ const visualRight = cellContentRight - tableCellInsetX;
+ const visualWidth = Math.max(0, visualRight - visualLeft);
+ const clipLeft = tableViewportLeft;
+ const clipRight = Math.min(cellContentRight, tableViewportRight);
+
+ if (visualWidth <= 0 || Math.min(visualRight, clipRight) <= Math.max(visualLeft, clipLeft)) {
+ return;
+ }
+
+ cells.push({
+ cell,
+ cellRect: {
+ bottom: cellTop + cellPageHeight - cellMarginBottom - cellMarginTop,
+ left: Math.max(cellLeft, tableViewportLeft),
+ right: Math.min(cellContentRight, tableViewportRight),
+ top: cellTop,
+ },
+ clipLeft,
+ clipRight,
+ columnIndex,
+ pageLeft: cellLeft,
+ pageTop: cellTop,
+ row,
+ rowIndex,
+ visualLeft,
+ visualWidth,
+ });
+ });
+ });
+
+ contexts.push({
+ cells,
+ page,
+ pageIndex,
+ pageLeft,
+ pageTop,
+ rootPage,
+ source,
+ table,
+ tableId: effectiveTableId,
+ tableRect: {
+ bottom: tableTop + table.height,
+ left: tableLeft,
+ right: tableLeft + table.width,
+ top: tableTop,
+ },
+ });
+ });
+}
+
+function getTableViewportLeft(pageLeft: number, tableLeft: number, viewport: unknown, docsLeft: number): number {
+ const viewportLeft = (viewport as Nullable<{ viewportLeft?: number }>)?.viewportLeft;
+ return viewportLeft != null
+ ? viewportLeft - docsLeft
+ : pageLeft + tableLeft;
+}
+
+function getSourceTableId(tableId: string): string {
+ return tableId.includes('#-#') ? tableId.split('#-#')[0] : tableId;
+}
+
+function getFiniteWidth(width: number | undefined): number {
+ return Number.isFinite(width) ? width! : 0;
+}
+
export function columnIterator(
pages: IDocumentSkeletonPage[],
iteratorFunction: (column: IDocumentSkeletonColumn) => void
@@ -1222,6 +1713,13 @@ export function getPageFromPath(skeletonData: IDocumentSkeletonCached, path: (st
const cellIndex = pathCopy.shift() as number;
page = page!.skeTables?.get(tableId)?.rows[rowIndex]?.cells[cellIndex];
+ } else if (field === 'skeColumnGroups') {
+ const columnGroupId = pathCopy.shift() as string;
+ pathCopy.shift(); // columns
+ const columnIndex = pathCopy.shift() as number;
+ pathCopy.shift(); // page
+
+ page = page!.skeColumnGroups?.get(columnGroupId)?.columns[columnIndex]?.page;
}
}
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 897622b6ea..a29b898a4b 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
@@ -182,6 +182,61 @@ describe('DocumentViewModel', () => {
},
]);
});
+
+ it('parses column group tokens into column nodes', () => {
+ const ds = [
+ DataStreamTreeTokenType.COLUMN_GROUP_START,
+ DataStreamTreeTokenType.COLUMN_START,
+ 'A',
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_START,
+ 'B',
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_END,
+ DataStreamTreeTokenType.SECTION_BREAK,
+ ].join('');
+
+ const { sectionList } = parseDataStreamToTree(ds);
+ const columnGroup = findFirstNodeByType(sectionList[0], DataStreamTreeNodeType.COLUMN_GROUP)!;
+
+ expect(columnGroup).toBeTruthy();
+ expect(columnGroup.startIndex).toBe(0);
+ expect(columnGroup.children.map((column: any) => column.nodeType)).toEqual([
+ DataStreamTreeNodeType.COLUMN,
+ DataStreamTreeNodeType.COLUMN,
+ ]);
+ expect(columnGroup.children.map((column: any) => column.children[0].content)).toEqual([
+ `A${DataStreamTreeTokenType.PARAGRAPH}`,
+ `B${DataStreamTreeTokenType.PARAGRAPH}`,
+ ]);
+ });
+
+ it('keeps section break nodes inside columns', () => {
+ const ds = [
+ DataStreamTreeTokenType.COLUMN_GROUP_START,
+ DataStreamTreeTokenType.COLUMN_START,
+ 'A',
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.SECTION_BREAK,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_START,
+ 'B',
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.SECTION_BREAK,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_END,
+ DataStreamTreeTokenType.SECTION_BREAK,
+ ].join('');
+
+ const { sectionList } = parseDataStreamToTree(ds);
+ const columnGroup = findFirstNodeByType(sectionList[0], DataStreamTreeNodeType.COLUMN_GROUP)!;
+ const firstColumnSection = columnGroup.children[0].children[0];
+
+ expect(firstColumnSection.nodeType).toBe(DataStreamTreeNodeType.SECTION_BREAK);
+ expect(firstColumnSection.children[0].content).toBe(`A${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`);
+ });
});
describe('DocumentViewModel class', () => {
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 8d9e136626..2ace6eefaf 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
@@ -16,7 +16,9 @@
import type {
DocumentDataModel,
+ IColumnGroup,
ICustomBlock,
+ ICustomColumnGroup,
ICustomDecorationForInterceptor,
ICustomRangeForInterceptor,
ICustomTable,
@@ -83,9 +85,23 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[
const tableList: ITableCache[] = [];
const tableRowList: DataStreamTreeNode[] = [];
const tableCellList: DataStreamTreeNode[] = [];
+ const columnGroupList: DataStreamTreeNode[] = [];
+ const columnList: DataStreamTreeNode[] = [];
+ const columnParagraphList: DataStreamTreeNode[] = [];
+ const columnSectionList: DataStreamTreeNode[] = [];
const currentBlocks: number[] = [];
- const getParagraphList = () => tableCellList.length > 0 ? cellParagraphList : paragraphList;
+ const getParagraphList = () => {
+ if (tableCellList.length > 0) {
+ return cellParagraphList;
+ }
+
+ if (columnGroupList.length > 0) {
+ return columnParagraphList;
+ }
+
+ return paragraphList;
+ };
const appendToPreviousParagraph = (char: string) => {
const tempParagraphList = getParagraphList();
const lastParagraph = tempParagraphList[tempParagraphList.length - 1];
@@ -128,12 +144,18 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[
if (tableCellList.length > 0) {
cellParagraphList.push(paragraphNode);
+ } else if (columnGroupList.length > 0) {
+ columnParagraphList.push(paragraphNode);
} else {
paragraphList.push(paragraphNode);
}
} else if (char === DataStreamTreeTokenType.SECTION_BREAK) {
const sectionNode = DataStreamTreeNode.create(DataStreamTreeNodeType.SECTION_BREAK);
- const tempParagraphList = tableCellList.length > 0 ? cellParagraphList : paragraphList;
+ const tempParagraphList = tableCellList.length > 0
+ ? cellParagraphList
+ : columnGroupList.length > 0
+ ? columnParagraphList
+ : paragraphList;
if (tempParagraphList.length === 0) {
const emptyParagraph = DataStreamTreeNode.create(DataStreamTreeNodeType.PARAGRAPH, '');
@@ -153,6 +175,8 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[
const lastCell = tableCellList[tableCellList.length - 1];
batchParent(lastCell, [sectionNode], DataStreamTreeNodeType.TABLE_CELL);
+ } else if (columnGroupList.length > 0) {
+ columnSectionList.push(sectionNode);
} else {
sectionList.push(sectionNode);
}
@@ -188,6 +212,36 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[
const lastRow = tableRowList[tableRowList.length - 1];
batchParent(lastRow, [cellNode!], DataStreamTreeNodeType.TABLE_ROW);
+ } else if (char === DataStreamTreeTokenType.COLUMN_GROUP_START) {
+ const columnGroupNode = DataStreamTreeNode.create(DataStreamTreeNodeType.COLUMN_GROUP);
+ columnGroupNode.setIndexRange(i, i);
+
+ columnGroupList.push(columnGroupNode);
+ } else if (char === DataStreamTreeTokenType.COLUMN_START) {
+ const columnNode = DataStreamTreeNode.create(DataStreamTreeNodeType.COLUMN);
+ columnNode.setIndexRange(i, i);
+
+ columnList.push(columnNode);
+ } else if (char === DataStreamTreeTokenType.COLUMN_END) {
+ const columnNode = columnList[columnList.length - 1];
+ const columnChildren = columnSectionList.length > 0 ? columnSectionList : columnParagraphList;
+ const columnStartIndex = columnNode.startIndex;
+
+ batchParent(columnNode, columnChildren, DataStreamTreeNodeType.COLUMN);
+ columnNode.setIndexRange(columnStartIndex, i);
+ columnParagraphList.length = 0;
+ columnSectionList.length = 0;
+ } else if (char === DataStreamTreeTokenType.COLUMN_GROUP_END) {
+ const columnGroupNode = columnGroupList.pop();
+ const columnGroupStartIndex = columnGroupNode!.startIndex;
+
+ batchParent(columnGroupNode!, columnList, DataStreamTreeNodeType.COLUMN_GROUP);
+ columnGroupNode!.setIndexRange(columnGroupStartIndex, i);
+ paragraphList.push(columnGroupNode!);
+ columnList.length = 0;
+ columnParagraphList.length = 0;
+ columnSectionList.length = 0;
+ content = '';
} else if (char === DataStreamTreeTokenType.BLOCK_START) {
content += char;
} else if (char === DataStreamTreeTokenType.BLOCK_END) {
@@ -210,6 +264,11 @@ interface ITableCoupleCache {
tableSource: ITable;
}
+interface IColumnGroupCoupleCache {
+ columnGroup: ICustomColumnGroup;
+ columnGroupSource: IColumnGroup;
+}
+
export class DocumentViewModel implements IDisposable {
private _interceptor: Nullable<ICustomRangeInterceptor> = null;
@@ -225,6 +284,8 @@ export class DocumentViewModel implements IDisposable {
private _tableCache: Map<number, ITableCoupleCache> = new Map();
+ private _columnGroupCache: Map<number, IColumnGroupCoupleCache> = new Map();
+
private _tableNodeCache: Map<string, ITableNodeCache> = new Map();
private _children: DataStreamTreeNode[] = [];
@@ -272,6 +333,7 @@ export class DocumentViewModel implements IDisposable {
this._sectionBreakCache.clear();
this._customBlockCache.clear();
this._tableCache.clear();
+ this._columnGroupCache.clear();
this._tableNodeCache.clear();
// this._headerTreeMap.clear();
// this._footerTreeMap.clear();
@@ -380,6 +442,10 @@ export class DocumentViewModel implements IDisposable {
return this._tableCache.get(index);
}
+ getColumnGroupByStartIndex(index: number) {
+ return this._columnGroupCache.get(index);
+ }
+
findTableNodeById(id: string) {
return this._tableNodeCache.get(id)?.table;
}
@@ -434,6 +500,7 @@ export class DocumentViewModel implements IDisposable {
this._buildSectionBreakCache();
this._buildCustomBlockCache();
this._buildTableCache();
+ this._buildColumnGroupCache();
}
private _buildParagraphCache() {
@@ -491,6 +558,27 @@ export class DocumentViewModel implements IDisposable {
}
}
+ private _buildColumnGroupCache() {
+ this._columnGroupCache.clear();
+
+ const columnGroups = this.getBody()?.columnGroups;
+ if (columnGroups == null) {
+ return;
+ }
+
+ for (const columnGroup of columnGroups) {
+ const { startIndex } = columnGroup;
+ if (!columnGroup.columns) {
+ continue;
+ }
+
+ this._columnGroupCache.set(startIndex, {
+ columnGroup,
+ columnGroupSource: columnGroup as IColumnGroup,
+ });
+ }
+ }
+
private _buildTextRunsCache() {
const textRuns = this.getBody()?.textRuns ?? [];
this._textRunsCache.clear();
diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.ts
index 2a70ac352b..9ba5824645 100644
--- a/packages/engine-render/src/index.ts
+++ b/packages/engine-render/src/index.ts
@@ -28,13 +28,19 @@ export * from './components/docs/layout/doc-simple-skeleton';
export { DocumentSkeleton } from './components/docs/layout/doc-skeleton';
export type { IFindNodeRestrictions } from './components/docs/layout/doc-skeleton';
export {
+ compareDocumentSkeletonNestedPagePathOrder,
+ documentSkeletonLineIterator,
+ documentSkeletonTableIterator,
getCharSpaceApply,
+ getDocumentSkeletonColumnPagePathInfo,
+ getDocumentSkeletonNestedPageOffset,
getLastLine,
getNumberUnitValue,
getPageFromPath,
glyphIterator,
lineIterator,
} from './components/docs/layout/tools';
+export type { IDocumentSkeletonColumnPagePathInfo, IDocumentSkeletonLineContext, IDocumentSkeletonLineIteratorOptions, IDocumentSkeletonTableCellGeometry, IDocumentSkeletonTableContext, IDocumentSkeletonTableIteratorOptions } from './components/docs/layout/tools';
export { getLastColumn } from './components/docs/layout/tools';
export { Liquid } from './components/docs/liquid';
export type {