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): add section and agent-friendly facade APIs (#7243)

Univer9bd60cd87919
diff --git a/common/debugger/src/controllers/e2e/data/default-doc.ts b/common/debugger/src/controllers/e2e/data/default-doc.ts
index 7f38a91115..b3c3bfc268 100644
--- a/common/debugger/src/controllers/e2e/data/default-doc.ts
+++ b/common/debugger/src/controllers/e2e/data/default-doc.ts
@@ -634,6 +634,7 @@ export function getDefaultDocData(): IDocumentData {
],
sectionBreaks: [
{
+ sectionId: 'section_common_debugger_default_doc_1',
startIndex: 3066,
// columnProperties: [
// {
diff --git a/common/mockdata/src/docs/default-document-data-cn.ts b/common/mockdata/src/docs/default-document-data-cn.ts
index 414dbf7cf4..b994dd317e 100644
--- a/common/mockdata/src/docs/default-document-data-cn.ts
+++ b/common/mockdata/src/docs/default-document-data-cn.ts
@@ -658,6 +658,7 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {
],
sectionBreaks: [
{
+ sectionId: 'section_mockdata_default_document_cn_1',
startIndex: 3066,
// columnProperties: [
// {
diff --git a/common/mockdata/src/docs/default-document-data-dreamer.ts b/common/mockdata/src/docs/default-document-data-dreamer.ts
index c6b72a726d..046c130571 100644
--- a/common/mockdata/src/docs/default-document-data-dreamer.ts
+++ b/common/mockdata/src/docs/default-document-data-dreamer.ts
@@ -252,6 +252,7 @@ export const DEFAULT_DOCUMENT_DATA_DREAMER: IDocumentData = {
],
sectionBreaks: [
{
+ sectionId: 'section_mockdata_default_document_dreamer_1',
startIndex: 3319,
columnProperties: [
{
diff --git a/common/mockdata/src/docs/default-document-data-en.ts b/common/mockdata/src/docs/default-document-data-en.ts
index 362a2afa28..eab238da45 100644
--- a/common/mockdata/src/docs/default-document-data-en.ts
+++ b/common/mockdata/src/docs/default-document-data-en.ts
@@ -355,11 +355,13 @@ export const DEFAULT_DOCUMENT_DATA_EN: IDocumentData = {
],
sectionBreaks: [
{
+ sectionId: 'section_mockdata_default_document_en_1',
startIndex: 1245,
// textDirection: textDirectionDocument,
// contentDirection: textDirection!,
},
{
+ sectionId: 'section_mockdata_default_document_en_2',
startIndex: 2629,
columnProperties: [
{
diff --git a/common/mockdata/src/docs/default-document-data.ts b/common/mockdata/src/docs/default-document-data.ts
index 461f408411..f9a11a90ee 100644
--- a/common/mockdata/src/docs/default-document-data.ts
+++ b/common/mockdata/src/docs/default-document-data.ts
@@ -174,6 +174,7 @@ export const DEFAULT_DOCUMENT_DATA: IDocumentData = {
],
sectionBreaks: [
{
+ sectionId: 'section_mockdata_default_document_1',
startIndex: 407,
columnProperties: [
{
diff --git a/common/mockdata/src/docs/default-document.data-simple.ts b/common/mockdata/src/docs/default-document.data-simple.ts
index ab8e160b5b..e0f6ed4931 100644
--- a/common/mockdata/src/docs/default-document.data-simple.ts
+++ b/common/mockdata/src/docs/default-document.data-simple.ts
@@ -1,5 +1,5 @@
import type { IDocumentData, IParagraph, ISectionBreak, ITable, ITableCell, ITableColumn, ITableRow } from '@univerjs/core';
-import { BooleanNumber, createParagraphId, DocumentFlavor, HorizontalAlign, ObjectRelativeFromH, ObjectRelativeFromV, TableAlignmentType, TableRowHeightRule, TableSizeType, TableTextWrapType, Tools, VerticalAlignmentType } from '@univerjs/core';
+import { BooleanNumber, createParagraphId, createSectionId, DocumentFlavor, HorizontalAlign, ObjectRelativeFromH, ObjectRelativeFromV, TableAlignmentType, TableRowHeightRule, TableSizeType, TableTextWrapType, Tools, VerticalAlignmentType } from '@univerjs/core';
import { ptToPixel } from '@univerjs/engine-render';
const TABLE_START = '\x1A'; // 表格开始
@@ -51,6 +51,7 @@ function createParagraphAndSectionBreaks(dataStream: string) {
const paragraphs: IParagraph[] = [];
const sectionBreaks: ISectionBreak[] = [];
const existingParagraphIds = new Set<string>();
+ const existingSectionIds = new Set<string>();
for (let i = 0; i < dataStream.length; i++) {
const char = dataStream[i];
if (char === '\r') {
@@ -68,6 +69,7 @@ function createParagraphAndSectionBreaks(dataStream: string) {
if (char === '\n') {
sectionBreaks.push({
+ sectionId: createSectionId(existingSectionIds),
startIndex: i,
});
}
diff --git a/common/mockdata/src/sheets/default-workbook-data.ts b/common/mockdata/src/sheets/default-workbook-data.ts
index c3e1885733..654785b188 100644
--- a/common/mockdata/src/sheets/default-workbook-data.ts
+++ b/common/mockdata/src/sheets/default-workbook-data.ts
@@ -111,6 +111,7 @@ const richTextTestFloat: IDocumentData = {
],
sectionBreaks: [
{
+ sectionId: 'section_mockdata_default_workbook_1',
startIndex: 61,
columnProperties: [
{
@@ -199,6 +200,7 @@ const richTextTest: IDocumentData = {
],
sectionBreaks: [
{
+ sectionId: 'section_mockdata_default_workbook_2',
startIndex: 61,
columnProperties: [
{
diff --git a/common/mockdata/src/sheets/demo/default-workbook-data-default-style.ts b/common/mockdata/src/sheets/demo/default-workbook-data-default-style.ts
index f01b8eeb5d..c595d54af2 100644
--- a/common/mockdata/src/sheets/demo/default-workbook-data-default-style.ts
+++ b/common/mockdata/src/sheets/demo/default-workbook-data-default-style.ts
@@ -34205,6 +34205,7 @@ export const DEFAULT_WORKBOOK_DATA_DEMO_DEFAULT_STYLE = {
],
sectionBreaks: [
{
+ sectionId: 'section_mockdata_default_workbook_style_1',
startIndex: 517,
columnProperties: [
{
diff --git a/common/mockdata/src/sheets/demo/default-workbook-data-demo.ts b/common/mockdata/src/sheets/demo/default-workbook-data-demo.ts
index 0ec917ba8a..1883186ac7 100644
--- a/common/mockdata/src/sheets/demo/default-workbook-data-demo.ts
+++ b/common/mockdata/src/sheets/demo/default-workbook-data-demo.ts
@@ -14192,6 +14192,7 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {
],
sectionBreaks: [
{
+ sectionId: 'section_mockdata_default_workbook_demo_1',
startIndex: 2,
},
],
@@ -14299,6 +14300,7 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {
],
sectionBreaks: [
{
+ sectionId: 'section_mockdata_default_workbook_demo_2',
startIndex: 94,
},
],
@@ -14441,6 +14443,7 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {
],
sectionBreaks: [
{
+ sectionId: 'section_mockdata_default_workbook_demo_3',
startIndex: 2,
},
],
@@ -14495,6 +14498,7 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {
],
sectionBreaks: [
{
+ sectionId: 'section_mockdata_default_workbook_demo_4',
startIndex: 2,
},
],
@@ -24349,13 +24353,13 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {
{
name: 'SHEET_UNIVER_THREAD_COMMENT_PLUGIN',
data: JSON.stringify({
- 'sheet-0011': [{ text: { textRuns: [], paragraphs: [{ paragraphId: 'para_common_mockdata_src_sheets_demo_default_workbook_data_demo_9', startIndex: 3, paragraphStyle: {} }], sectionBreaks: [{ startIndex: 4 }], dataStream: '123\r\n', customRanges: [] }, dT: '2024/05/17 21:16', id: 'jwV0QtHwUbhG3o--iy1qa', ref: 'H9', personId: 'Owner_qxVnhPbQ', unitId: 'workbook-01', subUnitId: 'sheet-0011' }],
+ 'sheet-0011': [{ text: { textRuns: [], paragraphs: [{ paragraphId: 'para_common_mockdata_src_sheets_demo_default_workbook_data_demo_9', startIndex: 3, paragraphStyle: {} }], sectionBreaks: [{ sectionId: 'section_mockdata_thread_comment_1', startIndex: 4 }], dataStream: '123\r\n', customRanges: [] }, dT: '2024/05/17 21:16', id: 'jwV0QtHwUbhG3o--iy1qa', ref: 'H9', personId: 'Owner_qxVnhPbQ', unitId: 'workbook-01', subUnitId: 'sheet-0011' }],
'dv-test': [
{
text: {
textRuns: [],
paragraphs: [{ paragraphId: 'para_common_mockdata_src_sheets_demo_default_workbook_data_demo_10', startIndex: 3, paragraphStyle: {} }],
- sectionBreaks: [{ startIndex: 4 }],
+ sectionBreaks: [{ sectionId: 'section_mockdata_thread_comment_2', startIndex: 4 }],
dataStream: '1\r\n',
customRanges: [],
},
@@ -24370,7 +24374,7 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {
text: {
textRuns: [],
paragraphs: [{ paragraphId: 'para_common_mockdata_src_sheets_demo_default_workbook_data_demo_11', startIndex: 3, paragraphStyle: {} }],
- sectionBreaks: [{ startIndex: 4 }],
+ sectionBreaks: [{ sectionId: 'section_mockdata_thread_comment_3', startIndex: 4 }],
dataStream: '1\r\n',
customRanges: [],
},
@@ -24385,7 +24389,7 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {
text: {
textRuns: [],
paragraphs: [{ paragraphId: 'para_common_mockdata_src_sheets_demo_default_workbook_data_demo_12', startIndex: 3, paragraphStyle: {} }],
- sectionBreaks: [{ startIndex: 4 }],
+ sectionBreaks: [{ sectionId: 'section_mockdata_thread_comment_4', startIndex: 4 }],
dataStream: '2\r\n',
customRanges: [],
},
@@ -24400,7 +24404,7 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {
text: {
textRuns: [],
paragraphs: [{ paragraphId: 'para_common_mockdata_src_sheets_demo_default_workbook_data_demo_13', startIndex: 3, paragraphStyle: {} }],
- sectionBreaks: [{ startIndex: 4 }],
+ sectionBreaks: [{ sectionId: 'section_mockdata_thread_comment_5', startIndex: 4 }],
dataStream: '3\r\n',
customRanges: [],
},
@@ -24415,7 +24419,7 @@ export const DEFAULT_WORKBOOK_DATA_DEMO: IWorkbookData = {
text: {
textRuns: [],
paragraphs: [{ paragraphId: 'para_common_mockdata_src_sheets_demo_default_workbook_data_demo_14', startIndex: 3, paragraphStyle: {} }],
- sectionBreaks: [{ startIndex: 4 }],
+ sectionBreaks: [{ sectionId: 'section_mockdata_thread_comment_6', startIndex: 4 }],
dataStream: '4\r\n',
customRanges: [],
},
diff --git a/common/mockdata/src/slides/rich-text/page5-richtext1.ts b/common/mockdata/src/slides/rich-text/page5-richtext1.ts
index 69871d69f8..ead113a2ed 100644
--- a/common/mockdata/src/slides/rich-text/page5-richtext1.ts
+++ b/common/mockdata/src/slides/rich-text/page5-richtext1.ts
@@ -138,6 +138,7 @@ export const PAGE5_RICHTEXT_1: IDocumentData = {
],
sectionBreaks: [
{
+ sectionId: 'section_mockdata_slide_page5_richtext1_1',
startIndex: 517,
columnProperties: [
{
diff --git a/e2e/__testing__/emptysheet.ts b/e2e/__testing__/emptysheet.ts
index 9813ae4b00..6aa6cd06f2 100644
--- a/e2e/__testing__/emptysheet.ts
+++ b/e2e/__testing__/emptysheet.ts
@@ -34175,6 +34175,7 @@ export const sheetData = {
],
sectionBreaks: [
{
+ sectionId: 'section_e2e_empty_sheet_1',
startIndex: 517,
columnProperties: [
{
diff --git a/packages/core/src/docs/__tests__/paragraph-id.spec.ts b/packages/core/src/docs/__tests__/paragraph-id.spec.ts
index 7fb7f5e943..08f3eb8a2f 100644
--- a/packages/core/src/docs/__tests__/paragraph-id.spec.ts
+++ b/packages/core/src/docs/__tests__/paragraph-id.spec.ts
@@ -29,7 +29,7 @@ function createBody(): IDocumentBody {
{ startIndex: 5, paragraphId: 'para_alpha' },
{ startIndex: 10, paragraphId: 'para_existing' },
],
- sectionBreaks: [{ startIndex: 11 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1', startIndex: 11 }],
};
}
diff --git a/packages/core/src/docs/__tests__/section-header-footer.spec.ts b/packages/core/src/docs/__tests__/section-header-footer.spec.ts
new file mode 100644
index 0000000000..58c7af9323
--- /dev/null
+++ b/packages/core/src/docs/__tests__/section-header-footer.spec.ts
@@ -0,0 +1,57 @@
+/**
+ * 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 { resolveSectionHeaderFooterReference, resolveSectionHeaderFooterReferences } from '../section-header-footer';
+
+describe('section header/footer references', () => {
+ const documentStyle = { defaultHeaderId: 'header-global', defaultFooterId: 'footer-global' };
+ const sections = [
+ { sectionId: 'section_1', startIndex: 3 },
+ { sectionId: 'section_2', startIndex: 7 },
+ { sectionId: 'section_3', startIndex: 11, defaultHeaderId: 'header-3' },
+ { sectionId: 'section_4', startIndex: 15 },
+ ];
+
+ it('uses document defaults only for the first section and inherits through later sections', () => {
+ expect(resolveSectionHeaderFooterReference(documentStyle, sections, 0, 'defaultHeaderId')).toEqual({
+ segmentId: 'header-global',
+ linkedToPrevious: false,
+ });
+ expect(resolveSectionHeaderFooterReference(documentStyle, sections, 1, 'defaultHeaderId')).toEqual({
+ segmentId: 'header-global',
+ linkedToPrevious: true,
+ sourceSectionId: undefined,
+ });
+ expect(resolveSectionHeaderFooterReference(documentStyle, sections, 2, 'defaultHeaderId')).toEqual({
+ segmentId: 'header-3',
+ linkedToPrevious: false,
+ sourceSectionId: 'section_3',
+ });
+ expect(resolveSectionHeaderFooterReference(documentStyle, sections, 3, 'defaultHeaderId')).toEqual({
+ segmentId: 'header-3',
+ linkedToPrevious: true,
+ sourceSectionId: 'section_3',
+ });
+ });
+
+ it('resolves all six reference variants independently', () => {
+ expect(resolveSectionHeaderFooterReferences(documentStyle, sections, 1)).toEqual({
+ defaultHeaderId: 'header-global',
+ defaultFooterId: 'footer-global',
+ });
+ });
+});
diff --git a/packages/core/src/docs/data-model/__tests__/replacement.spec.ts b/packages/core/src/docs/data-model/__tests__/replacement.spec.ts
index df8eebf36d..841897373b 100644
--- a/packages/core/src/docs/data-model/__tests__/replacement.spec.ts
+++ b/packages/core/src/docs/data-model/__tests__/replacement.spec.ts
@@ -82,6 +82,7 @@ function getTestDocumentBody() {
],
sectionBreaks: [
{
+ sectionId: 'section_fixture_replacement',
startIndex: 12,
},
],
@@ -146,6 +147,7 @@ describe('test case in replaceInDocumentBody utils', () => {
],
sectionBreaks: [
{
+ sectionId: 'section_fixture_replacement',
startIndex: 16,
},
],
@@ -207,6 +209,7 @@ describe('test case in replaceInDocumentBody utils', () => {
],
sectionBreaks: [
{
+ sectionId: 'section_fixture_replacement',
startIndex: 8,
},
],
diff --git a/packages/core/src/docs/data-model/__tests__/utils.spec.ts b/packages/core/src/docs/data-model/__tests__/utils.spec.ts
index 043c75c0e4..1351211a55 100644
--- a/packages/core/src/docs/data-model/__tests__/utils.spec.ts
+++ b/packages/core/src/docs/data-model/__tests__/utils.spec.ts
@@ -39,6 +39,10 @@ describe('document data-model utils', () => {
ff: '"SF Mono", "Cascadia Code", Consolas, monospace',
fs: 12,
});
+ const fractionalStyle = getFontStyleString({
+ ff: 'Arial',
+ fs: 10.5,
+ });
expect(defaultStyle).toEqual({
fontCache: `${DEFAULT_STYLES.fs}pt ${DEFAULT_STYLES.ff}`,
@@ -48,12 +52,14 @@ describe('document data-model utils', () => {
fontFamily: DEFAULT_STYLES.ff,
});
expect(superscriptStyle.fontFamily).toBe('"Noto Sans"');
- expect(superscriptStyle.originFontSize).toBe(13);
- expect(superscriptStyle.fontSize).toBeCloseTo(7.8);
+ expect(superscriptStyle.originFontSize).toBe(12.2);
+ expect(superscriptStyle.fontSize).toBeCloseTo(7.32);
expect(superscriptStyle.fontString).toContain(DEFAULT_FONTFACE_PLANE);
expect(normalStyle.fontCache).toBe('normal normal 14pt "Ping Fang"');
expect(fontStackStyle.fontFamily).toBe('"SF Mono", "Cascadia Code", Consolas, monospace');
expect(fontStackStyle.fontString).toContain('"SF Mono", "Cascadia Code", Consolas, monospace');
+ expect(fractionalStyle.originFontSize).toBe(10.5);
+ expect(fractionalStyle.fontCache).toContain('10.5pt');
});
it('should expose baseline offsets and convert text rotation', () => {
diff --git a/packages/core/src/docs/data-model/empty-snapshot.ts b/packages/core/src/docs/data-model/empty-snapshot.ts
index e74ef8a360..c14a522a48 100644
--- a/packages/core/src/docs/data-model/empty-snapshot.ts
+++ b/packages/core/src/docs/data-model/empty-snapshot.ts
@@ -21,6 +21,7 @@ import { BooleanNumber } from '../../types/enum';
import { LocaleType } from '../../types/enum/locale-type';
import { DocumentFlavor, PaperType } from '../../types/interfaces';
import { createParagraphId } from '../paragraph-id';
+import { createSectionId } from '../section-break-id';
export function getEmptySnapshot(
unitID = generateRandomId(6),
@@ -57,6 +58,7 @@ export function getEmptySnapshot(
],
sectionBreaks: [
{
+ sectionId: createSectionId(new Set()),
startIndex: 1,
},
],
diff --git a/packages/core/src/docs/data-model/index.ts b/packages/core/src/docs/data-model/index.ts
index cd07b89237..8c9014b957 100644
--- a/packages/core/src/docs/data-model/index.ts
+++ b/packages/core/src/docs/data-model/index.ts
@@ -35,7 +35,7 @@ export { DEFAULT_DOCUMENT_SUB_COMPONENT_ID } from './subdocument';
export { ActionIterator } from './text-x/action-iterator';
export { PRESERVE_INSERTED_PARAGRAPH_IDS, TextXActionType } from './text-x/action-types';
export type { IDeleteAction, IInsertAction, IRetainAction, TextXAction } from './text-x/action-types';
-export { normalizeTextRuns, RESTORE_INSERTED_PARAGRAPH_IDS } from './text-x/apply-utils/common';
+export { normalizeInsertedSectionIdsForDocument, normalizeTextRuns, RESTORE_INSERTED_PARAGRAPH_IDS } from './text-x/apply-utils/common';
export { updateAttributeByDelete } from './text-x/apply-utils/delete-apply';
export { updateAttributeByInsert } from './text-x/apply-utils/insert-apply';
export * from './text-x/build-utils';
diff --git a/packages/core/src/docs/data-model/rich-text-builder.ts b/packages/core/src/docs/data-model/rich-text-builder.ts
index e413b65586..d4df5f5edb 100644
--- a/packages/core/src/docs/data-model/rich-text-builder.ts
+++ b/packages/core/src/docs/data-model/rich-text-builder.ts
@@ -36,6 +36,7 @@ import { generateRandomId } from '../../shared/random-id';
import { BooleanNumber } from '../../types/enum';
import { CustomRangeType } from '../../types/interfaces';
import { createParagraphId } from '../paragraph-id';
+import { createSectionId } from '../section-break-id';
import { DocumentDataModel } from './document-data-model';
import { PresetListType } from './preset-list-type';
import { BuildTextUtils } from './text-x/build-utils';
@@ -71,6 +72,12 @@ export function normalizeBody(body: IDocumentBody) {
if (!body.sectionBreaks) {
body.sectionBreaks = [];
+ const existingSectionIds = new Set<string>();
+ for (let i = 0; i < body.dataStream.length; i++) {
+ if (body.dataStream[i] === '\n') {
+ body.sectionBreaks.push({ startIndex: i, sectionId: createSectionId(existingSectionIds) });
+ }
+ }
}
if (!body.tables) {
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.ts
index d6217ca7bf..80a6019935 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.ts
@@ -115,7 +115,7 @@ describe('document block ranges', () => {
{ startIndex: 2, paragraphId: 'inside-block' },
{ startIndex: 5, paragraphId: 'after-block' },
],
- sectionBreaks: [{ startIndex: 6 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_5', startIndex: 6 }],
blockRanges: [{
blockId: 'code-1',
blockType: DocumentBlockRangeType.CODE,
@@ -147,7 +147,7 @@ describe('document block ranges', () => {
{ startIndex: 2, paragraphId: 'inside-block' },
{ startIndex: 5, paragraphId: 'after-block' },
],
- sectionBreaks: [{ startIndex: 6 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_6', startIndex: 6 }],
blockRanges: [{
blockId: 'code-1',
blockType: DocumentBlockRangeType.CODE,
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/body-structure-validator.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/body-structure-validator.spec.ts
index 5cb9176407..98af229cdd 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/body-structure-validator.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/body-structure-validator.spec.ts
@@ -25,7 +25,7 @@ describe('validateDocBodyStructure', () => {
const body: IDocumentBody = {
dataStream: `A${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,
paragraphs: [{ startIndex: 1, paragraphId: 'para-1' }],
- sectionBreaks: [{ startIndex: 2 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_7', startIndex: 2 }],
};
expect(validateDocBodyStructure(body)).toEqual([]);
@@ -47,7 +47,7 @@ describe('validateDocBodyStructure', () => {
const body: IDocumentBody = {
dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`,
paragraphs: [{ startIndex: 4, paragraphId: 'bad-para' }],
- sectionBreaks: [{ startIndex: 5 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_8', startIndex: 5 }],
columnGroups: [{ startIndex: 0, endIndex: 5, columnGroupId: 'cg-1' }],
};
@@ -65,7 +65,10 @@ describe('validateDocBodyStructure', () => {
{ startIndex: 1, paragraphId: 'first' },
{ startIndex: 1, paragraphId: 'duplicate-first' },
],
- sectionBreaks: [{ startIndex: 4 }, { startIndex: 4 }],
+ sectionBreaks: [
+ { sectionId: 'section_duplicate_a', startIndex: 4 },
+ { sectionId: 'section_duplicate_b', startIndex: 4 },
+ ],
};
expect(validateDocBodyStructure(body).map((issue) => issue.code)).toEqual([
@@ -79,7 +82,7 @@ describe('validateDocBodyStructure', () => {
const body: IDocumentBody = {
dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.PARAGRAPH}${T.SECTION_BREAK}`,
paragraphs: [{ startIndex: 5, paragraphId: 'root' }],
- sectionBreaks: [{ startIndex: 6 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_11', startIndex: 6 }],
columnGroups: [{ startIndex: 0, endIndex: 4, columnGroupId: 'cg-1' }],
};
@@ -94,7 +97,7 @@ describe('validateDocBodyStructure', () => {
{ startIndex: 4, paragraphId: 'cell' },
{ startIndex: 8, paragraphId: 'after-table' },
],
- sectionBreaks: [{ startIndex: 9 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_12', startIndex: 9 }],
tables: [{ startIndex: 0, endIndex: 8, tableId: 'table-1' }],
};
@@ -111,8 +114,8 @@ describe('validateDocBodyStructure', () => {
{ startIndex: tableStream.length + 5, paragraphId: 'after-table' },
],
sectionBreaks: [
- { startIndex: 5 },
- { startIndex: tableStream.length + 6 },
+ { sectionId: 'section_fixture_13', startIndex: 5 },
+ { sectionId: 'section_fixture_14', startIndex: tableStream.length + 6 },
],
tables: [{ startIndex: 0, endIndex: tableStream.length, tableId: 'table-1' }],
};
@@ -131,7 +134,10 @@ describe('validateDocBodyStructure', () => {
{ startIndex: 3, paragraphId: 'cell' },
{ startIndex: 8, paragraphId: 'after-table' },
],
- sectionBreaks: [{ startIndex: 4 }, { startIndex: 9 }],
+ sectionBreaks: [
+ { sectionId: 'section_cell', startIndex: 4 },
+ { sectionId: 'section_root', startIndex: 9 },
+ ],
};
expect(validateDocBodyStructure(body).map((issue) => issue.code)).toContain('missing-table-metadata');
@@ -145,7 +151,7 @@ describe('validateDocBodyStructure', () => {
{ startIndex: 2, paragraphId: 'outer' },
{ startIndex: 5, paragraphId: 'inner' },
],
- sectionBreaks: [{ startIndex: 7 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_17', startIndex: 7 }],
blockRanges: [
{ startIndex: 0, endIndex: 6, blockId: 'outer', blockType: DocumentBlockRangeType.CODE },
{ startIndex: 3, endIndex: 6, blockId: 'inner', blockType: DocumentBlockRangeType.CALLOUT },
@@ -166,7 +172,7 @@ describe('validateDocBodyStructure', () => {
{ startIndex: 2, paragraphId: 'first' },
{ startIndex: 5, paragraphId: 'second' },
],
- sectionBreaks: [{ startIndex: 7 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_18', startIndex: 7 }],
blockRanges: [
{ startIndex: 0, endIndex: 3, blockId: 'first', blockType: DocumentBlockRangeType.CODE },
{ startIndex: 4, endIndex: 6, blockId: 'second', blockType: DocumentBlockRangeType.CALLOUT },
@@ -184,12 +190,12 @@ describe('validateDocBodyStructure', () => {
{ startIndex: 1, paragraphId: 'inside' },
{ startIndex: 3, paragraphId: 'after' },
],
- sectionBreaks: [{ startIndex: 4 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_19', startIndex: 4 }],
};
const unbalanced: IDocumentBody = {
dataStream: `${T.BLOCK_START}${T.PARAGRAPH}${T.SECTION_BREAK}`,
paragraphs: [{ startIndex: 1, paragraphId: 'inside' }],
- sectionBreaks: [{ startIndex: 2 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_20', startIndex: 2 }],
};
expect(validateDocBodyStructure(missingMetadata).map((issue) => issue.code)).toContain('missing-block-range-metadata');
@@ -205,7 +211,7 @@ describe('validateDocBodyStructure', () => {
{ startIndex: 2, paragraphId: 'left' },
{ startIndex: 5, paragraphId: 'right' },
],
- sectionBreaks: [{ startIndex: 8 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_21', startIndex: 8 }],
};
expect(validateDocBodyStructure(baseBody).map((issue) => issue.code)).toContain('missing-column-group-metadata');
@@ -250,7 +256,7 @@ describe('validateDocBodyStructure', () => {
const valid: IDocumentBody = {
dataStream: `${T.CUSTOM_BLOCK}${T.PARAGRAPH}${T.SECTION_BREAK}`,
paragraphs: [{ startIndex: 1, paragraphId: 'after-custom-block' }],
- sectionBreaks: [{ startIndex: 2 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_22', startIndex: 2 }],
customBlocks: [{ startIndex: 0, blockId: 'drawing-1' }],
};
@@ -274,7 +280,7 @@ describe('validateDocBodyStructure', () => {
const body: IDocumentBody = {
dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`,
paragraphs: [{ startIndex: 3, paragraphId: 'para-1' }],
- sectionBreaks: [{ startIndex: 5 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_23', startIndex: 5 }],
};
expect(validateDocBodyStructure(body).map((issue) => issue.code)).toContain('unbalanced-column-group');
@@ -286,7 +292,7 @@ describe('validateDocBodyStructure', () => {
body: {
dataStream: `${T.PARAGRAPH}${T.SECTION_BREAK}`,
paragraphs: [{ startIndex: 0, paragraphId: 'body' }],
- sectionBreaks: [{ startIndex: 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_24', startIndex: 1 }],
},
headers: {
'header-1': {
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/column-groups.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/column-groups.spec.ts
index 47a5c2884b..236b2d4cf9 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/column-groups.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/column-groups.spec.ts
@@ -40,7 +40,7 @@ describe('TextX column groups', () => {
body: {
dataStream: `${T.PARAGRAPH}${T.SECTION_BREAK}`,
paragraphs: [{ startIndex: 0, paragraphId: 'inserted' }],
- sectionBreaks: [{ startIndex: 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_25', startIndex: 1 }],
},
},
]);
@@ -49,7 +49,7 @@ describe('TextX column groups', () => {
startIndex: 2,
paragraphId: expect.any(String),
}]);
- expect(body.sectionBreaks).toEqual([{ startIndex: 3 }]);
+ expect(body.sectionBreaks).toEqual([{ sectionId: expect.any(String), startIndex: 3 }]);
});
it('adds inserted column group metadata to documents without existing column groups', () => {
@@ -57,7 +57,7 @@ describe('TextX column groups', () => {
const body: IDocumentBody = {
dataStream: `A${T.PARAGRAPH}${T.SECTION_BREAK}`,
paragraphs: [{ startIndex: 1, paragraphId: 'before' }],
- sectionBreaks: [{ startIndex: 2 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_26', startIndex: 2 }],
};
TextX.apply(body, [
@@ -84,7 +84,7 @@ describe('TextX column groups', () => {
{ startIndex: 2, paragraphId: 'left' },
{ startIndex: 5, paragraphId: 'right' },
],
- sectionBreaks: [{ startIndex: 8 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_27', startIndex: 8 }],
columnGroups: [{ startIndex: 0, endIndex: 7, columnGroupId: 'cg-1' }],
};
@@ -108,7 +108,7 @@ describe('TextX column groups', () => {
{ startIndex: 7, paragraphId: 'right' },
{ startIndex: 9, paragraphId: 'after' },
],
- sectionBreaks: [{ startIndex: 10 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_28', startIndex: 10 }],
columnGroups: [{ startIndex: 0, endIndex: 9, columnGroupId: 'cg-1' }],
};
@@ -129,7 +129,7 @@ describe('TextX column groups', () => {
{ startIndex: 3, paragraphId: 'left' },
{ startIndex: 6, paragraphId: 'after' },
],
- sectionBreaks: [{ startIndex: 7 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_29', startIndex: 7 }],
columnGroups: [{ startIndex: 0, endIndex: 5, columnGroupId: 'cg-1' }],
};
@@ -147,7 +147,7 @@ describe('TextX column groups', () => {
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 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_30', startIndex: 5 }],
columnGroups: [{ startIndex: 0, endIndex: 4, columnGroupId: 'cg-1' }],
};
const actions: TextXAction[] = [
@@ -166,7 +166,7 @@ describe('TextX column groups', () => {
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 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_31', startIndex: 5 }],
columnGroups: [{ startIndex: 0, endIndex: 4, columnGroupId: 'cg-1' }],
};
@@ -181,7 +181,7 @@ describe('TextX column groups', () => {
const body: IDocumentBody = {
dataStream: `${T.COLUMN_GROUP_START}${T.COLUMN_START}A${T.PARAGRAPH}${T.COLUMN_END}${T.COLUMN_GROUP_END}${T.SECTION_BREAK}`,
paragraphs: [{ startIndex: 3, paragraphId: 'left' }],
- sectionBreaks: [{ startIndex: 6 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_32', startIndex: 6 }],
columnGroups: [{ startIndex: 0, endIndex: 5, columnGroupId: 'cg-1' }],
};
@@ -207,7 +207,7 @@ describe('TextX column groups', () => {
{ startIndex: 3, paragraphId: 'first' },
{ startIndex: 5, paragraphId: 'second' },
],
- sectionBreaks: [{ startIndex: 8 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_33', startIndex: 8 }],
columnGroups: [{ startIndex: 0, endIndex: 7, columnGroupId: 'cg-1' }],
};
@@ -231,8 +231,8 @@ describe('TextX column groups', () => {
{ startIndex: 11, paragraphId: 'right' },
],
sectionBreaks: [
- { startIndex: 8 },
- { startIndex: 14 },
+ { sectionId: 'section_fixture_34', startIndex: 8 },
+ { sectionId: 'section_fixture_35', startIndex: 14 },
],
columnGroups: [{ startIndex: 0, endIndex: 13, columnGroupId: 'cg-1' }],
};
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/invert.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/invert.spec.ts
index fac7b7612b..3a73361274 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/invert.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/invert.spec.ts
@@ -179,6 +179,8 @@ describe('test TextX static methods invert and makeInvertible', () => {
},
oldBody: {
dataStream: '',
+ paragraphs: undefined,
+ sectionBreaks: [],
textRuns: [{
st: 0,
ed: 3,
@@ -188,6 +190,7 @@ describe('test TextX static methods invert and makeInvertible', () => {
}],
customRanges: [],
customDecorations: [],
+ customBlocks: undefined,
},
coverType: UpdateDocsAttributeType.COVER,
}];
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/section-id.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/section-id.spec.ts
new file mode 100644
index 0000000000..c3ff2ad1c8
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/__tests__/section-id.spec.ts
@@ -0,0 +1,125 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentBody } from '../../../../types/interfaces';
+import type { TextXAction } from '../action-types';
+import { describe, expect, it } from 'vitest';
+import { UpdateDocsAttributeType } from '../../../../shared';
+import { createSectionId, SECTION_ID_PREFIX } from '../../../section-break-id';
+import { DataStreamTreeTokenType } from '../../types';
+import { TextXActionType } from '../action-types';
+import { validateDocBodyStructure } from '../structure-validator';
+import { TextX } from '../text-x';
+
+describe('section break identity', () => {
+ it('creates scoped section ids', () => {
+ const ids = new Set<string>();
+ const first = createSectionId(ids);
+ const second = createSectionId(ids);
+
+ expect(first).toMatch(new RegExp(`^${SECTION_ID_PREFIX}`));
+ expect(second).not.toBe(first);
+ expect(ids).toEqual(new Set([first, second]));
+ });
+
+ it('freshens a colliding inserted section id before applying TextX', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `A${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 1, paragraphId: 'para_a' }],
+ sectionBreaks: [{ startIndex: 2, sectionId: 'section_existing' }],
+ };
+ const actions: TextXAction[] = [{
+ t: TextXActionType.INSERT,
+ len: 1,
+ body: {
+ dataStream: T.SECTION_BREAK,
+ sectionBreaks: [{ startIndex: 0, sectionId: 'section_existing' }],
+ },
+ }];
+
+ TextX.makeInvertible(actions, body);
+ TextX.apply(body, actions);
+
+ expect(body.sectionBreaks?.map((section) => section.sectionId)).toHaveLength(2);
+ expect(new Set(body.sectionBreaks?.map((section) => section.sectionId)).size).toBe(2);
+ });
+
+ it('restores the original section id and config through undo', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `A${T.SECTION_BREAK}B${T.SECTION_BREAK}`,
+ sectionBreaks: [
+ { startIndex: 1, sectionId: 'section_left', sectionType: 1 },
+ { startIndex: 3, sectionId: 'section_right' },
+ ],
+ };
+ const actions: TextXAction[] = [
+ { t: TextXActionType.RETAIN, len: 1 },
+ { t: TextXActionType.DELETE, len: 1 },
+ ];
+
+ TextX.makeInvertible(actions, body);
+ TextX.apply(body, actions);
+ TextX.apply(body, TextX.invert(actions));
+
+ expect(body.sectionBreaks?.[0]).toMatchObject({
+ startIndex: 1,
+ sectionId: 'section_left',
+ sectionType: 1,
+ });
+ });
+
+ it('preserves identity when section configuration is replaced', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: T.SECTION_BREAK,
+ sectionBreaks: [{ startIndex: 0, sectionId: 'section_original' }],
+ };
+
+ TextX.apply(body, [{
+ t: TextXActionType.RETAIN,
+ len: 1,
+ coverType: UpdateDocsAttributeType.REPLACE,
+ body: {
+ dataStream: '',
+ sectionBreaks: [{ startIndex: 0, sectionId: 'section_attempted_replacement', sectionType: 1 }],
+ },
+ }]);
+
+ expect(body.sectionBreaks?.[0]).toMatchObject({
+ sectionId: 'section_original',
+ sectionType: 1,
+ });
+ });
+
+ it('reports missing and duplicate section ids', () => {
+ const T = DataStreamTreeTokenType;
+ const body = {
+ dataStream: `${T.SECTION_BREAK}${T.SECTION_BREAK}${T.SECTION_BREAK}`,
+ sectionBreaks: [
+ { startIndex: 0, sectionId: '' },
+ { startIndex: 1, sectionId: 'section_duplicate' },
+ { startIndex: 2, sectionId: 'section_duplicate' },
+ ],
+ } as IDocumentBody;
+
+ expect(validateDocBodyStructure(body).map((issue) => issue.code)).toEqual(expect.arrayContaining([
+ 'missing-section-id',
+ 'duplicate-section-id',
+ ]));
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/tables.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/tables.spec.ts
index d25b6ec981..d412511826 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/tables.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/tables.spec.ts
@@ -33,8 +33,8 @@ describe('TextX tables', () => {
{ startIndex: 12, paragraphId: 'after-table' },
],
sectionBreaks: [
- { startIndex: 8 },
- { startIndex: 13 },
+ { sectionId: 'section_fixture_36', startIndex: 8 },
+ { sectionId: 'section_fixture_37', startIndex: 13 },
],
tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
};
@@ -54,8 +54,8 @@ describe('TextX tables', () => {
{ startIndex: 12, paragraphId: 'after-table' },
],
sectionBreaks: [
- { startIndex: 8 },
- { startIndex: 13 },
+ { sectionId: 'section_fixture_38', startIndex: 8 },
+ { sectionId: 'section_fixture_39', startIndex: 13 },
],
tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
};
@@ -70,7 +70,7 @@ describe('TextX tables', () => {
const body: IDocumentBody = {
dataStream: `A${T.PARAGRAPH}${T.SECTION_BREAK}`,
paragraphs: [{ startIndex: 1, paragraphId: 'before' }],
- sectionBreaks: [{ startIndex: 2 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_40', startIndex: 2 }],
};
TextX.apply(body, [
@@ -83,7 +83,7 @@ describe('TextX tables', () => {
{ startIndex: 4, paragraphId: 'cell' },
{ startIndex: 9, paragraphId: 'after-table' },
],
- sectionBreaks: [{ startIndex: 5 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_41', startIndex: 5 }],
tables: [{ startIndex: 0, endIndex: 9, tableId: 'table-1' }],
},
len: 10,
@@ -101,7 +101,7 @@ describe('TextX tables', () => {
{ startIndex: 1, paragraphId: 'before' },
{ startIndex: 6, paragraphId: 'cell' },
],
- sectionBreaks: [{ startIndex: 10 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_42', startIndex: 10 }],
tables: [{ startIndex: 2, endIndex: 9, tableId: 'table-1' }],
};
@@ -130,8 +130,8 @@ describe('TextX tables', () => {
{ startIndex: 18, paragraphId: 'after' },
],
sectionBreaks: [
- { startIndex: 8 },
- { startIndex: 19 },
+ { sectionId: 'section_fixture_43', startIndex: 8 },
+ { sectionId: 'section_fixture_44', startIndex: 19 },
],
tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
};
@@ -159,8 +159,8 @@ describe('TextX tables', () => {
{ startIndex: 12, paragraphId: 'after' },
],
sectionBreaks: [
- { startIndex: 8 },
- { startIndex: 13 },
+ { sectionId: 'section_fixture_45', startIndex: 8 },
+ { sectionId: 'section_fixture_46', startIndex: 13 },
],
tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
};
@@ -185,8 +185,8 @@ describe('TextX tables', () => {
{ startIndex: tableStream.length + 5, paragraphId: 'after' },
],
sectionBreaks: [
- { startIndex: 8 },
- { startIndex: tableStream.length + 6 },
+ { sectionId: 'section_fixture_47', startIndex: 8 },
+ { sectionId: 'section_fixture_48', startIndex: tableStream.length + 6 },
],
tables: [{ startIndex: 0, endIndex: tableStream.length, tableId: 'table-1' }],
};
@@ -214,8 +214,8 @@ describe('TextX tables', () => {
{ startIndex: columnGroupStart + 6, paragraphId: 'column' },
],
sectionBreaks: [
- { startIndex: 8 },
- { startIndex: columnGroupStart + columnGroupStream.length - 1 },
+ { sectionId: 'section_fixture_49', startIndex: 8 },
+ { sectionId: 'section_fixture_50', startIndex: columnGroupStart + columnGroupStream.length - 1 },
],
tables: [{ startIndex: 0, endIndex: tableEnd, tableId: 'table-1' }],
columnGroups: [{
@@ -249,8 +249,8 @@ describe('TextX tables', () => {
{ startIndex: 12, paragraphId: 'after' },
],
sectionBreaks: [
- { startIndex: 8 },
- { startIndex: 13 },
+ { sectionId: 'section_fixture_51', startIndex: 8 },
+ { sectionId: 'section_fixture_52', startIndex: 13 },
],
tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
};
@@ -280,8 +280,8 @@ describe('TextX tables', () => {
{ startIndex: 18, paragraphId: 'after' },
],
sectionBreaks: [
- { startIndex: 8 },
- { startIndex: 19 },
+ { sectionId: 'section_fixture_53', startIndex: 8 },
+ { sectionId: 'section_fixture_54', startIndex: 19 },
],
tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
};
@@ -312,8 +312,8 @@ describe('TextX tables', () => {
{ startIndex: 18, paragraphId: 'after' },
],
sectionBreaks: [
- { startIndex: 8 },
- { startIndex: 19 },
+ { sectionId: 'section_fixture_55', startIndex: 8 },
+ { sectionId: 'section_fixture_56', startIndex: 19 },
],
tables: [{ startIndex: 0, endIndex: 12, tableId: 'table-1' }],
};
@@ -329,7 +329,6 @@ describe('TextX tables', () => {
];
TextX.apply(body, TextX.compose(firstUpdate, secondUpdate));
-
expect(body.dataStream).toBe(`${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cel啊手l${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}After${T.PARAGRAPH}${T.SECTION_BREAK}`);
expect(body.tables).toEqual([{ startIndex: 0, endIndex: 14, tableId: 'table-1' }]);
expect(body.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([9, 20]);
@@ -341,8 +340,8 @@ describe('TextX tables', () => {
dataStream: `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}A${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.SECTION_BREAK}`,
paragraphs: [{ startIndex: 4, paragraphId: 'cell' }],
sectionBreaks: [
- { startIndex: 5 },
- { startIndex: 9 },
+ { sectionId: 'section_fixture_57', startIndex: 5 },
+ { sectionId: 'section_fixture_58', startIndex: 9 },
],
tables: [{ startIndex: 0, endIndex: 8, 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 e9e40e21ac..bdb5a12308 100644
--- a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
@@ -31,6 +31,7 @@ import { shallowEqual } from '../../../../common/equal';
import { horizontalLineSegmentsSubtraction, sortRulesFactory, Tools } from '../../../../shared';
import { isSameStyleTextRun } from '../../../../shared/compare';
import { cloneParagraphWithId } from '../../../paragraph-id';
+import { cloneSectionBreakWithId } from '../../../section-break-id';
import { DataStreamTreeTokenType } from '../../types';
import { PRESERVE_INSERTED_PARAGRAPH_IDS } from '../action-types';
import {
@@ -397,6 +398,8 @@ export function insertSectionBreaks(
body.sectionBreaks ??= [];
const { sectionBreaks } = body;
+ const insertSectionBreaks = insertBody.sectionBreaks;
+ normalizeInsertedSectionIdsForDocument(sectionBreaks, insertSectionBreaks);
for (let i = 0, len = sectionBreaks.length; i < len; i++) {
const sectionBreak = sectionBreaks[i];
@@ -413,7 +416,6 @@ export function insertSectionBreaks(
}
}
- const insertSectionBreaks = insertBody.sectionBreaks;
if (insertSectionBreaks) {
for (let i = 0, len = insertSectionBreaks.length; i < len; i++) {
const sectionBreak = insertSectionBreaks[i];
@@ -425,6 +427,26 @@ export function insertSectionBreaks(
}
}
+export function normalizeInsertedSectionIdsForDocument(
+ sectionBreaks: ISectionBreak[] | undefined,
+ insertSectionBreaks: ISectionBreak[] | undefined,
+ reservedSectionIds: Set<string> = new Set()
+): void {
+ if (!insertSectionBreaks?.length) {
+ return;
+ }
+
+ const existingSectionIds = new Set(sectionBreaks?.map((sectionBreak) => sectionBreak.sectionId) ?? []);
+ for (const sectionId of reservedSectionIds) {
+ existingSectionIds.add(sectionId);
+ }
+
+ for (let i = 0; i < insertSectionBreaks.length; i++) {
+ insertSectionBreaks[i] = cloneSectionBreakWithId(insertSectionBreaks[i], existingSectionIds);
+ reservedSectionIds.add(insertSectionBreaks[i].sectionId);
+ }
+}
+
export function insertCustomBlocks(
body: IDocumentBody,
insertBody: IDocumentBody,
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 ee3d94d68b..3441e9b882 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
@@ -347,7 +347,19 @@ function updateSectionBreaks(
newUpdateSectionBreaks.push(...splitUpdateSectionBreaks);
splitUpdateSectionBreaks = [];
}
- updateBody.sectionBreaks = newUpdateSectionBreaks;
+ updateBody.sectionBreaks = newUpdateSectionBreaks.map((updateSectionBreak) => {
+ const removed = removeSectionBreaks.find((sectionBreak) => sectionBreak.startIndex === updateSectionBreak.startIndex);
+ return removed
+ ? { ...updateSectionBreak, sectionId: removed.sectionId }
+ : updateSectionBreak;
+ });
+ } else {
+ updateBody.sectionBreaks = updateDataSectionBreaks.map((updateSectionBreak) => {
+ const removed = removeSectionBreaks.find((sectionBreak) => sectionBreak.startIndex === updateSectionBreak.startIndex);
+ return removed
+ ? { ...updateSectionBreak, sectionId: removed.sectionId }
+ : updateSectionBreak;
+ });
}
insertSectionBreaks(body, updateBody, textLength, currentIndex);
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/drawings.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/drawings.spec.ts
index ee18ac6179..5011022cc3 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/drawings.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/drawings.spec.ts
@@ -27,7 +27,7 @@ describe('drawing build utils', () => {
body: {
dataStream: '\r\n',
paragraphs: [{ startIndex: 0, paragraphId: 'para_top' }],
- sectionBreaks: [{ startIndex: 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_59', startIndex: 1 }],
customBlocks: [],
},
drawings: {},
@@ -65,7 +65,7 @@ describe('drawing build utils', () => {
{ startIndex: 2, paragraphId: expect.stringMatching(/^para_/) },
]);
expect(doc.getBody()?.customBlocks).toEqual([{ startIndex: 1, blockId: 'drawing-new' }]);
- expect(doc.getBody()?.sectionBreaks).toEqual([{ startIndex: 3 }]);
+ expect(doc.getBody()?.sectionBreaks).toEqual([{ sectionId: expect.any(String), startIndex: 3 }]);
});
it('should resolve custom blocks and replace selected drawings in the document body', () => {
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/replace-selection.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/replace-selection.spec.ts
index 5f3b180557..0bfa0ed5d7 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/replace-selection.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/replace-selection.spec.ts
@@ -28,7 +28,7 @@ describe('replaceSelectionTextX', () => {
const body: IDocumentBody = {
dataStream: `A${T.PARAGRAPH}${T.SECTION_BREAK}`,
paragraphs: [{ startIndex: 1, paragraphId: 'para_minimum' }],
- sectionBreaks: [{ startIndex: 2 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_60', startIndex: 2 }],
};
const doc = new DocumentDataModel({ body });
@@ -52,7 +52,7 @@ describe('replaceSelectionTextX', () => {
const body: IDocumentBody = {
dataStream: `A${T.PARAGRAPH}${T.SECTION_BREAK}`,
paragraphs: [{ startIndex: 1, paragraphId: 'para_minimum' }],
- sectionBreaks: [{ startIndex: 2 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_61', startIndex: 2 }],
};
const doc = new DocumentDataModel({ body });
@@ -78,7 +78,7 @@ describe('replaceSelectionTextX', () => {
{ startIndex: 1, paragraphId: 'first' },
{ startIndex: 3, paragraphId: 'second' },
],
- sectionBreaks: [{ startIndex: 4 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_62', startIndex: 4 }],
};
const actions = BuildTextUtils.selection.delete(
@@ -100,7 +100,7 @@ describe('replaceSelectionTextX', () => {
{ startIndex: 5, paragraphId: 'first' },
{ startIndex: 10, paragraphId: 'second' },
],
- sectionBreaks: [{ startIndex: 11 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_63', startIndex: 11 }],
};
const actions = BuildTextUtils.selection.delete(
@@ -124,7 +124,7 @@ describe('replaceSelectionTextX', () => {
{ startIndex: 5, paragraphId: 'first', bullet },
{ startIndex: 10, paragraphId: 'second' },
],
- sectionBreaks: [{ startIndex: 11 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_64', startIndex: 11 }],
};
const actions = BuildTextUtils.selection.delete(
diff --git a/packages/core/src/docs/data-model/text-x/structure-validator.ts b/packages/core/src/docs/data-model/text-x/structure-validator.ts
index 2ae598e7f2..f36184bae8 100644
--- a/packages/core/src/docs/data-model/text-x/structure-validator.ts
+++ b/packages/core/src/docs/data-model/text-x/structure-validator.ts
@@ -30,6 +30,8 @@ export type DocStructureIssueCode =
| 'duplicate-paragraph-metadata'
| 'section-break-token-mismatch'
| 'duplicate-section-break-metadata'
+ | 'missing-section-id'
+ | 'duplicate-section-id'
| 'table-start-token-mismatch'
| 'table-end-token-mismatch'
| 'missing-table-metadata'
@@ -111,7 +113,14 @@ function validateParagraphMetadata(body: IDocumentBody, issues: IDocStructureIss
function validateSectionBreakMetadata(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {
const metadataCounts = new Map<number, number>();
+ const sectionIds = new Map<string, number>();
for (const sectionBreak of body.sectionBreaks ?? []) {
+ if (!sectionBreak.sectionId) {
+ issues.push(createIssue(context, 'missing-section-id', 'Section break metadata must have a stable section id.', sectionBreak.startIndex));
+ } else {
+ sectionIds.set(sectionBreak.sectionId, (sectionIds.get(sectionBreak.sectionId) ?? 0) + 1);
+ }
+
if (body.dataStream[sectionBreak.startIndex] !== DataStreamTreeTokenType.SECTION_BREAK) {
issues.push(createIssue(
context,
@@ -129,6 +138,12 @@ function validateSectionBreakMetadata(body: IDocumentBody, issues: IDocStructure
duplicateCode: 'duplicate-section-break-metadata',
duplicateMessage: 'Section break sentinel must have exactly one section break metadata entry.',
}, issues);
+
+ for (const [sectionId, count] of sectionIds) {
+ if (count > 1) {
+ issues.push(createIssue(context, 'duplicate-section-id', `Section id "${sectionId}" must be unique within a document segment.`));
+ }
+ }
}
function validatePointMetadataDuplicates(
diff --git a/packages/core/src/docs/data-model/text-x/text-x.ts b/packages/core/src/docs/data-model/text-x/text-x.ts
index 00a8fbad6c..7fec18491c 100644
--- a/packages/core/src/docs/data-model/text-x/text-x.ts
+++ b/packages/core/src/docs/data-model/text-x/text-x.ts
@@ -22,7 +22,7 @@ import { Tools } from '../../../shared/tools';
import { ActionIterator } from './action-iterator';
import { PRESERVE_INSERTED_PARAGRAPH_IDS, TextXActionType } from './action-types';
import { textXApply } from './apply';
-import { normalizeInsertedParagraphIdsForDocument, RESTORE_INSERTED_PARAGRAPH_IDS } from './apply-utils/common';
+import { normalizeInsertedParagraphIdsForDocument, normalizeInsertedSectionIdsForDocument, RESTORE_INSERTED_PARAGRAPH_IDS } from './apply-utils/common';
import { transformBody } from './transform-utils';
import { composeBody, getBodySlice, isUselessRetainAction } from './utils';
@@ -281,10 +281,12 @@ export class TextX {
let index = 0;
const reservedParagraphIds = new Set<string>();
+ const reservedSectionIds = new Set<string>();
for (const action of actions) {
if (action.t === TextXActionType.INSERT) {
normalizeInsertActionParagraphIds(action.body, doc, index, reservedParagraphIds);
+ normalizeInsertedSectionIdsForDocument(doc.sectionBreaks, action.body.sectionBreaks, reservedSectionIds);
}
if (action.t === TextXActionType.DELETE && (action.body == null || (action.body && action.body.dataStream.length !== action.len))) {
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 9820ff36a8..472075b5c1 100644
--- a/packages/core/src/docs/data-model/text-x/utils.ts
+++ b/packages/core/src/docs/data-model/text-x/utils.ts
@@ -322,6 +322,12 @@ export function getBodySlice(
}
docBody.paragraphs = getParagraphsSlice(body, startOffset, endOffset, type);
+ const sectionBreaks = getSectionBreakSlice(body, startOffset, endOffset - 1);
+ if (sectionBreaks) {
+ docBody.sectionBreaks = sectionBreaks;
+ } else if (returnEmptyArray) {
+ docBody.sectionBreaks = [];
+ }
if (type === SliceBodyType.cut) {
const customDecorations = getCustomDecorationSlice(body, startOffset, endOffset);
diff --git a/packages/core/src/docs/data-model/utils.ts b/packages/core/src/docs/data-model/utils.ts
index f8a8f3edda..6a0d6b8bf1 100644
--- a/packages/core/src/docs/data-model/utils.ts
+++ b/packages/core/src/docs/data-model/utils.ts
@@ -68,7 +68,7 @@ export function getFontStyleString(
// font-size/line-height
let originFontSize = defaultFontSize;
if (textStyle.fs) {
- originFontSize = Math.ceil(textStyle.fs);
+ originFontSize = textStyle.fs;
}
const fontFamilyResult = normalizeFontFamily(textStyle.ff, defaultFont);
diff --git a/packages/core/src/docs/index.ts b/packages/core/src/docs/index.ts
index fc47b0203e..a8eac4a3aa 100644
--- a/packages/core/src/docs/index.ts
+++ b/packages/core/src/docs/index.ts
@@ -22,3 +22,19 @@ export {
PARAGRAPH_ID_PREFIX,
} from './paragraph-id';
export type { IParagraphIdScope } from './paragraph-id';
+export {
+ cloneSectionBreakWithId,
+ createSectionId,
+ SECTION_ID_PREFIX,
+} from './section-break-id';
+export {
+ getSectionHeaderFooterReferenceKey,
+ resolveSectionHeaderFooterReference,
+ resolveSectionHeaderFooterReferences,
+} from './section-header-footer';
+export type {
+ IResolvedSectionHeaderFooterReference,
+ SectionHeaderFooterKind,
+ SectionHeaderFooterReferenceKey,
+ SectionHeaderFooterVariant,
+} from './section-header-footer';
diff --git a/packages/core/src/docs/section-break-id.ts b/packages/core/src/docs/section-break-id.ts
new file mode 100644
index 0000000000..bf7efe6dad
--- /dev/null
+++ b/packages/core/src/docs/section-break-id.ts
@@ -0,0 +1,48 @@
+/**
+ * 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 { ISectionBreak } from '../types/interfaces/i-document-data';
+import { generateRandomId } from '../shared/random-id';
+import { Tools } from '../shared/tools';
+
+export const SECTION_ID_PREFIX = 'section_';
+
+export function createSectionId(existingIds: Set<string>): string {
+ let sectionId = `${SECTION_ID_PREFIX}${generateRandomId(12)}`;
+
+ while (existingIds.has(sectionId)) {
+ sectionId = `${SECTION_ID_PREFIX}${generateRandomId(12)}`;
+ }
+
+ existingIds.add(sectionId);
+ return sectionId;
+}
+
+export function cloneSectionBreakWithId(sectionBreak: ISectionBreak, existingIds: Set<string>, preserveId = true): ISectionBreak {
+ const cloned = Tools.deepClone(sectionBreak);
+
+ if (preserveId && isValidSectionId(cloned.sectionId) && !existingIds.has(cloned.sectionId)) {
+ existingIds.add(cloned.sectionId);
+ return cloned;
+ }
+
+ cloned.sectionId = createSectionId(existingIds);
+ return cloned;
+}
+
+function isValidSectionId(value: unknown): value is string {
+ return typeof value === 'string' && value.startsWith(SECTION_ID_PREFIX) && value.length > SECTION_ID_PREFIX.length;
+}
diff --git a/packages/core/src/docs/section-header-footer.ts b/packages/core/src/docs/section-header-footer.ts
new file mode 100644
index 0000000000..83a209491c
--- /dev/null
+++ b/packages/core/src/docs/section-header-footer.ts
@@ -0,0 +1,106 @@
+/**
+ * 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 { IDocumentStyle, ISectionBreak } from '../types/interfaces/i-document-data';
+
+export type SectionHeaderFooterKind = 'header' | 'footer';
+export type SectionHeaderFooterVariant = 'default' | 'first' | 'even';
+export type SectionHeaderFooterReferenceKey =
+ | 'defaultHeaderId'
+ | 'defaultFooterId'
+ | 'firstPageHeaderId'
+ | 'firstPageFooterId'
+ | 'evenPageHeaderId'
+ | 'evenPageFooterId';
+
+export interface IResolvedSectionHeaderFooterReference {
+ segmentId?: string;
+ linkedToPrevious: boolean;
+ sourceSectionId?: string;
+}
+
+export function getSectionHeaderFooterReferenceKey(
+ kind: SectionHeaderFooterKind,
+ variant: SectionHeaderFooterVariant
+): SectionHeaderFooterReferenceKey {
+ const prefix = variant === 'default' ? 'default' : variant === 'first' ? 'firstPage' : 'evenPage';
+ return `${prefix}${kind === 'header' ? 'Header' : 'Footer'}Id` as SectionHeaderFooterReferenceKey;
+}
+
+/**
+ * Resolves one OOXML header/footer reference for a document section.
+ * A missing reference after the first section inherits the previous section.
+ * Document-level references are defaults for the first section only.
+ */
+export function resolveSectionHeaderFooterReference(
+ documentStyle: IDocumentStyle,
+ sections: Readonly<ISectionBreak[]>,
+ sectionIndex: number,
+ key: SectionHeaderFooterReferenceKey
+): IResolvedSectionHeaderFooterReference {
+ if (sectionIndex < 0 || sectionIndex >= sections.length) {
+ return { linkedToPrevious: false };
+ }
+
+ const current = sections[sectionIndex];
+ const explicit = current[key];
+ if (typeof explicit === 'string' && explicit) {
+ return {
+ segmentId: explicit,
+ linkedToPrevious: false,
+ sourceSectionId: current.sectionId,
+ };
+ }
+
+ if (sectionIndex === 0) {
+ const documentDefault = documentStyle[key];
+ return {
+ ...(typeof documentDefault === 'string' && documentDefault ? { segmentId: documentDefault } : {}),
+ linkedToPrevious: false,
+ };
+ }
+
+ const inherited = resolveSectionHeaderFooterReference(documentStyle, sections, sectionIndex - 1, key);
+ return {
+ ...(inherited.segmentId ? { segmentId: inherited.segmentId } : {}),
+ linkedToPrevious: true,
+ sourceSectionId: inherited.sourceSectionId,
+ };
+}
+
+export function resolveSectionHeaderFooterReferences(
+ documentStyle: IDocumentStyle,
+ sections: Readonly<ISectionBreak[]>,
+ sectionIndex: number
+): Pick<ISectionBreak, SectionHeaderFooterReferenceKey> {
+ const result: Pick<ISectionBreak, SectionHeaderFooterReferenceKey> = {};
+ const keys: SectionHeaderFooterReferenceKey[] = [
+ 'defaultHeaderId',
+ 'defaultFooterId',
+ 'firstPageHeaderId',
+ 'firstPageFooterId',
+ 'evenPageHeaderId',
+ 'evenPageFooterId',
+ ];
+
+ for (const key of keys) {
+ const { segmentId } = resolveSectionHeaderFooterReference(documentStyle, sections, sectionIndex, key);
+ if (segmentId) {
+ result[key] = segmentId;
+ }
+ }
+ return result;
+}
diff --git a/packages/core/src/sheets/util.ts b/packages/core/src/sheets/util.ts
index 8bf1a9456f..4be897b73b 100644
--- a/packages/core/src/sheets/util.ts
+++ b/packages/core/src/sheets/util.ts
@@ -23,6 +23,7 @@ import { BuildTextUtils, DocumentDataModel } from '../docs';
import { TextX } from '../docs/data-model/text-x/text-x';
import { convertTextRotation } from '../docs/data-model/utils';
import { createParagraphId } from '../docs/paragraph-id';
+import { createSectionId } from '../docs/section-break-id';
import { Rectangle } from '../shared';
import { HorizontalAlign, VerticalAlign, WrapStrategy } from '../types/enum';
import { CustomRangeType, DocumentFlavor } from '../types/interfaces';
@@ -106,6 +107,7 @@ export function createDocumentModelWithStyle(content: string, textStyle: ITextSt
},
],
sectionBreaks: [{
+ sectionId: createSectionId(new Set()),
startIndex: contentLength + 1,
}],
},
diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.ts
index 4cbf1914a9..5bba83839a 100644
--- a/packages/core/src/types/interfaces/i-document-data.ts
+++ b/packages/core/src/types/interfaces/i-document-data.ts
@@ -474,8 +474,10 @@ export interface IDocStyleBase extends IMargin {
documentFlavor?: DocumentFlavor; // DocumentFlavor: TRADITIONAL, MODERN
- marginHeader?: number; // marginHeader
- marginFooter?: number; // marginFooter
+ /** Distance from the page edge to the header, in points (pt). */
+ marginHeader?: number;
+ /** Distance from the page edge to the footer, in points (pt). */
+ marginFooter?: number;
renderConfig?: IDocumentRenderConfig;
}
@@ -559,6 +561,8 @@ export interface ISectionBreakBase {
* Properties of section break
*/
export interface ISectionBreak extends IDocStyleBase, ISectionBreakBase, IHeaderAndFooterBase {
+ /** Stable identity of the section-break metadata entry. */
+ sectionId: string;
startIndex: number;
}
@@ -595,7 +599,9 @@ export enum TextDirectionType {
* Properties of section column
*/
export interface ISectionColumnProperties {
+ /** Column width in points (pt). */
width: number;
+ /** Trailing space after the column in points (pt). */
paddingEnd: number;
}
diff --git a/packages/core/src/types/interfaces/i-style-data.ts b/packages/core/src/types/interfaces/i-style-data.ts
index ff02905a5d..c2716ea9ab 100644
--- a/packages/core/src/types/interfaces/i-style-data.ts
+++ b/packages/core/src/types/interfaces/i-style-data.ts
@@ -213,11 +213,7 @@ export interface IStyleBase {
* fontFamily
*/
ff?: Nullable<string>;
- /**
- * fontSize
- *
- * pt
- */
+ /** Font size in points (pt), where 1 pt is 1/72 inch. */
fs?: number;
/**
* italic
diff --git a/packages/docs-thread-comment-ui/src/views/__tests__/DocThreadCommentPanel.spec.tsx b/packages/docs-thread-comment-ui/src/views/__tests__/DocThreadCommentPanel.spec.tsx
index d53a983004..31c77a3592 100644
--- a/packages/docs-thread-comment-ui/src/views/__tests__/DocThreadCommentPanel.spec.tsx
+++ b/packages/docs-thread-comment-ui/src/views/__tests__/DocThreadCommentPanel.spec.tsx
@@ -147,6 +147,7 @@ function createTextBody(text: string): IDocumentBody {
],
sectionBreaks: [
{
+ sectionId: `section-${text}`,
startIndex: dataStream.length - 1,
},
],
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 2c3cd7d8c1..22f83e4a4d 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
@@ -64,7 +64,7 @@ function getDocumentDataWithColumnGroup(): IDocumentData {
{ paragraphId: 'right', startIndex: 14 },
{ paragraphId: 'after', startIndex: 17 },
],
- sectionBreaks: [{ startIndex: 18 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_201', startIndex: 18 }],
columnGroups: [{ columnGroupId: 'cg-1', startIndex: 7, endIndex: 16 }],
},
documentStyle: {
@@ -92,7 +92,7 @@ function getDocumentDataWithAdjacentBlocks(): IDocumentData {
{ paragraphId: 'callout-paragraph', startIndex: 6, paragraphStyle: { indentStart: { v: 60 } } },
{ paragraphId: 'trailing-paragraph', startIndex: 8 },
],
- sectionBreaks: [{ startIndex: 9 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_202', startIndex: 9 }],
blockRanges: [
{ blockId: 'code-1', blockType: DocumentBlockRangeType.CODE, startIndex: 0, endIndex: 3 },
{ blockId: 'callout-1', blockType: DocumentBlockRangeType.CALLOUT, startIndex: 4, endIndex: 7 },
diff --git a/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts
index 9fd1cc8eb5..eaad8cc476 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts
@@ -227,7 +227,7 @@ describe('test cases in clipboard', () => {
],
sectionBreaks: [
...tableData.sectionBreaks,
- { startIndex: dataStream.length - 1 },
+ { sectionId: 'section_fixture_203', startIndex: dataStream.length - 1 },
],
tables: [{
startIndex: 0,
@@ -264,7 +264,7 @@ describe('test cases in clipboard', () => {
{ paragraphId: 'para_docs_ui_clipboard_block', startIndex: 1 },
{ paragraphId: 'para_docs_ui_clipboard_block_tail', startIndex: dataStream.length - 2 },
],
- sectionBreaks: [{ startIndex: dataStream.length - 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_204', startIndex: dataStream.length - 1 }],
customBlocks: [{ blockId: 'drawing-1', startIndex: 0 }],
},
drawings: {
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 58b60d3b2a..61eec3113a 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
@@ -32,7 +32,7 @@ describe('buildMoveDocBlockActions', () => {
it('moves a paragraph and remaps paragraph indexes', () => {
const documentData = createDocument('A\rB\rC\r\n', {
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_9', startIndex: 1 }, { paragraphId: 'para_docs_ui_fixture_10', startIndex: 3 }, { paragraphId: 'para_docs_ui_fixture_11', startIndex: 5 }],
- sectionBreaks: [{ startIndex: 6 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_205', startIndex: 6 }],
});
const { nextDocumentData, movedRange } = buildMoveDocBlockActions({
@@ -49,7 +49,7 @@ describe('buildMoveDocBlockActions', () => {
it('moves a block range as one unit', () => {
const documentData = createDocument('aa\rBB\rcc\r\n', {
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_12', startIndex: 2 }, { paragraphId: 'para_docs_ui_fixture_13', startIndex: 5 }, { paragraphId: 'para_docs_ui_fixture_14', startIndex: 8 }],
- sectionBreaks: [{ startIndex: 9 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_206', startIndex: 9 }],
blockRanges: [{ blockId: 'quote-1', blockType: DocumentBlockRangeType.QUOTE, startIndex: 3, endIndex: 5 }],
});
@@ -68,7 +68,7 @@ describe('buildMoveDocBlockActions', () => {
it('moves a table range and remaps custom ranges and text runs', () => {
const documentData = createDocument('aa\rTT\rcc\r\n', {
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_15', startIndex: 2 }, { paragraphId: 'para_docs_ui_fixture_16', startIndex: 5 }, { paragraphId: 'para_docs_ui_fixture_17', startIndex: 8 }],
- sectionBreaks: [{ startIndex: 9 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_207', startIndex: 9 }],
tables: [{ tableId: 'table-1', startIndex: 3, endIndex: 6 }],
customRanges: [{ rangeId: 'comment-1', rangeType: CustomRangeType.COMMENT, startIndex: 6, endIndex: 7 }],
textRuns: [{ st: 6, ed: 8, ts: {} }],
@@ -89,7 +89,7 @@ describe('buildMoveDocBlockActions', () => {
it('moves a custom block paragraph and keeps the custom block attached', () => {
const documentData = createDocument('\b\raa\r\n', {
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_18', startIndex: 1 }, { paragraphId: 'para_docs_ui_fixture_19', startIndex: 4 }],
- sectionBreaks: [{ startIndex: 5 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_208', startIndex: 5 }],
customBlocks: [{ blockId: 'custom-1', blockType: BlockType.CUSTOM, startIndex: 0 }],
});
@@ -120,7 +120,7 @@ describe('buildMoveDocBlockActions', () => {
const documentData = createDocument('A\rB\r\n', {
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_20', startIndex: 1 }, { paragraphId: 'para_docs_ui_fixture_21', startIndex: 3 }],
- sectionBreaks: [{ startIndex: 4 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_209', startIndex: 4 }],
});
const { nextDocumentData, movedRange } = buildMoveDocBlockActions({
@@ -136,7 +136,7 @@ describe('buildMoveDocBlockActions', () => {
it('remaps custom decorations that move with their paragraph', () => {
const documentData = createDocument('aa\rDD\rcc\r\n', {
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_22', startIndex: 2 }, { paragraphId: 'para_docs_ui_fixture_23', startIndex: 5 }, { paragraphId: 'para_docs_ui_fixture_24', startIndex: 8 }],
- sectionBreaks: [{ startIndex: 9 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_210', startIndex: 9 }],
customDecorations: [{ id: 'decoration-1', startIndex: 3, endIndex: 5 } as never],
});
@@ -154,7 +154,10 @@ describe('buildMoveDocBlockActions', () => {
it('keeps every document metadata collection ordered after moving content upward', () => {
const documentData = createDocument('aa\rMM\rzz\r\n', {
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_29', startIndex: 2 }, { paragraphId: 'para_docs_ui_fixture_30', startIndex: 5 }, { paragraphId: 'para_docs_ui_fixture_31', startIndex: 8 }],
- sectionBreaks: [{ startIndex: 6 }, { startIndex: 9 }],
+ sectionBreaks: [
+ { sectionId: 'section_move_two', startIndex: 6 },
+ { sectionId: 'section_move_three', startIndex: 9 },
+ ],
customBlocks: [{ blockId: 'custom-2', blockType: BlockType.CUSTOM, startIndex: 3 }, { blockId: 'custom-3', blockType: BlockType.CUSTOM, startIndex: 6 }],
tables: [{ tableId: 'table-2', startIndex: 3, endIndex: 5 }, { tableId: 'table-3', startIndex: 6, endIndex: 8 }],
blockRanges: [{ blockId: 'quote-2', blockType: DocumentBlockRangeType.QUOTE, startIndex: 3, endIndex: 5 }, { blockId: 'quote-3', blockType: DocumentBlockRangeType.QUOTE, startIndex: 6, endIndex: 8 }],
@@ -189,7 +192,7 @@ describe('buildMoveDocBlockActions', () => {
{ paragraphId: 'para_docs_ui_fixture_34', startIndex: 9 },
{ paragraphId: 'para_docs_ui_fixture_35', startIndex: 13 },
],
- sectionBreaks: [{ startIndex: 14 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_213', startIndex: 14 }],
columnGroups: [{ columnGroupId: 'column-group-1', startIndex: 2, endIndex: 11 }],
});
@@ -219,7 +222,7 @@ describe('MoveDocBlockCommand', () => {
it('moves a block through the real rich text mutation flow', async () => {
testBed = createCommandTestBed(createDocument('A\rB\rC\r\n', {
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_25', startIndex: 1 }, { paragraphId: 'para_docs_ui_fixture_26', startIndex: 3 }, { paragraphId: 'para_docs_ui_fixture_27', startIndex: 5 }],
- sectionBreaks: [{ startIndex: 6 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_214', startIndex: 6 }],
}));
const commandService = testBed.get(ICommandService);
commandService.registerCommand(MoveDocBlockCommand);
@@ -246,7 +249,7 @@ describe('MoveDocBlockCommand', () => {
{ paragraphId: 'para_docs_ui_fixture_38', startIndex: 9 },
{ paragraphId: 'para_docs_ui_fixture_39', startIndex: 13 },
],
- sectionBreaks: [{ startIndex: 14 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_215', startIndex: 14 }],
columnGroups: [{ columnGroupId: 'column-group-1', startIndex: 2, endIndex: 11 }],
}));
const commandService = testBed.get(ICommandService);
@@ -270,7 +273,7 @@ describe('MoveDocBlockCommand', () => {
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 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_216', startIndex: 4 }],
}));
const commandService = testBed.get(ICommandService);
const moveValidatorService = testBed.get(DocBlockMoveValidatorService);
@@ -301,7 +304,7 @@ describe('MoveDocBlockCommand', () => {
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 }],
- sectionBreaks: [{ startIndex: 2 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_217', startIndex: 2 }],
}));
const commandService = testBed.get(ICommandService);
commandService.registerCommand(MoveDocBlockCommand);
@@ -320,7 +323,7 @@ describe('buildReplaceDocumentBodyActions', () => {
it('uses TextX and local body patches instead of replacing whole body fields', () => {
const previousDocumentData = createDocument('A\rB\rC\r\n', {
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_42', startIndex: 1 }, { paragraphId: 'para_docs_ui_fixture_43', startIndex: 3 }, { paragraphId: 'para_docs_ui_fixture_44', startIndex: 5 }],
- sectionBreaks: [{ startIndex: 6 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_218', startIndex: 6 }],
});
const sourceRange = { startOffset: 0, endOffset: 2 };
const targetOffset = 6;
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 3f73a9f115..88f0bb44f8 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
@@ -111,7 +111,7 @@ function createTableFixture(rowCount = 3, colCount = 3): ITableFixture {
...sectionBreak,
startIndex: sectionBreak.startIndex + tableStartIndex,
})),
- { startIndex: dataStream.length - 1 },
+ { sectionId: 'section_fixture_219', startIndex: dataStream.length - 1 },
],
tables: [{
startIndex: tableStartIndex,
@@ -635,7 +635,7 @@ describe('doc table create command helpers', () => {
body: {
...documentData.body!,
paragraphs: [{ paragraphId: 'para_block_range', startIndex: 8 }],
- sectionBreaks: [{ startIndex: 11 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_220', startIndex: 11 }],
blockRanges: [{ blockId: 'callout-1', blockType: DocumentBlockRangeType.CALLOUT, startIndex: 0, endIndex: 9 }],
},
});
@@ -703,7 +703,7 @@ describe('doc table create command helpers', () => {
dataStream: 'A\b\r\n',
textRuns: [{ st: 0, ed: 2, ts: {} }],
paragraphs: [{ paragraphId: 'para_custom_block', startIndex: 2 }],
- sectionBreaks: [{ startIndex: 3 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_221', startIndex: 3 }],
customBlocks: [{ startIndex: 1, blockId: 'custom-block-1' }],
},
});
@@ -756,7 +756,7 @@ function createParagraphDocument(dataStream: string): IDocumentData {
ts: {},
}],
paragraphs: [{ paragraphId: 'para_docs_ui_create_table', startIndex: dataStream.length - 2 }],
- sectionBreaks: [{ startIndex: dataStream.length - 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_222', startIndex: dataStream.length - 1 }],
customBlocks: [],
},
documentStyle: {
diff --git a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts
index fbbe6879e7..51420e9caa 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts
@@ -207,6 +207,7 @@ function createBaseDoc(dataStream = 'Hello world\r\n'): IDocumentData {
}],
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_22', startIndex: dataStream.length - 2 }],
sectionBreaks: [{
+ sectionId: 'section_fixture_base',
startIndex: dataStream.length - 1,
}],
customBlocks: [],
@@ -346,6 +347,7 @@ function createMultiParagraphDoc(): IDocumentData {
headingId: 'heading-1',
} }, { paragraphId: 'para_docs_ui_fixture_24', startIndex: 10 }],
sectionBreaks: [{
+ sectionId: 'section_fixture_multi',
startIndex: 11,
}],
customBlocks: [],
@@ -440,6 +442,7 @@ function createTableDoc(): IDocumentData {
startIndex: sectionBreak.startIndex + prefix.length,
})),
{
+ sectionId: 'section_fixture_223',
startIndex: dataStream.length - 1,
},
],
@@ -485,6 +488,7 @@ function createTableCommandDoc(rowCount = 2, colCount = 2): IDocumentData {
sectionBreaks: [
...table.sectionBreaks,
{
+ sectionId: 'section_fixture_224',
startIndex: dataStream.length - 1,
},
],
@@ -558,6 +562,7 @@ function createTableDocWithParagraphsBeforeTable(): IDocumentData {
startIndex: sectionBreak.startIndex + prefix.length,
})),
{
+ sectionId: 'section_fixture_225',
startIndex: dataStream.length - 1,
},
],
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 a054304299..70723620c3 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
@@ -184,7 +184,7 @@ describe('replace or cover content of document', () => {
{ paragraphId: 'para_replace_right', startIndex: 14 },
{ paragraphId: 'para_replace_after', startIndex: 17 },
],
- sectionBreaks: [{ startIndex: 18 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_226', startIndex: 18 }],
customBlocks: [],
columnGroups,
},
@@ -254,7 +254,7 @@ describe('replace or cover content of document', () => {
body: {
dataStream: 'Snapshot\r\n',
paragraphs: [{ paragraphId: 'para_replace_snapshot_shape', startIndex: 8 }],
- sectionBreaks: [{ startIndex: 9 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_227', startIndex: 9 }],
textRuns: [],
},
};
diff --git a/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.ts
index fc0ac766be..b23372087c 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.ts
@@ -112,7 +112,7 @@ function getBoundaryDocumentData(leftType: BoundaryNodeType, rightType: Boundary
} else {
body.dataStream += `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${side}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
body.paragraphs!.push({ paragraphId, paragraphStyle, startIndex: body.dataStream.length - 5 });
- body.sectionBreaks!.push({ startIndex: body.dataStream.length - 4 });
+ body.sectionBreaks!.push({ sectionId: `section_${side}`, startIndex: body.dataStream.length - 4 });
body.tables!.push({ tableId: `${side}-table`, startIndex, endIndex: body.dataStream.length });
}
@@ -124,7 +124,7 @@ function getBoundaryDocumentData(leftType: BoundaryNodeType, rightType: Boundary
const rightParagraphId = append(rightType, 'right');
body.dataStream += `${T.PARAGRAPH}${T.SECTION_BREAK}`;
body.paragraphs!.push({ paragraphId: 'trailing', startIndex: body.dataStream.length - 2 });
- body.sectionBreaks!.push({ startIndex: body.dataStream.length - 1 });
+ body.sectionBreaks!.push({ sectionId: 'section_trailing', startIndex: body.dataStream.length - 1 });
return {
documentData: {
diff --git a/packages/docs-ui/src/commands/commands/break-line.command.ts b/packages/docs-ui/src/commands/commands/break-line.command.ts
index faf66416f0..adcca70bae 100644
--- a/packages/docs-ui/src/commands/commands/break-line.command.ts
+++ b/packages/docs-ui/src/commands/commands/break-line.command.ts
@@ -14,61 +14,14 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ICommand, IDocumentBody, IMutationInfo, IParagraph, IParagraphBorder, ITextRangeParam } from '@univerjs/core';
+import type { DocumentDataModel, ICommand, IDocumentBody, IMutationInfo, IParagraphBorder, ITextRangeParam } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
-import { BuildTextUtils, CommandType, createParagraphId, DataStreamTreeTokenType, generateRandomId, getRichTextEditPath, ICommandService, IUniverInstanceService, JSONX, PresetListType, TextX, TextXActionType, Tools, UniverInstanceType, UpdateDocsAttributeType } from '@univerjs/core';
-import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
+import { BuildTextUtils, CommandType, DataStreamTreeTokenType, getRichTextEditPath, ICommandService, IUniverInstanceService, JSONX, PresetListType, TextX, TextXActionType, UniverInstanceType, UpdateDocsAttributeType } from '@univerjs/core';
+import { DocSelectionManagerService, generateParagraphs, RichTextEditingMutation } from '@univerjs/docs';
import { getTextRunAtPosition } from '../../basics/paragraph';
import { DocMenuStyleService } from '../../services/doc-menu-style.service';
-export function generateParagraphs(
- dataStream: string,
- prevParagraph?: IParagraph,
- borderBottom?: IParagraphBorder
-): IParagraph[] {
- const paragraphs: IParagraph[] = [];
- const existingParagraphIds = new Set<string>();
-
- for (let i = 0, len = dataStream.length; i < len; i++) {
- const char = dataStream[i];
-
- if (char !== DataStreamTreeTokenType.PARAGRAPH) {
- continue;
- }
-
- paragraphs.push({
- startIndex: i,
- paragraphId: createParagraphId(existingParagraphIds),
- });
- }
-
- if (prevParagraph) {
- for (const paragraph of paragraphs) {
- if (prevParagraph.bullet) {
- paragraph.bullet = Tools.deepClone(prevParagraph.bullet);
- }
-
- if (prevParagraph.paragraphStyle) {
- paragraph.paragraphStyle = Tools.deepClone(prevParagraph.paragraphStyle);
- delete paragraph.paragraphStyle.borderBottom;
- if (prevParagraph.paragraphStyle.headingId) {
- paragraph.paragraphStyle.headingId = generateRandomId(6);
- }
- }
- }
- }
-
- if (borderBottom) {
- for (const paragraph of paragraphs) {
- if (!paragraph.paragraphStyle) {
- paragraph.paragraphStyle = {};
- }
- paragraph.paragraphStyle.borderBottom = borderBottom;
- }
- }
-
- return paragraphs;
-}
+export { generateParagraphs };
interface IBreakLineCommandParams {
horizontalLine?: IParagraphBorder;
diff --git a/packages/docs-ui/src/commands/commands/doc-header-footer.command.ts b/packages/docs-ui/src/commands/commands/doc-header-footer.command.ts
index 3194b86fe6..52141694ff 100644
--- a/packages/docs-ui/src/commands/commands/doc-header-footer.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-header-footer.command.ts
@@ -21,9 +21,10 @@ import {
CommandType,
ICommandService,
IUniverInstanceService,
+ resolveSectionHeaderFooterReferences,
UniverInstanceType,
} from '@univerjs/core';
-import { CreateHeaderFooterCommand, DocSelectionManagerService, DocSkeletonManagerService, HeaderFooterType } from '@univerjs/docs';
+import { CreateHeaderFooterCommand, DocSelectionManagerService, DocSkeletonManagerService, getTopLevelSectionBreaks, HeaderFooterType } from '@univerjs/docs';
import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';
import { findFirstCursorOffset } from '../../basics/selection';
import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';
@@ -33,6 +34,7 @@ export interface ICoreHeaderFooterParams {
unitId: string;
createType?: HeaderFooterType;
segmentId?: string;
+ sectionId?: string;
headerFooterProps?: IHeaderFooterProps;
}
@@ -49,7 +51,7 @@ export const CoreHeaderFooterCommand: ICommand<ICoreHeaderFooterParams> = {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const renderManagerService = accessor.get(IRenderManagerService);
- const { unitId, segmentId, createType, headerFooterProps } = params;
+ const { unitId, segmentId, createType, headerFooterProps, sectionId: requestedSectionId } = params;
const docSkeletonManagerService = renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService);
const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
const docViewModel = docSkeletonManagerService?.getViewModel();
@@ -60,7 +62,18 @@ export const CoreHeaderFooterCommand: ICommand<ICoreHeaderFooterParams> = {
const editArea = docViewModel.getEditArea();
- const { documentStyle } = docDataModel.getSnapshot();
+ const snapshot = docDataModel.getSnapshot();
+ const sectionId = requestedSectionId;
+ const sections = snapshot.body ? getTopLevelSectionBreaks(snapshot.body) : [];
+ const sectionIndex = sectionId == null ? -1 : sections.findIndex((section) => section.sectionId === sectionId);
+ const section = sectionIndex < 0 ? undefined : sections[sectionIndex];
+ const headerFooterConfig = sectionId == null
+ ? snapshot.documentStyle
+ : {
+ ...snapshot.documentStyle,
+ ...section,
+ ...resolveSectionHeaderFooterReferences(snapshot.documentStyle, sections, sectionIndex),
+ };
let resolvedCreateType = createType;
@@ -69,9 +82,9 @@ export const CoreHeaderFooterCommand: ICommand<ICoreHeaderFooterParams> = {
const value = headerFooterProps[key as keyof IHeaderFooterProps];
// need create first page header/footer if useFirstPageHeaderFooter is true and firstPageHeaderId is not set.
- if (resolvedCreateType == null && key === 'useFirstPageHeaderFooter' && value === BooleanNumber.TRUE && !documentStyle.firstPageHeaderId) {
+ if (resolvedCreateType == null && key === 'useFirstPageHeaderFooter' && value === BooleanNumber.TRUE && !headerFooterConfig.firstPageHeaderId) {
resolvedCreateType = editArea === DocumentEditArea.HEADER ? HeaderFooterType.FIRST_PAGE_HEADER : HeaderFooterType.FIRST_PAGE_FOOTER;
- } else if (resolvedCreateType == null && key === 'evenAndOddHeaders' && value === BooleanNumber.TRUE && !documentStyle.evenPageHeaderId) {
+ } else if (resolvedCreateType == null && key === 'evenAndOddHeaders' && value === BooleanNumber.TRUE && !headerFooterConfig.evenPageHeaderId) {
resolvedCreateType = editArea === DocumentEditArea.HEADER ? HeaderFooterType.EVEN_PAGE_HEADER : HeaderFooterType.EVEN_PAGE_FOOTER;
}
});
@@ -82,7 +95,8 @@ export const CoreHeaderFooterCommand: ICommand<ICoreHeaderFooterParams> = {
segmentId,
createType: resolvedCreateType,
headerFooterProps,
- createMode: 'pair',
+ createMode: sectionId == null ? 'pair' : 'single',
+ sectionId,
});
return result;
diff --git a/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.ts b/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.ts
index ff1fda1d6b..a709e6915f 100644
--- a/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.ts
@@ -20,8 +20,7 @@ import { BuildTextUtils, CommandType, getRichTextEditPath, ICommandService, IUni
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
export interface IDocParagraphSettingCommandParams {
- paragraph: Partial<Pick<IParagraphStyle, 'hanging' | 'horizontalAlign' | 'spaceBelow' | 'spaceAbove' | 'indentEnd' | 'indentStart' | 'lineSpacing' | 'indentFirstLine' | 'snapToGrid' | 'spacingRule'>>;
- sections?: Record<string, any>;
+ paragraph?: Partial<Pick<IParagraphStyle, 'hanging' | 'horizontalAlign' | 'spaceBelow' | 'spaceAbove' | 'indentEnd' | 'indentStart' | 'lineSpacing' | 'indentFirstLine' | 'snapToGrid' | 'spacingRule'>>;
};
export const DocParagraphSettingCommand: ICommand<IDocParagraphSettingCommandParams> = {
id: 'doc-paragraph-setting.command',
@@ -44,8 +43,9 @@ export const DocParagraphSettingCommand: ICommand<IDocParagraphSettingCommandPar
const unitId = docDataModel.getUnitId();
const segment = docDataModel.getSelfOrHeaderFooterModel(segmentId);
- const allParagraphs = segment?.getBody()?.paragraphs ?? [];
- const dataStream = segment?.getBody()?.dataStream ?? '';
+ const segmentBody = segment?.getBody();
+ const allParagraphs = segmentBody?.paragraphs ?? [];
+ const dataStream = segmentBody?.dataStream ?? '';
const paragraphs = BuildTextUtils.range.getParagraphsInRanges(docRanges, allParagraphs, dataStream) ?? [];
const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
@@ -57,6 +57,9 @@ export const DocParagraphSettingCommand: ICommand<IDocParagraphSettingCommandPar
},
};
+ if (!config.paragraph || Object.keys(config.paragraph).length === 0) {
+ return false;
+ }
const memoryCursor = new MemoryCursor();
memoryCursor.reset();
@@ -69,23 +72,19 @@ export const DocParagraphSettingCommand: ICommand<IDocParagraphSettingCommandPar
t: TextXActionType.RETAIN,
len: startIndex - memoryCursor.cursor,
});
- // See: univer/packages/engine-render/src/components/docs/block/paragraph/layout-ruler.ts line:802 comments.
- const paragraphStyle: IParagraphStyle = {
- ...paragraph.paragraphStyle,
- ...config.paragraph,
- };
textX.push({
t: TextXActionType.RETAIN,
len: 1,
body: {
dataStream: '',
- paragraphs: [
- {
- ...paragraph,
- paragraphStyle,
- startIndex: 0,
+ paragraphs: [{
+ ...paragraph,
+ paragraphStyle: {
+ ...paragraph.paragraphStyle,
+ ...config.paragraph,
},
- ],
+ startIndex: 0,
+ }],
},
coverType: UpdateDocsAttributeType.REPLACE,
});
diff --git a/packages/docs-ui/src/commands/commands/table/table.ts b/packages/docs-ui/src/commands/commands/table/table.ts
index 30e7e72802..a82043980d 100644
--- a/packages/docs-ui/src/commands/commands/table/table.ts
+++ b/packages/docs-ui/src/commands/commands/table/table.ts
@@ -16,7 +16,7 @@
import type { IParagraph, ISectionBreak, ITable, ITableCell, ITableColumn, ITableRow, Nullable } from '@univerjs/core';
import type { DataStreamTreeNode, DocumentViewModel, ITextRangeWithStyle } from '@univerjs/engine-render';
-import { createParagraphId, DataStreamTreeTokenType, generateRandomId, ObjectRelativeFromH, ObjectRelativeFromV, TableAlignmentType, TableRowHeightRule, TableSizeType, TableTextWrapType, Tools } from '@univerjs/core';
+import { createParagraphId, createSectionId, DataStreamTreeTokenType, generateRandomId, ObjectRelativeFromH, ObjectRelativeFromV, TableAlignmentType, TableRowHeightRule, TableSizeType, TableTextWrapType, Tools } from '@univerjs/core';
export enum INSERT_ROW_POSITION {
ABOVE,
@@ -33,6 +33,7 @@ export function genEmptyTable(rowCount: number, colCount: number) {
const paragraphs: IParagraph[] = [];
const sectionBreaks: ISectionBreak[] = [];
const existingParagraphIds = new Set<string>();
+ const existingSectionIds = new Set<string>();
for (let i = 0; i < rowCount; i++) {
dataStream += DataStreamTreeTokenType.TABLE_ROW_START;
@@ -49,6 +50,7 @@ export function genEmptyTable(rowCount: number, colCount: number) {
},
});
sectionBreaks.push({
+ sectionId: createSectionId(existingSectionIds),
startIndex: dataStream.length - 2,
});
}
@@ -220,6 +222,7 @@ export function getInsertRowBody(col: number) {
const paragraphs: IParagraph[] = [];
const sectionBreaks: ISectionBreak[] = [];
const existingParagraphIds = new Set<string>();
+ const existingSectionIds = new Set<string>();
for (let i = 0; i < col; i++) {
dataStream += `${DataStreamTreeTokenType.TABLE_CELL_START}\r\n${DataStreamTreeTokenType.TABLE_CELL_END}`;
@@ -233,6 +236,7 @@ export function getInsertRowBody(col: number) {
},
});
sectionBreaks.push({
+ sectionId: createSectionId(existingSectionIds),
startIndex: dataStream.length - 2,
});
}
@@ -261,6 +265,7 @@ export function getInsertColumnBody() {
},
});
sectionBreaks.push({
+ sectionId: createSectionId(new Set()),
startIndex: 2,
});
diff --git a/packages/docs-ui/src/commands/operations/doc-section-setting-panel.operation.ts b/packages/docs-ui/src/commands/operations/doc-section-setting-panel.operation.ts
new file mode 100644
index 0000000000..af7e1d2230
--- /dev/null
+++ b/packages/docs-ui/src/commands/operations/doc-section-setting-panel.operation.ts
@@ -0,0 +1,28 @@
+/**
+ * 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 { ICommand } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
+import { DocSectionSettingController } from '../../controllers/doc-section-setting.controller';
+
+export const DocSectionSettingPanelOperation: ICommand = {
+ id: 'sidebar.operation.doc-section-setting-panel',
+ type: CommandType.OPERATION,
+ handler: (accessor) => {
+ accessor.get(DocSectionSettingController).openPanel();
+ return true;
+ },
+};
diff --git a/packages/docs-ui/src/controllers/components.controller.ts b/packages/docs-ui/src/controllers/components.controller.ts
index 0121a229a6..f63ab12a78 100644
--- a/packages/docs-ui/src/controllers/components.controller.ts
+++ b/packages/docs-ui/src/controllers/components.controller.ts
@@ -108,6 +108,8 @@ import {
} from '../views/paragraph-menu/component-keys';
import { ParagraphSettingIndex } from '../views/paragraph-setting/index';
import { ParagraphMenu, TableBlockMenu } from '../views/ParagraphMenu';
+import { DOC_SECTION_SETTING_COMPONENT } from '../views/section-setting/component-name';
+import { SectionSettingIndex } from '../views/section-setting/index';
import { COMPONENT_DOC_CREATE_TABLE_CONFIRM } from '../views/table/create/component-name';
import { DocCreateTableConfirm } from '../views/table/create/TableCreate';
@@ -214,6 +216,7 @@ export class ComponentsController extends Disposable {
}
this.disposeWithMe(this._componentManager.register(paragraphSettingIndexKey, ParagraphSettingIndex));
+ this.disposeWithMe(this._componentManager.register(DOC_SECTION_SETTING_COMPONENT, SectionSettingIndex));
([
[BULLET_LIST_TYPE_COMPONENT, BulletListTypePicker],
[ORDER_LIST_TYPE_COMPONENT, OrderListTypePicker],
diff --git a/packages/docs-ui/src/controllers/doc-header-footer.controller.ts b/packages/docs-ui/src/controllers/doc-header-footer.controller.ts
index 19293b123d..e758c09d22 100644
--- a/packages/docs-ui/src/controllers/doc-header-footer.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-header-footer.controller.ts
@@ -18,6 +18,7 @@ import type { DocumentDataModel, ICommandInfo, Nullable } from '@univerjs/core';
import type {
Documents,
DocumentViewModel,
+ IDocumentSkeletonPage,
IMouseEvent,
IPageRenderConfig,
IPathProps,
@@ -45,6 +46,7 @@ import { neoGetDocObject } from '../basics/component-tools';
import { CloseHeaderFooterCommand, CoreHeaderFooterCommand } from '../commands/commands/doc-header-footer.command';
import { IEditorService } from '../services/editor/editor-manager.service';
import { DocSelectionRenderService } from '../services/selection/doc-selection-render.service';
+import { getDocPageSectionContext } from '../utils/section-header-footer';
import { TextBubbleShape } from '../views/header-footer/text-bubble';
const HEADER_FOOTER_STROKE_COLOR = 'rgba(58, 96, 247, 1)';
@@ -53,11 +55,17 @@ const HEADER_FOOTER_FILL_COLOR = 'rgba(58, 96, 247, 0.08)';
interface IHeaderFooterCreate {
createType: Nullable<HeaderFooterType>;
headerFooterId: Nullable<string>;
+ sectionId?: string;
}
-// TODO: @JOCS also need to check sectionBreak config in the future.
-function checkCreateHeaderFooterType(viewModel: DocumentViewModel, editArea: DocumentEditArea, segmentPage: number): IHeaderFooterCreate {
- const { documentStyle } = viewModel.getDataModel().getSnapshot();
+function checkCreateHeaderFooterType(
+ viewModel: DocumentViewModel,
+ editArea: DocumentEditArea,
+ segmentPage: number,
+ page?: IDocumentSkeletonPage
+): IHeaderFooterCreate {
+ const snapshot = viewModel.getDataModel().getSnapshot();
+ const { sectionId, config } = getDocPageSectionContext(snapshot, page);
const {
defaultHeaderId,
defaultFooterId,
@@ -67,67 +75,40 @@ function checkCreateHeaderFooterType(viewModel: DocumentViewModel, editArea: Doc
firstPageFooterId,
evenAndOddHeaders,
useFirstPageHeaderFooter,
- } = documentStyle;
-
- switch (editArea) {
- case DocumentEditArea.BODY:
- return {
- createType: null,
- headerFooterId: null,
- };
- case DocumentEditArea.HEADER: {
- if (useFirstPageHeaderFooter === BooleanNumber.TRUE && !firstPageHeaderId) {
- return {
- createType: HeaderFooterType.FIRST_PAGE_HEADER,
- headerFooterId: null,
- };
- }
-
- if (evenAndOddHeaders === BooleanNumber.TRUE && segmentPage % 2 === 0 && !evenPageHeaderId) {
- return {
- createType: HeaderFooterType.EVEN_PAGE_HEADER,
- headerFooterId: null,
- };
- }
-
- return defaultHeaderId
- ? {
- createType: null,
- headerFooterId: defaultHeaderId,
- }
- : {
- createType: HeaderFooterType.DEFAULT_HEADER,
- headerFooterId: null,
- };
- }
- case DocumentEditArea.FOOTER: {
- if (useFirstPageHeaderFooter === BooleanNumber.TRUE && !firstPageFooterId) {
- return {
- createType: HeaderFooterType.FIRST_PAGE_FOOTER,
- headerFooterId: null,
- };
- }
+ } = config;
+ const isFirstPage = page ? page.pageNumber === page.pageNumberStart : segmentPage === 0;
+ const isEvenPage = page ? page.pageNumber % 2 === 0 : segmentPage % 2 === 1;
- if (evenAndOddHeaders === BooleanNumber.TRUE && segmentPage % 2 === 0 && !evenPageFooterId) {
- return {
- createType: HeaderFooterType.EVEN_PAGE_FOOTER,
- headerFooterId: null,
- };
- }
+ if (editArea === DocumentEditArea.BODY) {
+ return { createType: null, headerFooterId: null, sectionId };
+ }
- return defaultFooterId
- ? {
- createType: null,
- headerFooterId: defaultFooterId,
- }
- : {
- createType: HeaderFooterType.DEFAULT_FOOTER,
- headerFooterId: null,
- };
- }
- default:
- throw new Error(`Invalid editArea: ${editArea}`);
+ const isHeader = editArea === DocumentEditArea.HEADER;
+ if (!isHeader && editArea !== DocumentEditArea.FOOTER) {
+ throw new Error(`Invalid editArea: ${editArea}`);
}
+ const variants = isHeader
+ ? {
+ first: [firstPageHeaderId, HeaderFooterType.FIRST_PAGE_HEADER] as const,
+ even: [evenPageHeaderId, HeaderFooterType.EVEN_PAGE_HEADER] as const,
+ default: [defaultHeaderId, HeaderFooterType.DEFAULT_HEADER] as const,
+ }
+ : {
+ first: [firstPageFooterId, HeaderFooterType.FIRST_PAGE_FOOTER] as const,
+ even: [evenPageFooterId, HeaderFooterType.EVEN_PAGE_FOOTER] as const,
+ default: [defaultFooterId, HeaderFooterType.DEFAULT_FOOTER] as const,
+ };
+ const [headerFooterId, createType] = useFirstPageHeaderFooter === BooleanNumber.TRUE && isFirstPage
+ ? variants.first
+ : evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage
+ ? variants.even
+ : variants.default;
+
+ return {
+ createType: headerFooterId ? null : createType,
+ headerFooterId: headerFooterId ?? null,
+ sectionId,
+ };
}
export class DocHeaderFooterController extends Disposable implements IRenderModule {
@@ -246,13 +227,17 @@ export class DocHeaderFooterController extends Disposable implements IRenderModu
pageMarginTop
);
- if (preEditArea === editArea) {
+ if (
+ preEditArea === editArea &&
+ (editArea === DocumentEditArea.BODY || this._docSelectionRenderService.getSegmentPage() === pageNumber)
+ ) {
return;
}
viewModel.setEditArea(editArea);
- const { createType, headerFooterId } = checkCreateHeaderFooterType(viewModel, editArea, pageNumber);
+ const page = skeleton.getSkeletonData()?.pages[pageNumber];
+ const { createType, headerFooterId, sectionId } = checkCreateHeaderFooterType(viewModel, editArea, pageNumber, page);
if (editArea === DocumentEditArea.BODY) {
this._docSelectionRenderService.setSegment('');
@@ -269,6 +254,7 @@ export class DocHeaderFooterController extends Disposable implements IRenderModu
unitId,
createType,
segmentId,
+ sectionId,
});
} else if (headerFooterId != null) {
this._docSelectionRenderService.setSegment(headerFooterId);
diff --git a/packages/docs-ui/src/controllers/doc-section-setting.controller.ts b/packages/docs-ui/src/controllers/doc-section-setting.controller.ts
new file mode 100644
index 0000000000..5e8c9fd572
--- /dev/null
+++ b/packages/docs-ui/src/controllers/doc-section-setting.controller.ts
@@ -0,0 +1,40 @@
+/**
+ * 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 { Disposable, Inject } from '@univerjs/core';
+import { ISidebarService } from '@univerjs/ui';
+import { DOC_SECTION_SETTING_COMPONENT } from '../views/section-setting/component-name';
+
+export class DocSectionSettingController extends Disposable {
+ private readonly _panelId = 'DocSectionSetting';
+
+ constructor(@Inject(ISidebarService) private readonly _sidebarService: ISidebarService) {
+ super();
+ }
+
+ openPanel(): void {
+ this._sidebarService.open({
+ header: { title: 'docs-ui.doc.slider.sectionSetting' },
+ id: this._panelId,
+ children: { label: DOC_SECTION_SETTING_COMPONENT },
+ width: 300,
+ });
+ }
+
+ closePanel(): void {
+ this._sidebarService.close(this._panelId);
+ }
+}
diff --git a/packages/docs-ui/src/locale/ar-SA.ts b/packages/docs-ui/src/locale/ar-SA.ts
index 4d87fdc51f..eaffaf570d 100644
--- a/packages/docs-ui/src/locale/ar-SA.ts
+++ b/packages/docs-ui/src/locale/ar-SA.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: 'حذف الجدول',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: 'رأس',
footer: 'تذييل',
panel: 'إعدادات الرأس والتذييل',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'إعدادات الفقرة',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'إعدادات الفقرة',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'محاذاة',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'قيمة ثابتة (بكسل)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'نسخ',
diff --git a/packages/docs-ui/src/locale/ca-ES.ts b/packages/docs-ui/src/locale/ca-ES.ts
index 254d4eb452..fdda338e03 100644
--- a/packages/docs-ui/src/locale/ca-ES.ts
+++ b/packages/docs-ui/src/locale/ca-ES.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: 'Elimina taula',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: 'Capçalera',
footer: 'Peu de pàgina',
panel: 'Configuració de capçalera i peu de pàgina',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'Configuració de paràgraf',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'Configuració de paràgraf',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'Alineació',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'Valor fix (px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'Copia',
diff --git a/packages/docs-ui/src/locale/de-DE.ts b/packages/docs-ui/src/locale/de-DE.ts
index 68597deae3..84200be803 100644
--- a/packages/docs-ui/src/locale/de-DE.ts
+++ b/packages/docs-ui/src/locale/de-DE.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: 'Tabelle löschen',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: 'Kopfzeile',
footer: 'Fußzeile',
panel: 'Kopf- und Fußzeileneinstellungen',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'Absatzeinstellungen',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'Absatzeinstellungen',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'Ausrichtung',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'Fester Wert (px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'Kopieren',
diff --git a/packages/docs-ui/src/locale/en-US.ts b/packages/docs-ui/src/locale/en-US.ts
index eaa46e11ec..f6a1374dc9 100644
--- a/packages/docs-ui/src/locale/en-US.ts
+++ b/packages/docs-ui/src/locale/en-US.ts
@@ -78,6 +78,7 @@ const locale = {
header: 'Header',
footer: 'Footer',
panel: 'Header & Footer Settings',
+ linkToPrevious: 'Link to previous',
firstPageCheckBox: 'Different first page',
oddEvenCheckBox: 'Different odd and even pages',
headerTopMargin: 'Header top margin(px)',
@@ -97,9 +98,11 @@ const locale = {
doc: {
menu: {
paragraphSetting: 'Paragraph Settings',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'Paragraph Settings',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'Alignment',
@@ -117,6 +120,20 @@ const locale = {
exactly: 'Exactly (px)',
fixedValue: 'Fixed Value(px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'Copy',
diff --git a/packages/docs-ui/src/locale/es-ES.ts b/packages/docs-ui/src/locale/es-ES.ts
index 3b1a031bd3..3cdbd0ed7e 100644
--- a/packages/docs-ui/src/locale/es-ES.ts
+++ b/packages/docs-ui/src/locale/es-ES.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: 'Eliminar tabla',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: 'Encabezado',
footer: 'Pie de página',
panel: 'Configuración de encabezado y pie de página',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'Configuración de párrafo',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'Configuración de párrafo',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'Alineación',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'Valor fijo (px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'Copiar',
diff --git a/packages/docs-ui/src/locale/fa-IR.ts b/packages/docs-ui/src/locale/fa-IR.ts
index 136958250c..b45cdf74ea 100644
--- a/packages/docs-ui/src/locale/fa-IR.ts
+++ b/packages/docs-ui/src/locale/fa-IR.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: 'حذف جدول',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: 'هدر',
footer: 'فوتر',
panel: 'تنظیمات هدر و فوتر',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'تنظیمات پاراگراف',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'تنظیمات پاراگراف',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'تراز',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'مقدار ثابت(px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'کپی',
diff --git a/packages/docs-ui/src/locale/fr-FR.ts b/packages/docs-ui/src/locale/fr-FR.ts
index 9aefb92631..16a8795ac2 100644
--- a/packages/docs-ui/src/locale/fr-FR.ts
+++ b/packages/docs-ui/src/locale/fr-FR.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: 'Supprimer le tableau',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: 'En-tête',
footer: 'Pied de page',
panel: 'En-tête et pied de page',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'Paramètres de paragraphe',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'Paramètres de paragraphe',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'Alignement',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'Valeur fixe(px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'Copier',
diff --git a/packages/docs-ui/src/locale/id-ID.ts b/packages/docs-ui/src/locale/id-ID.ts
index a0553b9909..7fc686ed21 100644
--- a/packages/docs-ui/src/locale/id-ID.ts
+++ b/packages/docs-ui/src/locale/id-ID.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: 'Hapus tabel',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: 'Header',
footer: 'Footer',
panel: 'Pengaturan Header & Footer',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'Pengaturan Paragraf',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'Pengaturan Paragraf',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'Perataan',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'Nilai Tetap(px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'Salin',
diff --git a/packages/docs-ui/src/locale/it-IT.ts b/packages/docs-ui/src/locale/it-IT.ts
index a96dc9a77b..ca84d71dd3 100644
--- a/packages/docs-ui/src/locale/it-IT.ts
+++ b/packages/docs-ui/src/locale/it-IT.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: 'Elimina tabella',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: 'Intestazione',
footer: 'Piè di pagina',
panel: 'Impostazioni Intestazione e Piè di Pagina',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'Impostazioni Paragrafo',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'Impostazioni Paragrafo',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'Allineamento',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'Valore fisso (px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'Copia',
diff --git a/packages/docs-ui/src/locale/ja-JP.ts b/packages/docs-ui/src/locale/ja-JP.ts
index 787f041115..8dffffbe1c 100644
--- a/packages/docs-ui/src/locale/ja-JP.ts
+++ b/packages/docs-ui/src/locale/ja-JP.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: '表を削除',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: 'ヘッダー',
footer: 'フッター',
panel: 'ヘッダーとフッターの設定',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: '段落設定',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: '段落設定',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: '配置',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: '固定値(px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'コピー',
diff --git a/packages/docs-ui/src/locale/ko-KR.ts b/packages/docs-ui/src/locale/ko-KR.ts
index 26a48e5862..71144c12cc 100644
--- a/packages/docs-ui/src/locale/ko-KR.ts
+++ b/packages/docs-ui/src/locale/ko-KR.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: '표 삭제',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: '머리글',
footer: '바닥글',
panel: '머리글 및 바닥글 설정',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: '문단 설정',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: '문단 설정',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: '정렬',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: '고정 값(px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: '복사',
diff --git a/packages/docs-ui/src/locale/pl-PL.ts b/packages/docs-ui/src/locale/pl-PL.ts
index 797599dcf0..13750ab29e 100644
--- a/packages/docs-ui/src/locale/pl-PL.ts
+++ b/packages/docs-ui/src/locale/pl-PL.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: 'Usuń tabelę',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: 'Nagłówek',
footer: 'Stopka',
panel: 'Ustawienia nagłówka i stopki',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'Ustawienia akapitu',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'Ustawienia akapitu',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'Wyrównanie',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'Wartość stała (px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'Kopiuj',
diff --git a/packages/docs-ui/src/locale/pt-BR.ts b/packages/docs-ui/src/locale/pt-BR.ts
index 4f80b62c46..9daac61681 100644
--- a/packages/docs-ui/src/locale/pt-BR.ts
+++ b/packages/docs-ui/src/locale/pt-BR.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: 'Excluir tabela',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: 'Cabeçalho',
footer: 'Rodapé',
panel: 'Configurações de cabeçalho e rodapé',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'Configurações de parágrafo',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'Configurações de parágrafo',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'Alinhamento',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'Valor fixo (px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'Copiar',
diff --git a/packages/docs-ui/src/locale/ru-RU.ts b/packages/docs-ui/src/locale/ru-RU.ts
index 0e67ab5cbd..0088d3ee9e 100644
--- a/packages/docs-ui/src/locale/ru-RU.ts
+++ b/packages/docs-ui/src/locale/ru-RU.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: 'Удалить таблицу',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: 'Верхний колонтитул',
footer: 'Нижний колонтитул',
panel: 'Настройки верхнего и нижнего колонтитулов',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'Настройка абзаца',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'Настройка абзаца',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'Выравнивание',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'Фиксированное значение (px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'Копировать',
diff --git a/packages/docs-ui/src/locale/sk-SK.ts b/packages/docs-ui/src/locale/sk-SK.ts
index 1f2804eaec..aba97cf3ef 100644
--- a/packages/docs-ui/src/locale/sk-SK.ts
+++ b/packages/docs-ui/src/locale/sk-SK.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: 'Odstrániť tabuľku',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: 'Hlavička',
footer: 'Päta',
panel: 'Nastavenia hlavičky a päty',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'Nastavenia odseku',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'Nastavenia odseku',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'Zarovnanie',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'Pevná hodnota (px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'Kopírovať',
diff --git a/packages/docs-ui/src/locale/vi-VN.ts b/packages/docs-ui/src/locale/vi-VN.ts
index 084fd4a542..d29d948cf5 100644
--- a/packages/docs-ui/src/locale/vi-VN.ts
+++ b/packages/docs-ui/src/locale/vi-VN.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: 'Xóa bảng',
},
headerFooter: {
+ linkToPrevious: 'Link to previous',
header: 'Đầu trang',
footer: 'Chân trang',
panel: 'Cài đặt đầu trang và chân trang',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'Paragraph Setting',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'Paragraph Setting',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'Alignment',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'Fixed Value(px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: 'Sao chép',
diff --git a/packages/docs-ui/src/locale/zh-CN.ts b/packages/docs-ui/src/locale/zh-CN.ts
index 9329201f28..d9c3c2771c 100644
--- a/packages/docs-ui/src/locale/zh-CN.ts
+++ b/packages/docs-ui/src/locale/zh-CN.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: '删除表格',
},
headerFooter: {
+ linkToPrevious: '链接到上一节',
header: '页眉',
footer: '页脚',
panel: '页眉页脚设置',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: '段落设置',
+ sectionSetting: '节设置',
},
slider: {
paragraphSetting: '段落设置',
+ sectionSetting: '节设置',
},
paragraphSetting: {
alignment: '对齐方式',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: '固定值(px)',
fixedValue: '固定值(px)',
},
+ sectionSetting: {
+ selectedSections: '已选择 {0} 个节',
+ columnCount: '栏数',
+ columnGap: '栏间距',
+ columnSeparator: '分隔线',
+ none: '无',
+ betweenColumns: '栏间分隔线',
+ sectionStart: '节起始位置',
+ unspecified: '未指定',
+ continuous: '连续',
+ nextPage: '下一页',
+ evenPage: '偶数页',
+ oddPage: '奇数页',
+ },
},
rightClick: {
copy: '复制',
diff --git a/packages/docs-ui/src/locale/zh-HK.ts b/packages/docs-ui/src/locale/zh-HK.ts
index 83e11db6f1..951f4813e1 100644
--- a/packages/docs-ui/src/locale/zh-HK.ts
+++ b/packages/docs-ui/src/locale/zh-HK.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: 'Delete table',
},
headerFooter: {
+ linkToPrevious: '連結到上一節',
header: '頁眉',
footer: '頁腳',
panel: '頁眉頁腳設置',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'Paragraph Setting',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'Paragraph Setting',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'Alignment',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'Fixed Value(px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: '複製',
diff --git a/packages/docs-ui/src/locale/zh-TW.ts b/packages/docs-ui/src/locale/zh-TW.ts
index 36bc433751..963829eea8 100644
--- a/packages/docs-ui/src/locale/zh-TW.ts
+++ b/packages/docs-ui/src/locale/zh-TW.ts
@@ -77,6 +77,7 @@ const locale: typeof enUS = {
deleteTable: '刪除表格',
},
headerFooter: {
+ linkToPrevious: '連結到上一節',
header: '頁眉',
footer: '頁腳',
panel: '頁眉頁腳設置',
@@ -99,9 +100,11 @@ const locale: typeof enUS = {
doc: {
menu: {
paragraphSetting: 'Paragraph Setting',
+ sectionSetting: 'Section Settings',
},
slider: {
paragraphSetting: 'Paragraph Setting',
+ sectionSetting: 'Section Settings',
},
paragraphSetting: {
alignment: 'Alignment',
@@ -119,6 +122,20 @@ const locale: typeof enUS = {
exactly: 'Exactly (px)',
fixedValue: 'Fixed Value(px)',
},
+ sectionSetting: {
+ selectedSections: '{0} sections selected',
+ columnCount: 'Column count',
+ columnGap: 'Column gap',
+ columnSeparator: 'Separator',
+ none: 'None',
+ betweenColumns: 'Between columns',
+ sectionStart: 'Section start',
+ unspecified: 'Unspecified',
+ continuous: 'Continuous',
+ nextPage: 'Next page',
+ evenPage: 'Even page',
+ oddPage: 'Odd page',
+ },
},
rightClick: {
copy: '複製',
diff --git a/packages/docs-ui/src/menu/context-menu.ts b/packages/docs-ui/src/menu/context-menu.ts
index e64daae205..77c7ccf699 100644
--- a/packages/docs-ui/src/menu/context-menu.ts
+++ b/packages/docs-ui/src/menu/context-menu.ts
@@ -19,7 +19,7 @@ import type { IRectRangeWithStyle } from '@univerjs/engine-render';
import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';
import type { Subscriber } from 'rxjs';
import type { LocaleKey } from '../locale/types';
-import { DOC_RANGE_TYPE, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { DOC_RANGE_TYPE, DocumentFlavor, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
import { combineLatest, Observable } from 'rxjs';
@@ -37,6 +37,7 @@ import {
DocTableInsertRowBellowCommand,
} from '../commands/commands/table/doc-table-insert.command';
import { DocParagraphSettingPanelOperation } from '../commands/operations/doc-paragraph-setting-panel.operation';
+import { DocSectionSettingPanelOperation } from '../commands/operations/doc-section-setting-panel.operation';
const getDisableOnCollapsedObservable = (accessor: IAccessor) => {
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
@@ -179,6 +180,43 @@ export function TableInsertMenuItemFactory(accessor: IAccessor): IMenuSelectorIt
};
}
+function getSectionSettingUnavailableObservable(accessor: IAccessor): Observable<boolean> {
+ const selectionManager = accessor.get(DocSelectionManagerService);
+ const instanceService = accessor.get(IUniverInstanceService);
+
+ return new Observable((subscriber) => {
+ const emit = () => {
+ const documentDataModel = instanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const activeRange = selectionManager.getActiveTextRange();
+ const body = documentDataModel?.getBody();
+ const unavailable = !documentDataModel ||
+ documentDataModel.getDocumentStyle().documentFlavor !== DocumentFlavor.TRADITIONAL ||
+ !activeRange ||
+ Boolean(activeRange.segmentId) ||
+ Boolean(body?.tables?.some((table) => activeRange.startOffset > table.startIndex && activeRange.startOffset < table.endIndex));
+ subscriber.next(unavailable);
+ };
+
+ emit();
+ const subscription = selectionManager.textSelection$.subscribe(emit);
+ return () => subscription.unsubscribe();
+ });
+}
+
+export function SectionSettingMenuFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
+ return {
+ id: DocSectionSettingPanelOperation.id,
+ type: MenuItemType.BUTTON,
+ icon: 'MenuIcon',
+ title: 'docs-ui.doc.menu.sectionSetting',
+ hidden$: combineLatest(
+ getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
+ getSectionSettingUnavailableObservable(accessor),
+ (hidden, unavailable) => hidden || unavailable
+ ),
+ };
+}
+
export function InsertRowBeforeMenuItemFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
return {
id: DocTableInsertRowAboveCommand.id,
diff --git a/packages/docs-ui/src/menu/schema.ts b/packages/docs-ui/src/menu/schema.ts
index 5212cc62ef..7ccdc9b21a 100644
--- a/packages/docs-ui/src/menu/schema.ts
+++ b/packages/docs-ui/src/menu/schema.ts
@@ -76,6 +76,7 @@ import {
} from '../commands/commands/table/doc-table-insert.command';
import { DocCreateTableOperation } from '../commands/operations/doc-create-table.operation';
import { DocParagraphSettingPanelOperation } from '../commands/operations/doc-paragraph-setting-panel.operation';
+import { DocSectionSettingPanelOperation } from '../commands/operations/doc-section-setting-panel.operation';
import { DocOpenPageSettingCommand } from '../commands/operations/open-page-setting.operation';
import {
CopyMenuFactory,
@@ -90,6 +91,7 @@ import {
InsertRowBeforeMenuItemFactory,
ParagraphSettingMenuFactory,
PasteMenuFactory,
+ SectionSettingMenuFactory,
TABLE_DELETE_MENU_ID,
TABLE_INSERT_MENU_ID,
TableDeleteMenuItemFactory,
@@ -327,6 +329,10 @@ export const menuSchema: MenuSchemaType = {
order: 0,
menuItemFactory: ParagraphSettingMenuFactory,
},
+ [DocSectionSettingPanelOperation.id]: {
+ order: 1,
+ menuItemFactory: SectionSettingMenuFactory,
+ },
[TABLE_INSERT_MENU_ID]: {
order: 1,
menuItemFactory: TableInsertMenuItemFactory,
@@ -419,6 +425,10 @@ export const menuSchema: MenuSchemaType = {
order: 0,
menuItemFactory: ParagraphSettingMenuFactory,
},
+ [DocSectionSettingPanelOperation.id]: {
+ order: 1,
+ menuItemFactory: SectionSettingMenuFactory,
+ },
[INSERT_BELLOW_MENU_ID]: {
order: 1,
menuItemFactory: DocInsertBellowMenuItemFactory,
@@ -532,6 +542,10 @@ export const menuSchema: MenuSchemaType = {
order: 0,
menuItemFactory: ParagraphSettingMenuFactory,
},
+ [DocSectionSettingPanelOperation.id]: {
+ order: 1,
+ menuItemFactory: SectionSettingMenuFactory,
+ },
[BulletListCommand.id]: {
order: 1,
menuItemFactory: EmptyParagraphBulletListMenuItemFactory,
diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.ts
index 2d3d84b914..673b6eb2cb 100644
--- a/packages/docs-ui/src/plugin.ts
+++ b/packages/docs-ui/src/plugin.ts
@@ -94,6 +94,7 @@ import {
import { DocTableTabCommand } from './commands/commands/table/doc-table-tab.command';
import { MoveCursorOperation, MoveSelectionOperation } from './commands/operations/doc-cursor.operation';
import { DocParagraphSettingPanelOperation } from './commands/operations/doc-paragraph-setting-panel.operation';
+import { DocSectionSettingPanelOperation } from './commands/operations/doc-section-setting-panel.operation';
import { DocOpenPageSettingCommand } from './commands/operations/open-page-setting.operation';
import { SetDocZoomRatioOperation } from './commands/operations/set-doc-zoom-ratio.operation';
import { defaultPluginConfig, DOCS_UI_PLUGIN_CONFIG_KEY } from './config/config';
@@ -102,6 +103,7 @@ import { DocAutoFormatController } from './controllers/doc-auto-format.controlle
import { DocHeaderFooterController } from './controllers/doc-header-footer.controller';
import { DocMoveCursorController } from './controllers/doc-move-cursor.controller';
import { DocParagraphSettingController } from './controllers/doc-paragraph-setting.controller';
+import { DocSectionSettingController } from './controllers/doc-section-setting.controller';
import { DocTableController } from './controllers/doc-table.controller';
import { DocBackScrollRenderController } from './controllers/render-controllers/back-scroll.render-controller';
import { DocChecklistRenderController } from './controllers/render-controllers/doc-checklist.render-controller';
@@ -213,6 +215,7 @@ export class UniverDocsUIPlugin extends Plugin {
[DocAutoFormatController],
[DocMoveCursorController],
[DocParagraphSettingController],
+ [DocSectionSettingController],
[DocTableController],
[ComponentsController],
@@ -287,6 +290,7 @@ export class UniverDocsUIPlugin extends Plugin {
SetDocZoomRatioCommand,
DocSelectAllCommand,
DocParagraphSettingPanelOperation,
+ DocSectionSettingPanelOperation,
MoveCursorOperation,
MoveSelectionOperation,
ReplaceTextRunsCommand,
@@ -372,6 +376,7 @@ export class UniverDocsUIPlugin extends Plugin {
[DocTableController],
[DocMoveCursorController],
[DocParagraphSettingController],
+ [DocSectionSettingController],
[IEditorService, { useClass: EditorService }],
[IDocClipboardService, { useClass: DocClipboardService }],
[DocClipboardPasteAdapterService],
diff --git a/packages/docs-ui/src/services/__tests__/doc-auto-format.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-auto-format.service.spec.ts
index adf79a9adb..7cb69a4776 100644
--- a/packages/docs-ui/src/services/__tests__/doc-auto-format.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-auto-format.service.spec.ts
@@ -48,7 +48,7 @@ function createService() {
body: {
dataStream: 'Hello world\r\n',
paragraphs: [{ paragraphId: 'p1', startIndex: 11 }],
- sectionBreaks: [{ startIndex: 13 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_228', startIndex: 13 }],
customRanges: [{
startIndex: 6,
endIndex: 10,
diff --git a/packages/docs-ui/src/services/clipboard/__tests__/html-and-udm-convert.spec.ts b/packages/docs-ui/src/services/clipboard/__tests__/html-and-udm-convert.spec.ts
index c4eea09e8c..540dfce966 100644
--- a/packages/docs-ui/src/services/clipboard/__tests__/html-and-udm-convert.spec.ts
+++ b/packages/docs-ui/src/services/clipboard/__tests__/html-and-udm-convert.spec.ts
@@ -403,7 +403,12 @@ describe('test case in html and udm convert', () => {
{ paragraphId: 'para_docs_ui_fixture_56', startIndex: 21 },
{ paragraphId: 'para_docs_ui_fixture_57', startIndex: 27 },
],
- sectionBreaks: [{ startIndex: 10 }, { startIndex: 14 }, { startIndex: 22 }, { startIndex: 28 }],
+ sectionBreaks: [
+ { sectionId: 'section_html_1', startIndex: 10 },
+ { sectionId: 'section_html_2', startIndex: 14 },
+ { sectionId: 'section_html_3', startIndex: 22 },
+ { sectionId: 'section_html_4', startIndex: 28 },
+ ],
},
tableSource: {
'table-1': {
@@ -587,7 +592,7 @@ describe('test case in html and udm convert', () => {
dataStream: 'AB',
textRuns: [{ st: 0, ed: 1, ts: { bl: BooleanNumber.TRUE } }],
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_65', startIndex: 1 }],
- sectionBreaks: [{ startIndex: 2 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_233', startIndex: 2 }],
blockRanges: [{ startIndex: 0, endIndex: 1, blockId: 'quote-1', blockType: DocumentBlockRangeType.QUOTE }],
customRanges: [{ startIndex: 0, endIndex: 1, rangeId: 'range-1', rangeType: 0 }],
customDecorations: [{ startIndex: 0, endIndex: 1, id: 'decoration-1', type: CustomDecorationType.COMMENT }],
@@ -601,7 +606,7 @@ describe('test case in html and udm convert', () => {
dataStream: 'CD',
textRuns: [{ st: 0, ed: 2, ts: { it: BooleanNumber.TRUE } }],
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_66', startIndex: 2 }],
- sectionBreaks: [{ startIndex: 2 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_234', startIndex: 2 }],
blockRanges: [{ startIndex: 0, endIndex: 2, blockId: 'code-1', blockType: DocumentBlockRangeType.CODE }],
customRanges: [{ startIndex: 0, endIndex: 1, rangeId: 'range-2', rangeType: 0 }],
customDecorations: [{ startIndex: 1, endIndex: 2, id: 'decoration-2', type: CustomDecorationType.COMMENT }],
diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts
index 4b4a6f2003..9e94dfa8dc 100644
--- a/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts
+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts
@@ -19,6 +19,7 @@ import type { IAfterProcessRule, IPastePlugin, IStyleRule } from './paste-plugin
import {
ColorKit,
createParagraphId,
+ createSectionId,
CustomRangeType,
DataStreamTreeTokenType,
DocumentBlockRangeType,
@@ -107,6 +108,10 @@ export class HtmlToUDMService {
return createParagraphId(new Set(body.paragraphs?.map((paragraph) => paragraph.paragraphId)));
}
+ private _createSectionId(body: IDocumentBody): string {
+ return createSectionId(new Set(body.sectionBreaks?.map((sectionBreak) => sectionBreak.sectionId)));
+ }
+
convert(html: string, metaConfig: { unitId?: string } = {}): Partial<IDocumentData> {
const pastePlugin = HtmlToUDMService._pluginList.find((plugin) => plugin.checkPasteType(html));
const normalizedHtml = pastePlugin?.preprocessHtml?.(html) ?? html;
@@ -478,6 +483,7 @@ export class HtmlToUDMService {
body.sectionBreaks ??= [];
body.sectionBreaks.push({
+ sectionId: this._createSectionId(body),
startIndex: body.dataStream.length,
});
@@ -600,6 +606,7 @@ export class HtmlToUDMService {
}
body.sectionBreaks?.push({
+ sectionId: this._createSectionId(body),
startIndex: body.dataStream.length,
});
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 250117c832..a0e3c0647e 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
@@ -95,7 +95,7 @@ describe('test case in html and udm convert', () => {
body: {
dataStream: 'Exported\r\n',
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_73', startIndex: 'Exported'.length }],
- sectionBreaks: [{ startIndex: 'Exported\r\n'.length - 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_235', startIndex: 'Exported\r\n'.length - 1 }],
},
}),
});
@@ -106,7 +106,7 @@ describe('test case in html and udm convert', () => {
body: {
dataStream: 'Original\r\n',
paragraphs: [{ paragraphId: 'para_docs_ui_fixture_74', startIndex: 'Original'.length }],
- sectionBreaks: [{ startIndex: 'Original\r\n'.length - 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_236', startIndex: 'Original\r\n'.length - 1 }],
},
}]);
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 05a4bf07b4..47a1858834 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
@@ -22,6 +22,7 @@ import {
BaselineOffset,
BooleanNumber,
createParagraphId,
+ createSectionId,
CustomRangeType,
DataStreamTreeNodeType,
DocumentBlockRangeType,
@@ -251,6 +252,7 @@ export function convertBodyToHtml(doc: IDocumentData): string {
});
sectionBreaks.push({
+ sectionId: createSectionId(new Set(sectionBreaks.map((sectionBreak) => sectionBreak.sectionId))),
startIndex: dataStream.length - 1,
});
diff --git a/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts b/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts
index 4b23b73602..31fd0799f4 100644
--- a/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts
+++ b/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts
@@ -207,7 +207,7 @@ function createService(renderManagerServiceClass: unknown = RenderManagerService
body: {
dataStream: 'abc\r\n',
paragraphs: [{ startIndex: 3, paragraphId: createParagraphId(new Set()) }],
- sectionBreaks: [{ startIndex: 4 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_237', startIndex: 4 }],
customRanges: [],
tables: [],
textRuns: [],
diff --git a/packages/docs-ui/src/services/editor/editor.ts b/packages/docs-ui/src/services/editor/editor.ts
index 9da5d71881..a75484cd2b 100644
--- a/packages/docs-ui/src/services/editor/editor.ts
+++ b/packages/docs-ui/src/services/editor/editor.ts
@@ -34,7 +34,7 @@ import type {
} from '@univerjs/engine-render';
import type { Observable } from 'rxjs';
import type { IEditorInputConfig } from '../selection/doc-selection-render.service';
-import { createParagraphId, Disposable, isInternalEditorID, UniverInstanceType } from '@univerjs/core';
+import { createParagraphId, createSectionId, Disposable, isInternalEditorID, UniverInstanceType } from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
import { IRenderManagerService } from '@univerjs/engine-render';
import { KeyCode } from '@univerjs/ui';
@@ -349,7 +349,7 @@ export class Editor extends Disposable implements IEditor {
paragraphId: createParagraphId(new Set()),
}],
customRanges: [],
- sectionBreaks: [{ startIndex: text.length + 1 }],
+ sectionBreaks: [{ sectionId: createSectionId(new Set()), startIndex: text.length + 1 }],
tables: [],
textRuns: [],
},
diff --git a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts
index f7292ac994..6ed2dc590d 100644
--- a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts
+++ b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts
@@ -20,10 +20,10 @@ import type { IDisposable, IDocumentData } from '@univerjs/core';
import type { Mock } from 'vitest';
import { DataStreamTreeTokenType, DOC_RANGE_TYPE, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, Univer, UniverInstanceType } from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
-import { EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, EmbedInteractionBoundaryService, EmbedRuntimeFocusCoordinator } from '../../doc-embed-integration.service';
import { GlyphType, RenderUnit } from '@univerjs/engine-render';
import { ILayoutService } from '@univerjs/ui';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, EmbedInteractionBoundaryService, EmbedRuntimeFocusCoordinator } from '../../doc-embed-integration.service';
import { DocSelectionRenderService } from '../doc-selection-render.service';
import { TextRange } from '../text-range';
@@ -1184,6 +1184,9 @@ describe('DocSelectionRenderService', () => {
it('keeps segment state stable while the editor is reused by header, footer, and body selection flows', () => {
const { renderUnit, service, univer } = createRealSelectionRenderService();
cleanup.push(() => renderUnit.dispose(), () => univer.dispose());
+ const contexts: Array<{ segmentId: string; segmentPage: number }> = [];
+ const subscription = service.segmentContext$.subscribe((context) => contexts.push(context));
+ cleanup.push(() => subscription.unsubscribe());
service.setSegment('header-1');
service.setSegmentPage(3);
@@ -1197,6 +1200,13 @@ describe('DocSelectionRenderService', () => {
expect(service.getSegment()).toBe('');
expect(service.getSegmentPage()).toBe(-1);
+ expect(contexts).toEqual([
+ { segmentId: '', segmentPage: -1 },
+ { segmentId: 'header-1', segmentPage: -1 },
+ { segmentId: 'header-1', segmentPage: 3 },
+ { segmentId: '', segmentPage: 3 },
+ { segmentId: '', segmentPage: -1 },
+ ]);
});
it('selects the current word on double click and the paragraph on triple click', () => {
diff --git a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts b/packages/docs-ui/src/services/selection/doc-selection-render.service.ts
index 5439773d54..cf267a0242 100644
--- a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts
+++ b/packages/docs-ui/src/services/selection/doc-selection-render.service.ts
@@ -119,6 +119,8 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
private _currentSegmentId: string = '';
private _currentSegmentPage: number = -1;
+ private readonly _segmentContext$ = new BehaviorSubject({ segmentId: '', segmentPage: -1 });
+ readonly segmentContext$ = this._segmentContext$.asObservable();
private _selectionStyle: ITextSelectionStyle = NORMAL_TEXT_SELECTION_PLUGIN_STYLE;
private _onPointerEvent = false;
@@ -192,7 +194,11 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
}
setSegment(id: string) {
+ if (this._currentSegmentId === id) {
+ return;
+ }
this._currentSegmentId = id;
+ this._segmentContext$.next({ segmentId: id, segmentPage: this._currentSegmentPage });
}
getSegment() {
@@ -200,7 +206,11 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
}
setSegmentPage(pageIndex: number) {
+ if (this._currentSegmentPage === pageIndex) {
+ return;
+ }
this._currentSegmentPage = pageIndex;
+ this._segmentContext$.next({ segmentId: this._currentSegmentId, segmentPage: pageIndex });
}
getSegmentPage() {
@@ -1529,5 +1539,6 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
this._onFocus$.complete();
this._onBlur$.complete();
this._onPointerDown$.complete();
+ this._segmentContext$.complete();
}
}
diff --git a/packages/docs-ui/src/utils/__tests__/section-header-footer.spec.ts b/packages/docs-ui/src/utils/__tests__/section-header-footer.spec.ts
new file mode 100644
index 0000000000..a1e715245d
--- /dev/null
+++ b/packages/docs-ui/src/utils/__tests__/section-header-footer.spec.ts
@@ -0,0 +1,91 @@
+/**
+ * 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 { BooleanNumber } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { getDocPageSectionContext } from '../section-header-footer';
+
+describe('section header/footer context', () => {
+ it('resolves the owning section and overlays it on document defaults', () => {
+ const snapshot = {
+ id: 'section-header-footer-doc',
+ documentStyle: {
+ defaultHeaderId: 'global-header',
+ defaultFooterId: 'global-footer',
+ marginHeader: 12,
+ useFirstPageHeaderFooter: BooleanNumber.FALSE,
+ },
+ body: {
+ dataStream: '\r\n',
+ sectionBreaks: [{
+ sectionId: 'section_2',
+ startIndex: 1,
+ defaultHeaderId: 'section-header',
+ marginHeader: 24,
+ useFirstPageHeaderFooter: BooleanNumber.TRUE,
+ }],
+ },
+ };
+
+ expect(getDocPageSectionContext(snapshot, { sectionId: 'section_2' })).toMatchObject({
+ sectionId: 'section_2',
+ config: {
+ defaultHeaderId: 'section-header',
+ defaultFooterId: 'global-footer',
+ marginHeader: 24,
+ useFirstPageHeaderFooter: BooleanNumber.TRUE,
+ },
+ });
+ });
+
+ it('falls back to document defaults when a page has no owning section', () => {
+ const snapshot = {
+ id: 'global-header-footer-doc',
+ documentStyle: { defaultHeaderId: 'global-header' },
+ };
+
+ expect(getDocPageSectionContext(snapshot)).toEqual({
+ sectionId: undefined,
+ sectionIndex: -1,
+ sections: [],
+ section: undefined,
+ config: { defaultHeaderId: 'global-header' },
+ });
+ });
+
+ it('inherits the previous section instead of falling back to the document default', () => {
+ const snapshot = {
+ id: 'inherited-header-footer-doc',
+ documentStyle: { defaultHeaderId: 'global-header' },
+ body: {
+ dataStream: 'A\r\nB\r\n',
+ paragraphs: [
+ { paragraphId: 'paragraph_a', startIndex: 1 },
+ { paragraphId: 'paragraph_b', startIndex: 4 },
+ ],
+ sectionBreaks: [
+ { sectionId: 'section_1', startIndex: 2, defaultHeaderId: 'section-header' },
+ { sectionId: 'section_2', startIndex: 5 },
+ ],
+ },
+ };
+
+ expect(getDocPageSectionContext(snapshot, { sectionId: 'section_2' })).toMatchObject({
+ sectionIndex: 1,
+ config: { defaultHeaderId: 'section-header' },
+ });
+ });
+});
diff --git a/packages/docs-ui/src/utils/section-header-footer.ts b/packages/docs-ui/src/utils/section-header-footer.ts
new file mode 100644
index 0000000000..d23ffee233
--- /dev/null
+++ b/packages/docs-ui/src/utils/section-header-footer.ts
@@ -0,0 +1,53 @@
+/**
+ * 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 { IDocumentData, IDocumentStyle, ISectionBreak } from '@univerjs/core';
+import type { IDocumentSkeletonPage } from '@univerjs/engine-render';
+import { resolveSectionHeaderFooterReferences } from '@univerjs/core';
+import { getTopLevelSectionBreaks } from '@univerjs/docs';
+
+export interface IDocPageSectionContext {
+ sectionId?: string;
+ sectionIndex: number;
+ sections: ISectionBreak[];
+ section?: ISectionBreak;
+ /** Effective config after applying the owning section over document defaults. */
+ config: IDocumentStyle & Partial<ISectionBreak>;
+}
+
+export function getDocPageSectionContext(
+ snapshot: IDocumentData,
+ page?: Pick<IDocumentSkeletonPage, 'sectionId'>
+): IDocPageSectionContext {
+ const sections = snapshot.body ? getTopLevelSectionBreaks(snapshot.body) : [];
+ const sectionIndex = page?.sectionId == null ? -1 : sections.findIndex((item) => item.sectionId === page.sectionId);
+ const section = sectionIndex < 0 ? undefined : sections[sectionIndex];
+ const references = section == null
+ ? {}
+ : resolveSectionHeaderFooterReferences(snapshot.documentStyle, sections, sectionIndex);
+
+ return {
+ sectionId: section?.sectionId,
+ sectionIndex,
+ sections,
+ section,
+ config: {
+ ...snapshot.documentStyle,
+ ...section,
+ ...references,
+ },
+ };
+}
diff --git a/packages/docs-ui/src/views/editor/utils.ts b/packages/docs-ui/src/views/editor/utils.ts
index 725a6ee880..a451214995 100644
--- a/packages/docs-ui/src/views/editor/utils.ts
+++ b/packages/docs-ui/src/views/editor/utils.ts
@@ -15,7 +15,7 @@
*/
import type { IDocumentData } from '@univerjs/core';
-import { createParagraphId, DEFAULT_EMPTY_DOCUMENT_VALUE, DocumentFlavor } from '@univerjs/core';
+import { createParagraphId, createSectionId, DEFAULT_EMPTY_DOCUMENT_VALUE, DocumentFlavor } from '@univerjs/core';
/**
*
@@ -27,6 +27,7 @@ export function genSnapShotByValue(id = '', value = '') {
const paragraphs = [];
const sectionBreaks = [];
const existingParagraphIds = new Set<string>();
+ const existingSectionIds = new Set<string>();
for (let i = 0; i < dataStream.length; i++) {
if (dataStream[i] === '\r') {
@@ -38,6 +39,7 @@ export function genSnapShotByValue(id = '', value = '') {
if (dataStream[i] === '\n') {
sectionBreaks.push({
+ sectionId: createSectionId(existingSectionIds),
startIndex: i,
});
}
diff --git a/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx b/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx
index 527f0f7975..a6c716d831 100644
--- a/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx
+++ b/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx
@@ -16,27 +16,31 @@
import type { DocumentDataModel, IDocumentStyle } from '@univerjs/core';
import type { IHeaderFooterProps } from '@univerjs/docs';
+import type { IDocumentSkeletonPage } from '@univerjs/engine-render';
import type { LocaleKey } from '../../../locale/types';
import {
BooleanNumber,
generateRandomId,
+ getSectionHeaderFooterReferenceKey,
ICommandService,
IUniverInstanceService,
LocaleService,
+ resolveSectionHeaderFooterReference,
UniverInstanceType,
} from '@univerjs/core';
import { Button, Checkbox, InputNumber } from '@univerjs/design';
-import { DocSkeletonManagerService } from '@univerjs/docs';
+import { DocSkeletonManagerService, SetSectionHeaderFooterLinkCommand } from '@univerjs/docs';
import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';
-import { ILayoutService, useDependency } from '@univerjs/ui';
-import { useEffect, useState } from 'react';
+import { ILayoutService, useDependency, useObservable } from '@univerjs/ui';
+import { useState } from 'react';
import {
CloseHeaderFooterCommand,
CoreHeaderFooterCommandId,
} from '../../../commands/commands/doc-header-footer.command';
import { DocSelectionRenderService } from '../../../services/selection/doc-selection-render.service';
+import { getDocPageSectionContext } from '../../../utils/section-header-footer';
-function getSegmentId(documentStyle: IDocumentStyle, editArea: DocumentEditArea, pageIndex: number): string {
+function getSegmentId(documentStyle: IDocumentStyle, editArea: DocumentEditArea, pageIndex: number, page?: IDocumentSkeletonPage): string {
const {
useFirstPageHeaderFooter,
evenAndOddHeaders,
@@ -47,26 +51,28 @@ function getSegmentId(documentStyle: IDocumentStyle, editArea: DocumentEditArea,
evenPageHeaderId,
evenPageFooterId,
} = documentStyle;
+ const isFirstPage = page ? page.pageNumber === page.pageNumberStart : pageIndex === 0;
+ const isEvenPage = page ? page.pageNumber % 2 === 0 : pageIndex % 2 === 1;
if (editArea === DocumentEditArea.HEADER) {
if (useFirstPageHeaderFooter === BooleanNumber.TRUE) {
- if (pageIndex === 0) {
+ if (isFirstPage) {
return firstPageHeaderId!;
} else {
- return evenAndOddHeaders === BooleanNumber.TRUE && pageIndex % 2 === 1 ? evenPageHeaderId! : defaultHeaderId!;
+ return evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage ? evenPageHeaderId! : defaultHeaderId!;
}
} else {
- return evenAndOddHeaders === BooleanNumber.TRUE && pageIndex % 2 === 1 ? evenPageHeaderId! : defaultHeaderId!;
+ return evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage ? evenPageHeaderId! : defaultHeaderId!;
}
} else {
if (useFirstPageHeaderFooter === BooleanNumber.TRUE) {
- if (pageIndex === 0) {
+ if (isFirstPage) {
return firstPageFooterId!;
} else {
- return evenAndOddHeaders === BooleanNumber.TRUE && pageIndex % 2 === 1 ? evenPageFooterId! : defaultFooterId!;
+ return evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage ? evenPageFooterId! : defaultFooterId!;
}
} else {
- return evenAndOddHeaders === BooleanNumber.TRUE && pageIndex % 2 === 1 ? evenPageFooterId! : defaultFooterId!;
+ return evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage ? evenPageFooterId! : defaultFooterId!;
}
}
}
@@ -76,6 +82,17 @@ export interface IDocHeaderFooterOptionsProps {
}
export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
+ const renderManagerService = useDependency(IRenderManagerService);
+ const docSelectionRenderService = renderManagerService.getRenderById(props.unitId)!.with(DocSelectionRenderService)!;
+ const segmentContext = useObservable(docSelectionRenderService.segmentContext$, {
+ segmentId: docSelectionRenderService.getSegment(),
+ segmentPage: docSelectionRenderService.getSegmentPage(),
+ });
+
+ return <DocHeaderFooterOptionsContent key={`${segmentContext?.segmentId ?? ''}:${segmentContext?.segmentPage ?? -1}`} {...props} />;
+};
+
+function DocHeaderFooterOptionsContent(props: IDocHeaderFooterOptionsProps) {
const localeService = useDependency(LocaleService);
const univerInstanceService = useDependency(IUniverInstanceService);
const renderManagerService = useDependency(IRenderManagerService);
@@ -86,8 +103,36 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
const { unitId } = props;
const docSelectionRenderService = renderManagerService.getRenderById(unitId)!.with(DocSelectionRenderService)!;
+ const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- const [options, setOptions] = useState<IHeaderFooterProps>({});
+ const getCurrentSectionContext = () => {
+ const snapshot = docDataModel?.getSnapshot();
+ const docSkeletonManagerService = renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService);
+ const page = docSkeletonManagerService?.getSkeleton?.()?.getSkeletonData()?.pages[docSelectionRenderService.getSegmentPage()];
+ return snapshot == null ? undefined : { ...getDocPageSectionContext(snapshot, page), page };
+ };
+ const [options, setOptions] = useState<IHeaderFooterProps>(() => {
+ const config = getCurrentSectionContext()?.config;
+ return {
+ marginHeader: config?.marginHeader ?? 0,
+ marginFooter: config?.marginFooter ?? 0,
+ useFirstPageHeaderFooter: config?.useFirstPageHeaderFooter ?? BooleanNumber.FALSE,
+ evenAndOddHeaders: config?.evenAndOddHeaders ?? BooleanNumber.FALSE,
+ };
+ });
+ const sectionContext = getCurrentSectionContext();
+ const editArea = renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService)?.getViewModel()?.getEditArea();
+ const headerFooterKind = editArea === DocumentEditArea.FOOTER ? 'footer' : 'header';
+ const variant = getHeaderFooterVariant(
+ sectionContext?.config ?? {},
+ docSelectionRenderService.getSegmentPage(),
+ sectionContext?.page
+ );
+ const referenceKey = getSectionHeaderFooterReferenceKey(headerFooterKind, variant);
+ const canLinkToPrevious = (sectionContext?.sectionIndex ?? -1) > 0;
+ const [linkedToPrevious, setLinkedToPrevious] = useState(
+ canLinkToPrevious && !sectionContext?.section?.[referenceKey]
+ );
const handleCheckboxChange = (val: boolean, type: 'useFirstPageHeaderFooter' | 'evenAndOddHeaders') => {
setOptions((prev) => ({
@@ -95,8 +140,8 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
[type]: val ? BooleanNumber.TRUE : BooleanNumber.FALSE,
}));
- const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- const documentStyle = docDataModel?.getSnapshot().documentStyle;
+ const sectionContext = getCurrentSectionContext();
+ const documentStyle = sectionContext?.config;
const docSkeletonManagerService = renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService);
const viewModel = docSkeletonManagerService?.getViewModel();
@@ -108,6 +153,10 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
let needCreateHeaderFooter = false;
const segmentPage = docSelectionRenderService.getSegmentPage();
+ const isFirstSectionPage = sectionContext?.page
+ ? sectionContext.page.pageNumber === sectionContext.page.pageNumberStart
+ : segmentPage === 0;
+ const isEvenPage = sectionContext?.page ? sectionContext.page.pageNumber % 2 === 0 : segmentPage % 2 === 1;
let needChangeSegmentId = false;
if (type === 'useFirstPageHeaderFooter' && val === true) {
if (editArea === DocumentEditArea.HEADER && !documentStyle.firstPageHeaderId) {
@@ -116,7 +165,7 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
needCreateHeaderFooter = true;
}
- if (needCreateHeaderFooter && segmentPage === 0) {
+ if (needCreateHeaderFooter && isFirstSectionPage) {
needChangeSegmentId = true;
}
}
@@ -128,7 +177,7 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
needCreateHeaderFooter = true;
}
- if (needCreateHeaderFooter && segmentPage % 2 === 1) {
+ if (needCreateHeaderFooter && isEvenPage) {
needChangeSegmentId = true;
}
}
@@ -147,6 +196,7 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
headerFooterProps: {
[type]: val ? BooleanNumber.TRUE : BooleanNumber.FALSE,
},
+ sectionId: sectionContext?.sectionId,
});
} else {
const segmentPageIndex = docSelectionRenderService.getSegmentPage();
@@ -158,7 +208,8 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
[type]: val ? BooleanNumber.TRUE : BooleanNumber.FALSE,
},
editArea,
- segmentPageIndex
+ segmentPageIndex,
+ sectionContext?.page
);
if (needFocusSegmentId && needFocusSegmentId !== prevSegmentId) {
@@ -170,6 +221,7 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
headerFooterProps: {
[type]: val ? BooleanNumber.TRUE : BooleanNumber.FALSE,
},
+ sectionId: sectionContext?.sectionId,
});
}
@@ -187,6 +239,7 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
headerFooterProps: {
[type]: val,
},
+ sectionId: getCurrentSectionContext()?.sectionId,
});
// To make sure input always has focus.
@@ -200,29 +253,47 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
});
};
- useEffect(() => {
- const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- const documentStyle = docDataModel?.getSnapshot().documentStyle;
-
- if (documentStyle) {
- const {
- marginHeader = 0,
- marginFooter = 0,
- useFirstPageHeaderFooter = BooleanNumber.FALSE,
- evenAndOddHeaders = BooleanNumber.FALSE,
- } = documentStyle;
-
- setOptions({
- marginHeader,
- marginFooter,
- useFirstPageHeaderFooter,
- evenAndOddHeaders,
- });
+ const handleLinkToPreviousChange = async (linked: boolean) => {
+ const context = getCurrentSectionContext();
+ if (!context?.sectionId || context.sectionIndex <= 0 || !docDataModel) {
+ return;
}
- }, [unitId]);
+ const currentEditArea = renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService)?.getViewModel()?.getEditArea();
+ const kind = currentEditArea === DocumentEditArea.FOOTER ? 'footer' : 'header';
+ const currentVariant = getHeaderFooterVariant(context.config, docSelectionRenderService.getSegmentPage(), context.page);
+ const key = getSectionHeaderFooterReferenceKey(kind, currentVariant);
+ const segmentId = generateRandomId(6);
+ const previousSegmentId = resolveSectionHeaderFooterReference(
+ docDataModel.getDocumentStyle(),
+ context.sections,
+ context.sectionIndex - 1,
+ key
+ ).segmentId;
+ const success = await commandService.executeCommand(SetSectionHeaderFooterLinkCommand.id, {
+ unitId,
+ sectionId: context.sectionId,
+ kind,
+ variant: currentVariant,
+ linkedToPrevious: linked,
+ ...(linked ? {} : { segmentId }),
+ });
+ if (!success) {
+ return;
+ }
+ setLinkedToPrevious(linked);
+ docSelectionRenderService.setSegment(linked ? previousSegmentId ?? '' : segmentId);
+ layoutService.focus();
+ };
return (
<div className="univer-grid univer-gap-4">
+ {canLinkToPrevious && (
+ <div>
+ <Checkbox checked={linkedToPrevious} onChange={(val) => { handleLinkToPreviousChange(val as boolean); }}>
+ {localeService.t<LocaleKey>('docs-ui.headerFooter.linkToPrevious')}
+ </Checkbox>
+ </div>
+ )}
<div className="univer-grid univer-gap-2">
<div>
<Checkbox
@@ -272,4 +343,16 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
</div>
</div>
);
-};
+}
+
+function getHeaderFooterVariant(documentStyle: IDocumentStyle, pageIndex: number, page?: IDocumentSkeletonPage) {
+ const isFirstPage = page ? page.pageNumber === page.pageNumberStart : pageIndex === 0;
+ const isEvenPage = page ? page.pageNumber % 2 === 0 : pageIndex % 2 === 1;
+ if (documentStyle.useFirstPageHeaderFooter === BooleanNumber.TRUE && isFirstPage) {
+ return 'first' as const;
+ }
+ if (documentStyle.evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage) {
+ return 'even' as const;
+ }
+ return 'default' as const;
+}
diff --git a/packages/docs-ui/src/views/header-footer/panel/__tests__/DocHeaderFooterOptions.spec.tsx b/packages/docs-ui/src/views/header-footer/panel/__tests__/DocHeaderFooterOptions.spec.tsx
index df8b8488f8..c22e95e839 100644
--- a/packages/docs-ui/src/views/header-footer/panel/__tests__/DocHeaderFooterOptions.spec.tsx
+++ b/packages/docs-ui/src/views/header-footer/panel/__tests__/DocHeaderFooterOptions.spec.tsx
@@ -43,7 +43,7 @@ import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render
import { ILayoutService, RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
-import { Subject } from 'rxjs';
+import { BehaviorSubject, Subject } from 'rxjs';
import { afterEach, describe, expect, it } from 'vitest';
import { CloseHeaderFooterCommand, CoreHeaderFooterCommandId } from '../../../../commands/commands/doc-header-footer.command';
import { DocSelectionRenderService } from '../../../../services/selection/doc-selection-render.service';
@@ -110,8 +110,9 @@ class TestLayoutService {
}
class TestSelectionRenderService {
+ readonly segmentContext$ = new BehaviorSubject({ segmentId: 'default-header', segmentPage: 3 });
private _segment = 'default-header';
- private _segmentPage = 0;
+ private _segmentPage = 3;
private _removeRangeCount = 0;
private _blurCount = 0;
@@ -133,6 +134,7 @@ class TestSelectionRenderService {
setSegment(segmentId: string): void {
this._segment = segmentId;
+ this.segmentContext$.next({ segmentId, segmentPage: this._segmentPage });
}
getSegmentPage(): number {
@@ -141,6 +143,7 @@ class TestSelectionRenderService {
setSegmentPage(page: number): void {
this._segmentPage = page;
+ this.segmentContext$.next({ segmentId: this._segment, segmentPage: page });
}
removeAllRanges(): void {
@@ -172,6 +175,14 @@ class TestDocSkeletonManagerService {
getViewModel(): TestDocumentViewModel {
return this._viewModel;
}
+
+ getSkeleton() {
+ return {
+ getSkeletonData: () => ({
+ pages: [undefined, undefined, undefined, { sectionId: 'section_options', pageNumber: 1, pageNumberStart: 1 }],
+ }),
+ };
+ }
}
class TestRenderUnit {
@@ -232,7 +243,7 @@ function createHeaderFooterOptionsTestBed() {
body: {
dataStream: '\r\n',
paragraphs: [],
- sectionBreaks: [],
+ sectionBreaks: [{ sectionId: 'section_options', startIndex: 1 }],
customRanges: [],
tables: [],
textRuns: [],
@@ -325,6 +336,7 @@ describe('DocHeaderFooterOptions', () => {
expect(params.headerFooterProps).toEqual({
useFirstPageHeaderFooter: BooleanNumber.TRUE,
});
+ expect(params.sectionId).toBe('section_options');
expect(params.segmentId).toHaveLength(6);
expect(rendered.selectionRenderService.segment).toBe(params.segmentId);
expect(rendered.layoutService.focusCount).toBe(1);
@@ -358,6 +370,7 @@ describe('DocHeaderFooterOptions', () => {
expect((rendered.records[0].params as ICoreHeaderFooterParams).headerFooterProps).toEqual({
marginHeader: 25.5,
});
+ expect((rendered.records[0].params as ICoreHeaderFooterParams).sectionId).toBe('section_options');
expect((rendered.records[1].params as { unitId: string })).toEqual({
unitId: UNIT_ID,
});
diff --git a/packages/docs-ui/src/views/paragraph-setting/Setting.tsx b/packages/docs-ui/src/views/paragraph-setting/Setting.tsx
index 2e7f81b171..949e5e65ac 100644
--- a/packages/docs-ui/src/views/paragraph-setting/Setting.tsx
+++ b/packages/docs-ui/src/views/paragraph-setting/Setting.tsx
@@ -218,6 +218,7 @@ export function ParagraphSetting() {
</ParagraphSettingRow>
</div>
</ParagraphSettingSection>
+
</div>
);
}
diff --git a/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts b/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts
index 0002b48ff9..29b4b8fd01 100644
--- a/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts
+++ b/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { DocumentDataModel, IDocumentBody, IDocumentStyle, IParagraph, ISectionBreak } from '@univerjs/core';
+import type { DocumentDataModel, IDocumentBody, IDocumentStyle, IParagraph } from '@univerjs/core';
import type { IDocParagraphSettingCommandParams } from '../../../commands/commands/doc-paragraph-setting.command';
import {
BuildTextUtils,
@@ -35,7 +35,6 @@ import { useEffect, useMemo, useState } from 'react';
import { BehaviorSubject } from 'rxjs';
import { bufferTime, filter, map } from 'rxjs/operators';
import { DocParagraphSettingCommand } from '../../../commands/commands/doc-paragraph-setting.command';
-import { findNearestSectionBreak } from '../../../commands/commands/list.command';
import { DocParagraphSettingController } from '../../../controllers/doc-paragraph-setting.controller';
import {
convertDisplayLineSpacingToStoredValue,
@@ -113,37 +112,6 @@ export const useCurrentParagraph = () => {
: resolveParagraphsForSettingPanel(currentParagraphs, body, docDataModel.getDocumentStyle());
};
-export const useCurrentSections = (currentParagraphs: IParagraph[]) => {
- const univerInstanceService = useDependency(IUniverInstanceService);
- const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
- const docRanges = useDocRanges();
-
- if (!docDataModel || docRanges.length === 0) {
- return [];
- }
-
- const segmentId = docRanges[0].segmentId;
-
- const sectionBreaks = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.sectionBreaks ?? [];
- const currentSectionBreaks = currentParagraphs
- .map((item) => findNearestSectionBreak(item.startIndex, sectionBreaks))
- .reduce((a, b, index, list) => {
- const isEnd = list.length - 1 === index;
- if (b) {
- a.map[b.startIndex] = b;
- }
- if (isEnd) {
- for (const key in a.map) {
- const v = a.map[key];
- a.result.push(v);
- }
- }
- return a;
- }, { map: {}, result: [] } as { map: Record<string, ISectionBreak>; result: ISectionBreak[] })
- .result;
- return currentSectionBreaks;
-};
-
export const useFirstParagraphHorizontalAlign = (paragraph: IParagraph[], defaultValue: string) => {
const commandService = useDependency(ICommandService);
diff --git a/packages/docs-ui/src/views/section-setting/Setting.tsx b/packages/docs-ui/src/views/section-setting/Setting.tsx
new file mode 100644
index 0000000000..32fb29ad01
--- /dev/null
+++ b/packages/docs-ui/src/views/section-setting/Setting.tsx
@@ -0,0 +1,104 @@
+/**
+ * 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 { ReactNode } from 'react';
+import type { LocaleKey } from '../../locale/types';
+import { ColumnSeparatorType, LocaleService, SectionType } from '@univerjs/core';
+import { InputNumber, Select } from '@univerjs/design';
+import { useDependency } from '@univerjs/ui';
+import { useEffect } from 'react';
+import { DocSectionSettingController } from '../../controllers/doc-section-setting.controller';
+import { useSectionSetting } from './use-section-setting';
+
+function SettingRow(props: { label: ReactNode; children: ReactNode }) {
+ return (
+ <div className="univer-grid univer-min-h-8 univer-items-center univer-gap-3" style={{ gridTemplateColumns: 'minmax(0, 1fr) minmax(140px, 160px)' }}>
+ <div
+ className="
+ univer-min-w-0 univer-text-xs univer-leading-5 univer-text-gray-900
+ dark:!univer-text-gray-100
+ "
+ >
+ {props.label}
+ </div>
+ <div className="univer-w-full univer-min-w-0">{props.children}</div>
+ </div>
+ );
+}
+
+export function SectionSetting() {
+ const localeService = useDependency(LocaleService);
+ const controller = useDependency(DocSectionSettingController);
+ const setting = useSectionSetting();
+
+ useEffect(() => {
+ if (!setting.valid) {
+ controller.closePanel();
+ }
+ }, [controller, setting.valid]);
+
+ if (!setting.valid) {
+ return null;
+ }
+
+ return (
+ <div className="univer-box-border univer-w-full">
+ {setting.selectedCount > 1 && (
+ <div
+ className="
+ univer-mb-4 univer-text-xs univer-text-gray-600
+ dark:!univer-text-gray-300
+ "
+ >
+ {localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.selectedSections', String(setting.selectedCount))}
+ </div>
+ )}
+ <div className="univer-grid univer-gap-3">
+ <SettingRow label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.columnCount')}>
+ <InputNumber className="univer-w-full" min={1} max={12} step={1} precision={0} value={setting.columnCount} onChange={(value) => value != null && setting.setColumnCount(value)} />
+ </SettingRow>
+ <SettingRow label={`${localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.columnGap')}(px)`}>
+ <InputNumber className="univer-w-full" min={0} max={1000} step={1} precision={1} value={setting.columnGap} onChange={(value) => value != null && setting.setColumnGap(value)} />
+ </SettingRow>
+ <SettingRow label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.columnSeparator')}>
+ <Select
+ className="univer-w-full"
+ value={setting.separatorType == null ? '' : String(setting.separatorType)}
+ options={[
+ { label: localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.none'), value: String(ColumnSeparatorType.NONE) },
+ { label: localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.betweenColumns'), value: String(ColumnSeparatorType.BETWEEN_EACH_COLUMN) },
+ ]}
+ onChange={(value) => setting.setSeparatorType(Number(value))}
+ />
+ </SettingRow>
+ <SettingRow label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.sectionStart')}>
+ <Select
+ className="univer-w-full"
+ value={setting.sectionType == null ? '' : String(setting.sectionType)}
+ options={[
+ { label: localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.unspecified'), value: String(SectionType.SECTION_TYPE_UNSPECIFIED) },
+ { label: localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.continuous'), value: String(SectionType.CONTINUOUS) },
+ { label: localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.nextPage'), value: String(SectionType.NEXT_PAGE) },
+ { label: localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.evenPage'), value: String(SectionType.EVEN_PAGE) },
+ { label: localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.oddPage'), value: String(SectionType.ODD_PAGE) },
+ ]}
+ onChange={(value) => setting.setSectionType(Number(value))}
+ />
+ </SettingRow>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/docs-ui/src/views/section-setting/__tests__/use-section-setting.spec.ts b/packages/docs-ui/src/views/section-setting/__tests__/use-section-setting.spec.ts
new file mode 100644
index 0000000000..ce53cf2357
--- /dev/null
+++ b/packages/docs-ui/src/views/section-setting/__tests__/use-section-setting.spec.ts
@@ -0,0 +1,106 @@
+/**
+ * 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 { ColumnSeparatorType, DataStreamTreeTokenType, DocumentDataModel, SectionType } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { createSectionColumnUpdates, getSectionSettingValues, getSelectedSections } from '../use-section-setting';
+
+describe('section setting selection', () => {
+ it('maps ranges to top-level sections by their stable ids', () => {
+ const model = new DocumentDataModel({
+ id: 'section-setting-selection',
+ body: {
+ dataStream: `A${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}B${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,
+ paragraphs: [
+ { paragraphId: 'paragraph_1', startIndex: 1 },
+ { paragraphId: 'paragraph_2', startIndex: 4 },
+ ],
+ sectionBreaks: [
+ { sectionId: 'section_1', startIndex: 2 },
+ { sectionId: 'section_2', startIndex: 5 },
+ ],
+ },
+ });
+
+ expect(getSelectedSections(model, [{ startOffset: 0, endOffset: 4, collapsed: false }]).map((section) => section.sectionId))
+ .toEqual(['section_1', 'section_2']);
+ expect(getSelectedSections(model, [{ startOffset: 3, endOffset: 4, collapsed: false }]).map((section) => section.sectionId))
+ .toEqual(['section_2']);
+ expect(getSelectedSections(model, [{ startOffset: 0, endOffset: 5, collapsed: false, segmentId: 'header' }]))
+ .toEqual([]);
+ });
+
+ it('reports mixed values instead of silently using the first section', () => {
+ const sections = [
+ {
+ sectionId: 'section_1',
+ startIndex: 2,
+ columnProperties: [
+ { width: 190, paddingEnd: 18 },
+ { width: 190, paddingEnd: 0 },
+ ],
+ columnSeparatorType: ColumnSeparatorType.NONE,
+ sectionType: SectionType.CONTINUOUS,
+ },
+ {
+ sectionId: 'section_2',
+ startIndex: 5,
+ columnProperties: [
+ { width: 120, paddingEnd: 12 },
+ { width: 120, paddingEnd: 12 },
+ { width: 120, paddingEnd: 0 },
+ ],
+ columnSeparatorType: ColumnSeparatorType.BETWEEN_EACH_COLUMN,
+ sectionType: SectionType.NEXT_PAGE,
+ },
+ ];
+
+ expect(getSectionSettingValues(sections)).toEqual({
+ columnCount: undefined,
+ columnGap: undefined,
+ separatorType: undefined,
+ sectionType: undefined,
+ });
+ });
+
+ it('preserves each section column count when applying a shared gap', () => {
+ const sections = [
+ {
+ sectionId: 'section_1',
+ startIndex: 2,
+ columnProperties: [
+ { width: 190, paddingEnd: 18 },
+ { width: 190, paddingEnd: 0 },
+ ],
+ },
+ {
+ sectionId: 'section_2',
+ startIndex: 5,
+ columnProperties: [
+ { width: 120, paddingEnd: 12 },
+ { width: 120, paddingEnd: 12 },
+ { width: 120, paddingEnd: 0 },
+ ],
+ },
+ ];
+ const updates = createSectionColumnUpdates(sections, {}, { columnGap: 24 });
+
+ expect(updates[0].config.columnProperties).toHaveLength(2);
+ expect(updates[1].config.columnProperties).toHaveLength(3);
+ expect(updates[0].config.columnProperties?.[0].paddingEnd).toBe(24);
+ expect(updates[1].config.columnProperties?.[0].paddingEnd).toBe(24);
+ });
+});
diff --git a/packages/docs-ui/src/views/section-setting/component-name.ts b/packages/docs-ui/src/views/section-setting/component-name.ts
new file mode 100644
index 0000000000..1176973903
--- /dev/null
+++ b/packages/docs-ui/src/views/section-setting/component-name.ts
@@ -0,0 +1,17 @@
+/**
+ * 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.
+ */
+
+export const DOC_SECTION_SETTING_COMPONENT = 'doc_ui_section-setting-panel';
diff --git a/packages/docs-ui/src/views/section-setting/index.tsx b/packages/docs-ui/src/views/section-setting/index.tsx
new file mode 100644
index 0000000000..4a00fc2f00
--- /dev/null
+++ b/packages/docs-ui/src/views/section-setting/index.tsx
@@ -0,0 +1,45 @@
+/**
+ * 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 { ISetTextSelectionsOperationParams } from '@univerjs/docs';
+import { generateRandomId, ICommandService, LocaleService } from '@univerjs/core';
+import { RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { useEffect, useState } from 'react';
+import { SectionSetting } from './Setting';
+
+export function SectionSettingIndex() {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ useObservable(localeService.currentLocale$);
+ const [key, setKey] = useState(() => generateRandomId(4));
+
+ useEffect(() => {
+ const disposable = commandService.onCommandExecuted((info) => {
+ if (info.id === SetTextSelectionsOperation.id) {
+ const ranges = (info.params as ISetTextSelectionsOperationParams).ranges;
+ if (ranges.length > 0) {
+ setKey(generateRandomId(4));
+ }
+ } else if (info.id === RichTextEditingMutation.id) {
+ setKey(generateRandomId(4));
+ }
+ });
+ return () => disposable.dispose();
+ }, [commandService]);
+
+ return <SectionSetting key={key} />;
+}
diff --git a/packages/docs-ui/src/views/section-setting/use-section-setting.ts b/packages/docs-ui/src/views/section-setting/use-section-setting.ts
new file mode 100644
index 0000000000..8a610c1a3c
--- /dev/null
+++ b/packages/docs-ui/src/views/section-setting/use-section-setting.ts
@@ -0,0 +1,154 @@
+/**
+ * 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 { DocumentDataModel, IDocumentStyle, ISectionBreak, ITextRangeParam } from '@univerjs/core';
+import type { IDocumentSectionConfig, IDocumentSectionUpdate } from '@univerjs/docs';
+import {
+ ColumnSeparatorType,
+ DocumentFlavor,
+ ICommandService,
+ IUniverInstanceService,
+ SectionType,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ createSectionColumnProperties,
+ DocSelectionManagerService,
+ getTopLevelSectionBreaks,
+ UpdateDocumentSectionCommand,
+} from '@univerjs/docs';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { useMemo } from 'react';
+
+const DEFAULT_SECTION_COLUMN_GAP = 18;
+
+export interface ISectionSettingValues {
+ columnCount: number | undefined;
+ columnGap: number | undefined;
+ separatorType: ColumnSeparatorType | undefined;
+ sectionType: SectionType | undefined;
+}
+
+function getCommonValue<T>(values: T[]): T | undefined {
+ const first = values[0];
+ return values.every((value) => value === first) ? first : undefined;
+}
+
+function getSectionColumnCount(section: ISectionBreak): number {
+ return section.columnProperties?.length || 1;
+}
+
+function getSectionColumnGap(section: ISectionBreak): number {
+ return section.columnProperties?.[0]?.paddingEnd ?? DEFAULT_SECTION_COLUMN_GAP;
+}
+
+export function getSectionSettingValues(sections: ISectionBreak[]): ISectionSettingValues {
+ return {
+ columnCount: getCommonValue(sections.map(getSectionColumnCount)),
+ columnGap: getCommonValue(sections.map(getSectionColumnGap)),
+ separatorType: getCommonValue(sections.map((section) => section.columnSeparatorType ?? ColumnSeparatorType.NONE)),
+ sectionType: getCommonValue(sections.map((section) => section.sectionType ?? SectionType.SECTION_TYPE_UNSPECIFIED)),
+ };
+}
+
+export function createSectionColumnUpdates(
+ sections: ISectionBreak[],
+ documentStyle: IDocumentStyle,
+ change: { columnCount: number } | { columnGap: number }
+): IDocumentSectionUpdate[] {
+ return sections.map((section) => {
+ const columnCount = 'columnCount' in change ? change.columnCount : getSectionColumnCount(section);
+ const columnGap = 'columnGap' in change ? change.columnGap : getSectionColumnGap(section);
+ return {
+ sectionId: section.sectionId,
+ config: {
+ columnProperties: createSectionColumnProperties(documentStyle, section, columnCount, columnGap),
+ },
+ };
+ });
+}
+
+export function getSelectedSections(documentDataModel: DocumentDataModel, ranges: Readonly<ITextRangeParam[]>): ISectionBreak[] {
+ const body = documentDataModel.getBody();
+ if (!body || ranges.length === 0 || ranges.some((range) => Boolean(range.segmentId))) {
+ return [];
+ }
+
+ const sections = getTopLevelSectionBreaks(body);
+ return sections.filter((section, index) => {
+ const sectionStart = index === 0 ? 0 : sections[index - 1].startIndex + 1;
+ return ranges.some((range) => {
+ const rangeStart = Math.min(range.startOffset, range.endOffset);
+ const rangeEnd = Math.max(range.startOffset, range.endOffset);
+ return rangeStart <= section.startIndex && rangeEnd >= sectionStart;
+ });
+ });
+}
+
+export function useSectionSetting() {
+ const commandService = useDependency(ICommandService);
+ const instanceService = useDependency(IUniverInstanceService);
+ const selectionManager = useDependency(DocSelectionManagerService);
+ const documentDataModel = useObservable(useMemo(
+ () => instanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC),
+ [instanceService]
+ ));
+ useObservable(selectionManager.textSelection$);
+ useObservable(documentDataModel?.change$);
+ const ranges = selectionManager.getDocRanges();
+ const sections = documentDataModel?.getDocumentStyle().documentFlavor === DocumentFlavor.TRADITIONAL
+ ? getSelectedSections(documentDataModel, ranges)
+ : [];
+ const values = getSectionSettingValues(sections);
+
+ const update = (updates: IDocumentSectionUpdate[]) => {
+ if (!documentDataModel || updates.length === 0) {
+ return Promise.resolve(false);
+ }
+ return commandService.executeCommand(UpdateDocumentSectionCommand.id, {
+ unitId: documentDataModel.getUnitId(),
+ updates,
+ });
+ };
+
+ const updateAll = (config: Partial<IDocumentSectionConfig>) => update(
+ sections.map((section) => ({ sectionId: section.sectionId, config }))
+ );
+
+ return {
+ valid: Boolean(documentDataModel && sections.length > 0),
+ selectedCount: sections.length,
+ ...values,
+ setColumnCount(value: number) {
+ const next = Math.max(1, Math.round(value));
+ return update(documentDataModel
+ ? createSectionColumnUpdates(sections, documentDataModel.getDocumentStyle(), { columnCount: next })
+ : []);
+ },
+ setColumnGap(value: number) {
+ const next = Math.max(0, value);
+ return update(documentDataModel
+ ? createSectionColumnUpdates(sections, documentDataModel.getDocumentStyle(), { columnGap: next })
+ : []);
+ },
+ setSeparatorType(value: ColumnSeparatorType) {
+ return updateAll({ columnSeparatorType: value });
+ },
+ setSectionType(value: SectionType) {
+ return updateAll({ sectionType: value });
+ },
+ };
+}
diff --git a/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts b/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts
index cd51f78042..1b51dfa74b 100644
--- a/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts
+++ b/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts
@@ -70,7 +70,7 @@ describe('core editing commands', () => {
body: {
dataStream: 'Body\r\n',
paragraphs: [{ startIndex: 4, paragraphId: 'body' }],
- sectionBreaks: [{ startIndex: 5 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_101', startIndex: 5 }],
},
headers: {
'header-1': {
@@ -78,7 +78,7 @@ describe('core editing commands', () => {
body: {
dataStream: 'Head\r\n',
paragraphs: [{ startIndex: 4, paragraphId: 'header' }],
- sectionBreaks: [{ startIndex: 5 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_102', startIndex: 5 }],
},
},
},
@@ -108,7 +108,7 @@ describe('core editing commands', () => {
body: {
dataStream: 'B\r\n',
paragraphs: [{ startIndex: 1, paragraphId: 'body' }],
- sectionBreaks: [{ startIndex: 2 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_103', startIndex: 2 }],
},
headers: {
'header-1': {
@@ -116,7 +116,7 @@ describe('core editing commands', () => {
body: {
dataStream: 'LongHead\r\n',
paragraphs: [{ startIndex: 8, paragraphId: 'header' }],
- sectionBreaks: [{ startIndex: 9 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_104', startIndex: 9 }],
},
},
},
@@ -147,7 +147,7 @@ describe('core editing commands', () => {
body: {
dataStream: 'B\r\n',
paragraphs: [{ startIndex: 1, paragraphId: 'body' }],
- sectionBreaks: [{ startIndex: 2 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_105', startIndex: 2 }],
},
footers: {
'footer-1': {
@@ -155,7 +155,7 @@ describe('core editing commands', () => {
body: {
dataStream: 'LongFooter\r\n',
paragraphs: [{ startIndex: 10, paragraphId: 'footer' }],
- sectionBreaks: [{ startIndex: 11 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_106', startIndex: 11 }],
},
},
},
@@ -186,7 +186,7 @@ describe('core editing commands', () => {
body: {
dataStream: 'Body\r\n',
paragraphs: [{ startIndex: 4, paragraphId: 'body' }],
- sectionBreaks: [{ startIndex: 5 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_107', startIndex: 5 }],
},
headers: {
'header-1': {
@@ -194,7 +194,7 @@ describe('core editing commands', () => {
body: {
dataStream: 'Head\r\n',
paragraphs: [{ startIndex: 4, paragraphId: 'header' }],
- sectionBreaks: [{ startIndex: 5 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_108', startIndex: 5 }],
},
},
},
diff --git a/packages/docs/src/commands/commands/__tests__/create-header-footer.command.spec.ts b/packages/docs/src/commands/commands/__tests__/create-header-footer.command.spec.ts
index 3f83505b41..df5eefcb18 100644
--- a/packages/docs/src/commands/commands/__tests__/create-header-footer.command.spec.ts
+++ b/packages/docs/src/commands/commands/__tests__/create-header-footer.command.spec.ts
@@ -27,6 +27,7 @@ describe('CreateHeaderFooterCommand', () => {
const documentData = createDocumentData('test', {
dataStream: 'Hello,\r\n',
paragraphs: [{ startIndex: 6, paragraphId: 'para_fixture_19' }],
+ sectionBreaks: [{ sectionId: 'section_fixture_109', startIndex: 7 }],
});
documentData.documentStyle = {
...documentData.documentStyle,
@@ -67,4 +68,19 @@ describe('CreateHeaderFooterCommand', () => {
expect(snapshot.documentStyle.defaultFooterId).toEqual(expect.any(String));
expect(snapshot.footers?.[snapshot.documentStyle.defaultFooterId!].body?.dataStream).toBe('\r\n');
});
+
+ it('links a header to a specific section without changing the document default', () => {
+ const sectionId = testBed.doc.getSnapshot().body?.sectionBreaks?.[0].sectionId;
+ expect(commandService.syncExecuteCommand(CreateHeaderFooterCommand.id, {
+ unitId: 'test',
+ segmentId: 'section-header-1',
+ createType: HeaderFooterType.DEFAULT_HEADER,
+ sectionId,
+ })).toBe(true);
+
+ const snapshot = testBed.doc.getSnapshot();
+ expect(snapshot.body?.sectionBreaks?.[0].defaultHeaderId).toBe('section-header-1');
+ expect(snapshot.documentStyle.defaultHeaderId).toBeFalsy();
+ expect(snapshot.headers?.['section-header-1'].body?.dataStream).toBe('\r\n');
+ });
});
diff --git a/packages/docs/src/commands/commands/__tests__/set-section-header-footer-link.command.spec.ts b/packages/docs/src/commands/commands/__tests__/set-section-header-footer-link.command.spec.ts
new file mode 100644
index 0000000000..355adf82cf
--- /dev/null
+++ b/packages/docs/src/commands/commands/__tests__/set-section-header-footer-link.command.spec.ts
@@ -0,0 +1,145 @@
+/**
+ * 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 { DocumentFlavor, ICommandService } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createDocumentData, createTestBed } from '../../../facade/__tests__/create-test-bed';
+import { SetSectionHeaderFooterLinkCommand } from '../set-section-header-footer-link.command';
+
+describe('SetSectionHeaderFooterLinkCommand', () => {
+ let testBed: ReturnType<typeof createTestBed>;
+ let commandService: ICommandService;
+
+ beforeEach(() => {
+ const data = createDocumentData('section-header-link-doc', {
+ dataStream: 'One\r\nTwo\r\nThree\r\n',
+ paragraphs: [
+ { startIndex: 3, paragraphId: 'para_one' },
+ { startIndex: 8, paragraphId: 'para_two' },
+ { startIndex: 15, paragraphId: 'para_three' },
+ ],
+ sectionBreaks: [
+ { startIndex: 4, sectionId: 'section_one', defaultHeaderId: 'header-a' },
+ { startIndex: 9, sectionId: 'section_two' },
+ { startIndex: 16, sectionId: 'section_three', defaultHeaderId: 'header-c' },
+ ],
+ });
+ data.documentStyle = { ...data.documentStyle, documentFlavor: DocumentFlavor.TRADITIONAL };
+ data.headers = {
+ 'header-a': {
+ headerId: 'header-a',
+ body: {
+ dataStream: 'Shared\r\n',
+ paragraphs: [{ startIndex: 6, paragraphId: 'header_para' }],
+ sectionBreaks: [{ startIndex: 7, sectionId: 'header_section' }],
+ },
+ },
+ 'header-c': {
+ headerId: 'header-c',
+ body: {
+ dataStream: 'Third\r\n',
+ paragraphs: [{ startIndex: 5, paragraphId: 'header_c_para' }],
+ sectionBreaks: [{ startIndex: 6, sectionId: 'header_c_section' }],
+ },
+ },
+ };
+ testBed = createTestBed(data);
+ commandService = testBed.get(ICommandService);
+ });
+
+ afterEach(() => testBed.univer.dispose());
+
+ it('unlinks by cloning the inherited resource and links again by removing the explicit reference', () => {
+ const bodyBefore = testBed.doc.getBody()?.dataStream;
+ expect(commandService.syncExecuteCommand(SetSectionHeaderFooterLinkCommand.id, {
+ unitId: 'section-header-link-doc',
+ sectionId: 'section_two',
+ kind: 'header',
+ variant: 'default',
+ linkedToPrevious: false,
+ segmentId: 'header-b',
+ })).toBe(true);
+
+ let snapshot = testBed.doc.getSnapshot();
+ expect(snapshot.body?.sectionBreaks?.[1].defaultHeaderId).toBe('header-b');
+ expect(snapshot.headers?.['header-b']).toEqual({
+ ...snapshot.headers?.['header-a'],
+ headerId: 'header-b',
+ });
+
+ expect(commandService.syncExecuteCommand(SetSectionHeaderFooterLinkCommand.id, {
+ unitId: 'section-header-link-doc',
+ sectionId: 'section_two',
+ kind: 'header',
+ variant: 'default',
+ linkedToPrevious: true,
+ })).toBe(true);
+
+ snapshot = testBed.doc.getSnapshot();
+ expect(snapshot.body?.sectionBreaks?.[1].defaultHeaderId).toBeUndefined();
+ expect(snapshot.headers?.['header-b']).toBeUndefined();
+ expect(snapshot.body?.dataStream).toBe(bodyBefore);
+ });
+
+ it('rejects linking the first section and duplicate unlink operations', () => {
+ expect(commandService.syncExecuteCommand(SetSectionHeaderFooterLinkCommand.id, {
+ unitId: 'section-header-link-doc',
+ sectionId: 'section_one',
+ kind: 'header',
+ variant: 'default',
+ linkedToPrevious: true,
+ })).toBe(false);
+ expect(commandService.syncExecuteCommand(SetSectionHeaderFooterLinkCommand.id, {
+ unitId: 'section-header-link-doc',
+ sectionId: 'section_three',
+ kind: 'header',
+ variant: 'default',
+ linkedToPrevious: false,
+ segmentId: 'header-d',
+ })).toBe(false);
+ });
+
+ it('creates an empty independent footer when the previous section has none', () => {
+ expect(commandService.syncExecuteCommand(SetSectionHeaderFooterLinkCommand.id, {
+ unitId: 'section-header-link-doc',
+ sectionId: 'section_two',
+ kind: 'footer',
+ variant: 'default',
+ linkedToPrevious: false,
+ segmentId: 'footer-b',
+ })).toBe(true);
+
+ const snapshot = testBed.doc.getSnapshot();
+ expect(snapshot.body?.sectionBreaks?.[1].defaultFooterId).toBe('footer-b');
+ expect(snapshot.footers?.['footer-b'].body?.dataStream).toBe('\r\n');
+ });
+
+ it('rejects the operation in modern documents', () => {
+ testBed.doc.updateDocumentStyle({
+ ...testBed.doc.getDocumentStyle(),
+ documentFlavor: DocumentFlavor.MODERN,
+ });
+ expect(commandService.syncExecuteCommand(SetSectionHeaderFooterLinkCommand.id, {
+ unitId: 'section-header-link-doc',
+ sectionId: 'section_two',
+ kind: 'header',
+ variant: 'default',
+ linkedToPrevious: false,
+ segmentId: 'header-modern',
+ })).toBe(false);
+ expect(testBed.doc.getSnapshot().headers?.['header-modern']).toBeUndefined();
+ });
+});
diff --git a/packages/docs/src/commands/commands/__tests__/update-document-section.command.spec.ts b/packages/docs/src/commands/commands/__tests__/update-document-section.command.spec.ts
new file mode 100644
index 0000000000..d193ada058
--- /dev/null
+++ b/packages/docs/src/commands/commands/__tests__/update-document-section.command.spec.ts
@@ -0,0 +1,100 @@
+/**
+ * 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 { ColumnSeparatorType, DocumentFlavor, ICommandService, SectionType } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createDocumentData, createTestBed } from '../../../facade/__tests__/create-test-bed';
+import { UpdateDocumentSectionCommand } from '../update-document-section.command';
+
+describe('UpdateDocumentSectionCommand', () => {
+ let testBed: ReturnType<typeof createTestBed>;
+ let commandService: ICommandService;
+
+ beforeEach(() => {
+ const data = createDocumentData('section-command-doc', {
+ dataStream: 'One\r\nTwo\r\n',
+ paragraphs: [
+ { startIndex: 3, paragraphId: 'para_one' },
+ { startIndex: 8, paragraphId: 'para_two' },
+ ],
+ sectionBreaks: [
+ { startIndex: 4, sectionId: 'section_one' },
+ { startIndex: 9, sectionId: 'section_two' },
+ ],
+ });
+ data.documentStyle = { ...data.documentStyle, documentFlavor: DocumentFlavor.TRADITIONAL };
+ testBed = createTestBed(data);
+ commandService = testBed.get(ICommandService);
+ });
+
+ afterEach(() => testBed.univer.dispose());
+
+ it('updates selected sections by id through one rich-text command', () => {
+ expect(commandService.syncExecuteCommand(UpdateDocumentSectionCommand.id, {
+ unitId: 'section-command-doc',
+ updates: [
+ {
+ sectionId: 'section_one',
+ config: {
+ columnProperties: [
+ { width: 190, paddingEnd: 18 },
+ { width: 190, paddingEnd: 0 },
+ ],
+ columnSeparatorType: ColumnSeparatorType.BETWEEN_EACH_COLUMN,
+ sectionType: SectionType.CONTINUOUS,
+ },
+ },
+ {
+ sectionId: 'section_two',
+ config: {
+ columnProperties: [
+ { width: 120, paddingEnd: 12 },
+ { width: 120, paddingEnd: 12 },
+ { width: 120, paddingEnd: 0 },
+ ],
+ columnSeparatorType: ColumnSeparatorType.BETWEEN_EACH_COLUMN,
+ sectionType: SectionType.NEXT_PAGE,
+ },
+ },
+ ],
+ })).toBe(true);
+
+ expect(testBed.doc.getBody()?.sectionBreaks).toEqual([
+ expect.objectContaining({ sectionId: 'section_one', sectionType: SectionType.CONTINUOUS, columnProperties: expect.arrayContaining([expect.objectContaining({ width: 190 })]) }),
+ expect.objectContaining({ sectionId: 'section_two', sectionType: SectionType.NEXT_PAGE, columnProperties: expect.arrayContaining([expect.objectContaining({ width: 120 })]) }),
+ ]);
+ });
+
+ it('rejects unknown ids and modern documents without partial updates', () => {
+ expect(commandService.syncExecuteCommand(UpdateDocumentSectionCommand.id, {
+ unitId: 'section-command-doc',
+ updates: [
+ { sectionId: 'section_one', config: { sectionType: SectionType.NEXT_PAGE } },
+ { sectionId: 'missing', config: { sectionType: SectionType.NEXT_PAGE } },
+ ],
+ })).toBe(false);
+ expect(testBed.doc.getBody()?.sectionBreaks?.[0].sectionType).toBeUndefined();
+
+ testBed.doc.updateDocumentStyle({
+ ...testBed.doc.getDocumentStyle(),
+ documentFlavor: DocumentFlavor.MODERN,
+ });
+ expect(commandService.syncExecuteCommand(UpdateDocumentSectionCommand.id, {
+ unitId: 'section-command-doc',
+ updates: [{ sectionId: 'section_one', config: { sectionType: SectionType.NEXT_PAGE } }],
+ })).toBe(false);
+ });
+});
diff --git a/packages/docs/src/commands/commands/create-header-footer.command.ts b/packages/docs/src/commands/commands/create-header-footer.command.ts
index 0307eb3208..5f1a14f70f 100644
--- a/packages/docs/src/commands/commands/create-header-footer.command.ts
+++ b/packages/docs/src/commands/commands/create-header-footer.command.ts
@@ -14,12 +14,13 @@
* limitations under the License.
*/
-import type { BooleanNumber, DocumentDataModel, ICommand, IDocumentBody, IMutationInfo, JSONXActions } from '@univerjs/core';
+import type { BooleanNumber, DocumentDataModel, ICommand, IDocumentBody, IHeaderAndFooterBase, IMutationInfo, JSONXActions } from '@univerjs/core';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';
import {
CommandType,
createParagraphId,
+ createSectionId,
DocumentFlavor,
generateRandomId,
ICommandService,
@@ -39,7 +40,9 @@ export enum HeaderFooterType {
}
export interface IHeaderFooterProps {
+ /** Distance from the page edge to the header, in points (pt). */
marginHeader?: number;
+ /** Distance from the page edge to the footer, in points (pt). */
marginFooter?: number;
useFirstPageHeaderFooter?: BooleanNumber;
evenAndOddHeaders?: BooleanNumber;
@@ -53,6 +56,8 @@ export interface ICreateHeaderFooterCommandParams {
segmentId?: string;
headerFooterProps?: IHeaderFooterProps;
createMode?: HeaderFooterCreateMode;
+ /** Optional stable section id. Omit to configure the document-level default. */
+ sectionId?: string;
}
export function getEmptyHeaderFooterBody(): IDocumentBody {
@@ -79,6 +84,7 @@ export function getEmptyHeaderFooterBody(): IDocumentBody {
],
sectionBreaks: [
{
+ sectionId: createSectionId(new Set()),
startIndex: 1,
},
],
@@ -88,9 +94,10 @@ export function getEmptyHeaderFooterBody(): IDocumentBody {
export function createHeaderFooterAction(
segmentId: string | undefined,
createType: HeaderFooterType,
- documentStyle: IHeaderFooterProps,
+ headerFooterConfig: IHeaderFooterProps,
actions: JSONXActions,
- createMode: HeaderFooterCreateMode = 'single'
+ createMode: HeaderFooterCreateMode = 'single',
+ configPath: Array<string | number> = ['documentStyle']
) {
const jsonX = JSONX.getInstance();
const ID_LEN = 6;
@@ -148,11 +155,11 @@ export function createHeaderFooterAction(
}
for (const [k, id] of linkedSegmentIds) {
- if (documentStyle[k as keyof IHeaderFooterProps] != null) {
- const replaceAction = jsonX.replaceOp(['documentStyle', k], documentStyle[k as keyof IHeaderFooterProps], id);
+ if (headerFooterConfig[k as keyof IHeaderFooterProps] != null) {
+ const replaceAction = jsonX.replaceOp([...configPath, k], headerFooterConfig[k as keyof IHeaderFooterProps], id);
actions!.push(replaceAction!);
} else {
- const insertAction = jsonX.insertOp(['documentStyle', k], id);
+ const insertAction = jsonX.insertOp([...configPath, k], id);
actions!.push(insertAction!);
}
}
@@ -166,14 +173,14 @@ export const CreateHeaderFooterCommand: ICommand<ICreateHeaderFooterCommandParam
handler: (accessor, params: ICreateHeaderFooterCommandParams) => {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const { unitId, segmentId, createType, headerFooterProps, createMode = 'single' } = params;
+ const { unitId, segmentId, createType, headerFooterProps, createMode = 'single', sectionId } = params;
const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
if (docDataModel == null) {
return false;
}
- const { documentStyle } = docDataModel.getSnapshot();
+ const { documentStyle, body } = docDataModel.getSnapshot();
// The modern document flavor does not support header/footer, so we return false if the document is modern.
if (documentStyle.documentFlavor === DocumentFlavor.MODERN) {
@@ -182,22 +189,31 @@ export const CreateHeaderFooterCommand: ICommand<ICreateHeaderFooterCommandParam
const rawActions: JSONXActions = [];
const jsonX = JSONX.getInstance();
+ const sectionIndex = sectionId == null ? -1 : body?.sectionBreaks?.findIndex((section) => section.sectionId === sectionId) ?? -1;
+ const sectionBreak = sectionIndex < 0 ? undefined : body?.sectionBreaks?.[sectionIndex];
+ if (sectionId != null && !sectionBreak) {
+ return false;
+ }
+ const headerFooterConfig: IHeaderFooterProps & IHeaderAndFooterBase = sectionBreak ?? documentStyle;
+ const configPath: Array<string | number> = sectionId == null
+ ? ['documentStyle']
+ : ['body', 'sectionBreaks', sectionIndex];
if (createType != null) {
- createHeaderFooterAction(segmentId, createType, documentStyle, rawActions, createMode);
+ createHeaderFooterAction(segmentId, createType, headerFooterConfig, rawActions, createMode, configPath);
}
if (headerFooterProps != null) {
Object.keys(headerFooterProps).forEach((key) => {
const value = headerFooterProps[key as keyof IHeaderFooterProps];
- const oldValue = documentStyle[key as keyof IHeaderFooterProps];
+ const oldValue = headerFooterConfig[key as keyof IHeaderFooterProps];
if (value === oldValue) {
return;
}
const action = oldValue === undefined
- ? jsonX.insertOp(['documentStyle', key], value)
- : jsonX.replaceOp(['documentStyle', key], oldValue, value);
+ ? jsonX.insertOp([...configPath, key], value)
+ : jsonX.replaceOp([...configPath, key], oldValue, value);
rawActions.push(action!);
});
diff --git a/packages/docs/src/commands/commands/set-section-header-footer-link.command.ts b/packages/docs/src/commands/commands/set-section-header-footer-link.command.ts
new file mode 100644
index 0000000000..9cebc0f59d
--- /dev/null
+++ b/packages/docs/src/commands/commands/set-section-header-footer-link.command.ts
@@ -0,0 +1,154 @@
+/**
+ * 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 { DocumentDataModel, ICommand, IDocumentData, IMutationInfo, ISectionBreak, JSONXActions, SectionHeaderFooterKind, SectionHeaderFooterReferenceKey, SectionHeaderFooterVariant } from '@univerjs/core';
+import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';
+import {
+ CommandType,
+ DocumentFlavor,
+ generateRandomId,
+ getSectionHeaderFooterReferenceKey,
+ ICommandService,
+ IUniverInstanceService,
+ JSONX,
+ resolveSectionHeaderFooterReference,
+ Tools,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { getTopLevelSectionBreaks } from '../../utils/sections';
+import { RichTextEditingMutation } from '../mutations/core-editing.mutation';
+import { getEmptyHeaderFooterBody } from './create-header-footer.command';
+
+export interface ISetSectionHeaderFooterLinkCommandParams {
+ unitId: string;
+ sectionId: string;
+ kind: SectionHeaderFooterKind;
+ variant: SectionHeaderFooterVariant;
+ linkedToPrevious: boolean;
+ /** Stable id to use when unlinking. Generated automatically when omitted. */
+ segmentId?: string;
+}
+
+interface ISectionHeaderFooterLinkContext {
+ snapshot: IDocumentData;
+ sections: ISectionBreak[];
+ sectionIndex: number;
+ storageIndex: number;
+ key: SectionHeaderFooterReferenceKey;
+}
+
+export const SetSectionHeaderFooterLinkCommand: ICommand<ISetSectionHeaderFooterLinkCommandParams> = {
+ id: 'doc.command.set-section-header-footer-link',
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+ const instanceService = accessor.get(IUniverInstanceService);
+ const commandService = accessor.get(ICommandService);
+ const documentDataModel = instanceService.getUnit<DocumentDataModel>(params.unitId, UniverInstanceType.UNIVER_DOC);
+ const snapshot = documentDataModel?.getSnapshot();
+ if (!documentDataModel || !snapshot?.body || snapshot.documentStyle.documentFlavor !== DocumentFlavor.TRADITIONAL) {
+ return false;
+ }
+
+ const sections = getTopLevelSectionBreaks(snapshot.body);
+ const sectionIndex = sections.findIndex((section) => section.sectionId === params.sectionId);
+ if (sectionIndex <= 0) {
+ return false;
+ }
+ const storageIndex = snapshot.body.sectionBreaks?.findIndex((item) => item.sectionId === params.sectionId) ?? -1;
+ if (storageIndex < 0) {
+ return false;
+ }
+
+ const key = getSectionHeaderFooterReferenceKey(params.kind, params.variant);
+ const context = { snapshot, sections, sectionIndex, storageIndex, key };
+ const rawActions = params.linkedToPrevious
+ ? buildLinkActions(context, params.kind)
+ : buildUnlinkActions(context, params.kind, params.segmentId);
+ if (!rawActions) {
+ return false;
+ }
+
+ const mutation: IMutationInfo<IRichTextEditingMutationParams> = {
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: params.unitId,
+ actions: rawActions.reduce((actions, action) => JSONX.compose(actions, action as JSONXActions), null as JSONXActions),
+ textRanges: null,
+ noNeedSetTextRange: true,
+ debounce: true,
+ isEditing: false,
+ trigger: SetSectionHeaderFooterLinkCommand.id,
+ },
+ };
+ return Boolean(commandService.syncExecuteCommand(mutation.id, mutation.params));
+ },
+};
+
+function buildLinkActions(context: ISectionHeaderFooterLinkContext, kind: SectionHeaderFooterKind): JSONXActions | null {
+ const { snapshot, sections, sectionIndex, storageIndex, key } = context;
+ const section = sections[sectionIndex];
+ const explicitSegmentId = section[key];
+ if (typeof explicitSegmentId !== 'string' || !explicitSegmentId) {
+ return null;
+ }
+
+ const jsonX = JSONX.getInstance();
+ const actions: JSONXActions = [jsonX.removeOp(['body', 'sectionBreaks', storageIndex, key], explicitSegmentId)!];
+ const referenceKeys = kind === 'header'
+ ? ['defaultHeaderId', 'firstPageHeaderId', 'evenPageHeaderId'] as const
+ : ['defaultFooterId', 'firstPageFooterId', 'evenPageFooterId'] as const;
+ const referencedByDocument = referenceKeys.some((referenceKey) => snapshot.documentStyle[referenceKey] === explicitSegmentId);
+ const referencedBySection = sections.some((item) => referenceKeys.some((referenceKey) => (
+ !(item.sectionId === section.sectionId && referenceKey === key) && item[referenceKey] === explicitSegmentId
+ )));
+ const resources = kind === 'header' ? snapshot.headers : snapshot.footers;
+ if (!referencedByDocument && !referencedBySection && resources?.[explicitSegmentId]) {
+ actions.push(jsonX.removeOp([kind === 'header' ? 'headers' : 'footers', explicitSegmentId], resources[explicitSegmentId])!);
+ }
+ return actions;
+}
+
+function buildUnlinkActions(
+ context: ISectionHeaderFooterLinkContext,
+ kind: SectionHeaderFooterKind,
+ requestedSegmentId?: string
+): JSONXActions | null {
+ const { snapshot, sections, sectionIndex, storageIndex, key } = context;
+ const explicitSegmentId = sections[sectionIndex][key];
+ if (typeof explicitSegmentId === 'string' && explicitSegmentId) {
+ return null;
+ }
+
+ const sourceSegmentId = resolveSectionHeaderFooterReference(snapshot.documentStyle, sections, sectionIndex - 1, key).segmentId;
+ const segmentId = requestedSegmentId ?? generateRandomId(6);
+ const resources = kind === 'header' ? snapshot.headers : snapshot.footers;
+ if (resources?.[segmentId]) {
+ return null;
+ }
+ const source = sourceSegmentId ? resources?.[sourceSegmentId] : undefined;
+ const idKey = kind === 'header' ? 'headerId' : 'footerId';
+ const resource = source
+ ? { ...Tools.deepClone(source), [idKey]: segmentId }
+ : { [idKey]: segmentId, body: getEmptyHeaderFooterBody() };
+ const jsonX = JSONX.getInstance();
+ return [
+ jsonX.insertOp([kind === 'header' ? 'headers' : 'footers', segmentId], resource)!,
+ jsonX.insertOp(['body', 'sectionBreaks', storageIndex, key], segmentId)!,
+ ];
+}
diff --git a/packages/docs/src/commands/commands/update-document-section.command.ts b/packages/docs/src/commands/commands/update-document-section.command.ts
new file mode 100644
index 0000000000..1858652541
--- /dev/null
+++ b/packages/docs/src/commands/commands/update-document-section.command.ts
@@ -0,0 +1,233 @@
+/**
+ * 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 { DocumentDataModel, ICommand, IMutationInfo, ISectionBreak } from '@univerjs/core';
+import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';
+import {
+ CommandType,
+ containsInteriorInsertionOffset,
+ DataStreamTreeTokenType,
+ DocumentFlavor,
+ getBlockRangeInterval,
+ getColumnGroupRangeInterval,
+ getRichTextEditPath,
+ getTableRangeInterval,
+ ICommandService,
+ IUniverInstanceService,
+ JSONX,
+ MemoryCursor,
+ TextX,
+ TextXActionType,
+ Tools,
+ UniverInstanceType,
+ UpdateDocsAttributeType,
+} from '@univerjs/core';
+import { getTopLevelSectionBreaks } from '../../utils/sections';
+import { RichTextEditingMutation } from '../mutations/core-editing.mutation';
+
+export type IDocumentSectionConfig = Omit<ISectionBreak, 'sectionId' | 'startIndex'>;
+
+export interface IDocumentSectionUpdate {
+ sectionId: string;
+ config: Partial<IDocumentSectionConfig>;
+}
+
+export interface IUpdateDocumentSectionCommandParams {
+ unitId: string;
+ updates: IDocumentSectionUpdate[];
+}
+
+export interface IInsertDocumentSectionBreakCommandParams {
+ unitId: string;
+ offset: number;
+ sectionId: string;
+ config?: Partial<IDocumentSectionConfig>;
+}
+
+export interface IDeleteDocumentSectionBreakCommandParams {
+ unitId: string;
+ sectionId: string;
+}
+
+export const UpdateDocumentSectionCommand: ICommand<IUpdateDocumentSectionCommandParams> = {
+ id: 'doc.command.update-section',
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => {
+ if (!params?.updates.length || params.updates.some(({ sectionId, config }) => !sectionId || Object.keys(config).length === 0)) {
+ return false;
+ }
+
+ const instanceService = accessor.get(IUniverInstanceService);
+ const commandService = accessor.get(ICommandService);
+ const documentDataModel = instanceService.getUnit<DocumentDataModel>(params.unitId, UniverInstanceType.UNIVER_DOC);
+ if (!documentDataModel || documentDataModel.getDocumentStyle().documentFlavor !== DocumentFlavor.TRADITIONAL) {
+ return false;
+ }
+
+ const body = documentDataModel.getBody();
+ if (!body) {
+ return false;
+ }
+
+ const updates = new Map(params.updates.map(({ sectionId, config }) => [sectionId, config]));
+ if (updates.size !== params.updates.length) {
+ return false;
+ }
+ const selectedIds = new Set(updates.keys());
+ const sections = getTopLevelSectionBreaks(body)
+ .filter((section) => selectedIds.has(section.sectionId))
+ .sort((left, right) => left.startIndex - right.startIndex);
+ if (sections.length !== selectedIds.size) {
+ return false;
+ }
+
+ const cursor = new MemoryCursor();
+ const textX = new TextX();
+ for (const section of sections) {
+ textX.push({ t: TextXActionType.RETAIN, len: section.startIndex - cursor.cursor });
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len: 1,
+ coverType: UpdateDocsAttributeType.REPLACE,
+ body: {
+ dataStream: '',
+ sectionBreaks: [{
+ ...Tools.deepClone(section),
+ ...Tools.deepClone(updates.get(section.sectionId)!),
+ sectionId: section.sectionId,
+ startIndex: 0,
+ }],
+ },
+ });
+ cursor.moveCursorTo(section.startIndex + 1);
+ }
+
+ const jsonX = JSONX.getInstance();
+ const mutation: IMutationInfo<IRichTextEditingMutationParams> = {
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: params.unitId,
+ actions: jsonX.editOp(textX.serialize(), getRichTextEditPath(documentDataModel)),
+ textRanges: null,
+ noNeedSetTextRange: true,
+ debounce: true,
+ isEditing: false,
+ trigger: UpdateDocumentSectionCommand.id,
+ },
+ };
+
+ return Boolean(commandService.syncExecuteCommand(mutation.id, mutation.params));
+ },
+};
+
+export const InsertDocumentSectionBreakCommand: ICommand<IInsertDocumentSectionBreakCommandParams> = {
+ id: 'doc.command.insert-section-break',
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+ const context = getTraditionalDocumentContext(accessor, params.unitId);
+ if (!context || !params.sectionId || !Number.isInteger(params.offset)) {
+ return false;
+ }
+ const { body, documentDataModel, commandService } = context;
+ if (
+ params.offset < 0 ||
+ params.offset > body.dataStream.length ||
+ body.sectionBreaks?.some((section) => section.sectionId === params.sectionId) ||
+ body.tables?.some((range) => containsInteriorInsertionOffset(getTableRangeInterval(range), params.offset)) ||
+ body.columnGroups?.some((range) => containsInteriorInsertionOffset(getColumnGroupRangeInterval(range), params.offset)) ||
+ body.blockRanges?.some((range) => containsInteriorInsertionOffset(getBlockRangeInterval(range), params.offset))
+ ) {
+ return false;
+ }
+
+ const textX = new TextX();
+ textX.retain(params.offset);
+ textX.insert(1, {
+ dataStream: DataStreamTreeTokenType.SECTION_BREAK,
+ sectionBreaks: [{
+ ...Tools.deepClone(params.config ?? {}),
+ sectionId: params.sectionId,
+ startIndex: 0,
+ }],
+ });
+ return executeSectionTextX(commandService, documentDataModel, textX, InsertDocumentSectionBreakCommand.id);
+ },
+};
+
+export const DeleteDocumentSectionBreakCommand: ICommand<IDeleteDocumentSectionBreakCommandParams> = {
+ id: 'doc.command.delete-section-break',
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+ const context = getTraditionalDocumentContext(accessor, params.unitId);
+ if (!context || !params.sectionId) {
+ return false;
+ }
+ const sections = getTopLevelSectionBreaks(context.body);
+ if (sections.length <= 1) {
+ return false;
+ }
+ const section = sections.find((item) => item.sectionId === params.sectionId);
+ if (!section) {
+ return false;
+ }
+
+ const textX = new TextX();
+ textX.retain(section.startIndex);
+ textX.delete(1);
+ return executeSectionTextX(context.commandService, context.documentDataModel, textX, DeleteDocumentSectionBreakCommand.id);
+ },
+};
+
+function getTraditionalDocumentContext(accessor: Parameters<typeof UpdateDocumentSectionCommand.handler>[0], unitId?: string) {
+ if (!unitId) {
+ return null;
+ }
+ const instanceService = accessor.get(IUniverInstanceService);
+ const documentDataModel = instanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
+ const body = documentDataModel?.getBody();
+ if (!documentDataModel || !body || documentDataModel.getDocumentStyle().documentFlavor !== DocumentFlavor.TRADITIONAL) {
+ return null;
+ }
+ return {
+ body,
+ documentDataModel,
+ commandService: accessor.get(ICommandService),
+ };
+}
+
+function executeSectionTextX(
+ commandService: ICommandService,
+ documentDataModel: DocumentDataModel,
+ textX: TextX,
+ trigger: string
+): boolean {
+ const actions = JSONX.getInstance().editOp(textX.serialize(), getRichTextEditPath(documentDataModel));
+ return Boolean(commandService.syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId: documentDataModel.getUnitId(),
+ actions,
+ textRanges: null,
+ noNeedSetTextRange: true,
+ debounce: true,
+ isEditing: false,
+ trigger,
+ }));
+}
diff --git a/packages/docs/src/facade/__tests__/create-test-bed.ts b/packages/docs/src/facade/__tests__/create-test-bed.ts
index ae81015ec5..fed2264806 100644
--- a/packages/docs/src/facade/__tests__/create-test-bed.ts
+++ b/packages/docs/src/facade/__tests__/create-test-bed.ts
@@ -72,7 +72,7 @@ export function createSimpleDocument(id = 'test'): IDocumentData {
{ startIndex: 10, paragraphId: 'para_beta' },
{ startIndex: 16, paragraphId: 'para_gamma' },
],
- sectionBreaks: [{ startIndex: 17 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_110', startIndex: 17 }],
});
}
@@ -84,7 +84,7 @@ export function createDuplicateDocument(id = 'test'): IDocumentData {
{ startIndex: 9, paragraphId: 'para_same_2' },
{ startIndex: 14, paragraphId: 'para_tail' },
],
- sectionBreaks: [{ startIndex: 15 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_111', startIndex: 15 }],
});
}
@@ -103,7 +103,7 @@ export function createTaskDocument(id = 'test'): IDocumentData {
},
{ startIndex: 9, paragraphId: 'para_done' },
],
- sectionBreaks: [{ startIndex: 10 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_112', startIndex: 10 }],
});
}
@@ -122,7 +122,7 @@ export function createBulletDocument(id = 'test'): IDocumentData {
},
{ startIndex: 11, paragraphId: 'para_bullet_tail' },
],
- sectionBreaks: [{ startIndex: 12 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_113', startIndex: 12 }],
});
}
@@ -136,7 +136,7 @@ export function createBlockRangeDocument(blockType = DocumentBlockRangeType.QUOT
startIndex: 0,
endIndex: 5,
}],
- sectionBreaks: [{ startIndex: 12 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_114', startIndex: 12 }],
});
}
@@ -145,7 +145,7 @@ export function createTableDocument(id = 'test'): IDocumentData {
dataStream: 'TT\raa\r\n',
paragraphs: [{ startIndex: 2, paragraphId: 'para_fixture_21' }, { startIndex: 5, paragraphId: 'para_after_table' }],
tables: [{ tableId: 'table-1', startIndex: 0, endIndex: 2 }],
- sectionBreaks: [{ startIndex: 6 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_115', startIndex: 6 }],
});
}
@@ -154,7 +154,7 @@ export function createCustomBlockDocument(id = 'test'): IDocumentData {
dataStream: '\b\raa\r\n',
paragraphs: [{ startIndex: 1, paragraphId: 'para_fixture_22' }, { startIndex: 4, paragraphId: 'para_after_custom_block' }],
customBlocks: [{ blockId: 'custom-1', blockType: 'custom' as never, startIndex: 0 }],
- sectionBreaks: [{ startIndex: 5 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_116', startIndex: 5 }],
});
}
diff --git a/packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts b/packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts
index 33d8548891..53beef0416 100644
--- a/packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts
@@ -124,6 +124,56 @@ describe('FDocumentParagraph', () => {
]);
});
+ it('reads and updates a text range across existing style-run boundaries', () => {
+ const data = createSimpleDocument();
+ data.body!.textRuns = [
+ { st: 0, ed: 5, ts: { cl: { rgb: '#FF0000' }, bl: 1 } },
+ { st: 5, ed: 10, ts: { cl: { rgb: '#FF0000' }, it: 1 } },
+ ];
+ createDocumentFacade(data);
+
+ const range = document.getTextRange(2, 8);
+
+ expect(range.getText()).toBe('pha\rBe');
+ expect(range.getTextStyleRuns()).toEqual([
+ { startOffset: 2, endOffset: 5, textStyle: { cl: { rgb: '#FF0000' }, bl: 1 } },
+ { startOffset: 5, endOffset: 8, textStyle: { cl: { rgb: '#FF0000' }, it: 1 } },
+ ]);
+ expect(range.getCommonTextStyle()).toEqual({ cl: { rgb: '#FF0000' } });
+ expect(range.getExplicitTextStyleRuns()).toEqual(range.getTextStyleRuns());
+ expect(range.getCommonExplicitTextStyle()).toEqual(range.getCommonTextStyle());
+ expect(range.describe()).toMatchObject({
+ startOffset: 2,
+ endOffset: 8,
+ segmentId: '',
+ length: 6,
+ text: 'pha\rBe',
+ explicitTextStyleRuns: range.getTextStyleRuns(),
+ commonExplicitTextStyle: { cl: { rgb: '#FF0000' } },
+ });
+
+ expect(range.setTextStyle({ fs: 20 })).toBe(true);
+ expect(document.save().body?.textRuns).toEqual([
+ { st: 0, ed: 2, ts: { cl: { rgb: '#FF0000' }, bl: 1 } },
+ { st: 2, ed: 5, ts: { cl: { rgb: '#FF0000' }, bl: 1, fs: 20 } },
+ { st: 5, ed: 8, ts: { cl: { rgb: '#FF0000' }, it: 1, fs: 20 } },
+ { st: 8, ed: 10, ts: { cl: { rgb: '#FF0000' }, it: 1 } },
+ ]);
+ expect(document.getParagraphs()[0].getTextRange().getRange()).toEqual({
+ startOffset: 0,
+ endOffset: 5,
+ segmentId: '',
+ });
+ });
+
+ it('rejects invalid document text ranges', () => {
+ createDocumentFacade(createSimpleDocument());
+
+ expect(() => document.getTextRange(-1, 2)).toThrow(RangeError);
+ expect(() => document.getTextRange(4, 2)).toThrow(RangeError);
+ expect(() => document.getTextRange(0, 999)).toThrow(RangeError);
+ });
+
it('keeps a paragraph after a block scoped outside the block end token', () => {
const T = DataStreamTreeTokenType;
createDocumentFacade(createDocumentData('doc-after-block', {
@@ -132,7 +182,7 @@ describe('FDocumentParagraph', () => {
{ startIndex: 5, paragraphId: 'para_code' },
{ startIndex: 12, paragraphId: 'para_after' },
],
- sectionBreaks: [{ startIndex: 13 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_117', startIndex: 13 }],
blockRanges: [{
blockId: 'code-1',
blockType: DocumentBlockRangeType.CODE,
@@ -164,7 +214,7 @@ describe('FDocumentParagraph', () => {
...createDocumentData('doc-with-header', {
dataStream: 'Body\r\n',
paragraphs: [{ startIndex: 4, paragraphId: 'para_body' }],
- sectionBreaks: [{ startIndex: 5 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_118', startIndex: 5 }],
}),
headers: {
[headerId]: {
@@ -172,7 +222,7 @@ describe('FDocumentParagraph', () => {
body: {
dataStream: 'Head\r\n',
paragraphs: [{ startIndex: 4, paragraphId: 'para_header' }],
- sectionBreaks: [{ startIndex: 5 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_119', startIndex: 5 }],
},
},
},
diff --git a/packages/docs/src/facade/__tests__/f-document.spec.ts b/packages/docs/src/facade/__tests__/f-document.spec.ts
index 5ce2db9d2a..0f7390c6db 100644
--- a/packages/docs/src/facade/__tests__/f-document.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document.spec.ts
@@ -16,7 +16,7 @@
import type { IDocumentData, Univer } from '@univerjs/core';
import type { FDocument } from '../f-document';
-import { DocumentFlavor, ICommandService, IResourceManagerService, IUndoRedoService, UniverInstanceType } from '@univerjs/core';
+import { ColumnSeparatorType, DataStreamTreeTokenType, DocumentFlavor, ICommandService, IResourceManagerService, IUndoRedoService, SectionType, UniverInstanceType } from '@univerjs/core';
import { InsertTextCommand } from '@univerjs/docs';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { createDocumentData, createSimpleDocument, createTestBed } from './create-test-bed';
@@ -39,6 +39,11 @@ describe('FDocument', () => {
createDocumentFacade();
});
+ it('exposes section enums through univerAPI', () => {
+ expect(univerAPI.Enum.SectionType.NEXT_PAGE).toBe(SectionType.NEXT_PAGE);
+ expect(univerAPI.Enum.ColumnSeparatorType.BETWEEN_EACH_COLUMN).toBe(ColumnSeparatorType.BETWEEN_EACH_COLUMN);
+ });
+
afterEach(() => {
univer.dispose();
});
@@ -122,7 +127,7 @@ describe('FDocument', () => {
createDocumentFacade(createDocumentData('doc-with-ids', {
dataStream: 'Legacy\r\n',
paragraphs: [{ startIndex: 6, paragraphId: 'para_fixture_26' }],
- sectionBreaks: [{ startIndex: 7 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_120', startIndex: 7 }],
}));
const paragraph = document.getParagraphs()[0];
@@ -136,7 +141,7 @@ describe('FDocument', () => {
createDocumentFacade(createDocumentData('empty-doc', {
dataStream: '\r\n',
paragraphs: [{ startIndex: 0, paragraphId: 'para_empty' }],
- sectionBreaks: [{ startIndex: 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_121', startIndex: 1 }],
}));
document.deleteRange({ startOffset: 0, endOffset: 5 });
@@ -160,6 +165,9 @@ describe('FDocument', () => {
};
createDocumentFacade(documentData);
+ expect(document.setHeaderFooterOptions({ marginHeader: 36, marginFooter: 40 })).toBe(true);
+ expect(document.getHeaderFooterOptions()).toMatchObject({ marginHeader: 36, marginFooter: 40 });
+
const headerId = document.ensurePageHeader();
let snapshot = document.save();
@@ -178,4 +186,199 @@ describe('FDocument', () => {
expect(snapshot.documentStyle?.defaultFooterId).toBe(footerId);
expect(snapshot.footers?.[footerId].body?.dataStream).toBe('\r\n');
});
+
+ it('reads and updates OOXML-compatible columns on traditional document sections', () => {
+ univer.dispose();
+ const data = createDocumentData('section-doc', {
+ dataStream: 'One\r\nTwo\r\n',
+ paragraphs: [
+ { startIndex: 3, paragraphId: 'para-one' },
+ { startIndex: 8, paragraphId: 'para-two' },
+ ],
+ sectionBreaks: [
+ { sectionId: 'section_fixture_122', startIndex: 4, sectionType: SectionType.CONTINUOUS },
+ { sectionId: 'section_fixture_123', startIndex: 9 },
+ ],
+ });
+ data.documentStyle = {
+ ...data.documentStyle,
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ };
+ createDocumentFacade(data);
+
+ expect(document.getSections()).toHaveLength(2);
+ expect(document.getSectionAt(6)?.getIndex()).toBe(1);
+ const first = document.getSection(0)!;
+ expect(first.getRange()).toEqual({ startOffset: 0, endOffset: 4, segmentId: '' });
+ expect(first.setColumns(2, { gap: 20, separator: true, sectionType: SectionType.CONTINUOUS })).toBe(true);
+ expect(first.describe()).toMatchObject({
+ columnCount: 2,
+ columnSeparatorType: ColumnSeparatorType.BETWEEN_EACH_COLUMN,
+ sectionType: SectionType.CONTINUOUS,
+ });
+ expect(first.getColumns()[0].paddingEnd).toBe(20);
+ const headerId = first.ensureHeader();
+ expect(document.save().body?.sectionBreaks?.[0].defaultHeaderId).toBe(headerId);
+ expect(document.save().documentStyle.defaultHeaderId).toBeFalsy();
+ expect(document.insertColumnBreak(2)).toBe(true);
+ expect(document.save().body?.dataStream[2]).toBe(DataStreamTreeTokenType.COLUMN_BREAK);
+ });
+
+ it('keeps traditional section mutation unavailable in modern documents', () => {
+ expect(document.getSections()).toEqual([]);
+ expect(() => document.insertColumnBreak(0)).toThrow('Section column APIs are supported only in traditional documents');
+ });
+
+ it('keeps section facade identity stable when section order changes', () => {
+ univer.dispose();
+ const data = createDocumentData('stable-section-doc', {
+ dataStream: 'One\r\nTwo\r\n',
+ paragraphs: [
+ { startIndex: 3, paragraphId: 'para-one' },
+ { startIndex: 8, paragraphId: 'para-two' },
+ ],
+ sectionBreaks: [
+ { sectionId: 'section_stable_one', startIndex: 4 },
+ { sectionId: 'section_stable_two', startIndex: 9 },
+ ],
+ });
+ data.documentStyle = { ...data.documentStyle, documentFlavor: DocumentFlavor.TRADITIONAL };
+ createDocumentFacade(data);
+
+ const originalFirst = document.getSection(0)!;
+ const originalId = originalFirst.getId();
+ const inserted = document.insertSectionBreak(0);
+
+ expect(inserted).not.toBeNull();
+ expect(originalFirst.getId()).toBe(originalId);
+ expect(originalFirst.getIndex()).toBe(1);
+ expect(originalFirst.getConfig().sectionId).toBe(originalId);
+ });
+
+ it('reads and changes header links through stable section ids', () => {
+ univer.dispose();
+ const data = createDocumentData('section-header-facade-doc', {
+ dataStream: 'One\r\nTwo\r\n',
+ paragraphs: [
+ { startIndex: 3, paragraphId: 'para_header_one' },
+ { startIndex: 8, paragraphId: 'para_header_two' },
+ ],
+ sectionBreaks: [
+ { sectionId: 'section_header_one', startIndex: 4, defaultHeaderId: 'header-one' },
+ { sectionId: 'section_header_two', startIndex: 9 },
+ ],
+ });
+ data.documentStyle = { ...data.documentStyle, documentFlavor: DocumentFlavor.TRADITIONAL };
+ data.headers = {
+ 'header-one': {
+ headerId: 'header-one',
+ body: {
+ dataStream: 'Shared\r\n',
+ paragraphs: [{ startIndex: 6, paragraphId: 'header_facade_para' }],
+ sectionBreaks: [{ startIndex: 7, sectionId: 'header_facade_section' }],
+ },
+ },
+ };
+ createDocumentFacade(data);
+ const second = document.getSection(1)!;
+ get(IUndoRedoService);
+
+ expect(second.isHeaderLinkedToPrevious()).toBe(true);
+ expect(second.getHeaderId()).toBe('header-one');
+ expect(second.describe().headerFooter.defaultHeader).toEqual({
+ segmentId: 'header-one',
+ linkedToPrevious: true,
+ });
+ expect(second.setHeaderLinkedToPrevious(false)).toBe(true);
+ expect(second.isHeaderLinkedToPrevious()).toBe(false);
+ expect(second.getHeaderId()).not.toBe('header-one');
+ expect(document.save().headers?.[second.getHeaderId()!].body?.dataStream).toBe('Shared\r\n');
+ expect(document.undo()).toBe(true);
+ expect(second.isHeaderLinkedToPrevious()).toBe(true);
+ expect(second.getHeaderId()).toBe('header-one');
+ expect(document.redo()).toBe(true);
+ expect(second.isHeaderLinkedToPrevious()).toBe(false);
+ expect(second.setHeaderLinkedToPrevious(true)).toBe(true);
+ expect(second.isHeaderLinkedToPrevious()).toBe(true);
+ expect(second.getHeaderId()).toBe('header-one');
+ });
+
+ it('rejects reads from a retained section facade after switching to modern mode', () => {
+ univer.dispose();
+ const data = createDocumentData('retained-section-doc', {
+ dataStream: 'Alpha\r\n',
+ paragraphs: [{ startIndex: 5, paragraphId: 'para_retained_section' }],
+ sectionBreaks: [{ startIndex: 6, sectionId: 'section_retained' }],
+ });
+ data.documentStyle = { ...data.documentStyle, documentFlavor: DocumentFlavor.TRADITIONAL };
+ createDocumentFacade(data);
+ const section = document.getSection(0)!;
+
+ document.getDocumentDataModel().updateDocumentStyle({
+ ...document.getDocumentDataModel().getDocumentStyle(),
+ documentFlavor: DocumentFlavor.MODERN,
+ });
+
+ expect(section.getId()).toBe('section_retained');
+ expect(() => section.getConfig()).toThrow('Section column APIs are supported only in traditional documents');
+ expect(() => section.getRange()).toThrow('Section column APIs are supported only in traditional documents');
+ });
+
+ it('does not expose table-cell section sentinels as document sections', () => {
+ univer.dispose();
+ const T = DataStreamTreeTokenType;
+ const dataStream = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const data = createDocumentData('top-level-section-doc', {
+ dataStream,
+ paragraphs: [
+ { startIndex: 3, paragraphId: 'para_cell' },
+ { startIndex: 8, paragraphId: 'para_root' },
+ ],
+ sectionBreaks: [
+ { startIndex: 4, sectionId: 'section_cell' },
+ { startIndex: 9, sectionId: 'section_root' },
+ ],
+ });
+ data.documentStyle = { ...data.documentStyle, documentFlavor: DocumentFlavor.TRADITIONAL };
+ createDocumentFacade(data);
+
+ expect(document.getSections().map((section) => section.getId())).toEqual(['section_root']);
+ expect(document.getSection(0)?.getRange()).toEqual({ startOffset: 0, endOffset: 9, segmentId: '' });
+ });
+
+ it('inserts and removes traditional sections through stable ids', () => {
+ univer.dispose();
+ const data = createDocumentData('section-lifecycle-doc', {
+ dataStream: 'Alpha\r\n',
+ paragraphs: [{ startIndex: 5, paragraphId: 'para_alpha_section' }],
+ sectionBreaks: [{ startIndex: 6, sectionId: 'section_root' }],
+ });
+ data.documentStyle = { ...data.documentStyle, documentFlavor: DocumentFlavor.TRADITIONAL };
+ createDocumentFacade(data);
+
+ const inserted = document.insertSectionBreak(6, { sectionType: SectionType.CONTINUOUS });
+ expect(inserted?.getId()).toMatch(/^section_/u);
+ expect(inserted?.getConfig().sectionType).toBe(SectionType.CONTINUOUS);
+ expect(document.getSections()).toHaveLength(2);
+
+ expect(inserted?.remove()).toBe(true);
+ expect(document.getSections().map((section) => section.getId())).toEqual(['section_root']);
+ expect(document.getSection(0)?.remove()).toBe(false);
+ });
+
+ it('inserts a horizontal rule as a bordered paragraph', () => {
+ univer.dispose();
+ createDocumentFacade(createSimpleDocument());
+ const offset = document.getBody().sectionBreaks![0].startIndex;
+
+ const rule = document.insertHorizontalRule(offset);
+
+ expect(rule).not.toBeNull();
+ expect(rule?.getText()).toBe('');
+ expect(rule?.getInfo().paragraph.paragraphStyle?.borderBottom).toMatchObject({
+ padding: 5,
+ width: 1,
+ color: { rgb: '#CDD0D8' },
+ });
+ });
});
diff --git a/packages/docs/src/facade/f-document-paragraph.ts b/packages/docs/src/facade/f-document-paragraph.ts
index 11d798e109..f86859dc83 100644
--- a/packages/docs/src/facade/f-document-paragraph.ts
+++ b/packages/docs/src/facade/f-document-paragraph.ts
@@ -18,6 +18,7 @@ import type { IDocumentBody, Injector, IParagraph, IParagraphStyle } from '@univ
import type { FDocument } from './f-document';
import type { IFDocumentTextRange } from './utils';
import { getParagraphContentStartOffset, PresetListType, RESTORE_INSERTED_PARAGRAPH_IDS, UpdateDocsAttributeType } from '@univerjs/core';
+import { FDocumentTextRange } from './f-document-text-range';
import { buildPlainTextInsertBody, replaceBodyRange, retainBodyRange } from './utils';
/**
@@ -132,6 +133,22 @@ export class FDocumentParagraph {
return { startOffset, endOffset, segmentId: this._segmentId };
}
+ /**
+ * Returns an agent-friendly facade for reading and styling this paragraph's text.
+ * @returns {FDocumentTextRange} The paragraph text range, excluding the trailing paragraph break.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const paragraph = fDocument?.findParagraphByText('Launch');
+ * const range = paragraph?.getTextRange();
+ * console.log(range?.describe());
+ * ```
+ */
+ getTextRange(): FDocumentTextRange {
+ const { startOffset, endOffset } = this.getInfo();
+ return this._injector.createInstance(FDocumentTextRange, this._document, startOffset, endOffset, this._segmentId, this._injector);
+ }
+
/**
* Get this paragraph's plain text.
* @returns {string} The paragraph text without the trailing paragraph break.
@@ -193,6 +210,7 @@ export class FDocumentParagraph {
/**
* Apply paragraph style to a paragraph handle or text range.
+ * `style.textStyle.fs` is a font size in points (pt), not CSS pixels.
* @param {IParagraphStyle} style The Univer paragraph style patch.
* @returns {boolean} `true` if the style was applied.
* @example
diff --git a/packages/docs/src/facade/f-document-section.ts b/packages/docs/src/facade/f-document-section.ts
new file mode 100644
index 0000000000..95a828d619
--- /dev/null
+++ b/packages/docs/src/facade/f-document-section.ts
@@ -0,0 +1,516 @@
+/**
+ * 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 { Injector, IResolvedSectionHeaderFooterReference, ISectionBreak, ISectionColumnProperties, SectionHeaderFooterKind, SectionHeaderFooterVariant } from '@univerjs/core';
+import type { IHeaderFooterProps } from '@univerjs/docs';
+import type { FDocument } from './f-document';
+import type { IFDocumentTextRange } from './utils';
+import { ColumnSeparatorType, DocumentFlavor, generateRandomId, getSectionHeaderFooterReferenceKey, ICommandService, resolveSectionHeaderFooterReference, SectionType, Tools } from '@univerjs/core';
+import { CreateHeaderFooterCommand, createSectionColumnProperties, DeleteDocumentSectionBreakCommand, getTopLevelSectionBreaks, HeaderFooterType, SetSectionHeaderFooterLinkCommand, UpdateDocumentSectionCommand } from '@univerjs/docs';
+
+export interface IFDocumentSectionColumnOptions {
+ /** Gap after each column except the last, in points (pt). */
+ gap?: number;
+ /** Optional explicit column widths in points (pt). Length must equal `columnCount`. */
+ widths?: number[];
+ /** Whether to draw separators, or the exact separator enum value. */
+ separator?: boolean | ColumnSeparatorType;
+ /** How the following section starts. */
+ sectionType?: SectionType;
+}
+
+export interface IFDocumentSectionDescription {
+ sectionId: string;
+ index: number;
+ range: IFDocumentTextRange;
+ columnCount: number;
+ columns: ISectionColumnProperties[];
+ columnSeparatorType: ColumnSeparatorType;
+ sectionType: SectionType;
+ headerFooter: Record<`${SectionHeaderFooterVariant}${Capitalize<SectionHeaderFooterKind>}`, {
+ segmentId: string | null;
+ linkedToPrevious: boolean;
+ }>;
+ config: ISectionBreak;
+}
+
+/** Error thrown when traditional section APIs are used to mutate a modern document. */
+export class DocsSectionUnsupportedDocumentFlavorError extends Error {
+ constructor() {
+ super('Section column APIs are supported only in traditional documents. Use ColumnGroup APIs for modern documents.');
+ this.name = 'DocsSectionUnsupportedDocumentFlavorError';
+ }
+}
+
+/**
+ * Facade wrapper for an OOXML-compatible traditional document section.
+ * Modern documents use ColumnGroup APIs and cannot mutate this facade.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * if (fDocument && !fDocument.isModern()) {
+ * console.log(fDocument.getSection(0)?.describe());
+ * }
+ * ```
+ */
+export class FDocumentSection {
+ constructor(
+ private readonly _document: FDocument,
+ private readonly _sectionId: string,
+ private readonly _injector: Injector
+ ) {}
+
+ /**
+ * Returns the persisted section id.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * console.log(fDocument?.getSection(0)?.getId());
+ * ```
+ */
+ getId(): string {
+ return this._sectionId;
+ }
+
+ /**
+ * Returns the current zero-based section index.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * console.log(fDocument?.getSection(0)?.getIndex());
+ * ```
+ */
+ getIndex(): number {
+ return this._resolve().index;
+ }
+
+ /**
+ * Returns the section break snapshot that terminates this section.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * console.log(fDocument?.getSection(0)?.getConfig());
+ * ```
+ */
+ getConfig(): ISectionBreak {
+ const { sectionBreak } = this._resolve();
+ return Tools.deepClone(sectionBreak);
+ }
+
+ /**
+ * Returns the section content range, excluding its terminating section-break token.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * console.log(fDocument?.getSection(0)?.getRange());
+ * ```
+ */
+ getRange(): IFDocumentTextRange {
+ const sectionBreaks = getTopLevelSectionBreaks(this._document.getBody());
+ const { index, sectionBreak } = this._resolve();
+
+ return {
+ startOffset: index === 0 ? 0 : sectionBreaks[index - 1].startIndex + 1,
+ endOffset: sectionBreak.startIndex,
+ segmentId: '',
+ };
+ }
+
+ /**
+ * Returns the explicit columns. An empty array means the normal single-column layout.
+ * Column widths and trailing spaces are in points (pt).
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * console.log(fDocument?.getSection(0)?.getColumns());
+ * ```
+ */
+ getColumns(): ISectionColumnProperties[] {
+ return Tools.deepClone(this.getConfig().columnProperties ?? []);
+ }
+
+ /**
+ * Returns a compact serializable section summary.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * console.log(fDocument?.getSection(0)?.describe());
+ * ```
+ */
+ describe(): IFDocumentSectionDescription {
+ const config = this.getConfig();
+ const columns = config.columnProperties ?? [];
+ const headerFooter = {
+ defaultHeader: this._describeHeaderFooterReference('header', 'default'),
+ defaultFooter: this._describeHeaderFooterReference('footer', 'default'),
+ firstHeader: this._describeHeaderFooterReference('header', 'first'),
+ firstFooter: this._describeHeaderFooterReference('footer', 'first'),
+ evenHeader: this._describeHeaderFooterReference('header', 'even'),
+ evenFooter: this._describeHeaderFooterReference('footer', 'even'),
+ };
+ return {
+ sectionId: this._sectionId,
+ index: this.getIndex(),
+ range: this.getRange(),
+ columnCount: columns.length || 1,
+ columns: Tools.deepClone(columns),
+ columnSeparatorType: config.columnSeparatorType ?? ColumnSeparatorType.NONE,
+ sectionType: config.sectionType ?? SectionType.SECTION_TYPE_UNSPECIFIED,
+ headerFooter,
+ config,
+ };
+ }
+
+ /**
+ * Sets equal or explicitly sized columns for this traditional section.
+ * Use `columnCount = 1` to restore normal single-column layout.
+ * `gap` and `widths` are in points (pt).
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * if (fDocument && !fDocument.isModern()) {
+ * fDocument.getSection(0)?.setColumns(2, { gap: 18, separator: true });
+ * }
+ * ```
+ */
+ setColumns(columnCount: number, options: IFDocumentSectionColumnOptions = {}): boolean {
+ this._assertTraditionalDocument();
+ if (!Number.isInteger(columnCount) || columnCount < 1) {
+ throw new RangeError('Section column count must be a positive integer.');
+ }
+ if (options.widths && options.widths.length !== columnCount) {
+ throw new RangeError('Section column widths must match the column count.');
+ }
+
+ const gap = Math.max(0, options.gap ?? 18);
+ const config = this.getConfig();
+ const columns = createSectionColumnProperties(
+ this._document.getDocumentDataModel().getSnapshot().documentStyle,
+ config,
+ columnCount,
+ gap,
+ options.widths
+ );
+ const separator = typeof options.separator === 'boolean'
+ ? options.separator ? ColumnSeparatorType.BETWEEN_EACH_COLUMN : ColumnSeparatorType.NONE
+ : options.separator ?? ColumnSeparatorType.NONE;
+
+ return this._update({
+ columnProperties: columns,
+ columnSeparatorType: separator,
+ ...(options.sectionType == null ? {} : { sectionType: options.sectionType }),
+ });
+ }
+
+ /**
+ * Sets explicit OOXML-compatible column width and trailing-space values in points (pt).
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * if (fDocument && !fDocument.isModern()) {
+ * fDocument.getSection(0)?.setColumnProperties([
+ * { width: 240, paddingEnd: 18 },
+ * { width: 240, paddingEnd: 0 },
+ * ], univerAPI.Enum.ColumnSeparatorType.BETWEEN_EACH_COLUMN);
+ * }
+ * ```
+ */
+ setColumnProperties(columns: ISectionColumnProperties[], separator = ColumnSeparatorType.NONE): boolean {
+ this._assertTraditionalDocument();
+ if (columns.some(({ width, paddingEnd }) => width < 0 || paddingEnd < 0)) {
+ throw new RangeError('Section column widths and padding must be non-negative.');
+ }
+ return this._update({
+ columnProperties: Tools.deepClone(columns),
+ columnSeparatorType: separator,
+ });
+ }
+
+ /**
+ * Sets how the next section begins.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * if (fDocument && !fDocument.isModern()) {
+ * fDocument.getSection(0)?.setSectionType(univerAPI.Enum.SectionType.NEXT_PAGE);
+ * }
+ * ```
+ */
+ setSectionType(sectionType: SectionType): boolean {
+ this._assertTraditionalDocument();
+ return this._update({ sectionType });
+ }
+
+ /**
+ * Ensures a header segment linked specifically to this section.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * if (fDocument && !fDocument.isModern()) {
+ * const segmentId = fDocument.getSection(0)?.ensureHeader();
+ * if (segmentId) {
+ * fDocument.insertText(0, 'Quarterly report', segmentId);
+ * }
+ * }
+ * ```
+ */
+ ensureHeader(variant: SectionHeaderFooterVariant = 'default'): string {
+ return this._ensureHeaderFooter('header', variant);
+ }
+
+ /**
+ * Ensures a footer segment linked specifically to this section.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * if (fDocument && !fDocument.isModern()) {
+ * const segmentId = fDocument.getSection(0)?.ensureFooter('first');
+ * if (segmentId) {
+ * fDocument.insertText(0, 'Confidential', segmentId);
+ * }
+ * }
+ * ```
+ */
+ ensureFooter(variant: SectionHeaderFooterVariant = 'default'): string {
+ return this._ensureHeaderFooter('footer', variant);
+ }
+
+ /**
+ * Returns the effective header id after resolving links to previous sections.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * console.log(fDocument?.getSection(0)?.getHeaderId('default'));
+ * ```
+ */
+ getHeaderId(variant: SectionHeaderFooterVariant = 'default'): string | null {
+ return this._getHeaderFooterReference('header', variant).segmentId ?? null;
+ }
+
+ /**
+ * Returns the effective footer id after resolving links to previous sections.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * console.log(fDocument?.getSection(0)?.getFooterId('first'));
+ * ```
+ */
+ getFooterId(variant: SectionHeaderFooterVariant = 'default'): string | null {
+ return this._getHeaderFooterReference('footer', variant).segmentId ?? null;
+ }
+
+ /**
+ * Whether this header variant inherits the previous section's reference.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * console.log(fDocument?.getSection(1)?.isHeaderLinkedToPrevious());
+ * ```
+ */
+ isHeaderLinkedToPrevious(variant: SectionHeaderFooterVariant = 'default'): boolean {
+ return this._getHeaderFooterReference('header', variant).linkedToPrevious;
+ }
+
+ /**
+ * Whether this footer variant inherits the previous section's reference.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * console.log(fDocument?.getSection(1)?.isFooterLinkedToPrevious('even'));
+ * ```
+ */
+ isFooterLinkedToPrevious(variant: SectionHeaderFooterVariant = 'default'): boolean {
+ return this._getHeaderFooterReference('footer', variant).linkedToPrevious;
+ }
+
+ /**
+ * Links or unlinks this header variant. Unlinking clones the inherited header.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * if (fDocument && !fDocument.isModern()) {
+ * fDocument.getSection(1)?.setHeaderLinkedToPrevious(false, 'default');
+ * }
+ * ```
+ */
+ setHeaderLinkedToPrevious(linkedToPrevious: boolean, variant: SectionHeaderFooterVariant = 'default'): boolean {
+ return this._setHeaderFooterLinkedToPrevious('header', variant, linkedToPrevious);
+ }
+
+ /**
+ * Links or unlinks this footer variant. Unlinking clones the inherited footer.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * if (fDocument && !fDocument.isModern()) {
+ * fDocument.getSection(1)?.setFooterLinkedToPrevious(true, 'even');
+ * }
+ * ```
+ */
+ setFooterLinkedToPrevious(linkedToPrevious: boolean, variant: SectionHeaderFooterVariant = 'default'): boolean {
+ return this._setHeaderFooterLinkedToPrevious('footer', variant, linkedToPrevious);
+ }
+
+ /**
+ * Updates header/footer switches and margins on this section break.
+ * `marginHeader` and `marginFooter` are in points (pt).
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * if (fDocument && !fDocument.isModern()) {
+ * fDocument.getSection(0)?.setHeaderFooterOptions({
+ * marginHeader: 36,
+ * marginFooter: 36,
+ * useFirstPageHeaderFooter: univerAPI.Enum.BooleanNumber.TRUE,
+ * });
+ * }
+ * ```
+ */
+ setHeaderFooterOptions(options: IHeaderFooterProps): boolean {
+ this._assertTraditionalDocument();
+ return this._update(options);
+ }
+
+ /**
+ * Deletes this section break. The final top-level section break cannot be removed.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * if (fDocument && !fDocument.isModern()) {
+ * const sections = fDocument.getSections();
+ * if (sections.length > 1) {
+ * sections[0].remove();
+ * }
+ * }
+ * ```
+ */
+ remove(): boolean {
+ this._assertTraditionalDocument();
+ return this._injector.get(ICommandService).syncExecuteCommand(DeleteDocumentSectionBreakCommand.id, {
+ unitId: this._document.getId(),
+ sectionId: this._sectionId,
+ });
+ }
+
+ private _update(patch: Partial<ISectionBreak>): boolean {
+ const { sectionId: _sectionId, startIndex: _startIndex, ...config } = patch;
+ return this._injector.get(ICommandService).syncExecuteCommand(UpdateDocumentSectionCommand.id, {
+ unitId: this._document.getId(),
+ updates: [{ sectionId: this._sectionId, config }],
+ });
+ }
+
+ private _ensureHeaderFooter(kind: SectionHeaderFooterKind, variant: SectionHeaderFooterVariant): string {
+ this._assertTraditionalDocument();
+ const { index } = this._resolve();
+ const config = this.getConfig();
+ const key = getSectionHeaderFooterReferenceKey(kind, variant);
+ const existing = config[key];
+ if (typeof existing === 'string' && existing) {
+ return existing;
+ }
+
+ if (index > 0) {
+ const segmentId = generateRandomId(6);
+ const success = this._injector.get(ICommandService).syncExecuteCommand(SetSectionHeaderFooterLinkCommand.id, {
+ unitId: this._document.getId(),
+ sectionId: this._sectionId,
+ kind,
+ variant,
+ linkedToPrevious: false,
+ segmentId,
+ });
+ if (!success) {
+ throw new Error(`Failed to create section ${kind}.`);
+ }
+ return segmentId;
+ }
+
+ const types = {
+ default: kind === 'header' ? HeaderFooterType.DEFAULT_HEADER : HeaderFooterType.DEFAULT_FOOTER,
+ first: kind === 'header' ? HeaderFooterType.FIRST_PAGE_HEADER : HeaderFooterType.FIRST_PAGE_FOOTER,
+ even: kind === 'header' ? HeaderFooterType.EVEN_PAGE_HEADER : HeaderFooterType.EVEN_PAGE_FOOTER,
+ };
+ const segmentId = generateRandomId(6);
+ const success = this._injector.get(ICommandService).syncExecuteCommand(CreateHeaderFooterCommand.id, {
+ unitId: this._document.getId(),
+ segmentId,
+ createType: types[variant],
+ sectionId: this._sectionId,
+ });
+ if (!success) {
+ throw new Error(`Failed to create section ${kind}.`);
+ }
+ return segmentId;
+ }
+
+ private _getHeaderFooterReference(
+ kind: SectionHeaderFooterKind,
+ variant: SectionHeaderFooterVariant
+ ): IResolvedSectionHeaderFooterReference {
+ const { index } = this._resolve();
+ const snapshot = this._document.getDocumentDataModel().getSnapshot();
+ return resolveSectionHeaderFooterReference(
+ snapshot.documentStyle,
+ getTopLevelSectionBreaks(this._document.getBody()),
+ index,
+ getSectionHeaderFooterReferenceKey(kind, variant)
+ );
+ }
+
+ private _describeHeaderFooterReference(
+ kind: SectionHeaderFooterKind,
+ variant: SectionHeaderFooterVariant
+ ): { segmentId: string | null; linkedToPrevious: boolean } {
+ const reference = this._getHeaderFooterReference(kind, variant);
+ return {
+ segmentId: reference.segmentId ?? null,
+ linkedToPrevious: reference.linkedToPrevious,
+ };
+ }
+
+ private _setHeaderFooterLinkedToPrevious(
+ kind: SectionHeaderFooterKind,
+ variant: SectionHeaderFooterVariant,
+ linkedToPrevious: boolean
+ ): boolean {
+ this._assertTraditionalDocument();
+ return this._injector.get(ICommandService).syncExecuteCommand(SetSectionHeaderFooterLinkCommand.id, {
+ unitId: this._document.getId(),
+ sectionId: this._sectionId,
+ kind,
+ variant,
+ linkedToPrevious,
+ ...(linkedToPrevious ? {} : { segmentId: generateRandomId(6) }),
+ });
+ }
+
+ private _assertTraditionalDocument(): void {
+ if (this._document.getDocumentDataModel().getSnapshot().documentStyle.documentFlavor !== DocumentFlavor.TRADITIONAL) {
+ throw new DocsSectionUnsupportedDocumentFlavorError();
+ }
+ }
+
+ private _resolve(): { index: number; sectionBreak: ISectionBreak } {
+ this._assertTraditionalDocument();
+ const sectionBreaks = getTopLevelSectionBreaks(this._document.getBody());
+ const index = sectionBreaks.findIndex((section) => section.sectionId === this._sectionId);
+ if (index < 0) {
+ throw new Error(`Document section with id ${this._sectionId} not found.`);
+ }
+ return { index, sectionBreak: sectionBreaks[index] };
+ }
+}
diff --git a/packages/docs/src/facade/f-document-text-range.ts b/packages/docs/src/facade/f-document-text-range.ts
new file mode 100644
index 0000000000..9891299e10
--- /dev/null
+++ b/packages/docs/src/facade/f-document-text-range.ts
@@ -0,0 +1,264 @@
+/**
+ * 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 { Injector, ITextStyle } from '@univerjs/core';
+import type { FDocument } from './f-document';
+import type { IFDocumentTextRange } from './utils';
+import { Tools, UpdateDocsAttributeType } from '@univerjs/core';
+import { buildPlainTextInsertBody, replaceBodyRange, retainBodyRange } from './utils';
+
+/** A clipped text-style run in document offsets. */
+export interface IFDocumentTextStyleRun {
+ /** Inclusive start offset in the document segment. */
+ startOffset: number;
+ /** Exclusive end offset in the document segment. */
+ endOffset: number;
+ /** Explicit text style stored on this run. */
+ textStyle: ITextStyle;
+}
+
+/** Agent-friendly summary of a document text range. */
+export interface IFDocumentTextRangeDescription extends IFDocumentTextRange {
+ text: string;
+ length: number;
+ /** Explicit styles stored directly in text runs. */
+ explicitTextStyleRuns: IFDocumentTextStyleRun[];
+ /** Top-level explicit style properties common to the complete range. */
+ commonExplicitTextStyle: ITextStyle;
+ /** @deprecated Use `explicitTextStyleRuns`. */
+ textStyleRuns: IFDocumentTextStyleRun[];
+ /** @deprecated Use `commonExplicitTextStyle`. */
+ commonTextStyle: ITextStyle;
+}
+
+/**
+ * Facade wrapper for reading and styling a fixed document text range.
+ *
+ * Offsets are fixed when the wrapper is created. Create a new range after edits
+ * that insert or remove content before it.
+ * @hideconstructor
+ */
+export class FDocumentTextRange {
+ constructor(
+ private readonly _document: FDocument,
+ private readonly _startOffset: number,
+ private readonly _endOffset: number,
+ private readonly _segmentId: string,
+ private readonly _injector: Injector
+ ) {
+ this._validateRange();
+ }
+
+ /**
+ * Returns the serializable document range.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const range = fDocument?.findParagraphByText('Launch')?.getTextRange();
+ * console.log(range?.getRange());
+ * ```
+ */
+ getRange(): IFDocumentTextRange {
+ return {
+ startOffset: this._startOffset,
+ endOffset: this._endOffset,
+ segmentId: this._segmentId,
+ };
+ }
+
+ /**
+ * Returns the plain data-stream text in this range.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const range = fDocument?.findParagraphByText('Launch')?.getTextRange();
+ * console.log(range?.getText());
+ * ```
+ */
+ getText(): string {
+ return this._document.getBody(this._segmentId).dataStream.slice(this._startOffset, this._endOffset);
+ }
+
+ /**
+ * Returns explicit text-style runs intersecting this range.
+ * Returned offsets are clipped to the range and remain document-relative.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const range = fDocument?.findParagraphByText('Launch')?.getTextRange();
+ * console.log(range?.getExplicitTextStyleRuns());
+ * ```
+ */
+ getExplicitTextStyleRuns(): IFDocumentTextStyleRun[] {
+ const { textRuns = [] } = this._document.getBody(this._segmentId);
+ return textRuns
+ .filter((run) => run.st < this._endOffset && run.ed > this._startOffset)
+ .map((run) => ({
+ startOffset: Math.max(run.st, this._startOffset),
+ endOffset: Math.min(run.ed, this._endOffset),
+ textStyle: Tools.deepClone(run.ts ?? {}),
+ }));
+ }
+
+ /** @deprecated Use `getExplicitTextStyleRuns()` to distinguish stored styles from effective styles. */
+ getTextStyleRuns(): IFDocumentTextStyleRun[] {
+ return this.getExplicitTextStyleRuns();
+ }
+
+ /**
+ * Returns top-level style properties that have the same explicit value
+ * across the complete range. Unstyled gaps make a property non-common.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const range = fDocument?.findParagraphByText('Launch')?.getTextRange();
+ * console.log(range?.getCommonExplicitTextStyle());
+ * ```
+ */
+ getCommonExplicitTextStyle(): ITextStyle {
+ if (this._startOffset === this._endOffset) {
+ return {};
+ }
+
+ const runs = this._getStyleSegments();
+ const [first, ...rest] = runs;
+ const common = Tools.deepClone(first.textStyle);
+
+ for (const key of Object.keys(common) as Array<keyof ITextStyle>) {
+ if (rest.some((run) => !isDeepEqual(run.textStyle[key], common[key]))) {
+ delete common[key];
+ }
+ }
+
+ return common;
+ }
+
+ /** @deprecated Use `getCommonExplicitTextStyle()` to distinguish stored styles from effective styles. */
+ getCommonTextStyle(): ITextStyle {
+ return this.getCommonExplicitTextStyle();
+ }
+
+ /**
+ * Returns a serializable summary suitable for an agent/tool response.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const range = fDocument?.findParagraphByText('Launch')?.getTextRange();
+ * console.log(range?.describe());
+ * ```
+ */
+ describe(): IFDocumentTextRangeDescription {
+ const explicitTextStyleRuns = this.getExplicitTextStyleRuns();
+ const commonExplicitTextStyle = this.getCommonExplicitTextStyle();
+ return {
+ ...this.getRange(),
+ text: this.getText(),
+ length: this._endOffset - this._startOffset,
+ explicitTextStyleRuns,
+ commonExplicitTextStyle,
+ textStyleRuns: explicitTextStyleRuns,
+ commonTextStyle: commonExplicitTextStyle,
+ };
+ }
+
+ /**
+ * Merges a text-style patch into every character in the range.
+ * Existing text-run splitting, merging, and normalization are handled by
+ * the document mutation pipeline.
+ * `style.fs` is a font size in points (pt), not CSS pixels.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const range = fDocument?.findParagraphByText('Launch')?.getTextRange();
+ * range?.setTextStyle({ fs: 10.5, bl: univerAPI.Enum.BooleanNumber.TRUE });
+ * ```
+ */
+ setTextStyle(style: ITextStyle): boolean {
+ if (this._startOffset === this._endOffset) {
+ return false;
+ }
+
+ return retainBodyRange(
+ this.getRange(),
+ {
+ dataStream: '',
+ textRuns: [{
+ st: 0,
+ ed: this._endOffset - this._startOffset,
+ ts: Tools.deepClone(style),
+ }],
+ },
+ UpdateDocsAttributeType.COVER,
+ this._document.getDocumentDataModel(),
+ this._injector
+ );
+ }
+
+ /**
+ * Replaces the range with plain text while preserving document mutation semantics.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const range = fDocument?.findParagraphByText('Draft')?.getTextRange();
+ * range?.setText('Final');
+ * ```
+ */
+ setText(text: string): boolean {
+ return replaceBodyRange(
+ this.getRange(),
+ buildPlainTextInsertBody(text),
+ this._document.getDocumentDataModel(),
+ this._injector
+ );
+ }
+
+ private _validateRange(): void {
+ const bodyLength = this._document.getBody(this._segmentId).dataStream.length;
+ if (
+ !Number.isInteger(this._startOffset) ||
+ !Number.isInteger(this._endOffset) ||
+ this._startOffset < 0 ||
+ this._endOffset < this._startOffset ||
+ this._endOffset > bodyLength
+ ) {
+ throw new RangeError(`Invalid document text range [${this._startOffset}, ${this._endOffset}) for body length ${bodyLength}.`);
+ }
+ }
+
+ private _getStyleSegments(): IFDocumentTextStyleRun[] {
+ const explicitRuns = this.getExplicitTextStyleRuns();
+ const segments: IFDocumentTextStyleRun[] = [];
+ let offset = this._startOffset;
+
+ for (const run of explicitRuns) {
+ if (offset < run.startOffset) {
+ segments.push({ startOffset: offset, endOffset: run.startOffset, textStyle: {} });
+ }
+ segments.push(run);
+ offset = run.endOffset;
+ }
+
+ if (offset < this._endOffset) {
+ segments.push({ startOffset: offset, endOffset: this._endOffset, textStyle: {} });
+ }
+
+ return segments;
+ }
+}
+
+function isDeepEqual(left: unknown, right: unknown): boolean {
+ return JSON.stringify(left) === JSON.stringify(right);
+}
diff --git a/packages/docs/src/facade/f-document.ts b/packages/docs/src/facade/f-document.ts
index cde1e4aee9..cca2f9e06c 100644
--- a/packages/docs/src/facade/f-document.ts
+++ b/packages/docs/src/facade/f-document.ts
@@ -14,10 +14,14 @@
* limitations under the License.
*/
-import type { DocumentDataModel, IDocumentBody, IDocumentData } from '@univerjs/core';
+import type { DocumentDataModel, IDocumentBody, IDocumentData, IParagraphBorder, ISectionBreak, SectionHeaderFooterKind } from '@univerjs/core';
+import type { IHeaderFooterProps } from '@univerjs/docs';
import type { IFDocumentTextRange } from './utils';
import {
BooleanNumber,
+ createSectionId,
+ DashStyleType,
+ DataStreamTreeTokenType,
DocumentFlavor,
generateRandomId,
getParagraphContentStartOffset,
@@ -30,8 +34,10 @@ import {
UndoCommand,
} from '@univerjs/core';
import { FBaseInitialable } from '@univerjs/core/facade';
-import { CreateHeaderFooterCommand, HeaderFooterType } from '@univerjs/docs';
+import { CreateHeaderFooterCommand, generateParagraphs, getTopLevelSectionBreaks, HeaderFooterType, InsertDocumentSectionBreakCommand } from '@univerjs/docs';
import { FDocumentParagraph } from './f-document-paragraph';
+import { DocsSectionUnsupportedDocumentFlavorError, FDocumentSection } from './f-document-section';
+import { FDocumentTextRange } from './f-document-text-range';
import { buildPlainTextInsertBody, replaceBodyRange } from './utils';
export interface IFDocumentParagraphQuery {
@@ -248,6 +254,207 @@ export class FDocument extends FBaseInitialable {
);
}
+ /**
+ * Returns document-level header/footer switches and margins. Margin values are in points (pt).
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * console.log(fDocument?.getHeaderFooterOptions());
+ * ```
+ */
+ getHeaderFooterOptions(): IHeaderFooterProps {
+ const style = this._documentDataModel.getSnapshot().documentStyle;
+ return {
+ marginHeader: style.marginHeader,
+ marginFooter: style.marginFooter,
+ useFirstPageHeaderFooter: style.useFirstPageHeaderFooter,
+ evenAndOddHeaders: style.evenAndOddHeaders,
+ };
+ }
+
+ /**
+ * Updates document-level header/footer switches and margins in a traditional document.
+ * `marginHeader` and `marginFooter` are in points (pt).
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * if (fDocument && !fDocument.isModern()) {
+ * fDocument.setHeaderFooterOptions({ marginHeader: 36, marginFooter: 36 });
+ * }
+ * ```
+ */
+ setHeaderFooterOptions(options: IHeaderFooterProps): boolean {
+ if (this.isModern()) {
+ throw new Error('The document is a modern document, header/footer is not supported.');
+ }
+ return this._commandService.syncExecuteCommand(CreateHeaderFooterCommand.id, {
+ unitId: this.getId(),
+ headerFooterProps: options,
+ });
+ }
+
+ /**
+ * Creates a facade for reading and styling a document text range.
+ * The end offset is exclusive, and offsets are scoped to the selected body segment.
+ * @param {number} startOffset The inclusive start offset.
+ * @param {number} endOffset The exclusive end offset.
+ * @param {string} segmentId The header/footer segment id, or an empty string for the main body.
+ * @returns {FDocumentTextRange} A fixed text-range facade.
+ * @example
+ * ```ts
+ * const range = univerAPI.getActiveDocument()?.getTextRange(0, 5);
+ * console.log(range?.describe());
+ * range?.setTextStyle({ bl: 1 });
+ * ```
+ */
+ getTextRange(startOffset: number, endOffset: number, segmentId: string = ''): FDocumentTextRange {
+ return this._injector.createInstance(FDocumentTextRange, this, startOffset, endOffset, segmentId, this._injector);
+ }
+
+ /**
+ * Returns traditional document sections backed by persisted SectionBreak ids.
+ * Modern documents use ColumnGroup instead and return an empty array from this read API.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const sections = fDocument?.getSections() ?? [];
+ * console.log(sections.map((section) => section.describe()));
+ * ```
+ */
+ getSections(): FDocumentSection[] {
+ if (this._documentDataModel.getSnapshot().documentStyle.documentFlavor !== DocumentFlavor.TRADITIONAL) {
+ return [];
+ }
+ return getTopLevelSectionBreaks(this.getBody()).map((sectionBreak) =>
+ this._injector.createInstance(FDocumentSection, this, sectionBreak.sectionId, this._injector));
+ }
+
+ /**
+ * Returns a traditional section by zero-based index, or `null` in modern documents.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const firstSection = fDocument?.getSection(0);
+ * console.log(firstSection?.describe());
+ * ```
+ */
+ getSection(index: number): FDocumentSection | null {
+ return this.getSections()[index] ?? null;
+ }
+
+ /**
+ * Returns the traditional section containing a data-stream offset, or `null` in modern documents.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const paragraph = fDocument?.findParagraphByText('Launch');
+ * const offset = paragraph?.getInfo().startOffset;
+ * const section = offset == null ? null : fDocument?.getSectionAt(offset);
+ * console.log(section?.getId());
+ * ```
+ */
+ getSectionAt(offset: number): FDocumentSection | null {
+ return this.getSections().find((section) => {
+ const range = section.getRange();
+ return offset >= range.startOffset && offset <= range.endOffset;
+ }) ?? null;
+ }
+
+ /**
+ * Inserts a traditional document section break and returns its stable facade.
+ * Modern documents must use ColumnGroup and throw `DocsSectionUnsupportedDocumentFlavorError`.
+ * Numeric layout values in `config` are in points (pt).
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * if (fDocument && !fDocument.isModern()) {
+ * const paragraph = fDocument.findParagraphByText('Appendix');
+ * const offset = paragraph?.getInfo().startOffset;
+ * const section = offset == null ? null : fDocument.insertSectionBreak(offset);
+ * console.log(section?.getId());
+ * }
+ * ```
+ */
+ insertSectionBreak(offset: number, config: Partial<Omit<ISectionBreak, 'sectionId' | 'startIndex'>> = {}): FDocumentSection | null {
+ if (this._documentDataModel.getSnapshot().documentStyle.documentFlavor !== DocumentFlavor.TRADITIONAL) {
+ throw new DocsSectionUnsupportedDocumentFlavorError();
+ }
+ const sectionId = createSectionId(new Set((this.getBody().sectionBreaks ?? []).map((section) => section.sectionId)));
+ const success = this._commandService.syncExecuteCommand(InsertDocumentSectionBreakCommand.id, {
+ unitId: this.getId(),
+ offset,
+ sectionId,
+ config,
+ });
+ return success ? this._injector.createInstance(FDocumentSection, this, sectionId, this._injector) : null;
+ }
+
+ /**
+ * Inserts a column-break token in a traditional document.
+ * Modern documents must use ColumnGroup and throw `DocsSectionUnsupportedDocumentFlavorError`.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * if (fDocument && !fDocument.isModern()) {
+ * const paragraph = fDocument.findParagraphByText('Continue in next column');
+ * const offset = paragraph?.getInfo().startOffset;
+ * if (offset != null) {
+ * fDocument.insertColumnBreak(offset);
+ * }
+ * }
+ * ```
+ */
+ insertColumnBreak(offset: number): boolean {
+ if (this._documentDataModel.getSnapshot().documentStyle.documentFlavor !== DocumentFlavor.TRADITIONAL) {
+ throw new DocsSectionUnsupportedDocumentFlavorError();
+ }
+ return this.insertText(offset, DataStreamTreeTokenType.COLUMN_BREAK);
+ }
+
+ /**
+ * Inserts a horizontal rule using the existing paragraph `borderBottom` mechanism.
+ * The returned paragraph can be inspected or removed with normal paragraph APIs.
+ * Border width and padding are in points (pt).
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const paragraph = fDocument?.findParagraphByText('Summary');
+ * const offset = paragraph?.getInfo().startOffset;
+ * const rule = offset == null ? null : fDocument?.insertHorizontalRule(offset);
+ * console.log(rule?.getId());
+ * ```
+ */
+ insertHorizontalRule(
+ offset: number,
+ border: IParagraphBorder = {
+ padding: 5,
+ color: { rgb: '#CDD0D8' },
+ width: 1,
+ dashStyle: DashStyleType.SOLID,
+ },
+ segmentId: string = ''
+ ): FDocumentParagraph | null {
+ const body = this.getBody(segmentId);
+ const paragraphs = generateParagraphs(
+ DataStreamTreeTokenType.PARAGRAPH,
+ undefined,
+ border,
+ body.paragraphs?.map((paragraph) => paragraph.paragraphId)
+ );
+ const paragraphId = paragraphs[0].paragraphId;
+ const success = replaceBodyRange(
+ { startOffset: offset, endOffset: offset, segmentId },
+ {
+ dataStream: DataStreamTreeTokenType.PARAGRAPH,
+ paragraphs,
+ },
+ this._documentDataModel,
+ this._injector
+ );
+
+ return success ? this.getParagraph(paragraphId, segmentId) : null;
+ }
+
/**
* Get all paragraphs in the document body or header/footer body by the segment id.
* @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
@@ -484,7 +691,7 @@ export class FDocument extends FBaseInitialable {
return getParagraphContentStartOffset(body, paragraphs[index]);
}
- private _ensureHeaderFooter(kind: 'header' | 'footer', pageIndex: number): string {
+ private _ensureHeaderFooter(kind: SectionHeaderFooterKind, pageIndex: number): string {
if (this.isModern()) {
throw new Error('The document is a modern document, header/footer is not supported.');
}
@@ -508,7 +715,7 @@ export class FDocument extends FBaseInitialable {
return segmentId;
}
- private _getHeaderFooterCreateInfo(kind: 'header' | 'footer', pageIndex: number): {
+ private _getHeaderFooterCreateInfo(kind: SectionHeaderFooterKind, pageIndex: number): {
createType: HeaderFooterType;
segmentId: string;
} {
diff --git a/packages/docs/src/facade/f-enum.ts b/packages/docs/src/facade/f-enum.ts
new file mode 100644
index 0000000000..267dc3585a
--- /dev/null
+++ b/packages/docs/src/facade/f-enum.ts
@@ -0,0 +1,43 @@
+/**
+ * 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 { ColumnSeparatorType, SectionType } from '@univerjs/core';
+import { FEnum } from '@univerjs/core/facade';
+
+/** @ignore */
+export interface IFDocsEnumMixin {
+ /** OOXML-compatible section start types. */
+ SectionType: typeof SectionType;
+ /** Section column separator types. */
+ ColumnSeparatorType: typeof ColumnSeparatorType;
+}
+
+export class FDocsEnumMixin extends FEnum implements IFDocsEnumMixin {
+ override get SectionType(): typeof SectionType {
+ return SectionType;
+ }
+
+ override get ColumnSeparatorType(): typeof ColumnSeparatorType {
+ return ColumnSeparatorType;
+ }
+}
+
+FEnum.extend(FDocsEnumMixin);
+
+declare module '@univerjs/core/facade' {
+ // eslint-disable-next-line ts/naming-convention
+ export interface FEnum extends IFDocsEnumMixin {}
+}
diff --git a/packages/docs/src/facade/index.ts b/packages/docs/src/facade/index.ts
index 1f252fcc1a..bfd9731e61 100644
--- a/packages/docs/src/facade/index.ts
+++ b/packages/docs/src/facade/index.ts
@@ -15,10 +15,16 @@
*/
import './f-univer';
+import './f-enum';
export { FDocument } from './f-document';
export { FDocumentParagraph, isParagraphFacade } from './f-document-paragraph';
export type { IFDocumentParagraphInfo } from './f-document-paragraph';
+export { DocsSectionUnsupportedDocumentFlavorError, FDocumentSection } from './f-document-section';
+export type { IFDocumentSectionColumnOptions, IFDocumentSectionDescription } from './f-document-section';
+export { FDocumentTextRange } from './f-document-text-range';
+export type { IFDocumentTextRangeDescription, IFDocumentTextStyleRun } from './f-document-text-range';
+export * from './f-enum';
export type { FDocEmbedUnitFacadeMapAugmentation } from './f-types';
export type { IFDocumentTextRange } from './utils';
export { stripBlockTokens } from './utils';
diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.ts
index 74cfc3a88a..34251166ac 100644
--- a/packages/docs/src/index.ts
+++ b/packages/docs/src/index.ts
@@ -31,6 +31,10 @@ export type {
IDocumentDefaultParagraphStylePatch,
ISetDocumentDefaultParagraphStyleCommandParams,
} from './commands/commands/set-document-default-paragraph-style.command';
+export { SetSectionHeaderFooterLinkCommand } from './commands/commands/set-section-header-footer-link.command';
+export type { ISetSectionHeaderFooterLinkCommandParams } from './commands/commands/set-section-header-footer-link.command';
+export { DeleteDocumentSectionBreakCommand, InsertDocumentSectionBreakCommand, UpdateDocumentSectionCommand } from './commands/commands/update-document-section.command';
+export type { IDeleteDocumentSectionBreakCommandParams, IDocumentSectionConfig, IDocumentSectionUpdate, IInsertDocumentSectionBreakCommandParams, IUpdateDocumentSectionCommandParams } from './commands/commands/update-document-section.command';
export { RichTextEditingMutation } from './commands/mutations/core-editing.mutation';
export type { IRichTextEditingMutationParams } from './commands/mutations/core-editing.mutation';
export { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';
@@ -80,5 +84,8 @@ export {
addCustomRangeFactory,
deleteCustomRangeFactory,
} from './utils/custom-range-factory';
+export { generateParagraphs } from './utils/paragraphs';
export { replaceSelectionFactory } from './utils/replace-selection-factory';
+export { createSectionColumnProperties } from './utils/section-columns';
+export { getTopLevelSectionBreaks } from './utils/sections';
export { consumeContentInsertRange, isHeaderFooterSelection } from './utils/util';
diff --git a/packages/docs/src/plugin.ts b/packages/docs/src/plugin.ts
index 07fa908741..8c07571afb 100644
--- a/packages/docs/src/plugin.ts
+++ b/packages/docs/src/plugin.ts
@@ -28,6 +28,8 @@ import pkg from '../package.json';
import { DeleteTextCommand, InsertTextCommand, UpdateTextCommand } from './commands/commands/core-editing.command';
import { CreateHeaderFooterCommand } from './commands/commands/create-header-footer.command';
import { SetDocumentDefaultParagraphStyleCommand } from './commands/commands/set-document-default-paragraph-style.command';
+import { SetSectionHeaderFooterLinkCommand } from './commands/commands/set-section-header-footer-link.command';
+import { DeleteDocumentSectionBreakCommand, InsertDocumentSectionBreakCommand, UpdateDocumentSectionCommand } from './commands/commands/update-document-section.command';
import { RichTextEditingMutation } from './commands/mutations/core-editing.mutation';
import { DocsRenameMutation } from './commands/mutations/docs-rename.mutation';
import { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';
@@ -74,6 +76,10 @@ export class UniverDocsPlugin extends Plugin {
UpdateTextCommand,
CreateHeaderFooterCommand,
SetDocumentDefaultParagraphStyleCommand,
+ SetSectionHeaderFooterLinkCommand,
+ UpdateDocumentSectionCommand,
+ InsertDocumentSectionBreakCommand,
+ DeleteDocumentSectionBreakCommand,
RichTextEditingMutation,
DocsRenameMutation,
SetTextSelectionsOperation,
diff --git a/packages/docs/src/services/__tests__/doc-skeleton-manager.service.spec.ts b/packages/docs/src/services/__tests__/doc-skeleton-manager.service.spec.ts
index 669d5117e3..0578098c03 100644
--- a/packages/docs/src/services/__tests__/doc-skeleton-manager.service.spec.ts
+++ b/packages/docs/src/services/__tests__/doc-skeleton-manager.service.spec.ts
@@ -35,7 +35,7 @@ function createDocument() {
body: {
dataStream: 'Hello\r\n',
paragraphs: [{ paragraphId: 'p1', startIndex: 5 }],
- sectionBreaks: [{ startIndex: 7 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_126', startIndex: 7 }],
customRanges: [],
customDecorations: [],
customBlocks: [],
diff --git a/packages/docs/src/utils/paragraphs.ts b/packages/docs/src/utils/paragraphs.ts
new file mode 100644
index 0000000000..54650d4912
--- /dev/null
+++ b/packages/docs/src/utils/paragraphs.ts
@@ -0,0 +1,61 @@
+/**
+ * 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 { IParagraph, IParagraphBorder } from '@univerjs/core';
+import { createParagraphId, DataStreamTreeTokenType, generateRandomId, Tools } from '@univerjs/core';
+
+/** Builds paragraph metadata for inserted paragraph tokens, including horizontal-rule borders. */
+export function generateParagraphs(
+ dataStream: string,
+ prevParagraph?: IParagraph,
+ borderBottom?: IParagraphBorder,
+ existingParagraphIds: Iterable<string> = []
+): IParagraph[] {
+ const paragraphs: IParagraph[] = [];
+ const existingIds = new Set(existingParagraphIds);
+
+ for (let i = 0, len = dataStream.length; i < len; i++) {
+ if (dataStream[i] !== DataStreamTreeTokenType.PARAGRAPH) {
+ continue;
+ }
+
+ paragraphs.push({
+ startIndex: i,
+ paragraphId: createParagraphId(existingIds),
+ });
+ }
+
+ for (const paragraph of paragraphs) {
+ if (prevParagraph?.bullet) {
+ paragraph.bullet = Tools.deepClone(prevParagraph.bullet);
+ }
+
+ if (prevParagraph?.paragraphStyle) {
+ paragraph.paragraphStyle = Tools.deepClone(prevParagraph.paragraphStyle);
+ delete paragraph.paragraphStyle.borderBottom;
+ if (prevParagraph.paragraphStyle.headingId) {
+ paragraph.paragraphStyle.headingId = generateRandomId(6);
+ }
+ }
+
+ if (borderBottom) {
+ paragraph.paragraphStyle ??= {};
+ paragraph.paragraphStyle.borderBottom = Tools.deepClone(borderBottom);
+ }
+ }
+
+ return paragraphs;
+}
diff --git a/packages/docs/src/utils/section-columns.ts b/packages/docs/src/utils/section-columns.ts
new file mode 100644
index 0000000000..848356c8f2
--- /dev/null
+++ b/packages/docs/src/utils/section-columns.ts
@@ -0,0 +1,45 @@
+/**
+ * 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 { IDocumentStyle, ISectionBreak, ISectionColumnProperties } from '@univerjs/core';
+import { PAGE_SIZE, PaperType } from '@univerjs/core';
+
+/** Creates explicit OOXML section columns from a count, gap, and optional widths. */
+export function createSectionColumnProperties(
+ documentStyle: IDocumentStyle | undefined,
+ section: ISectionBreak | undefined,
+ columnCount: number,
+ gap: number,
+ widths?: number[]
+): ISectionColumnProperties[] {
+ if (columnCount <= 1) {
+ return [];
+ }
+
+ const safeGap = Math.max(0, gap);
+ const pageWidth = section?.pageSize?.width ?? documentStyle?.pageSize?.width ?? PAGE_SIZE[PaperType.A4].width;
+ const contentWidth = Math.max(
+ 0,
+ pageWidth - (section?.marginLeft ?? documentStyle?.marginLeft ?? 72) - (section?.marginRight ?? documentStyle?.marginRight ?? 72)
+ );
+ const availableWidth = Math.max(0, contentWidth - safeGap * (columnCount - 1));
+ const resolvedWidths = widths ?? Array.from({ length: columnCount }, () => availableWidth / columnCount);
+
+ return resolvedWidths.map((width, index) => ({
+ width: Math.max(0, width),
+ paddingEnd: index === columnCount - 1 ? 0 : safeGap,
+ }));
+}
diff --git a/packages/docs/src/utils/sections.ts b/packages/docs/src/utils/sections.ts
new file mode 100644
index 0000000000..831a321570
--- /dev/null
+++ b/packages/docs/src/utils/sections.ts
@@ -0,0 +1,46 @@
+/**
+ * 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, ISectionBreak } from '@univerjs/core';
+import { DataStreamTreeTokenType } from '@univerjs/core';
+
+/** Returns document-level section breaks, excluding table-cell and modern-column sentinels. */
+export function getTopLevelSectionBreaks(body: IDocumentBody): ISectionBreak[] {
+ const sectionBreakByIndex = new Map((body.sectionBreaks ?? []).map((sectionBreak) => [sectionBreak.startIndex, sectionBreak]));
+ const result: ISectionBreak[] = [];
+ let tableCellDepth = 0;
+ let columnDepth = 0;
+
+ for (let index = 0; index < body.dataStream.length; index++) {
+ const token = body.dataStream[index];
+ if (token === DataStreamTreeTokenType.TABLE_CELL_START) {
+ tableCellDepth++;
+ } else if (token === DataStreamTreeTokenType.TABLE_CELL_END) {
+ tableCellDepth = Math.max(0, tableCellDepth - 1);
+ } else if (token === DataStreamTreeTokenType.COLUMN_START) {
+ columnDepth++;
+ } else if (token === DataStreamTreeTokenType.COLUMN_END) {
+ columnDepth = Math.max(0, columnDepth - 1);
+ } else if (token === DataStreamTreeTokenType.SECTION_BREAK && tableCellDepth === 0 && columnDepth === 0) {
+ const sectionBreak = sectionBreakByIndex.get(index);
+ if (sectionBreak) {
+ result.push(sectionBreak);
+ }
+ }
+ }
+
+ return result;
+}
diff --git a/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts b/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts
index fcb4c4f6b6..eacb0eeb69 100644
--- a/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts
+++ b/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts
@@ -346,7 +346,7 @@ const getFunctionsTestWorkbookData = (): IWorkbookData => {
{ startIndex: 2, paragraphId: 'para_engine_formula_nested', paragraphStyle: { horizontalAlign: 0 } },
],
sectionBreaks: [
- { startIndex: 3 },
+ { sectionId: 'section_fixture_1062', startIndex: 3 },
],
customRanges: [],
customDecorations: [],
diff --git a/packages/engine-render/src/basics/__tests__/tools.spec.ts b/packages/engine-render/src/basics/__tests__/tools.spec.ts
index cdeb8bd56e..ac2bdbcb89 100644
--- a/packages/engine-render/src/basics/__tests__/tools.spec.ts
+++ b/packages/engine-render/src/basics/__tests__/tools.spec.ts
@@ -178,6 +178,10 @@ describe('tools extra', () => {
expect(fontStack.fontFamily).toBe('"SF Mono", "Cascadia Code", Consolas, monospace');
expect(fontStack.fontString).toContain('"SF Mono", "Cascadia Code", Consolas, monospace');
+ const fractional = getFontStyleString({ fs: 10.5, ff: 'Arial' } as any);
+ expect(fractional.originFontSize).toBe(10.5);
+ expect(fractional.fontString).toContain('10.5pt');
+
const superscript = getFontStyleString({
fs: 12,
ff: 'Arial',
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 d25ac83f4a..66fc2abee9 100644
--- a/packages/engine-render/src/basics/i-document-skeleton-cached.ts
+++ b/packages/engine-render/src/basics/i-document-skeleton-cached.ts
@@ -78,6 +78,8 @@ export enum DocumentSkeletonPageType {
};
export interface IDocumentSkeletonPage {
+ /** Stable id of the document section that owns this body page. */
+ sectionId?: string;
sections: IDocumentSkeletonSection[];
headerId: string;
footerId: string;
diff --git a/packages/engine-render/src/basics/interfaces.ts b/packages/engine-render/src/basics/interfaces.ts
index 260b75d0f3..b5d9738264 100644
--- a/packages/engine-render/src/basics/interfaces.ts
+++ b/packages/engine-render/src/basics/interfaces.ts
@@ -112,6 +112,7 @@ export interface IFooterIds {
}
export interface ISectionBreakConfig extends IDocStyleBase, ISectionBreakBase, IDocsConfig {
+ sectionId: string;
headerIds?: IHeaderIds;
footerIds?: IFooterIds;
useFirstPageHeaderFooter?: BooleanNumber;
diff --git a/packages/engine-render/src/basics/tools.ts b/packages/engine-render/src/basics/tools.ts
index 86a7ef0655..0e414bf046 100644
--- a/packages/engine-render/src/basics/tools.ts
+++ b/packages/engine-render/src/basics/tools.ts
@@ -291,7 +291,7 @@ export function getFontStyleString(
// font-size/line-height
let originFontSize = defaultFontSize;
if (textStyle.fs) {
- originFontSize = Math.ceil(textStyle.fs);
+ originFontSize = textStyle.fs;
}
let fontSize = originFontSize;
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 eeca00058a..12df7d4d08 100644
--- a/packages/engine-render/src/components/docs/__tests__/document.spec.ts
+++ b/packages/engine-render/src/components/docs/__tests__/document.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { DocumentFlavor } from '@univerjs/core';
+import { DashStyleType, DocumentFlavor } from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { setupRenderTestEnv } from '../../../__tests__/render-test-utils';
import {
@@ -730,6 +730,45 @@ describe('documents render', () => {
documents.dispose();
});
+ it('draws paragraph bottom borders with their configured width and dash style', () => {
+ const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;
+ const documents = new Documents('docs-paragraph-border', skeleton, {
+ pageLayoutType: PageLayoutType.VERTICAL,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ });
+ const page = createPage(DocumentSkeletonPageType.BODY, '');
+ const line = page.sections[0].columns[0].lines[1];
+ line.borderBottom = {
+ color: { rgb: '#ff0000' },
+ width: 2.5,
+ padding: 4,
+ dashStyle: DashStyleType.DASH,
+ };
+ (documents as any)._drawLiquid = { x: 0, y: 0 };
+
+ const ctx = {
+ save: vi.fn(),
+ restore: vi.fn(),
+ setLineWidthByPrecision: vi.fn(),
+ beginPath: vi.fn(),
+ moveToByPrecision: vi.fn(),
+ lineToByPrecision: vi.fn(),
+ setLineDash: vi.fn(),
+ stroke: vi.fn(),
+ closePathByEnv: vi.fn(),
+ set strokeStyle(_value: string) {},
+ } as any;
+
+ (documents as any)._drawBorderBottom(ctx, page, line);
+
+ expect(ctx.setLineWidthByPrecision).toHaveBeenCalledWith(2.5);
+ expect(ctx.setLineDash).toHaveBeenCalledWith([6]);
+ expect(ctx.stroke).toHaveBeenCalledTimes(1);
+
+ documents.dispose();
+ });
+
it('draws each physical table grid line only once', () => {
const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;
const documents = new Documents('docs-border-canonical', skeleton, {
diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.ts
index a4dae9c3b8..7e99b5025f 100644
--- a/packages/engine-render/src/components/docs/document.ts
+++ b/packages/engine-render/src/components/docs/document.ts
@@ -813,8 +813,10 @@ export class Documents extends DocComponent {
y += marginTop + top + line.lineHeight + (line.borderBottom?.padding ?? 0);
ctx.save();
- ctx.setLineWidthByPrecision(1);
- ctx.strokeStyle = line.borderBottom?.color.rgb ?? '#CDD0D8';
+ const border = line.borderBottom;
+ ctx.setLineWidthByPrecision(Math.max(0, border?.width ?? 1));
+ ctx.strokeStyle = border?.color.rgb ?? '#CDD0D8';
+ setDocsBorderDash(ctx, border?.dashStyle);
drawLineByBorderType(ctx, BORDER_LTRB.BOTTOM, 0, {
startX: x,
startY: y,
@@ -1196,7 +1198,7 @@ export class Documents extends DocComponent {
ctx.save();
ctx.setLineWidthByPrecision(lineWidth);
- setTableCellBorderDash(ctx, border.dashStyle);
+ setDocsBorderDash(ctx, border.dashStyle);
ctx.strokeStyle = color;
drawLineByBorderType(ctx, type, 0, position);
ctx.restore();
@@ -1464,7 +1466,7 @@ export class Documents extends DocComponent {
}
}
-function setTableCellBorderDash(ctx: UniverRenderingContext, dashStyle?: DashStyleType) {
+function setDocsBorderDash(ctx: UniverRenderingContext, dashStyle?: DashStyleType) {
if (dashStyle === DashStyleType.DOT) {
ctx.setLineDash([2]);
return;
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 1392ec4316..4ed7e2b263 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
@@ -757,6 +757,7 @@ describe('doc skeleton', () => {
],
sectionBreaks: [
{
+ sectionId: 'section_fixture_301',
startIndex: 2,
sectionType: SectionType.CONTINUOUS,
},
@@ -825,6 +826,7 @@ describe('doc skeleton', () => {
paragraphs,
sectionBreaks: [
{
+ sectionId: 'section_fixture_302',
startIndex: dataStream.length - 1,
pageSize: {
width: 793.7333333333332,
@@ -871,15 +873,19 @@ describe('doc skeleton', () => {
],
sectionBreaks: [
{
+ sectionId: 'section_fixture_303',
startIndex: 5,
},
{
+ sectionId: 'section_fixture_304',
startIndex: 9,
},
{
+ sectionId: 'section_fixture_305',
startIndex: 13,
},
{
+ sectionId: 'section_fixture_306',
startIndex: 20,
},
],
@@ -974,15 +980,19 @@ describe('doc skeleton', () => {
],
sectionBreaks: [
{
+ sectionId: 'section_fixture_307',
startIndex: 60,
},
{
+ sectionId: 'section_fixture_308',
startIndex: 91,
},
{
+ sectionId: 'section_fixture_309',
startIndex: 120,
},
{
+ sectionId: 'section_fixture_310',
startIndex: 127,
},
],
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 90f4829827..31fab0f4b8 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
@@ -520,6 +520,28 @@ describe('docs layout tools extra', () => {
expect(getPageFromPath(root as any, ['skeTables', 't1', 'rows', 0, 'cells', 0])).toBeNull();
});
+ it('inherits header and footer references from the previous traditional section', () => {
+ const sections = [
+ { sectionId: 'section_1', defaultHeaderId: 'header-section-1' },
+ { sectionId: 'section_2' },
+ ];
+ const ctx = {
+ docsConfig: {},
+ viewModel: {
+ getChildren: () => [{ endIndex: 4 }, { endIndex: 9 }],
+ getSectionBreak: (endIndex: number) => endIndex === 4 ? sections[0] : sections[1],
+ },
+ dataModel: {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ defaultHeaderId: 'header-global',
+ },
+ },
+ };
+
+ expect(prepareSectionBreakConfig(ctx as any, 1).headerIds?.defaultHeaderId).toBe('header-section-1');
+ });
+
it('iterates document skeleton lines with nested table and column layout context', () => {
const page = {
marginLeft: 60,
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 31ae7901b3..fb961d11dd 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,7 +15,7 @@
*/
import type { IDocumentSkeletonPage } from '../../../../../basics/i-document-skeleton-cached';
-import { BooleanNumber, ColumnLayoutType, ColumnResponsiveType, DataStreamTreeNodeType, DataStreamTreeTokenType, DocumentBlockRangeType, TableAlignmentType, TableRowHeightRule, TableSizeType, TableTextWrapType, VerticalAlignmentType } from '@univerjs/core';
+import { BooleanNumber, ColumnLayoutType, ColumnResponsiveType, DashStyleType, 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';
@@ -138,10 +138,21 @@ describe('section', () => {
body: {
dataStream,
paragraphs: [
- { startIndex: 5, paragraphId: 'left' },
- { startIndex: 12, paragraphId: 'right' },
+ {
+ startIndex: 6,
+ paragraphId: 'left',
+ paragraphStyle: {
+ borderBottom: {
+ color: { rgb: '#336699' },
+ dashStyle: DashStyleType.SOLID,
+ padding: 4,
+ width: 2,
+ },
+ },
+ },
+ { startIndex: 14, paragraphId: 'right' },
],
- sectionBreaks: [{ startIndex: dataStream.length - 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1014', startIndex: dataStream.length - 1 }],
columnGroups: [{
startIndex: 0,
endIndex: dataStream.length - 1,
@@ -177,6 +188,11 @@ describe('section', () => {
});
expect(columnGroup.height).toBeGreaterThan(0);
expect(columnGroup.columns[0].page.sections[0].columns[0].lines.length).toBeGreaterThan(0);
+ expect(columnGroup.columns[0].page.sections[0].columns[0].lines[0].borderBottom).toMatchObject({
+ color: { rgb: '#336699' },
+ padding: 4,
+ width: 2,
+ });
expect(page.sections[0].columns[0].lines.at(-1)).toMatchObject({
paragraphIndex: columnGroup.ed,
lineHeight: columnGroup.height,
@@ -205,7 +221,7 @@ describe('section', () => {
{ startIndex: 3, paragraphId: 'left' },
{ startIndex: 7, paragraphId: 'right' },
],
- sectionBreaks: [{ startIndex: dataStream.length - 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1015', startIndex: dataStream.length - 1 }],
columnGroups: [{
startIndex: 0,
endIndex: dataStream.length - 1,
@@ -260,7 +276,7 @@ describe('section', () => {
{ startIndex: 5, paragraphId: 'right' },
{ startIndex: 13, paragraphId: 'after' },
],
- sectionBreaks: [{ startIndex: dataStream.length - 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1016', startIndex: dataStream.length - 1 }],
columnGroups: [{
startIndex: 0,
endIndex: 7,
@@ -330,8 +346,8 @@ describe('section', () => {
{ startIndex: 14, paragraphId: 'right-column-para' },
],
sectionBreaks: [
- { startIndex: 7 },
- { startIndex: dataStream.length - 1 },
+ { sectionId: 'section_fixture_1017', startIndex: 7 },
+ { sectionId: 'section_fixture_1018', startIndex: dataStream.length - 1 },
],
tables: [{ startIndex: 2, endIndex: 11, tableId: 'table-in-column' }],
columnGroups: [{
@@ -406,7 +422,7 @@ describe('section', () => {
{ startIndex: 88, paragraphId: 'column-block-3' },
{ startIndex: 117, paragraphId: 'column-block-4' },
],
- sectionBreaks: [{ startIndex: dataStream.length - 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1019', startIndex: dataStream.length - 1 }],
blockRanges: [{
blockId: 'callout-column-1',
blockType: DocumentBlockRangeType.CALLOUT,
diff --git a/packages/engine-render/src/components/docs/layout/block/column.ts b/packages/engine-render/src/components/docs/layout/block/column.ts
index 0dc032e9ca..2b8777ad42 100644
--- a/packages/engine-render/src/components/docs/layout/block/column.ts
+++ b/packages/engine-render/src/components/docs/layout/block/column.ts
@@ -24,7 +24,7 @@ import { ColumnResponsiveType, DataStreamTreeNodeType } from '@univerjs/core';
import { DocumentSkeletonPageType, LineType } from '../../../../basics/i-document-skeleton-cached';
import { getDocumentCompatibilityPolicy } from '../../document-compatibility';
import { applyTrailingBlockRangeSpaceBelow, createSkeletonPage } from '../model/page';
-import { getLastNotFullColumnInfo, updateBlockIndex } from '../tools';
+import { getLastNotFullColumnInfo, updateBlockIndex, updateInlineDrawingCoordsAndBorder } from '../tools';
import { dealWidthParagraph } from './paragraph/paragraph-layout';
interface IColumnGroupLayoutColumn {
@@ -148,6 +148,7 @@ function createColumnContentPage(
dealWidthParagraph(ctx, viewModel, paragraphNode, page, columnSectionBreakConfig);
}
+ updateInlineDrawingCoordsAndBorder(ctx, [page]);
updateBlockIndex(
[page],
columnNode.startIndex,
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/create-paragraph-layout-test-bed.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/create-paragraph-layout-test-bed.ts
index 8c2126a1b3..4b4df85cbf 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/create-paragraph-layout-test-bed.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/create-paragraph-layout-test-bed.ts
@@ -56,7 +56,7 @@ function createDocModel(
dataStream,
textRuns: [{ st: 0, ed: dataStream.length, ts: {} }],
paragraphs: [{ startIndex: content.length, paragraphId: 'para_layout_test' }],
- sectionBreaks: [{ startIndex: content.length + 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1026', startIndex: content.length + 1 }],
...bodyOverride,
},
documentStyle: {
@@ -178,7 +178,7 @@ export function createSectionLayoutTestBed(
dataStream,
textRuns: [{ st: 0, ed: dataStream.length, ts: {} }],
paragraphs,
- sectionBreaks: [{ startIndex: dataStream.length - 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1027', startIndex: dataStream.length - 1 }],
...bodyOverride,
},
documentStyle: {
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.ts
index e45e4ab42b..b5b0791b39 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.ts
@@ -28,7 +28,7 @@ function createViewModel(content: string) {
dataStream,
textRuns: [{ st: 0, ed: dataStream.length, ts: {} }],
paragraphs: [{ startIndex: content.length, paragraphId: 'para_language_ruler_test' }],
- sectionBreaks: [{ startIndex: content.length + 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_311', startIndex: content.length + 1 }],
},
documentStyle: {},
drawings: {},
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts
index cacff45870..4549ba1925 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts
@@ -103,7 +103,7 @@ describe('line-adjustment', () => {
horizontalAlign: HorizontalAlign.CENTER,
},
}],
- sectionBreaks: [{ startIndex: 6 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1022', startIndex: 6 }],
},
});
const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
@@ -123,7 +123,7 @@ describe('line-adjustment', () => {
horizontalAlign: HorizontalAlign.RIGHT,
},
}],
- sectionBreaks: [{ startIndex: 6 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1023', startIndex: 6 }],
},
});
const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
@@ -143,7 +143,7 @@ describe('line-adjustment', () => {
horizontalAlign: HorizontalAlign.JUSTIFIED,
},
}],
- sectionBreaks: [{ startIndex: 17 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1024', startIndex: 17 }],
},
});
const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
@@ -164,7 +164,7 @@ describe('line-adjustment', () => {
horizontalAlign: HorizontalAlign.DISTRIBUTED,
},
}],
- sectionBreaks: [{ startIndex: text.length + 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1025', startIndex: text.length + 1 }],
},
});
const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts
index 4a58a35787..4230f57cb6 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts
@@ -99,7 +99,7 @@ describe('linebreaking', () => {
nestingLevel: 0,
},
}],
- sectionBreaks: [{ startIndex: 10 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1020', startIndex: 10 }],
},
lists: {
'test-list': {
@@ -714,13 +714,10 @@ describe('linebreaking', () => {
wholeEntity: true,
properties: { docxBreakType: 'column' },
}],
- sectionBreaks: [{
- startIndex: content.length + 1,
- columnProperties: [
- { width: 170, paddingEnd: 20 },
- { width: 170, paddingEnd: 0 },
- ],
- }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1021', startIndex: content.length + 1, columnProperties: [
+ { width: 170, paddingEnd: 20 },
+ { width: 170, paddingEnd: 0 },
+ ] }],
},
});
const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
diff --git a/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts b/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts
index 6c50afb68e..429364e052 100644
--- a/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts
@@ -87,6 +87,7 @@ describe('page model', () => {
const headerVM = { getChildren: () => [{}] };
const footerVM = { getChildren: () => [{}] };
const sectionBreakConfig = {
+ sectionId: 'section-page-model',
pageNumberStart: 1,
pageSize: { width: 200, height: 300 },
pageOrient: PageOrientType.PORTRAIT,
@@ -125,6 +126,7 @@ describe('page model', () => {
const firstPage = createSkeletonPage(ctx, sectionBreakConfig, skeletonResourceReference, 1);
expect(firstPage.headerId).toBe('h-first');
+ expect(firstPage.sectionId).toBe('section-page-model');
expect(firstPage.footerId).toBe('f-first');
expect(firstPage.pageWidth).toBe(200);
expect(firstPage.pageHeight).toBe(300);
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 767371fda1..74633eb7dc 100644
--- a/packages/engine-render/src/components/docs/layout/model/page.ts
+++ b/packages/engine-render/src/components/docs/layout/model/page.ts
@@ -47,6 +47,7 @@ export function createSkeletonPage(
const page: IDocumentSkeletonPage = _getNullPage();
const {
+ sectionId,
pageNumberStart = 1,
pageSize = { width: Number.POSITIVE_INFINITY, height: Number.POSITIVE_INFINITY },
pageOrient = PageOrientType.PORTRAIT,
@@ -72,6 +73,7 @@ export function createSkeletonPage(
const { width: pageWidth = Number.POSITIVE_INFINITY, height: pageHeight = Number.POSITIVE_INFINITY } = pageSize;
page.pageNumber = pageNumber;
+ page.sectionId = sectionId;
page.pageNumberStart = pageNumberStart;
page.renderConfig = renderConfig;
page.marginLeft = marginLeft;
@@ -211,6 +213,7 @@ function _createSkeletonHeaderFooter(
count = 0
): IDocumentSkeletonHeaderFooter {
const {
+ sectionId,
lists,
footerTreeMap,
headerTreeMap,
@@ -225,6 +228,7 @@ function _createSkeletonHeaderFooter(
const pageWidth = pageSize?.width || Number.POSITIVE_INFINITY;
const pageHeight = pageSize?.height || Number.POSITIVE_INFINITY;
const headerFooterConfig: ISectionBreakConfig = {
+ sectionId,
lists,
footerTreeMap,
headerTreeMap,
@@ -296,7 +300,7 @@ export function createNullCellPage(
availableHeight: number = Number.POSITIVE_INFINITY,
maxCellPageHeight: number = Number.POSITIVE_INFINITY
) {
- const { lists, footerTreeMap, headerTreeMap, localeService, drawings } = sectionBreakConfig;
+ const { sectionId, lists, footerTreeMap, headerTreeMap, localeService, drawings } = sectionBreakConfig;
const { skeletonResourceReference } = ctx;
const { cellMargin, tableRows, tableColumns, tableId } = tableConfig;
const cellConfig = tableRows[row].tableCells[col];
@@ -322,6 +326,7 @@ export function createNullCellPage(
const pageHeight = maxCellPageHeight;
const cellSectionBreakConfig: ISectionBreakConfig = {
+ sectionId,
lists,
footerTreeMap,
headerTreeMap,
diff --git a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/text-shaping.spec.ts b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/text-shaping.spec.ts
index 3c3659040a..ba948fd301 100644
--- a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/text-shaping.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/text-shaping.spec.ts
@@ -70,6 +70,7 @@ function getDocumentBody(): IDocumentBody {
],
sectionBreaks: [
{
+ sectionId: 'section_fixture_312',
startIndex: 37,
},
],
diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.ts
index 9d3c4baa02..ead3692f6a 100644
--- a/packages/engine-render/src/components/docs/layout/tools.ts
+++ b/packages/engine-render/src/components/docs/layout/tools.ts
@@ -67,6 +67,7 @@ import {
ObjectRelativeFromH,
ObjectRelativeFromV,
PageOrientType,
+ resolveSectionHeaderFooterReferences,
SectionType,
SpacingRule,
VerticalAlign,
@@ -1607,6 +1608,7 @@ export interface ILayoutContext {
}
const DEFAULT_SECTION_BREAK: ISectionBreak = {
+ sectionId: 'section_render_default',
columnProperties: [],
columnSeparatorType: ColumnSeparatorType.NONE,
sectionType: SectionType.SECTION_TYPE_UNSPECIFIED,
@@ -1656,6 +1658,11 @@ export function prepareSectionBreakConfig(ctx: ILayoutContext, nodeIndex: number
let { documentStyle } = dataModel;
const { documentFlavor } = documentStyle;
let sectionBreak = viewModel.getSectionBreak(sectionNode.endIndex) || DEFAULT_SECTION_BREAK;
+ const sectionBreaks = viewModel.getChildren().map((node) => viewModel.getSectionBreak(node.endIndex) || DEFAULT_SECTION_BREAK);
+ sectionBreak = {
+ ...sectionBreak,
+ ...resolveSectionHeaderFooterReferences(documentStyle, sectionBreaks, nodeIndex),
+ };
// If the configuration is in modern mode, use the style configuration of modern mode to overwrite the original configuration.
// In modern mode, there are no pages, no sections, no columns. There are no headers and footers, and margins are all defaults.
@@ -1704,6 +1711,7 @@ export function prepareSectionBreakConfig(ctx: ILayoutContext, nodeIndex: number
},
} = documentStyle;
const {
+ sectionId,
charSpace = 0, // charSpace
linePitch = 15.6, // linePitch pt
gridType = GridType.LINES, // gridType
@@ -1750,6 +1758,7 @@ export function prepareSectionBreakConfig(ctx: ILayoutContext, nodeIndex: number
}
const sectionBreakConfig: ISectionBreakConfig = {
+ sectionId,
charSpace,
linePitch,
gridType,
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 e2ec844305..bef56b2afd 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
@@ -258,7 +258,7 @@ describe('DocumentViewModel', () => {
dataStream: bodyStream,
textRuns: [{ st: 0, ed: 2, ts: {} }],
paragraphs: [{ startIndex: 0, paragraphId: 'para_view_model_header' }],
- sectionBreaks: [{ startIndex: 2 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1001', startIndex: 2 }],
customBlocks: [{ startIndex: 1, blockId: 'b1' }],
customRanges: [{ startIndex: 0, endIndex: 1, rangeId: 'r1' }],
customDecorations: [{ startIndex: 1, endIndex: 2, id: 'd1' }],
@@ -318,7 +318,7 @@ describe('DocumentViewModel', () => {
dataStream: `Z${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,
textRuns: [{ st: 0, ed: 1, ts: { fs: 14 } }],
paragraphs: [{ startIndex: 0, paragraphId: 'para_view_model_footer' }],
- sectionBreaks: [{ startIndex: 1 }],
+ sectionBreaks: [{ sectionId: 'section_fixture_1002', startIndex: 1 }],
customBlocks: [],
customRanges: [],
customDecorations: [],
diff --git a/packages/engine-render/src/components/sheets/util.ts b/packages/engine-render/src/components/sheets/util.ts
index 35af38d2ad..0f6f9156ec 100644
--- a/packages/engine-render/src/components/sheets/util.ts
+++ b/packages/engine-render/src/components/sheets/util.ts
@@ -27,6 +27,7 @@ import type {
} from '@univerjs/core';
import {
createParagraphId,
+ createSectionId,
DEFAULT_EMPTY_DOCUMENT_VALUE,
DocumentDataModel,
DocumentFlavor,
@@ -81,6 +82,7 @@ export function createDocumentModelWithStyle(content: string, textStyle: ITextSt
},
],
sectionBreaks: [{
+ sectionId: createSectionId(new Set()),
startIndex: contentLength + 1,
}],
},
diff --git a/packages/sheets-numfmt-ui/src/controllers/__tests__/editor.controller.spec.ts b/packages/sheets-numfmt-ui/src/controllers/__tests__/editor.controller.spec.ts
index a9a95e6b3c..36bc05f1fd 100644
--- a/packages/sheets-numfmt-ui/src/controllers/__tests__/editor.controller.spec.ts
+++ b/packages/sheets-numfmt-ui/src/controllers/__tests__/editor.controller.spec.ts
@@ -340,6 +340,7 @@ describe('test editor', () => {
],
sectionBreaks: [
{
+ sectionId: 'section_fixture_1028',
startIndex: 10,
},
],
diff --git a/packages/sheets-thread-comment-ui/src/views/__tests__/SheetsThreadCommentPanel.spec.tsx b/packages/sheets-thread-comment-ui/src/views/__tests__/SheetsThreadCommentPanel.spec.tsx
index 7b831501d4..2f8dd9fd6b 100644
--- a/packages/sheets-thread-comment-ui/src/views/__tests__/SheetsThreadCommentPanel.spec.tsx
+++ b/packages/sheets-thread-comment-ui/src/views/__tests__/SheetsThreadCommentPanel.spec.tsx
@@ -423,6 +423,7 @@ function createTextBody(text: string): IDocumentBody {
],
sectionBreaks: [
{
+ sectionId: `section_${text}`,
startIndex: dataStream.length - 1,
},
],
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/add-worksheet-merge.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/add-worksheet-merge.command.spec.ts
index c4da7bfef4..cfe65898e6 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/add-worksheet-merge.command.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/add-worksheet-merge.command.spec.ts
@@ -406,6 +406,7 @@ describe('Test add worksheet merge commands', () => {
],
sectionBreaks: [
{
+ sectionId: 'section_fixture_1106',
startIndex: 7,
},
],
diff --git a/packages/sheets-ui/src/controllers/clipboard/utils.ts b/packages/sheets-ui/src/controllers/clipboard/utils.ts
index 8c3a2705e3..5261238fbe 100644
--- a/packages/sheets-ui/src/controllers/clipboard/utils.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/utils.ts
@@ -28,6 +28,7 @@ import {
CellValueType,
cloneCellDataMatrix,
createParagraphId,
+ createSectionId,
CustomRangeType,
generateRandomId,
getNumfmtParseValueFilter,
@@ -558,6 +559,6 @@ export function generateBody(text: string): IDocumentBody {
return {
dataStream,
paragraphs,
- sectionBreaks: [{ startIndex: dataStream.indexOf('\n') }],
+ sectionBreaks: [{ sectionId: createSectionId(new Set()), startIndex: dataStream.indexOf('\n') }],
};
}
diff --git a/packages/slides-ui/src/services/slide-editor-bridge.service.ts b/packages/slides-ui/src/services/slide-editor-bridge.service.ts
index 0f1d672417..9953251cd9 100644
--- a/packages/slides-ui/src/services/slide-editor-bridge.service.ts
+++ b/packages/slides-ui/src/services/slide-editor-bridge.service.ts
@@ -20,6 +20,7 @@ import type { KeyCode } from '@univerjs/ui';
import type { Observable } from 'rxjs';
import {
createIdentifier,
+ createSectionId,
Disposable,
DocumentDataModel,
EDITOR_ACTIVATED,
@@ -308,7 +309,7 @@ export class SlideEditorBridgeService extends Disposable implements ISlideEditor
} as IParagraphStyle,
startIndex: content.length + 1,
}] as IParagraph[],
- sectionBreaks: [{ startIndex: content.length + 2 }],
+ sectionBreaks: [{ sectionId: createSectionId(new Set()), startIndex: content.length + 2 }],
} as IDocumentBody,
documentStyle: {
marginBottom: 0,
diff --git a/packages/slides/src/basics/demo-data.ts b/packages/slides/src/basics/demo-data.ts
index 85bbe4d653..d527b6d693 100644
--- a/packages/slides/src/basics/demo-data.ts
+++ b/packages/slides/src/basics/demo-data.ts
@@ -190,6 +190,7 @@ export const docsDemoData: IDocumentData = {
],
sectionBreaks: [
{
+ sectionId: 'section_slides_demo',
startIndex: 407,
columnProperties: [
{
diff --git a/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts b/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts
index d4b8ac6868..b0ed5cebf6 100644
--- a/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts
+++ b/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts
@@ -16,7 +16,7 @@
import type { IDocumentBody } from '@univerjs/core';
import type { IThreadCommentMention } from '@univerjs/thread-comment';
-import { createParagraphId, CustomRangeType, getBodySlice } from '@univerjs/core';
+import { createParagraphId, createSectionId, CustomRangeType, getBodySlice } from '@univerjs/core';
interface IThreadCommentEditorFocusService {
focus: (editorId: string) => void;
@@ -120,6 +120,7 @@ export const transformTextNodes2Document = (nodes: TextNode[]): IDocumentBody =>
],
sectionBreaks: [
{
+ sectionId: createSectionId(new Set()),
startIndex: str.length - 1,
},
],