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 Word-compatible pagination (#7334)

Univera6d281f36ce3
diff --git a/packages/core/src/docs/data-model/__tests__/paragraph-style.spec.ts b/packages/core/src/docs/data-model/__tests__/paragraph-style.spec.ts
new file mode 100644
index 0000000000..e4f55c1953
--- /dev/null
+++ b/packages/core/src/docs/data-model/__tests__/paragraph-style.spec.ts
@@ -0,0 +1,120 @@
+/**
+ * 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 { IDocStyles, IDocumentStyle } from '../../../types/interfaces';
+import { describe, expect, it } from 'vitest';
+import { BooleanNumber } from '../../../types/enum';
+import { DocStyleType, DocumentFlavor } from '../../../types/interfaces';
+import { resolveDocumentParagraphStyle } from '../paragraph-style';
+
+describe('resolveDocumentParagraphStyle pagination', () => {
+ const traditionalDocumentStyle: IDocumentStyle = {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ };
+
+ it('preserves direct false over a named style and document default', () => {
+ const styles: IDocStyles = {
+ base: {
+ name: 'Base',
+ type: DocStyleType.paragraph,
+ paragraphStyle: {
+ keepNext: BooleanNumber.TRUE,
+ keepLines: BooleanNumber.TRUE,
+ },
+ },
+ heading: {
+ name: 'Heading',
+ basedOn: 'base',
+ type: DocStyleType.paragraph,
+ paragraphStyle: {
+ pageBreakBefore: BooleanNumber.TRUE,
+ },
+ },
+ };
+
+ expect(resolveDocumentParagraphStyle(
+ {
+ ...traditionalDocumentStyle,
+ defaultParagraphStyle: {
+ keepNext: BooleanNumber.TRUE,
+ },
+ },
+ {
+ keepNext: BooleanNumber.FALSE,
+ widowControl: BooleanNumber.FALSE,
+ },
+ {
+ styles,
+ paragraphStyleId: 'heading',
+ }
+ )).toMatchObject({
+ keepNext: BooleanNumber.FALSE,
+ keepLines: BooleanNumber.TRUE,
+ widowControl: BooleanNumber.FALSE,
+ pageBreakBefore: BooleanNumber.TRUE,
+ });
+ });
+
+ it('uses the traditional widow default only when no higher-precedence value exists', () => {
+ expect(resolveDocumentParagraphStyle(traditionalDocumentStyle, {}))
+ .toMatchObject({ widowControl: BooleanNumber.TRUE });
+ expect(resolveDocumentParagraphStyle(
+ {
+ ...traditionalDocumentStyle,
+ defaultParagraphStyle: { widowControl: BooleanNumber.FALSE },
+ },
+ {}
+ )).toMatchObject({ widowControl: BooleanNumber.FALSE });
+ expect(resolveDocumentParagraphStyle(
+ { documentFlavor: DocumentFlavor.MODERN },
+ {}
+ ).widowControl).toBeUndefined();
+ });
+
+ it('terminates style cycles and reads current named-style values', () => {
+ const styles: IDocStyles = {
+ first: {
+ name: 'First',
+ basedOn: 'second',
+ type: DocStyleType.paragraph,
+ paragraphStyle: { keepNext: BooleanNumber.TRUE },
+ },
+ second: {
+ name: 'Second',
+ basedOn: 'first',
+ type: DocStyleType.paragraph,
+ paragraphStyle: { keepLines: BooleanNumber.TRUE },
+ },
+ };
+
+ expect(resolveDocumentParagraphStyle(traditionalDocumentStyle, {}, {
+ styles,
+ paragraphStyleId: 'first',
+ })).toMatchObject({
+ keepNext: BooleanNumber.TRUE,
+ keepLines: BooleanNumber.TRUE,
+ });
+
+ styles.first.paragraphStyle = { keepNext: BooleanNumber.FALSE };
+ expect(resolveDocumentParagraphStyle(traditionalDocumentStyle, {}, {
+ styles,
+ paragraphStyleId: 'first',
+ })).toMatchObject({
+ keepNext: BooleanNumber.FALSE,
+ keepLines: BooleanNumber.TRUE,
+ });
+ });
+});
diff --git a/packages/core/src/docs/data-model/empty-snapshot.ts b/packages/core/src/docs/data-model/empty-snapshot.ts
index c14a522a48..e495e51c1e 100644
--- a/packages/core/src/docs/data-model/empty-snapshot.ts
+++ b/packages/core/src/docs/data-model/empty-snapshot.ts
@@ -16,7 +16,7 @@
import type { IDocumentData } from '../../types/interfaces';
import { generateRandomId } from '../../shared/random-id';
-import { DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW, MODERN_DOCUMENT_WIDTH, ModernDocumentWidthMode, PAGE_SIZE } from '../../types/const';
+import { DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW, MODERN_DOCUMENT_WIDTH, ModernDocumentWidthMode, PAGE_SIZE, TRADITIONAL_DOCUMENT_DEFAULT_MARGIN } from '../../types/const';
import { BooleanNumber } from '../../types/enum';
import { LocaleType } from '../../types/enum/locale-type';
import { DocumentFlavor, PaperType } from '../../types/interfaces';
@@ -66,10 +66,10 @@ export function getEmptySnapshot(
documentStyle: {
pageSize: PAGE_SIZE[PaperType.A4],
documentFlavor,
- marginTop: 72,
- marginBottom: 72,
- marginRight: 72,
- marginLeft: 72,
+ marginTop: TRADITIONAL_DOCUMENT_DEFAULT_MARGIN,
+ marginBottom: TRADITIONAL_DOCUMENT_DEFAULT_MARGIN,
+ marginRight: TRADITIONAL_DOCUMENT_DEFAULT_MARGIN,
+ marginLeft: TRADITIONAL_DOCUMENT_DEFAULT_MARGIN,
autoHyphenation: BooleanNumber.TRUE,
doNotHyphenateCaps: BooleanNumber.FALSE,
consecutiveHyphenLimit: 2,
diff --git a/packages/core/src/docs/data-model/paragraph-style.ts b/packages/core/src/docs/data-model/paragraph-style.ts
index 35c9067ca3..61a5e468ab 100644
--- a/packages/core/src/docs/data-model/paragraph-style.ts
+++ b/packages/core/src/docs/data-model/paragraph-style.ts
@@ -15,7 +15,7 @@
*/
import type { Nullable } from '../../shared';
-import type { IDocumentStyle, IParagraphStyle } from '../../types/interfaces';
+import type { IDocStyles, IDocumentStyle, IParagraphStyle } from '../../types/interfaces';
import { Tools } from '../../shared';
import {
DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING,
@@ -23,11 +23,18 @@ import {
DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW,
NAMED_STYLE_SPACE_MAP,
} from '../../types/const';
-import { DocumentFlavor } from '../../types/interfaces';
+import { BooleanNumber } from '../../types/enum';
+import { DocStyleType, DocumentFlavor } from '../../types/interfaces';
export interface IResolveDocumentParagraphStyleOptions {
+ /** Exclude document-level outer spacing while retaining all other defaults. */
excludeDocumentOuterSpacing?: boolean;
+ /** Preserve the legacy Modern Doc spacing defaults when no explicit flavor is available. */
useLegacyModernDefaults?: boolean;
+ /** Named document styles keyed by stable style id. */
+ styles?: IDocStyles;
+ /** Named paragraph style referenced by the paragraph. */
+ paragraphStyleId?: string;
}
function _definedStyle(style: Nullable<IParagraphStyle>): IParagraphStyle {
@@ -35,9 +42,38 @@ function _definedStyle(style: Nullable<IParagraphStyle>): IParagraphStyle {
return {};
}
- return Object.fromEntries(
- Object.entries(style).filter(([, value]) => value != null)
- ) as IParagraphStyle;
+ const definedStyle = Tools.deepClone(style);
+ Tools.removeNull(definedStyle);
+ return definedStyle;
+}
+
+function _resolveNamedParagraphStyle(
+ styles: IDocStyles | undefined,
+ styleId: string | undefined
+): IParagraphStyle {
+ if (!styles || !styleId) {
+ return {};
+ }
+
+ const visiting = new Set<string>();
+ const resolve = (currentStyleId: string): IParagraphStyle => {
+ if (visiting.has(currentStyleId)) {
+ return {};
+ }
+ const style = styles[currentStyleId];
+ if (!style || style.type !== DocStyleType.paragraph) {
+ return {};
+ }
+
+ visiting.add(currentStyleId);
+ const base = style.basedOn ? resolve(style.basedOn) : {};
+ visiting.delete(currentStyleId);
+ return {
+ ...base,
+ ..._definedStyle(style.paragraphStyle),
+ };
+ };
+ return resolve(styleId);
}
export function resolveDocumentParagraphStyle(
@@ -54,7 +90,12 @@ export function resolveDocumentParagraphStyle(
spaceBelow: { v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW },
}
: {};
+ const traditionalStyle: IParagraphStyle =
+ documentStyle?.documentFlavor === DocumentFlavor.TRADITIONAL
+ ? { widowControl: BooleanNumber.TRUE }
+ : {};
const documentDefaults = {
+ ...traditionalStyle,
...legacyStyle,
..._definedStyle(documentStyle?.defaultParagraphStyle),
};
@@ -65,13 +106,19 @@ export function resolveDocumentParagraphStyle(
}
const definedParagraphStyle = _definedStyle(paragraphStyle);
- const namedStyle = definedParagraphStyle.namedStyleType == null
+ const referencedParagraphStyle = _resolveNamedParagraphStyle(
+ options.styles,
+ options.paragraphStyleId
+ );
+ const namedStyleType = definedParagraphStyle.namedStyleType ?? referencedParagraphStyle.namedStyleType;
+ const namedStyle = namedStyleType == null
? null
- : NAMED_STYLE_SPACE_MAP[definedParagraphStyle.namedStyleType];
+ : NAMED_STYLE_SPACE_MAP[namedStyleType];
return Tools.deepClone({
...documentDefaults,
...namedStyle,
+ ...referencedParagraphStyle,
...definedParagraphStyle,
});
}
diff --git a/packages/core/src/types/const/page-size.ts b/packages/core/src/types/const/page-size.ts
index 00bb111ea1..429020f91f 100644
--- a/packages/core/src/types/const/page-size.ts
+++ b/packages/core/src/types/const/page-size.ts
@@ -77,3 +77,6 @@ export const MODERN_DOCUMENT_WIDTH: Record<ModernDocumentWidthMode, number> = {
};
export const MODERN_DOCUMENT_DEFAULT_MARGIN = 50 / 0.75;
+
+/** Default margin for a paginated Traditional document, in 96-DPI layout pixels. */
+export const TRADITIONAL_DOCUMENT_DEFAULT_MARGIN = 72;
diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.ts
index 123709d473..b7d77b0067 100644
--- a/packages/core/src/types/interfaces/i-document-data.ts
+++ b/packages/core/src/types/interfaces/i-document-data.ts
@@ -35,6 +35,8 @@ export interface IDocumentData extends IReferenceSource {
title?: string;
body?: IDocumentBody; // Rich text.
documentStyle: IDocumentStyle;
+ /** OOXML-compatible named document styles keyed by stable style id. */
+ styles?: IDocStyles;
settings?: IDocumentSettings;
// The type of data depends on how the plug-in is defined
resources?: IResources;
@@ -165,10 +167,11 @@ export enum DocumentBlockType {
export interface IDocStyle {
name: string;
- basedOn: string;
- link: string;
+ basedOn?: string;
+ link?: string;
type: DocStyleType;
- textStyle: ITextStyle;
+ textStyle?: ITextStyle;
+ paragraphStyle?: IParagraphStyle;
}
export enum DocStyleType {
@@ -620,6 +623,8 @@ export interface IParagraph {
// elements: IElement[]; // elements
startIndex: number;
paragraphId: string;
+ /** Optional stable named-style reference. Direct paragraph style has higher precedence. */
+ styleId?: string;
paragraphStyle?: IParagraphStyle; // paragraphStyle
bullet?: IBullet; // bullet
// dIds?: string[]; // drawingIds drawingId
@@ -867,10 +872,52 @@ export interface IParagraphProperties extends IIndentStart {
borderBottom?: IParagraphBorder; // borderBottom
borderLeft?: IParagraphBorder; // borderLeft
borderRight?: IParagraphBorder; // borderRight
- keepLines?: BooleanNumber; // 17.3.1.14 keepLines (Keep All Lines On One Page)
- keepNext?: BooleanNumber; // 17.3.1.15 keepNext (Keep Paragraph With Next Paragraph)
+ /**
+ * Keeps all measured lines of this paragraph on one physical page when they fit.
+ *
+ * `undefined` inherits, `TRUE` enables, and an explicit `FALSE` disables an
+ * inherited value. An oversized paragraph still splits after starting on a
+ * fresh page. This Word-compatible pagination rule is rendered only by
+ * Traditional Docs.
+ *
+ * OOXML: 17.3.1.14 `keepLines`.
+ */
+ keepLines?: BooleanNumber;
+ /**
+ * Keeps this paragraph with the following paragraph when they fit together.
+ *
+ * Consecutive `TRUE` values form a bounded keep chain. Set the final
+ * paragraph to `FALSE` when it must terminate an inherited or authored chain.
+ * `undefined` inherits. This Word-compatible pagination rule is rendered only
+ * by Traditional Docs.
+ *
+ * OOXML: 17.3.1.15 `keepNext`.
+ */
+ keepNext?: BooleanNumber;
+ /**
+ * Starts this paragraph on the next physical page unless it is already at a
+ * page boundary.
+ *
+ * `undefined` inherits, `TRUE` enables, and an explicit `FALSE` disables an
+ * inherited value. Use a Section Break instead when the following content
+ * also needs different page geometry, columns, headers, or footers. This
+ * Word-compatible pagination rule is rendered only by Traditional Docs.
+ *
+ * OOXML: 17.3.1.23 `pageBreakBefore`.
+ */
+ pageBreakBefore?: BooleanNumber;
wordWrap?: BooleanNumber; // 17.3.1.45 wordWrap (Allow Line Breaking At Character Level)
- widowControl?: BooleanNumber; // 17.3.1.44 widowControl (Allow First/Last Line to Display on a Separate Page)
+ /**
+ * Avoids leaving a single measured first or last line on a separate page
+ * when the paragraph can be adjusted without violating stronger keep rules.
+ *
+ * `undefined` inherits, `TRUE` enables, and an explicit `FALSE` disables an
+ * inherited value. This Word-compatible pagination rule is rendered only by
+ * Traditional Docs.
+ *
+ * OOXML: 17.3.1.44 `widowControl`.
+ */
+ widowControl?: BooleanNumber;
shading?: IShading; // shading
suppressHyphenation?: BooleanNumber; // 17.3.1.34 suppressAutoHyphens (Suppress Hyphenation for Paragraph)
}
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
index dcfc62b2a5..0aa592b324 100644
--- 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
@@ -187,4 +187,32 @@ describe('UpdateDocumentSectionCommand', () => {
expect.objectContaining({ sectionId: 'section_two', startIndex: 10, sectionType: SectionType.ODD_PAGE }),
]);
});
+
+ it('rejects invalid section insertion inputs without partial changes', () => {
+ const originalBody = structuredClone(testBed.doc.getBody())!;
+
+ expect(commandService.syncExecuteCommand(InsertDocumentSectionBreakCommand.id, {
+ unitId: 'section-command-doc',
+ offset: 5,
+ sectionId: 'section_one',
+ })).toBe(false);
+ expect(commandService.syncExecuteCommand(InsertDocumentSectionBreakCommand.id, {
+ unitId: 'section-command-doc',
+ offset: 5,
+ sectionId: 'section_bad_geometry',
+ config: {
+ pageSize: { width: 100, height: 100 },
+ marginLeft: 50,
+ marginRight: 50,
+ },
+ })).toBe(false);
+ expect(commandService.syncExecuteCommand(InsertDocumentSectionBreakCommand.id, {
+ unitId: 'section-command-doc',
+ offset: 10,
+ sectionId: 'section_without_following_section',
+ nextSectionType: SectionType.NEXT_PAGE,
+ })).toBe(false);
+
+ expect(testBed.doc.getBody()).toEqual(originalBody);
+ });
});
diff --git a/packages/docs/src/commands/commands/update-document-paragraph-style.command.ts b/packages/docs/src/commands/commands/update-document-paragraph-style.command.ts
new file mode 100644
index 0000000000..3e27d6cfaf
--- /dev/null
+++ b/packages/docs/src/commands/commands/update-document-paragraph-style.command.ts
@@ -0,0 +1,187 @@
+/**
+ * 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, IDocumentBody, IParagraph, IParagraphStyle, JSONXActions } from '@univerjs/core';
+import {
+ CommandType,
+ getParagraphContentStartOffset,
+ getRichTextEditPath,
+ ICommandService,
+ IUniverInstanceService,
+ JSONX,
+ RESTORE_INSERTED_PARAGRAPH_IDS,
+ TextX,
+ TextXActionType,
+ Tools,
+ UniverInstanceType,
+ UpdateDocsAttributeType,
+} from '@univerjs/core';
+import { RichTextEditingMutation } from '../mutations/core-editing.mutation';
+
+export interface IUpdateDocumentParagraphStyleCommandParams {
+ unitId: string;
+ segmentId?: string;
+ paragraphId: string;
+ startOffset: number;
+ endOffset: number;
+ style: IParagraphStyle;
+}
+
+function isValidParams(
+ params: IUpdateDocumentParagraphStyleCommandParams | undefined
+): params is IUpdateDocumentParagraphStyleCommandParams {
+ return Boolean(
+ params?.unitId &&
+ params.paragraphId &&
+ Number.isInteger(params.startOffset) &&
+ Number.isInteger(params.endOffset) &&
+ params.startOffset >= 0 &&
+ params.endOffset >= params.startOffset &&
+ params.style &&
+ Object.keys(params.style).length > 0
+ );
+}
+
+function getCurrentParagraph(
+ body: IDocumentBody,
+ params: IUpdateDocumentParagraphStyleCommandParams
+): IParagraph | null {
+ const matches = (body.paragraphs ?? []).filter((paragraph) =>
+ paragraph.paragraphId === params.paragraphId);
+ if (matches.length !== 1) {
+ return null;
+ }
+
+ const paragraph = matches[0];
+ return getParagraphContentStartOffset(body, paragraph) === params.startOffset &&
+ paragraph.startIndex === params.endOffset &&
+ body.dataStream[params.endOffset] === '\r'
+ ? paragraph
+ : null;
+}
+
+function createParagraphStyleTextX(
+ body: IDocumentBody,
+ paragraph: IParagraph,
+ params: IUpdateDocumentParagraphStyleCommandParams
+): { textX: TextX; initializesTextRuns: boolean } {
+ const textX = new TextX();
+ const initializesTextRuns = Boolean(
+ params.style.textStyle &&
+ params.startOffset < params.endOffset &&
+ body.textRuns == null
+ );
+ if (params.startOffset > 0) {
+ textX.push({ t: TextXActionType.RETAIN, len: params.startOffset });
+ }
+ if (params.style.textStyle && params.startOffset < params.endOffset && !initializesTextRuns) {
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len: params.endOffset - params.startOffset,
+ coverType: UpdateDocsAttributeType.COVER,
+ body: {
+ dataStream: '',
+ textRuns: [{
+ st: 0,
+ ed: params.endOffset - params.startOffset,
+ ts: Tools.deepClone(params.style.textStyle),
+ }],
+ },
+ });
+ } else if (params.startOffset < params.endOffset) {
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len: params.endOffset - params.startOffset,
+ });
+ }
+
+ const paragraphBody: IDocumentBody = {
+ dataStream: '',
+ paragraphs: [{
+ ...Tools.deepClone(paragraph),
+ startIndex: 0,
+ paragraphStyle: {
+ ...Tools.deepClone(paragraph.paragraphStyle ?? {}),
+ ...Tools.deepClone(params.style),
+ },
+ }],
+ };
+ Object.defineProperty(paragraphBody, RESTORE_INSERTED_PARAGRAPH_IDS, {
+ value: true,
+ enumerable: true,
+ });
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len: 1,
+ coverType: UpdateDocsAttributeType.REPLACE,
+ body: paragraphBody,
+ });
+
+ return { textX, initializesTextRuns };
+}
+
+export const UpdateDocumentParagraphStyleCommand: ICommand<IUpdateDocumentParagraphStyleCommandParams> = {
+ id: 'doc.command.update-paragraph-style',
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => {
+ if (!isValidParams(params)) {
+ return false;
+ }
+
+ const instanceService = accessor.get(IUniverInstanceService);
+ const commandService = accessor.get(ICommandService);
+ const documentDataModel = instanceService.getUnit<DocumentDataModel>(
+ params.unitId,
+ UniverInstanceType.UNIVER_DOC
+ );
+ const segmentId = params.segmentId ?? '';
+ const body = documentDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+ if (!documentDataModel || !body) {
+ return false;
+ }
+
+ const paragraph = getCurrentParagraph(body, params);
+ if (!paragraph) {
+ return false;
+ }
+
+ const { textX, initializesTextRuns } = createParagraphStyleTextX(body, paragraph, params);
+ const jsonX = JSONX.getInstance();
+ const path = getRichTextEditPath(documentDataModel, segmentId);
+ let actions = jsonX.editOp(textX.serialize(), path);
+ if (initializesTextRuns) {
+ const initializeTextRunsActions: JSONXActions = jsonX.replaceOp([...path, 'textRuns'], undefined, [{
+ st: params.startOffset,
+ ed: params.endOffset,
+ ts: Tools.deepClone(params.style.textStyle),
+ }]);
+ actions = JSONX.compose(
+ initializeTextRunsActions,
+ actions
+ );
+ }
+
+ return Boolean(commandService.syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId: params.unitId,
+ segmentId,
+ actions,
+ textRanges: null,
+ noNeedSetTextRange: true,
+ isEditing: false,
+ trigger: UpdateDocumentParagraphStyleCommand.id,
+ }));
+ },
+};
diff --git a/packages/docs/src/commands/commands/update-document-section.command.ts b/packages/docs/src/commands/commands/update-document-section.command.ts
index 0c38cdd023..ab538f8194 100644
--- a/packages/docs/src/commands/commands/update-document-section.command.ts
+++ b/packages/docs/src/commands/commands/update-document-section.command.ts
@@ -166,8 +166,14 @@ export const InsertDocumentSectionBreakCommand: ICommand<IInsertDocumentSectionB
return false;
}
const { body, documentDataModel, commandService } = context;
+ const insertedSection: ISectionBreak = {
+ ...Tools.deepClone(params.config ?? {}),
+ sectionId: params.sectionId,
+ startIndex: params.offset,
+ };
if (!isValidTopLevelInsertionOffset(body, params.offset) ||
- body.sectionBreaks?.some((section) => section.sectionId === params.sectionId)) {
+ body.sectionBreaks?.some((section) => section.sectionId === params.sectionId) ||
+ !isValidSectionConfig(insertedSection, documentDataModel.getDocumentStyle())) {
return false;
}
const nextSection = params.nextSectionType == null
@@ -182,8 +188,7 @@ export const InsertDocumentSectionBreakCommand: ICommand<IInsertDocumentSectionB
textX.insert(1, {
dataStream: DataStreamTreeTokenType.SECTION_BREAK,
sectionBreaks: [{
- ...Tools.deepClone(params.config ?? {}),
- sectionId: params.sectionId,
+ ...insertedSection,
startIndex: 0,
}],
});
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 6579bcc1b8..b6c295af63 100644
--- a/packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts
@@ -16,8 +16,9 @@
import type { IDocumentData, Univer } from '@univerjs/core';
import type { FDocument } from '../f-document';
-import { DataStreamTreeTokenType, DocumentBlockRangeType, PresetListType } from '@univerjs/core';
+import { BooleanNumber, DataStreamTreeTokenType, DocumentBlockRangeType, ICommandService, IUndoRedoService, PresetListType } from '@univerjs/core';
import { afterEach, describe, expect, it } from 'vitest';
+import { UpdateDocumentParagraphStyleCommand } from '../../commands/commands/update-document-paragraph-style.command';
import {
createBulletDocument,
createDocumentData,
@@ -124,6 +125,75 @@ describe('FDocumentParagraph', () => {
]);
});
+ it('updates paragraph and text style as one undoable command and preserves explicit false', () => {
+ const testBed = createTestBed(createSimpleDocument());
+ univer = testBed.univer;
+ testBed.get(IUndoRedoService);
+ document = testBed.univerAPI.getActiveDocument()!;
+ const paragraph = document.getParagraphs()[0];
+
+ expect(paragraph.setStyle({
+ textStyle: {
+ bl: BooleanNumber.TRUE,
+ },
+ keepNext: BooleanNumber.FALSE,
+ keepLines: BooleanNumber.TRUE,
+ widowControl: BooleanNumber.FALSE,
+ pageBreakBefore: BooleanNumber.TRUE,
+ })).toBe(true);
+ expect(paragraph.getInfo().paragraph.paragraphStyle).toMatchObject({
+ keepNext: BooleanNumber.FALSE,
+ keepLines: BooleanNumber.TRUE,
+ widowControl: BooleanNumber.FALSE,
+ pageBreakBefore: BooleanNumber.TRUE,
+ });
+ expect(document.save().body?.textRuns).toEqual([{
+ st: 0,
+ ed: 5,
+ ts: { bl: BooleanNumber.TRUE },
+ }]);
+
+ expect(document.undo()).toBe(true);
+ expect(paragraph.getInfo().paragraph.paragraphStyle).toBeUndefined();
+ expect(document.save().body?.textRuns).toBeUndefined();
+
+ expect(document.redo()).toBe(true);
+ expect(paragraph.getInfo().paragraph.paragraphStyle).toMatchObject({
+ keepNext: BooleanNumber.FALSE,
+ keepLines: BooleanNumber.TRUE,
+ widowControl: BooleanNumber.FALSE,
+ pageBreakBefore: BooleanNumber.TRUE,
+ });
+ const saved = document.save();
+ createDocumentFacade(saved);
+ expect(document.getParagraphs()[0].getInfo().paragraph.paragraphStyle).toMatchObject({
+ keepNext: BooleanNumber.FALSE,
+ keepLines: BooleanNumber.TRUE,
+ widowControl: BooleanNumber.FALSE,
+ pageBreakBefore: BooleanNumber.TRUE,
+ });
+ });
+
+ it('rejects a stale paragraph range without a partial style update', () => {
+ const testBed = createTestBed(createSimpleDocument());
+ univer = testBed.univer;
+ document = testBed.univerAPI.getActiveDocument()!;
+ const paragraph = document.getParagraphs()[0];
+ const { startOffset, endOffset } = paragraph.getInfo();
+
+ expect(document.insertParagraph(0, 'Before').getText()).toBe('Before');
+ expect(testBed.get(ICommandService).syncExecuteCommand(UpdateDocumentParagraphStyleCommand.id, {
+ unitId: document.getId(),
+ paragraphId: paragraph.getId(),
+ startOffset,
+ endOffset,
+ style: {
+ keepNext: BooleanNumber.TRUE,
+ },
+ })).toBe(false);
+ expect(paragraph.getInfo().paragraph.paragraphStyle?.keepNext).toBeUndefined();
+ });
+
it('reads and updates a text range across existing style-run boundaries', () => {
const data = createSimpleDocument();
data.body!.textRuns = [
diff --git a/packages/docs/src/facade/__tests__/f-document.node.spec.ts b/packages/docs/src/facade/__tests__/f-document.node.spec.ts
index e43d2e08f1..7174c05ad7 100644
--- a/packages/docs/src/facade/__tests__/f-document.node.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document.node.spec.ts
@@ -70,6 +70,21 @@ describe('FDocument in Node', () => {
pageOrient: PageOrientType.LANDSCAPE,
},
});
+ expect(section?.getEffectivePageSetup()).toEqual({
+ pageNumberStart: 7,
+ pageSize: { width: 960, height: 720 },
+ pageOrient: PageOrientType.LANDSCAPE,
+ margins: {
+ top: 48,
+ bottom: 48,
+ left: 64,
+ right: 64,
+ },
+ contentSize: {
+ width: 832,
+ height: 624,
+ },
+ });
expect(document?.save().body?.customRanges).toContainEqual(expect.objectContaining({
startIndex: 3,
endIndex: 3,
diff --git a/packages/docs/src/facade/__tests__/f-document.spec.ts b/packages/docs/src/facade/__tests__/f-document.spec.ts
index 56d7d420d2..21a2f1a911 100644
--- a/packages/docs/src/facade/__tests__/f-document.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document.spec.ts
@@ -39,7 +39,8 @@ describe('FDocument', () => {
createDocumentFacade();
});
- it('exposes section enums through univerAPI', () => {
+ it('exposes document layout enums through univerAPI', () => {
+ expect(univerAPI.Enum.DocumentFlavor).toBe(DocumentFlavor);
expect(univerAPI.Enum.SectionType).toMatchObject({
SECTION_TYPE_UNSPECIFIED: 0,
CONTINUOUS: 1,
@@ -51,6 +52,21 @@ describe('FDocument', () => {
expect(univerAPI.Enum.ColumnSeparatorType.BETWEEN_EACH_COLUMN).toBe(ColumnSeparatorType.BETWEEN_EACH_COLUMN);
});
+ it.each([
+ { flavor: DocumentFlavor.TRADITIONAL, traditional: true, modern: false },
+ { flavor: DocumentFlavor.MODERN, traditional: false, modern: true },
+ { flavor: DocumentFlavor.UNSPECIFIED, traditional: false, modern: false },
+ ])('reports the exact $flavor document flavor', ({ flavor, traditional, modern }) => {
+ univer.dispose();
+ const data = createSimpleDocument(`flavor-${flavor}`);
+ data.documentStyle = { ...data.documentStyle, documentFlavor: flavor };
+ createDocumentFacade(data);
+
+ expect(document.getDocumentFlavor()).toBe(flavor);
+ expect(document.isTraditional()).toBe(traditional);
+ expect(document.isModern()).toBe(modern);
+ });
+
afterEach(() => {
univer.dispose();
});
@@ -289,6 +305,21 @@ describe('FDocument', () => {
expect(section.setPageSetup(pageSetup)).toBe(true);
expect(section.getPageSetup()).toEqual(pageSetup);
+ expect(section.getEffectivePageSetup()).toEqual({
+ pageNumberStart: 3,
+ pageSize: { width: 960, height: 720 },
+ pageOrient: PageOrientType.LANDSCAPE,
+ margins: {
+ top: 48,
+ bottom: 56,
+ left: 64,
+ right: 72,
+ },
+ contentSize: {
+ width: 824,
+ height: 616,
+ },
+ });
expect(document.undo()).toBe(true);
expect(section.getPageSetup()).toEqual({
pageNumberStart: undefined,
@@ -303,10 +334,19 @@ describe('FDocument', () => {
expect(section.getPageSetup()).toEqual(pageSetup);
});
- 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.each([DocumentFlavor.MODERN, DocumentFlavor.UNSPECIFIED])(
+ 'keeps traditional section mutation unavailable for document flavor %s',
+ (documentFlavor) => {
+ univer.dispose();
+ const data = createSimpleDocument(`unsupported-sections-${documentFlavor}`);
+ data.documentStyle = { ...data.documentStyle, documentFlavor };
+ createDocumentFacade(data);
+
+ expect(document.getSections()).toEqual([]);
+ expect(() => document.insertColumnBreak(0)).toThrow('Section column APIs are supported only in traditional documents');
+ expect(() => document.insertSectionBreak(0)).toThrow('Section column APIs are supported only in traditional documents');
+ }
+ );
it('keeps section facade identity stable when section order changes', () => {
univer.dispose();
@@ -445,6 +485,35 @@ describe('FDocument', () => {
expect(document.getSection(0)?.remove()).toBe(false);
});
+ it('atomically sets how the following section begins when inserting a section break', () => {
+ univer.dispose();
+ const data = createDocumentData('section-next-page-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);
+ get(IUndoRedoService);
+
+ const inserted = document.insertSectionBreak(6, {
+ sectionType: SectionType.CONTINUOUS,
+ nextSectionType: SectionType.NEXT_PAGE,
+ });
+
+ expect(inserted?.getConfig().sectionType).toBe(SectionType.CONTINUOUS);
+ expect(document.getSection(1)?.getId()).toBe('section_root');
+ expect(document.getSection(1)?.getConfig().sectionType).toBe(SectionType.NEXT_PAGE);
+
+ expect(document.undo()).toBe(true);
+ expect(document.getSections().map((section) => section.getId())).toEqual(['section_root']);
+ expect(document.getSection(0)?.getConfig().sectionType).toBeUndefined();
+
+ expect(document.redo()).toBe(true);
+ expect(document.getSections()).toHaveLength(2);
+ expect(document.getSection(1)?.getConfig().sectionType).toBe(SectionType.NEXT_PAGE);
+ });
+
it('inserts a horizontal rule as a bordered paragraph', () => {
univer.dispose();
createDocumentFacade(createSimpleDocument());
diff --git a/packages/docs/src/facade/f-document-paragraph.ts b/packages/docs/src/facade/f-document-paragraph.ts
index df7e607c6d..1886a35dd9 100644
--- a/packages/docs/src/facade/f-document-paragraph.ts
+++ b/packages/docs/src/facade/f-document-paragraph.ts
@@ -17,8 +17,9 @@
import type { IDocumentBody, Injector, IParagraph, IParagraphStyle } from '@univerjs/core';
import type { FDocument } from './f-document';
import type { IFDocumentTextRange } from './utils';
-import { getParagraphContentStartOffset, PresetListType, regexp, RESTORE_INSERTED_PARAGRAPH_IDS, UpdateDocsAttributeType } from '@univerjs/core';
+import { getParagraphContentStartOffset, ICommandService, PresetListType, regexp, RESTORE_INSERTED_PARAGRAPH_IDS, UpdateDocsAttributeType } from '@univerjs/core';
import { FBaseInitialable } from '@univerjs/core/facade';
+import { UpdateDocumentParagraphStyleCommand } from '@univerjs/docs';
import { FDocumentTextRange } from './f-document-text-range';
import { buildPlainTextInsertBody, replaceBodyRange, retainBodyRange } from './utils';
@@ -67,7 +68,8 @@ export class FDocumentParagraph extends FBaseInitialable {
protected readonly _document: FDocument,
protected readonly _paragraphId: string,
protected readonly _segmentId = '',
- protected override readonly _injector: Injector
+ protected override readonly _injector: Injector,
+ @ICommandService private readonly _commandService: ICommandService
) {
super(_injector);
}
@@ -314,77 +316,65 @@ export class FDocumentParagraph extends FBaseInitialable {
}
/**
- * Apply paragraph style to a paragraph handle or text range.
+ * Applies a paragraph and optional text-style patch through one document command.
+ *
+ * Pagination values use `BooleanNumber.TRUE` or `BooleanNumber.FALSE`; explicit
+ * false is preserved and overrides inherited true. The paragraph and text-style
+ * changes share one undo/redo item. A stale paragraph handle returns `false`
+ * without applying a partial update.
+ *
+ * The Traditional renderer applies these Word-compatible pagination rules:
+ * use `pageBreakBefore` for a hard chapter-page boundary, `keepLines` for a
+ * short paragraph that should stay intact, `keepNext` for a heading or caption
+ * that should accompany the next paragraph, and `widowControl` for natural
+ * multi-line body text. Do not enable every rule on every paragraph. Modern
+ * and Unspecified Docs preserve the values in the model but do not apply them
+ * to physical pages.
+ *
* `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.
+ * @returns {boolean} `true` when the complete patch was applied; otherwise `false`.
* @example
* ```ts
- * const fDocument = univerAPI.getActiveDocument();
- * const paragraph = fDocument.getParagraphs()[0];
- * paragraph?.setText('Styled text');
- * paragraph?.setStyle({
- * textStyle: {
- * cl: {
- * rgb: '#FF0000',
- * },
- * fs: 14,
- * },
- * horizontalAlign: 2,
+ * const document = univerAPI.getActiveDocument();
+ * if (!document) {
+ * throw new Error('No active document');
+ * }
+ * if (!document.isTraditional()) {
+ * throw new Error('Traditional document pagination is required');
+ * }
+ * const heading = document.findParagraphByText('Appendix');
+ * const following = document.findParagraphByText('Supporting details');
+ * if (!heading || !following) {
+ * throw new Error('Expected paragraphs were not found');
+ * }
+ *
+ * const headingUpdated = heading.setStyle({
+ * pageBreakBefore: univerAPI.Enum.BooleanNumber.TRUE,
+ * keepLines: univerAPI.Enum.BooleanNumber.TRUE,
+ * keepNext: univerAPI.Enum.BooleanNumber.TRUE,
+ * });
+ * const followingUpdated = following.setStyle({
+ * // Explicit FALSE terminates this authored keepNext chain even if a named
+ * // style or document default enables it.
+ * keepNext: univerAPI.Enum.BooleanNumber.FALSE,
+ * widowControl: univerAPI.Enum.BooleanNumber.TRUE,
* });
- * console.log(paragraph?.getInfo().paragraph.paragraphStyle);
+ * if (!headingUpdated || !followingUpdated) {
+ * throw new Error('Failed to update paragraph pagination');
+ * }
* ```
*/
setStyle(style: IParagraphStyle): boolean {
- const { paragraph, startOffset, endOffset } = this.getInfo();
- let result = true;
-
- if (style.textStyle && startOffset < endOffset) {
- result = retainBodyRange(
- {
- startOffset,
- endOffset,
- segmentId: this._segmentId,
- },
- {
- dataStream: '',
- textRuns: [{
- st: 0,
- ed: endOffset - startOffset,
- ts: style.textStyle,
- }],
- },
- UpdateDocsAttributeType.COVER,
- this._document.getDocumentDataModel(),
- this._injector
- );
- }
-
- const updateBody: IDocumentBody = {
- dataStream: '',
- paragraphs: [{
- ...paragraph,
- startIndex: 0,
- paragraphStyle: {
- ...paragraph.paragraphStyle,
- ...style,
- },
- }],
- };
-
- this._preserveExplicitParagraphIds(updateBody);
-
- return retainBodyRange(
- {
- startOffset: endOffset,
- endOffset: endOffset + 1,
- segmentId: this._segmentId,
- },
- updateBody,
- UpdateDocsAttributeType.REPLACE,
- this._document.getDocumentDataModel(),
- this._injector
- ) && result;
+ const { startOffset, endOffset } = this.getInfo();
+ return this._commandService.syncExecuteCommand(UpdateDocumentParagraphStyleCommand.id, {
+ unitId: this._document.getId(),
+ segmentId: this._segmentId,
+ paragraphId: this._paragraphId,
+ startOffset,
+ endOffset,
+ style,
+ });
}
/**
diff --git a/packages/docs/src/facade/f-document-section.ts b/packages/docs/src/facade/f-document-section.ts
index 78c5959b9b..46d66f2f00 100644
--- a/packages/docs/src/facade/f-document-section.ts
+++ b/packages/docs/src/facade/f-document-section.ts
@@ -15,11 +15,11 @@
*/
import type { IResolvedSectionHeaderFooterReference, ISectionBreak, ISectionColumnProperties, SectionHeaderFooterKind, SectionHeaderFooterVariant } from '@univerjs/core';
-import type { IHeaderFooterProps } from '@univerjs/docs';
+import type { IEffectiveSectionPageSetup, IHeaderFooterProps } from '@univerjs/docs';
import type { FDocument } from './f-document';
import type { IFDocumentTextRange } from './utils';
import { ColumnSeparatorType, DocumentFlavor, generateRandomId, getSectionHeaderFooterReferenceKey, ICommandService, PageOrientType, resolveSectionHeaderFooterReference, SectionType, Tools } from '@univerjs/core';
-import { CreateHeaderFooterCommand, createSectionColumnProperties, DeleteDocumentSectionBreakCommand, getSectionContentWidth, getTopLevelSectionBreaks, HeaderFooterType, SetSectionHeaderFooterLinkCommand, UpdateDocumentSectionCommand } from '@univerjs/docs';
+import { CreateHeaderFooterCommand, createSectionColumnProperties, DeleteDocumentSectionBreakCommand, getEffectiveSectionPageSetup, getSectionContentWidth, getTopLevelSectionBreaks, HeaderFooterType, SetSectionHeaderFooterLinkCommand, UpdateDocumentSectionCommand } from '@univerjs/docs';
export interface IFDocumentSectionColumnOptions {
/** Gap after each column except the last, in 96-DPI layout pixels. */
@@ -50,21 +50,40 @@ export interface IFDocumentSectionDescription {
config: ISectionBreak;
}
-/** Error thrown when traditional section APIs are used to mutate a modern document. */
+function validatePageSetup(pageSetup: FDocumentSectionPageSetup): void {
+ const { pageNumberStart, pageSize, pageOrient, marginTop, marginBottom, marginLeft, marginRight } = pageSetup;
+ if (pageNumberStart != null && (!Number.isInteger(pageNumberStart) || pageNumberStart < 1)) {
+ throw new RangeError('Section page number start must be a positive integer.');
+ }
+ if (pageSize && [pageSize.width, pageSize.height]
+ .some((size) => size != null && (!Number.isFinite(size) || size <= 0))) {
+ throw new RangeError('Section page size must be finite and positive.');
+ }
+ if (pageOrient != null && !Object.values(PageOrientType).includes(pageOrient)) {
+ throw new RangeError('Invalid section page orientation.');
+ }
+ if ([marginTop, marginBottom, marginLeft, marginRight]
+ .some((margin) => margin != null && (!Number.isFinite(margin) || margin < 0))) {
+ throw new RangeError('Section page margins must be finite and non-negative.');
+ }
+}
+
+/** Error thrown when a Traditional-only section API is used with another document flavor. */
export class DocsSectionUnsupportedDocumentFlavorError extends Error {
constructor() {
- super('Section column APIs are supported only in traditional documents. Use ColumnGroup APIs for modern documents.');
+ super('Section column APIs are supported only in traditional documents. Use ColumnGroup APIs for modern documents, or resolve an unspecified document flavor first.');
this.name = 'DocsSectionUnsupportedDocumentFlavorError';
}
}
/**
* Facade wrapper for an OOXML-compatible traditional document section.
- * Modern documents use ColumnGroup APIs and cannot mutate this facade.
+ * Modern documents use ColumnGroup APIs. Unspecified documents must resolve
+ * their flavor before using this facade.
* @example
* ```ts
* const fDocument = univerAPI.getActiveDocument();
- * if (fDocument && !fDocument.isModern()) {
+ * if (fDocument?.isTraditional()) {
* console.log(fDocument.getSection(0)?.describe());
* }
* ```
@@ -109,8 +128,7 @@ export class FDocumentSection {
* ```
*/
getConfig(): ISectionBreak {
- const { sectionBreak } = this._resolve();
- return Tools.deepClone(sectionBreak);
+ return this._getConfigSnapshot();
}
/**
@@ -122,14 +140,7 @@ export class FDocumentSection {
* ```
*/
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: '',
- };
+ return this._getRange(this._resolve().index);
}
/**
@@ -142,7 +153,7 @@ export class FDocumentSection {
* ```
*/
getColumns(): ISectionColumnProperties[] {
- return Tools.deepClone(this.getConfig().columnProperties ?? []);
+ return Tools.deepClone(this._getConfigSnapshot().columnProperties ?? []);
}
/**
@@ -154,7 +165,8 @@ export class FDocumentSection {
* ```
*/
describe(): IFDocumentSectionDescription {
- const config = this.getConfig();
+ const { index } = this._resolve();
+ const config = this._getConfigSnapshot();
const columns = config.columnProperties ?? [];
const headerFooter = {
defaultHeader: this._describeHeaderFooterReference('header', 'default'),
@@ -166,8 +178,8 @@ export class FDocumentSection {
};
return {
sectionId: this._sectionId,
- index: this.getIndex(),
- range: this.getRange(),
+ index,
+ range: this._getRange(index),
columnCount: columns.length || 1,
columns: Tools.deepClone(columns),
columnSeparatorType: config.columnSeparatorType ?? ColumnSeparatorType.NONE,
@@ -184,7 +196,7 @@ export class FDocumentSection {
* @example
* ```ts
* const fDocument = univerAPI.getActiveDocument();
- * if (fDocument && !fDocument.isModern()) {
+ * if (fDocument?.isTraditional()) {
* fDocument.getSection(0)?.setColumns(2, { gap: 18, separator: true });
* }
* ```
@@ -202,7 +214,7 @@ export class FDocumentSection {
}
const gap = Math.max(0, options.gap ?? 18);
- const config = this.getConfig();
+ const config = this._getConfigSnapshot();
const columns = createSectionColumnProperties(
this._document.getDocumentDataModel().getSnapshot().documentStyle,
config,
@@ -228,7 +240,7 @@ export class FDocumentSection {
* @example
* ```ts
* const fDocument = univerAPI.getActiveDocument();
- * if (fDocument && !fDocument.isModern()) {
+ * if (fDocument?.isTraditional()) {
* fDocument.getSection(0)?.setColumnProperties([
* { width: 240, paddingEnd: 18 },
* { width: 240, paddingEnd: 0 },
@@ -246,7 +258,7 @@ export class FDocumentSection {
}
const contentWidth = getSectionContentWidth(
this._document.getDocumentDataModel().getSnapshot().documentStyle,
- this.getConfig()
+ this._getConfigSnapshot()
);
if (columns.reduce((sum, { width, paddingEnd }) => sum + width + paddingEnd, 0) > contentWidth) {
throw new RangeError('Section columns exceed the available page content width.');
@@ -259,11 +271,27 @@ export class FDocumentSection {
/**
* Sets how this section begins relative to the previous section.
+ *
+ * The first section has no preceding boundary, so setting its type does not
+ * create an initial blank page. Prefer `FDocument.insertSectionBreak` with
+ * `nextSectionType` when creating a new boundary; use this method when
+ * updating an existing section after resolving it again from the document.
+ *
+ * @param {SectionType} sectionType How this section begins.
+ * @returns {boolean} `true` when the section command was applied.
* @example
* ```ts
- * const fDocument = univerAPI.getActiveDocument();
- * if (fDocument && !fDocument.isModern()) {
- * fDocument.getSection(0)?.setSectionType(univerAPI.Enum.SectionType.NEXT_PAGE);
+ * const document = univerAPI.getActiveDocument();
+ * if (!document?.isTraditional()) {
+ * throw new Error('A Traditional document is required');
+ * }
+ *
+ * const secondSection = document.getSection(1);
+ * if (!secondSection) {
+ * throw new Error('The second section does not exist');
+ * }
+ * if (!secondSection.setSectionType(univerAPI.Enum.SectionType.NEXT_PAGE)) {
+ * throw new Error('Failed to update the second section');
* }
* ```
*/
@@ -278,6 +306,17 @@ export class FDocumentSection {
/**
* Returns this section's explicit page setup overrides.
* Missing values inherit from the document style. Geometry values use 96-DPI layout pixels.
+ *
+ * Use `getEffectivePageSetup()` when an agent needs resolved page and content
+ * dimensions rather than only the overrides stored on this section.
+ *
+ * @returns {FDocumentSectionPageSetup} A cloned object containing only explicit section overrides.
+ * @example
+ * ```ts
+ * const document = univerAPI.getActiveDocument();
+ * const section = document?.getSection(0);
+ * console.log(section?.getPageSetup());
+ * ```
*/
getPageSetup(): FDocumentSectionPageSetup {
const {
@@ -288,7 +327,7 @@ export class FDocumentSection {
marginBottom,
marginLeft,
marginRight,
- } = this.getConfig();
+ } = this._getConfigSnapshot();
return Tools.deepClone({
pageNumberStart,
pageSize,
@@ -300,41 +339,90 @@ export class FDocumentSection {
});
}
+ /**
+ * Returns nominal page geometry after resolving this section's overrides
+ * against document defaults. All geometry values use 96-DPI layout pixels.
+ *
+ * This synchronous model-only API works without `engine-render`. It does not
+ * report physical page count, remaining page space, or final coordinates.
+ *
+ * @returns {IEffectiveSectionPageSetup} A cloned, serializable page setup.
+ * @example
+ * ```ts
+ * const document = univerAPI.getActiveDocument();
+ * if (!document) {
+ * throw new Error('No active document');
+ * }
+ * if (!document.isTraditional()) {
+ * throw new Error('Traditional document sections are required');
+ * }
+ *
+ * const section = document.getSection(0);
+ * if (!section) {
+ * throw new Error('The document has no traditional section');
+ * }
+ *
+ * const layout = section.getEffectivePageSetup();
+ * console.log({
+ * pageWidth: layout.pageSize.width,
+ * pageHeight: layout.pageSize.height,
+ * contentWidth: layout.contentSize.width,
+ * contentHeight: layout.contentSize.height,
+ * margins: layout.margins,
+ * });
+ * ```
+ */
+ getEffectivePageSetup(): IEffectiveSectionPageSetup {
+ this._assertTraditionalDocument();
+ const documentStyle = this._document.getDocumentDataModel().getSnapshot().documentStyle;
+ return Tools.deepClone(getEffectiveSectionPageSetup(documentStyle, this._getConfigSnapshot()));
+ }
+
/**
* Updates this section's page setup through the document section command.
* Geometry values use 96-DPI layout pixels.
+ *
+ * This method changes static page geometry; it does not choose where the
+ * section begins. Use `setSectionType()` for an existing boundary, or
+ * `insertSectionBreak(..., { nextSectionType })` while creating one.
+ *
+ * @param {FDocumentSectionPageSetup} pageSetup Explicit section overrides to patch.
+ * @returns {boolean} `true` when the section command was applied.
+ * @example
+ * ```ts
+ * const document = univerAPI.getActiveDocument();
+ * if (!document?.isTraditional()) {
+ * throw new Error('A Traditional document is required');
+ * }
+ *
+ * const section = document.getSection(1);
+ * if (!section) {
+ * throw new Error('The second section does not exist');
+ * }
+ * const updated = section.setPageSetup({
+ * pageSize: { width: 816, height: 1056 },
+ * marginTop: 96,
+ * marginBottom: 96,
+ * marginLeft: 96,
+ * marginRight: 96,
+ * });
+ * if (!updated) {
+ * throw new Error('Failed to update section page setup');
+ * }
+ * console.log(section.getEffectivePageSetup());
+ * ```
*/
setPageSetup(pageSetup: FDocumentSectionPageSetup): boolean {
this._assertTraditionalDocument();
- const { pageNumberStart, pageSize, pageOrient, marginTop, marginBottom, marginLeft, marginRight } = pageSetup;
- if (pageNumberStart != null && (!Number.isInteger(pageNumberStart) || pageNumberStart < 1)) {
- throw new RangeError('Section page number start must be a positive integer.');
- }
- if (pageSize && [pageSize.width, pageSize.height]
- .some((size) => size != null && (!Number.isFinite(size) || size <= 0))) {
- throw new RangeError('Section page size must be finite and positive.');
- }
- if (pageOrient != null && !Object.values(PageOrientType).includes(pageOrient)) {
- throw new RangeError('Invalid section page orientation.');
- }
- if ([marginTop, marginBottom, marginLeft, marginRight]
- .some((margin) => margin != null && (!Number.isFinite(margin) || margin < 0))) {
- throw new RangeError('Section page margins must be finite and non-negative.');
- }
- const current = this.getConfig();
+ validatePageSetup(pageSetup);
+ const definedPageSetup = Tools.deepClone(pageSetup);
+ Tools.removeNull(definedPageSetup);
const documentStyle = this._document.getDocumentDataModel().getSnapshot().documentStyle;
- const effectivePageSize = pageSize ?? current.pageSize ?? documentStyle.pageSize;
- const effectiveMarginTop = marginTop ?? current.marginTop ?? documentStyle.marginTop ?? 0;
- const effectiveMarginBottom = marginBottom ?? current.marginBottom ?? documentStyle.marginBottom ?? 0;
- const effectiveMarginLeft = marginLeft ?? current.marginLeft ?? documentStyle.marginLeft ?? 0;
- const effectiveMarginRight = marginRight ?? current.marginRight ?? documentStyle.marginRight ?? 0;
- if ((effectivePageSize?.width != null &&
- effectiveMarginLeft + effectiveMarginRight >= effectivePageSize.width) ||
- (effectivePageSize?.height != null &&
- effectiveMarginTop + effectiveMarginBottom >= effectivePageSize.height)) {
- throw new RangeError('Section page margins must leave a positive content area.');
- }
- return this._update(Tools.deepClone(pageSetup));
+ getEffectiveSectionPageSetup(documentStyle, {
+ ...this._getConfigSnapshot(),
+ ...definedPageSetup,
+ });
+ return this._update(definedPageSetup);
}
/**
@@ -342,7 +430,7 @@ export class FDocumentSection {
* @example
* ```ts
* const fDocument = univerAPI.getActiveDocument();
- * if (fDocument && !fDocument.isModern()) {
+ * if (fDocument?.isTraditional()) {
* const segmentId = fDocument.getSection(0)?.ensureHeader();
* if (segmentId) {
* fDocument.insertText(0, 'Quarterly report', segmentId);
@@ -359,7 +447,7 @@ export class FDocumentSection {
* @example
* ```ts
* const fDocument = univerAPI.getActiveDocument();
- * if (fDocument && !fDocument.isModern()) {
+ * if (fDocument?.isTraditional()) {
* const segmentId = fDocument.getSection(0)?.ensureFooter('first');
* if (segmentId) {
* fDocument.insertText(0, 'Confidential', segmentId);
@@ -424,7 +512,7 @@ export class FDocumentSection {
* @example
* ```ts
* const fDocument = univerAPI.getActiveDocument();
- * if (fDocument && !fDocument.isModern()) {
+ * if (fDocument?.isTraditional()) {
* fDocument.getSection(1)?.setHeaderLinkedToPrevious(false, 'default');
* }
* ```
@@ -438,7 +526,7 @@ export class FDocumentSection {
* @example
* ```ts
* const fDocument = univerAPI.getActiveDocument();
- * if (fDocument && !fDocument.isModern()) {
+ * if (fDocument?.isTraditional()) {
* fDocument.getSection(1)?.setFooterLinkedToPrevious(true, 'even');
* }
* ```
@@ -453,7 +541,7 @@ export class FDocumentSection {
* @example
* ```ts
* const fDocument = univerAPI.getActiveDocument();
- * if (fDocument && !fDocument.isModern()) {
+ * if (fDocument?.isTraditional()) {
* fDocument.getSection(0)?.setHeaderFooterOptions({
* marginHeader: 36,
* marginFooter: 36,
@@ -472,7 +560,7 @@ export class FDocumentSection {
* @example
* ```ts
* const fDocument = univerAPI.getActiveDocument();
- * if (fDocument && !fDocument.isModern()) {
+ * if (fDocument?.isTraditional()) {
* const sections = fDocument.getSections();
* if (sections.length > 1) {
* sections[0].remove();
@@ -499,7 +587,7 @@ export class FDocumentSection {
private _ensureHeaderFooter(kind: SectionHeaderFooterKind, variant: SectionHeaderFooterVariant): string {
this._assertTraditionalDocument();
const { index } = this._resolve();
- const config = this.getConfig();
+ const config = this._getConfigSnapshot();
const key = getSectionHeaderFooterReferenceKey(kind, variant);
const existing = config[key];
if (typeof existing === 'string' && existing) {
@@ -587,6 +675,19 @@ export class FDocumentSection {
}
}
+ private _getConfigSnapshot(): ISectionBreak {
+ return Tools.deepClone(this._resolve().sectionBreak);
+ }
+
+ private _getRange(index: number): IFDocumentTextRange {
+ const sectionBreaks = getTopLevelSectionBreaks(this._document.getBody());
+ return {
+ startOffset: index === 0 ? 0 : sectionBreaks[index - 1].startIndex + 1,
+ endOffset: sectionBreaks[index].startIndex,
+ segmentId: '',
+ };
+ }
+
private _resolve(): { index: number; sectionBreak: ISectionBreak } {
this._assertTraditionalDocument();
const sectionBreaks = getTopLevelSectionBreaks(this._document.getBody());
diff --git a/packages/docs/src/facade/f-document.ts b/packages/docs/src/facade/f-document.ts
index 7a66cc21f7..538356e15d 100644
--- a/packages/docs/src/facade/f-document.ts
+++ b/packages/docs/src/facade/f-document.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { DocumentDataModel, IDocumentBody, IDocumentData, IParagraphBorder, ISectionBreak, SectionHeaderFooterKind } from '@univerjs/core';
+import type { DocumentDataModel, IDocumentBody, IDocumentData, IParagraphBorder, ISectionBreak, SectionHeaderFooterKind, SectionType } from '@univerjs/core';
import type { IHeaderFooterProps } from '@univerjs/docs';
import type { IFDocumentTextRange } from './utils';
import {
@@ -46,6 +46,22 @@ export interface IFDocumentParagraphQuery {
segmentId?: string;
}
+/**
+ * Options for inserting a section break in a traditional document.
+ *
+ * Section properties such as margins and page size describe the section created
+ * before the inserted break. `nextSectionType` controls how the existing section
+ * after the break begins relative to that newly created section.
+ */
+export type IFDocumentInsertSectionBreakOptions = Partial<Omit<ISectionBreak, 'sectionId' | 'startIndex'>> & {
+ /**
+ * How the existing section after the inserted boundary begins relative to
+ * the newly created section. Prefer this atomic option to inserting a break
+ * and then resolving and updating the following section separately.
+ */
+ nextSectionType?: SectionType;
+};
+
/**
* Facade API object bounded to a document. It provides a set of methods to interact with the document.
* @hideconstructor
@@ -140,16 +156,75 @@ export class FDocument extends FBaseInitialable {
}
/**
- * Whether the document is a modern document or not.
- * @returns {boolean} `true` if the document is a modern document, or `false` if it is not.
+ * Returns the document's explicit layout flavor.
+ *
+ * Use this method when all three states matter. Do not infer a Traditional
+ * document from `!isModern()`: that expression is also true for
+ * `DocumentFlavor.UNSPECIFIED`.
+ *
+ * @returns {DocumentFlavor} `TRADITIONAL`, `MODERN`, or `UNSPECIFIED`.
+ * @example
+ * ```typescript
+ * const document = univerAPI.getActiveDocument();
+ * if (!document) {
+ * throw new Error('No active document');
+ * }
+ *
+ * switch (document.getDocumentFlavor()) {
+ * case univerAPI.Enum.DocumentFlavor.TRADITIONAL:
+ * console.log('Word-compatible physical pagination is available');
+ * break;
+ * case univerAPI.Enum.DocumentFlavor.MODERN:
+ * console.log('Use Modern Doc layout APIs such as ColumnGroup');
+ * break;
+ * default:
+ * console.log('Resolve the unspecified flavor before using flavor-specific APIs');
+ * }
+ * ```
+ */
+ getDocumentFlavor(): DocumentFlavor {
+ return this._resolveDocumentFlavor();
+ }
+
+ /**
+ * Whether this is a Traditional document with Word-compatible physical pagination.
+ *
+ * Prefer this positive guard before calling section, column-break, page-setup,
+ * or paragraph-pagination APIs.
+ *
+ * @returns {boolean} `true` only for `DocumentFlavor.TRADITIONAL`.
+ * @example
+ * ```typescript
+ * const document = univerAPI.getActiveDocument();
+ * if (document?.isTraditional()) {
+ * console.log(document.getSection(0)?.getEffectivePageSetup());
+ * }
+ * ```
+ */
+ isTraditional(): boolean {
+ return this._resolveDocumentFlavor() === DocumentFlavor.TRADITIONAL;
+ }
+
+ /**
+ * Whether this is a Modern document.
+ *
+ * A `false` result can mean either Traditional or Unspecified. Use
+ * `isTraditional()` before Traditional-only APIs, or `getDocumentFlavor()`
+ * when all three states matter.
+ *
+ * @returns {boolean} `true` only for `DocumentFlavor.MODERN`.
* @example
* ```typescript
* const fDocument = univerAPI.getActiveDocument();
- * console.log(fDocument.isModern());
+ * console.log(fDocument?.isModern());
* ```
*/
isModern(): boolean {
- return this._documentDataModel.getSnapshot().documentStyle.documentFlavor === DocumentFlavor.MODERN;
+ return this._resolveDocumentFlavor() === DocumentFlavor.MODERN;
+ }
+
+ private _resolveDocumentFlavor(): DocumentFlavor {
+ return this._documentDataModel.getSnapshot().documentStyle.documentFlavor ?? DocumentFlavor.UNSPECIFIED;
}
/**
@@ -273,12 +348,18 @@ export class FDocument extends FBaseInitialable {
}
/**
- * Updates document-level header/footer switches and margins in a traditional document.
- * `marginHeader` and `marginFooter` use 96-DPI layout pixels.
+ * Updates document-level header/footer switches and margins.
+ *
+ * Traditional and Unspecified documents keep the legacy header/footer
+ * behavior. Modern documents reject this API. `marginHeader` and
+ * `marginFooter` use 96-DPI layout pixels.
* @example
* ```ts
* const fDocument = univerAPI.getActiveDocument();
- * if (fDocument && !fDocument.isModern()) {
+ * if (
+ * fDocument &&
+ * fDocument.getDocumentFlavor() !== univerAPI.Enum.DocumentFlavor.MODERN
+ * ) {
* fDocument.setHeaderFooterOptions({ marginHeader: 36, marginFooter: 36 });
* }
* ```
@@ -362,29 +443,68 @@ export class FDocument extends FBaseInitialable {
/**
* 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 96-DPI layout pixels.
+ *
+ * `options` configures the section created before the inserted break.
+ * Set `options.nextSectionType` to control how the existing section after the
+ * break begins. For example, use `SectionType.NEXT_PAGE` to start a chapter on
+ * a new physical page. Both changes are executed by one command and are
+ * undone or redone together.
+ *
+ * The offset must be a top-level document position. To insert a break before
+ * a table or block such as a callout, use that object's start offset instead
+ * of an offset inside the object.
+ *
+ * Modern documents must use ColumnGroup. Unspecified documents must resolve
+ * their flavor first. Both throw `DocsSectionUnsupportedDocumentFlavorError`.
+ * Numeric layout values in `options` are in 96-DPI layout pixels.
+ *
+ * @param {number} offset Top-level data-stream offset where the section break is inserted.
+ * @param {IFDocumentInsertSectionBreakOptions} [options] Section properties and the optional type of the following section.
+ * @returns {FDocumentSection | null} The section created before the break, or `null` when the command rejects the insertion.
* @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());
+ * const document = univerAPI.getActiveDocument();
+ * if (!document) {
+ * throw new Error('No active document');
+ * }
+ * if (!document.isTraditional()) {
+ * throw new Error('Traditional document sections are required');
* }
+ *
+ * const chapter = document.findParagraphByText('Chapter 2');
+ * if (!chapter) {
+ * throw new Error('Chapter heading not found');
+ * }
+ *
+ * // Insert the boundary immediately before the chapter heading. The command
+ * // also marks the following section as NEXT_PAGE, so the two model changes
+ * // share one undo/redo step.
+ * const sectionBeforeChapter = document.insertSectionBreak(
+ * chapter.getInfo().startOffset,
+ * { nextSectionType: univerAPI.Enum.SectionType.NEXT_PAGE }
+ * );
+ * if (!sectionBeforeChapter) {
+ * throw new Error('The chapter heading is not at a valid top-level offset');
+ * }
+ *
+ * console.log({
+ * insertedSection: sectionBeforeChapter.describe(),
+ * chapterSection: document.getSectionAt(chapter.getInfo().startOffset)?.describe(),
+ * });
* ```
*/
- insertSectionBreak(offset: number, config: Partial<Omit<ISectionBreak, 'sectionId' | 'startIndex'>> = {}): FDocumentSection | null {
+ insertSectionBreak(offset: number, options: IFDocumentInsertSectionBreakOptions = {}): FDocumentSection | null {
if (this._documentDataModel.getSnapshot().documentStyle.documentFlavor !== DocumentFlavor.TRADITIONAL) {
throw new DocsSectionUnsupportedDocumentFlavorError();
}
+ const { nextSectionType, ...config } = options;
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,
+ nextSectionType,
});
return success ? this._injector.createInstance(FDocumentSection, this, sectionId) : null;
}
@@ -392,11 +512,12 @@ export class FDocument extends FBaseInitialable {
/**
* Inserts a column-break token in a traditional document.
* In a single-column section, the traditional renderer advances to the next physical page.
- * Modern documents must use ColumnGroup and throw `DocsSectionUnsupportedDocumentFlavorError`.
+ * Modern documents must use ColumnGroup. Unspecified documents must resolve
+ * their flavor first. Both throw `DocsSectionUnsupportedDocumentFlavorError`.
* @example
* ```ts
* const fDocument = univerAPI.getActiveDocument();
- * if (fDocument && !fDocument.isModern()) {
+ * if (fDocument?.isTraditional()) {
* const paragraph = fDocument.findParagraphByText('Continue in next column');
* const offset = paragraph?.getInfo().startOffset;
* if (offset != null) {
diff --git a/packages/docs/src/facade/f-enum.ts b/packages/docs/src/facade/f-enum.ts
index 267dc3585a..df3d6a303e 100644
--- a/packages/docs/src/facade/f-enum.ts
+++ b/packages/docs/src/facade/f-enum.ts
@@ -14,11 +14,13 @@
* limitations under the License.
*/
-import { ColumnSeparatorType, SectionType } from '@univerjs/core';
+import { ColumnSeparatorType, DocumentFlavor, SectionType } from '@univerjs/core';
import { FEnum } from '@univerjs/core/facade';
/** @ignore */
export interface IFDocsEnumMixin {
+ /** Document layout flavors. */
+ DocumentFlavor: typeof DocumentFlavor;
/** OOXML-compatible section start types. */
SectionType: typeof SectionType;
/** Section column separator types. */
@@ -26,6 +28,10 @@ export interface IFDocsEnumMixin {
}
export class FDocsEnumMixin extends FEnum implements IFDocsEnumMixin {
+ override get DocumentFlavor(): typeof DocumentFlavor {
+ return DocumentFlavor;
+ }
+
override get SectionType(): typeof SectionType {
return SectionType;
}
diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.ts
index 1076ae1882..36409f9fbc 100644
--- a/packages/docs/src/index.ts
+++ b/packages/docs/src/index.ts
@@ -33,6 +33,7 @@ export type {
} 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 { UpdateDocumentParagraphStyleCommand } from './commands/commands/update-document-paragraph-style.command';
export { DeleteDocumentSectionBreakCommand, InsertDocumentColumnBreakCommand, InsertDocumentSectionBreakCommand, UpdateDocumentSectionCommand } from './commands/commands/update-document-section.command';
export type { IDeleteDocumentSectionBreakCommandParams, IDocumentSectionConfig, IDocumentSectionUpdate, IInsertDocumentColumnBreakCommandParams, IInsertDocumentSectionBreakCommandParams, IUpdateDocumentSectionCommandParams } from './commands/commands/update-document-section.command';
export { RichTextEditingMutation } from './commands/mutations/core-editing.mutation';
@@ -86,7 +87,8 @@ export {
} from './utils/custom-range-factory';
export { generateParagraphs } from './utils/paragraphs';
export { replaceSelectionFactory } from './utils/replace-selection-factory';
-export { createSectionColumnProperties, getSectionContentWidth } from './utils/section-columns';
+export { createSectionColumnProperties, getEffectiveSectionPageSetup, getSectionContentWidth } from './utils/section-columns';
+export type { IEffectiveSectionPageSetup } from './utils/section-columns';
export { getTopLevelSectionBreaks } from './utils/sections';
export { buildDocTransform, docDrawingPositionToTransform, transformToDocDrawingPosition } from './utils/transform-position';
export { consumeContentInsertRange, getContentInsertRange, isHeaderFooterSelection, normalizeTextRange } from './utils/util';
diff --git a/packages/docs/src/plugin.ts b/packages/docs/src/plugin.ts
index aa16fa92db..dafba1b2f1 100644
--- a/packages/docs/src/plugin.ts
+++ b/packages/docs/src/plugin.ts
@@ -29,6 +29,7 @@ import { DeleteTextCommand, InsertTextCommand, UpdateTextCommand } from './comma
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 { UpdateDocumentParagraphStyleCommand } from './commands/commands/update-document-paragraph-style.command';
import { DeleteDocumentSectionBreakCommand, InsertDocumentColumnBreakCommand, 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';
@@ -77,6 +78,7 @@ export class UniverDocsPlugin extends Plugin {
CreateHeaderFooterCommand,
SetDocumentDefaultParagraphStyleCommand,
SetSectionHeaderFooterLinkCommand,
+ UpdateDocumentParagraphStyleCommand,
UpdateDocumentSectionCommand,
InsertDocumentSectionBreakCommand,
InsertDocumentColumnBreakCommand,
diff --git a/packages/docs/src/utils/section-columns.ts b/packages/docs/src/utils/section-columns.ts
index 5034421881..0f5a6c1a73 100644
--- a/packages/docs/src/utils/section-columns.ts
+++ b/packages/docs/src/utils/section-columns.ts
@@ -14,18 +14,107 @@
* limitations under the License.
*/
-import type { IDocumentStyle, ISectionBreak, ISectionColumnProperties } from '@univerjs/core';
-import { PAGE_SIZE, PaperType } from '@univerjs/core';
+import type { IDocumentStyle, ISectionBreak, ISectionColumnProperties, PageOrientType } from '@univerjs/core';
+import { PAGE_SIZE, PageOrientType as PageOrient, PaperType, TRADITIONAL_DOCUMENT_DEFAULT_MARGIN } from '@univerjs/core';
+
+export interface IEffectiveSectionPageSetup {
+ pageSize: {
+ width: number;
+ height: number;
+ };
+ pageOrient: PageOrientType;
+ margins: {
+ top: number;
+ bottom: number;
+ left: number;
+ right: number;
+ };
+ contentSize: {
+ width: number;
+ height: number;
+ };
+ pageNumberStart?: number;
+}
+
+function resolveSectionValue<T>(
+ sectionValue: T | undefined,
+ documentValue: T | undefined,
+ fallback: T
+): T {
+ return sectionValue ?? documentValue ?? fallback;
+}
+
+function getEffectivePageSize(
+ documentStyle: IDocumentStyle | undefined,
+ section: ISectionBreak | undefined
+): IEffectiveSectionPageSetup['pageSize'] {
+ const fallback = PAGE_SIZE[PaperType.A4];
+ return {
+ width: resolveSectionValue(section?.pageSize?.width, documentStyle?.pageSize?.width, fallback.width),
+ height: resolveSectionValue(section?.pageSize?.height, documentStyle?.pageSize?.height, fallback.height),
+ };
+}
+
+function getEffectiveMargins(
+ documentStyle: IDocumentStyle | undefined,
+ section: ISectionBreak | undefined
+): IEffectiveSectionPageSetup['margins'] {
+ return {
+ top: resolveSectionValue(section?.marginTop, documentStyle?.marginTop, TRADITIONAL_DOCUMENT_DEFAULT_MARGIN),
+ bottom: resolveSectionValue(section?.marginBottom, documentStyle?.marginBottom, TRADITIONAL_DOCUMENT_DEFAULT_MARGIN),
+ left: resolveSectionValue(section?.marginLeft, documentStyle?.marginLeft, TRADITIONAL_DOCUMENT_DEFAULT_MARGIN),
+ right: resolveSectionValue(section?.marginRight, documentStyle?.marginRight, TRADITIONAL_DOCUMENT_DEFAULT_MARGIN),
+ };
+}
+
+function assertPositivePageSetup(
+ pageSize: IEffectiveSectionPageSetup['pageSize'],
+ contentSize: IEffectiveSectionPageSetup['contentSize']
+): void {
+ if (![pageSize.width, pageSize.height, contentSize.width, contentSize.height]
+ .every((value) => Number.isFinite(value) && value > 0)) {
+ throw new RangeError('Effective section page setup must leave a positive content area and use finite positive page dimensions.');
+ }
+}
+
+/** Resolves nominal traditional page geometry without requiring a renderer. */
+export function getEffectiveSectionPageSetup(
+ documentStyle: IDocumentStyle | undefined,
+ section: ISectionBreak | undefined
+): IEffectiveSectionPageSetup {
+ const pageSize = getEffectivePageSize(documentStyle, section);
+ const margins = getEffectiveMargins(documentStyle, section);
+ const contentSize = {
+ width: getSectionContentWidth(documentStyle, section),
+ height: pageSize.height - margins.top - margins.bottom,
+ };
+ assertPositivePageSetup(pageSize, contentSize);
+
+ const pageNumberStart = section?.pageNumberStart ?? documentStyle?.pageNumberStart;
+ return {
+ pageSize,
+ pageOrient: resolveSectionValue(section?.pageOrient, documentStyle?.pageOrient, PageOrient.PORTRAIT),
+ margins,
+ contentSize,
+ ...(pageNumberStart == null ? {} : { pageNumberStart }),
+ };
+}
/** Returns the usable horizontal layout width for a traditional section. */
export function getSectionContentWidth(
documentStyle: IDocumentStyle | undefined,
section: ISectionBreak | undefined
): number {
- const pageWidth = section?.pageSize?.width ?? documentStyle?.pageSize?.width ?? PAGE_SIZE[PaperType.A4].width;
+ const pageWidth = resolveSectionValue(
+ section?.pageSize?.width,
+ documentStyle?.pageSize?.width,
+ PAGE_SIZE[PaperType.A4].width
+ );
return Math.max(
0,
- pageWidth - (section?.marginLeft ?? documentStyle?.marginLeft ?? 72) - (section?.marginRight ?? documentStyle?.marginRight ?? 72)
+ pageWidth -
+ resolveSectionValue(section?.marginLeft, documentStyle?.marginLeft, TRADITIONAL_DOCUMENT_DEFAULT_MARGIN) -
+ resolveSectionValue(section?.marginRight, documentStyle?.marginRight, TRADITIONAL_DOCUMENT_DEFAULT_MARGIN)
);
}
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 4b4df85cbf..b4df81e8b7 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
@@ -110,6 +110,15 @@ function createLayoutContext(viewModel: DocumentViewModel): ILayoutContext {
paragraphConfigCache: new Map(),
sectionBreakConfigCache: new Map(),
paragraphsOpenNewPage: new Set(),
+ paginationMetrics: {
+ constrainedParagraphs: 0,
+ noConstraintParagraphs: 0,
+ measuredLineCount: 0,
+ retryCount: 0,
+ movedLineCount: 0,
+ keepNextScanCount: 0,
+ peakCheckpointLineCount: 0,
+ },
hyphen: Hyphen.getInstance(),
languageDetector: LanguageDetector.getInstance(),
} as ILayoutContext;
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 e4bfbf3bc0..2a2d7b308f 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
@@ -18,6 +18,7 @@ import type { IDocumentSkeletonPage } from '../../../../../../basics/i-document-
import {
AlignTypeH,
AlignTypeV,
+ BooleanNumber,
DataStreamTreeTokenType,
DocumentBlockRangeType,
DocumentFlavor,
@@ -46,6 +47,31 @@ function createContext() {
} as any;
}
+function paragraphLines(page: IDocumentSkeletonPage, paragraphIndex: number) {
+ return page.sections.flatMap((section) =>
+ section.columns.flatMap((column) =>
+ column.lines.filter((line) => line.paragraphIndex === paragraphIndex)
+ )
+ );
+}
+
+function paginationSignature(pages: IDocumentSkeletonPage[]) {
+ return pages.map((page) => ({
+ pageNumber: page.pageNumber,
+ breakType: page.breakType,
+ sections: page.sections.map((section) => ({
+ columns: section.columns.map((column) => ({
+ lines: column.lines.map((line) => ({
+ paragraphIndex: line.paragraphIndex,
+ lineIndex: line.lineIndex,
+ top: line.top,
+ divideCount: line.divides.length,
+ })),
+ })),
+ })),
+ }));
+}
+
describe('linebreaking', () => {
beforeEach(() => {
vi.stubGlobal('document', {
@@ -78,6 +104,701 @@ describe('linebreaking', () => {
expect(result[0].sections.length).toBeGreaterThan(0);
});
+ it('starts pageBreakBefore paragraphs on the next physical page without doubling a blank page', () => {
+ const { viewModel, ctx, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed(['First', 'Second'], {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ },
+ body: {
+ paragraphs: [
+ { startIndex: 5, paragraphId: 'first' },
+ {
+ startIndex: 12,
+ paragraphId: 'second',
+ paragraphStyle: { pageBreakBefore: BooleanNumber.TRUE },
+ },
+ ],
+ },
+ });
+ const [firstParagraph, secondParagraph] = sectionNode.children;
+ const firstPages = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, firstParagraph.content!, viewModel, firstParagraph, sectionBreakConfig),
+ curPage,
+ firstParagraph,
+ sectionBreakConfig,
+ null
+ );
+ const result = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, secondParagraph.content!, viewModel, secondParagraph, sectionBreakConfig),
+ firstPages[firstPages.length - 1],
+ secondParagraph,
+ sectionBreakConfig,
+ null
+ );
+
+ expect(result).toHaveLength(2);
+ expect(paragraphLines(result[0], secondParagraph.endIndex)).toHaveLength(0);
+ expect(paragraphLines(result[1], secondParagraph.endIndex).length).toBeGreaterThan(0);
+
+ const blankTestBed = createParagraphLayoutTestBed('Only', {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ },
+ body: {
+ paragraphs: [{
+ startIndex: 4,
+ paragraphId: 'only',
+ paragraphStyle: { pageBreakBefore: BooleanNumber.TRUE },
+ }],
+ },
+ });
+ const blankResult = lineBreaking(
+ blankTestBed.ctx,
+ blankTestBed.viewModel,
+ shaping(
+ blankTestBed.ctx,
+ blankTestBed.paragraphNode.content!,
+ blankTestBed.viewModel,
+ blankTestBed.paragraphNode,
+ blankTestBed.sectionBreakConfig
+ ),
+ blankTestBed.curPage,
+ blankTestBed.paragraphNode,
+ blankTestBed.sectionBreakConfig,
+ null
+ );
+ expect(blankResult).toHaveLength(1);
+ });
+
+ it('does not duplicate a page boundary already created by an explicit page break', () => {
+ const firstContent = `Before${DataStreamTreeTokenType.PAGE_BREAK}`;
+ const secondContent = 'Chapter';
+ const firstEnd = firstContent.length;
+ const secondEnd = firstEnd + 1 + secondContent.length;
+ const testBed = createSectionLayoutTestBed([firstContent, secondContent], {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ },
+ body: {
+ paragraphs: [
+ { startIndex: firstEnd, paragraphId: 'explicit-break' },
+ {
+ startIndex: secondEnd,
+ paragraphId: 'chapter',
+ paragraphStyle: { pageBreakBefore: BooleanNumber.TRUE },
+ },
+ ],
+ },
+ });
+ const [firstParagraph, secondParagraph] = testBed.sectionNode.children;
+ const firstPages = lineBreaking(
+ testBed.ctx,
+ testBed.viewModel,
+ shaping(
+ testBed.ctx,
+ firstParagraph.content!,
+ testBed.viewModel,
+ firstParagraph,
+ testBed.sectionBreakConfig
+ ),
+ testBed.curPage,
+ firstParagraph,
+ testBed.sectionBreakConfig,
+ null
+ );
+ const result = lineBreaking(
+ testBed.ctx,
+ testBed.viewModel,
+ shaping(
+ testBed.ctx,
+ secondParagraph.content!,
+ testBed.viewModel,
+ secondParagraph,
+ testBed.sectionBreakConfig
+ ),
+ firstPages.at(-1)!,
+ secondParagraph,
+ testBed.sectionBreakConfig,
+ null
+ );
+
+ expect(firstPages).toHaveLength(2);
+ expect(result).toHaveLength(1);
+ expect(paragraphLines(result[0], secondParagraph.endIndex).length).toBeGreaterThan(0);
+ });
+
+ it.each([
+ { name: 'modern', flavor: DocumentFlavor.MODERN },
+ { name: 'unspecified', flavor: DocumentFlavor.UNSPECIFIED },
+ ])('does not apply Word-compatible paragraph pagination to $name documents', ({ name, flavor }) => {
+ const contents = ['First', 'Second'];
+ const firstEnd = contents[0].length;
+ const secondEnd = firstEnd + 1 + contents[1].length;
+ const testBed = createSectionLayoutTestBed(contents, {
+ documentStyle: {
+ documentFlavor: flavor,
+ },
+ body: {
+ paragraphs: [
+ { startIndex: firstEnd, paragraphId: `${name}-first` },
+ {
+ startIndex: secondEnd,
+ paragraphId: `${name}-second`,
+ paragraphStyle: {
+ pageBreakBefore: BooleanNumber.TRUE,
+ keepLines: BooleanNumber.TRUE,
+ keepNext: BooleanNumber.TRUE,
+ widowControl: BooleanNumber.TRUE,
+ },
+ },
+ ],
+ },
+ });
+ const [firstParagraph, secondParagraph] = testBed.sectionNode.children;
+ const firstPages = lineBreaking(
+ testBed.ctx,
+ testBed.viewModel,
+ shaping(
+ testBed.ctx,
+ firstParagraph.content!,
+ testBed.viewModel,
+ firstParagraph,
+ testBed.sectionBreakConfig
+ ),
+ testBed.curPage,
+ firstParagraph,
+ testBed.sectionBreakConfig,
+ null
+ );
+ const result = lineBreaking(
+ testBed.ctx,
+ testBed.viewModel,
+ shaping(
+ testBed.ctx,
+ secondParagraph.content!,
+ testBed.viewModel,
+ secondParagraph,
+ testBed.sectionBreakConfig
+ ),
+ firstPages.at(-1)!,
+ secondParagraph,
+ testBed.sectionBreakConfig,
+ null
+ );
+
+ expect(firstPages).toHaveLength(1);
+ expect(result).toHaveLength(1);
+ expect(paragraphLines(result[0], firstParagraph.endIndex).length).toBeGreaterThan(0);
+ expect(paragraphLines(result[0], secondParagraph.endIndex).length).toBeGreaterThan(0);
+ });
+
+ it('advances pageBreakBefore past every column on the current physical page', () => {
+ const contents = ['First column', 'New physical page'];
+ const firstEnd = contents[0].length;
+ const secondEnd = firstEnd + 1 + contents[1].length;
+ const { viewModel, ctx, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed(contents, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ },
+ body: {
+ paragraphs: [
+ { startIndex: firstEnd, paragraphId: 'first-column' },
+ {
+ startIndex: secondEnd,
+ paragraphId: 'new-physical-page',
+ paragraphStyle: { pageBreakBefore: BooleanNumber.TRUE },
+ },
+ ],
+ sectionBreaks: [{
+ sectionId: 'two-column-section',
+ startIndex: secondEnd + 1,
+ columnProperties: [
+ { width: 170, paddingEnd: 20 },
+ { width: 170, paddingEnd: 0 },
+ ],
+ }],
+ },
+ });
+ const [firstParagraph, secondParagraph] = sectionNode.children;
+ const firstPages = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, firstParagraph.content!, viewModel, firstParagraph, sectionBreakConfig),
+ curPage,
+ firstParagraph,
+ sectionBreakConfig,
+ null
+ );
+ const result = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, secondParagraph.content!, viewModel, secondParagraph, sectionBreakConfig),
+ firstPages.at(-1)!,
+ secondParagraph,
+ sectionBreakConfig,
+ null
+ );
+
+ expect(result).toHaveLength(2);
+ expect(paragraphLines(result[0], secondParagraph.endIndex)).toHaveLength(0);
+ expect(paragraphLines(result[1], secondParagraph.endIndex).length).toBeGreaterThan(0);
+ expect(result[0].sections[0].columns).toHaveLength(2);
+ });
+
+ it('moves a split keepLines paragraph when it fits on an empty page', () => {
+ const contents = ['Filler filler filler filler', 'One two three four five'];
+ const firstEnd = contents[0].length;
+ const secondEnd = firstEnd + 1 + contents[1].length;
+ const { viewModel, ctx, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed(contents, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 120, height: 100 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ body: {
+ paragraphs: [
+ { startIndex: firstEnd, paragraphId: 'filler' },
+ {
+ startIndex: secondEnd,
+ paragraphId: 'kept',
+ paragraphStyle: { keepLines: BooleanNumber.TRUE },
+ },
+ ],
+ },
+ });
+ const [firstParagraph, secondParagraph] = sectionNode.children;
+ const firstPages = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, firstParagraph.content!, viewModel, firstParagraph, sectionBreakConfig),
+ curPage,
+ firstParagraph,
+ sectionBreakConfig,
+ null
+ );
+ const result = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, secondParagraph.content!, viewModel, secondParagraph, sectionBreakConfig),
+ firstPages[firstPages.length - 1],
+ secondParagraph,
+ sectionBreakConfig,
+ null
+ );
+
+ expect(result.length).toBeGreaterThanOrEqual(2);
+ expect(paragraphLines(result[0], secondParagraph.endIndex)).toHaveLength(0);
+ expect(paragraphLines(result[1], secondParagraph.endIndex).length).toBeGreaterThan(1);
+ });
+
+ it('keeps a heading tail with the following paragraph when the pair fits on an empty page', () => {
+ const contents = [
+ 'Prefix prefix prefix prefix prefix prefix',
+ 'Heading',
+ 'Following paragraph words',
+ ];
+ let offset = 0;
+ const paragraphs = contents.map((content, index) => {
+ offset += content.length;
+ const paragraph = {
+ startIndex: offset,
+ paragraphId: `paragraph-${index}`,
+ ...(index === 1
+ ? { paragraphStyle: { keepNext: BooleanNumber.TRUE } }
+ : {}),
+ };
+ offset += 1;
+ return paragraph;
+ });
+ const { viewModel, ctx, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed(contents, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 120, height: 100 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ body: { paragraphs },
+ });
+
+ let currentPage = curPage;
+ let lastResult: IDocumentSkeletonPage[] = [curPage];
+ for (const paragraph of sectionNode.children) {
+ lastResult = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, paragraph.content!, viewModel, paragraph, sectionBreakConfig),
+ currentPage,
+ paragraph,
+ sectionBreakConfig,
+ null
+ );
+ currentPage = lastResult[lastResult.length - 1];
+ }
+
+ const headingIndex = sectionNode.children[1].endIndex;
+ const followingIndex = sectionNode.children[2].endIndex;
+ expect(lastResult.length).toBeGreaterThanOrEqual(2);
+ expect(paragraphLines(lastResult[0], headingIndex)).toHaveLength(0);
+ expect(paragraphLines(lastResult[1], headingIndex).length).toBeGreaterThan(0);
+ expect(paragraphLines(lastResult[1], followingIndex).length).toBeGreaterThan(0);
+ });
+
+ it('moves a bounded keepNext chain and stops at a manual break', () => {
+ const contents = [
+ 'Prefix prefix prefix prefix prefix prefix',
+ 'Heading one',
+ 'Heading two',
+ 'Following paragraph words',
+ ];
+ let offset = 0;
+ const paragraphs = contents.map((content, index) => {
+ offset += content.length;
+ const paragraph = {
+ startIndex: offset,
+ paragraphId: `keep-chain-${index}`,
+ ...(index === 1 || index === 2
+ ? { paragraphStyle: { keepNext: BooleanNumber.TRUE } }
+ : {}),
+ };
+ offset += 1;
+ return paragraph;
+ });
+ const testBed = createSectionLayoutTestBed(contents, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 220, height: 100 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ body: { paragraphs },
+ });
+
+ let currentPage = testBed.curPage;
+ let result = [currentPage];
+ for (const paragraph of testBed.sectionNode.children) {
+ result = lineBreaking(
+ testBed.ctx,
+ testBed.viewModel,
+ shaping(
+ testBed.ctx,
+ paragraph.content!,
+ testBed.viewModel,
+ paragraph,
+ testBed.sectionBreakConfig
+ ),
+ currentPage,
+ paragraph,
+ testBed.sectionBreakConfig,
+ null
+ );
+ currentPage = result.at(-1)!;
+ }
+ for (const paragraph of testBed.sectionNode.children.slice(1)) {
+ expect(paragraphLines(result[0], paragraph.endIndex)).toHaveLength(0);
+ expect(paragraphLines(result[1], paragraph.endIndex).length).toBeGreaterThan(0);
+ }
+
+ const manualContent = `After${DataStreamTreeTokenType.PAGE_BREAK}break`;
+ const manualBed = createSectionLayoutTestBed(['Heading', manualContent], {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ },
+ body: {
+ paragraphs: [
+ {
+ startIndex: 'Heading'.length,
+ paragraphId: 'manual-heading',
+ paragraphStyle: { keepNext: BooleanNumber.TRUE },
+ },
+ {
+ startIndex: 'Heading'.length + 1 + manualContent.length,
+ paragraphId: 'manual-following',
+ },
+ ],
+ },
+ });
+ const [manualHeading, manualFollowing] = manualBed.sectionNode.children;
+ const headingPages = lineBreaking(
+ manualBed.ctx,
+ manualBed.viewModel,
+ shaping(
+ manualBed.ctx,
+ manualHeading.content!,
+ manualBed.viewModel,
+ manualHeading,
+ manualBed.sectionBreakConfig
+ ),
+ manualBed.curPage,
+ manualHeading,
+ manualBed.sectionBreakConfig,
+ null
+ );
+ const manualResult = lineBreaking(
+ manualBed.ctx,
+ manualBed.viewModel,
+ shaping(
+ manualBed.ctx,
+ manualFollowing.content!,
+ manualBed.viewModel,
+ manualFollowing,
+ manualBed.sectionBreakConfig
+ ),
+ headingPages.at(-1)!,
+ manualFollowing,
+ manualBed.sectionBreakConfig,
+ null
+ );
+ expect(paragraphLines(manualResult[0], manualHeading.endIndex).length).toBeGreaterThan(0);
+ });
+
+ it('caps keepNext look-behind at 32 paragraphs for an oversized chain', () => {
+ const headings = Array.from({ length: 40 }, (_, index) => `H${index}`);
+ const contents = [
+ 'Prefix '.repeat(10),
+ ...headings,
+ 'Following paragraph words '.repeat(8),
+ ];
+ let offset = 0;
+ const paragraphs = contents.map((content, index) => {
+ offset += content.length;
+ const paragraph = {
+ startIndex: offset,
+ paragraphId: `bounded-chain-${index}`,
+ ...(index > 0 && index <= headings.length
+ ? { paragraphStyle: { keepNext: BooleanNumber.TRUE } }
+ : {}),
+ };
+ offset += 1;
+ return paragraph;
+ });
+ const testBed = createSectionLayoutTestBed(contents, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 140, height: 640 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ body: { paragraphs },
+ });
+
+ let currentPage = testBed.curPage;
+ let result = [currentPage];
+ for (const paragraph of testBed.sectionNode.children) {
+ result = lineBreaking(
+ testBed.ctx,
+ testBed.viewModel,
+ shaping(
+ testBed.ctx,
+ paragraph.content!,
+ testBed.viewModel,
+ paragraph,
+ testBed.sectionBreakConfig
+ ),
+ currentPage,
+ paragraph,
+ testBed.sectionBreakConfig,
+ null
+ );
+ currentPage = result.at(-1)!;
+ }
+
+ expect(result.length).toBeGreaterThanOrEqual(2);
+ expect(testBed.ctx.paginationMetrics?.keepNextScanCount).toBeLessThanOrEqual(32);
+ expect(testBed.ctx.paginationMetrics?.retryCount).toBeLessThanOrEqual(contents.length);
+ });
+
+ it('avoids a single natural widow line and lets oversized keepLines paragraphs terminate', () => {
+ const content = 'One two three four five six seven eight nine ten eleven twelve';
+ const widowBed = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 120, height: 85 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ body: {
+ paragraphs: [{
+ startIndex: content.length,
+ paragraphId: 'widow',
+ paragraphStyle: { widowControl: BooleanNumber.TRUE },
+ }],
+ },
+ });
+ const widowResult = lineBreaking(
+ widowBed.ctx,
+ widowBed.viewModel,
+ shaping(
+ widowBed.ctx,
+ widowBed.paragraphNode.content!,
+ widowBed.viewModel,
+ widowBed.paragraphNode,
+ widowBed.sectionBreakConfig
+ ),
+ widowBed.curPage,
+ widowBed.paragraphNode,
+ widowBed.sectionBreakConfig,
+ null
+ );
+ const widowCounts = widowResult.map((page) =>
+ paragraphLines(page, widowBed.paragraphNode.endIndex).length);
+ expect(widowCounts.filter(Boolean)).not.toContain(1);
+
+ const oversizedContent = content.repeat(4);
+ const oversizedBed = createParagraphLayoutTestBed(oversizedContent, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 120, height: 85 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ body: {
+ paragraphs: [{
+ startIndex: oversizedContent.length,
+ paragraphId: 'oversized',
+ paragraphStyle: { keepLines: BooleanNumber.TRUE },
+ }],
+ },
+ });
+ const oversizedResult = lineBreaking(
+ oversizedBed.ctx,
+ oversizedBed.viewModel,
+ shaping(
+ oversizedBed.ctx,
+ oversizedBed.paragraphNode.content!,
+ oversizedBed.viewModel,
+ oversizedBed.paragraphNode,
+ oversizedBed.sectionBreakConfig
+ ),
+ oversizedBed.curPage,
+ oversizedBed.paragraphNode,
+ oversizedBed.sectionBreakConfig,
+ null
+ );
+ expect(oversizedResult.length).toBeGreaterThan(2);
+ expect(oversizedResult.every((page) =>
+ paragraphLines(page, oversizedBed.paragraphNode.endIndex).length > 0)).toBe(true);
+ });
+
+ it('does not soften a manual page break with keep or widow constraints', () => {
+ const content = `Before${DataStreamTreeTokenType.PAGE_BREAK}After`;
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ },
+ body: {
+ paragraphs: [{
+ startIndex: content.length,
+ paragraphId: 'manual-break',
+ paragraphStyle: {
+ keepLines: BooleanNumber.TRUE,
+ keepNext: BooleanNumber.TRUE,
+ widowControl: BooleanNumber.TRUE,
+ },
+ }],
+ },
+ });
+ const result = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig),
+ curPage,
+ paragraphNode,
+ sectionBreakConfig,
+ null
+ );
+
+ expect(result).toHaveLength(2);
+ expect(paragraphLines(result[0], paragraphNode.endIndex).length).toBeGreaterThan(0);
+ expect(paragraphLines(result[1], paragraphNode.endIndex).length).toBeGreaterThan(0);
+ });
+
+ it('keeps pagination checkpoints bounded and produces a deterministic structure', () => {
+ const runLayout = () => {
+ const contents = [
+ 'Prefix prefix prefix prefix prefix prefix',
+ 'Heading',
+ 'Following paragraph words',
+ ];
+ let offset = 0;
+ const paragraphs = contents.map((content, index) => {
+ offset += content.length;
+ const paragraph = {
+ startIndex: offset,
+ paragraphId: `deterministic-${index}`,
+ ...(index === 1
+ ? { paragraphStyle: { keepNext: BooleanNumber.TRUE } }
+ : {}),
+ };
+ offset += 1;
+ return paragraph;
+ });
+ const testBed = createSectionLayoutTestBed(contents, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 120, height: 100 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ body: { paragraphs },
+ });
+ let currentPage = testBed.curPage;
+ let result = [currentPage];
+ for (const paragraph of testBed.sectionNode.children) {
+ result = lineBreaking(
+ testBed.ctx,
+ testBed.viewModel,
+ shaping(
+ testBed.ctx,
+ paragraph.content!,
+ testBed.viewModel,
+ paragraph,
+ testBed.sectionBreakConfig
+ ),
+ currentPage,
+ paragraph,
+ testBed.sectionBreakConfig,
+ null
+ );
+ currentPage = result.at(-1)!;
+ }
+ return {
+ signature: paginationSignature(result),
+ metrics: testBed.ctx.paginationMetrics!,
+ paragraphCount: testBed.sectionNode.children.length,
+ };
+ };
+
+ const first = runLayout();
+ const second = runLayout();
+
+ expect(second.signature).toEqual(first.signature);
+ expect(first.metrics.noConstraintParagraphs).toBeGreaterThan(0);
+ expect(first.metrics.constrainedParagraphs).toBeGreaterThan(0);
+ expect(first.metrics.retryCount).toBeLessThanOrEqual(first.paragraphCount);
+ expect(first.metrics.keepNextScanCount).toBeLessThanOrEqual(32);
+ expect(first.metrics.measuredLineCount).toBeGreaterThanOrEqual(first.metrics.movedLineCount);
+ expect(first.metrics.peakCheckpointLineCount).toBeLessThanOrEqual(first.metrics.measuredLineCount);
+ });
+
it('reserves bottom-border clearance when paragraph spacing is smaller', () => {
const content = 'Rule';
const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
@@ -1724,7 +2445,9 @@ describe('linebreaking', () => {
null
);
- expect(ctx.paragraphConfigCache.get('segment-1')?.get(3)?.paragraphStyle).toEqual({});
+ expect(ctx.paragraphConfigCache.get('segment-1')?.get(3)?.paragraphStyle).toEqual({
+ widowControl: BooleanNumber.TRUE,
+ });
expect(ctx.paragraphConfigCache.get('segment-1')?.get(3)?.useWordStyleLineHeight).toBe(true);
expect(paragraphStyle).toEqual({});
});
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts
index 98fdfac550..b9387c1388 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts
@@ -17,6 +17,7 @@
import type {
IBullet,
IDocDrawingBase,
+ IDocStyles,
IDocumentBody,
IDocumentStyle,
IDrawings,
@@ -39,6 +40,7 @@ import type { DocumentViewModel } from '../../../view-model/document-view-model'
import type { ILayoutContext } from '../../tools';
import type { IShapedText } from './shaping';
import {
+ BooleanNumber,
DataStreamTreeTokenType,
DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING,
DocumentBlockRangeType,
@@ -59,6 +61,7 @@ const BLOCK_LAYOUT_OUTER_SPACING_MAP = new Map([
[DocumentBlockRangeType.CODE, 32],
[DocumentBlockRangeType.QUOTE, 24],
]);
+const MAX_KEEP_NEXT_LOOKAHEAD = 32;
function _endsWithToken(text: string, glyphs: IDocumentSkeletonGlyph[], token: DataStreamTreeTokenType): boolean {
return text.endsWith(token) || glyphs[glyphs.length - 1]?.raw === token || glyphs[glyphs.length - 1]?.streamType === token;
@@ -293,12 +296,19 @@ function _applyBlockRangeLayoutParagraphStyle(
paragraph: IParagraph,
paragraphStyle: IParagraphStyle,
documentStyle: Nullable<IDocumentStyle>,
- useLegacyModernDefaults: boolean
+ useLegacyModernDefaults: boolean,
+ styles: IDocStyles | undefined,
+ paragraphStyleId: string | undefined
): IParagraphStyle {
const blockRanges = body?.blockRanges;
+ const resolveOptions = {
+ useLegacyModernDefaults,
+ styles,
+ paragraphStyleId,
+ };
if (!blockRanges?.length) {
- return resolveDocumentParagraphStyle(documentStyle, paragraphStyle, { useLegacyModernDefaults });
+ return resolveDocumentParagraphStyle(documentStyle, paragraphStyle, resolveOptions);
}
const blockRange = blockRanges.find((range) =>
@@ -308,12 +318,12 @@ function _applyBlockRangeLayoutParagraphStyle(
);
if (!blockRange) {
- return resolveDocumentParagraphStyle(documentStyle, paragraphStyle, { useLegacyModernDefaults });
+ return resolveDocumentParagraphStyle(documentStyle, paragraphStyle, resolveOptions);
}
const style = resolveDocumentParagraphStyle(documentStyle, paragraphStyle, {
+ ...resolveOptions,
excludeDocumentOuterSpacing: true,
- useLegacyModernDefaults,
});
// Keep the existing block line-height fallback when neither the document
@@ -432,6 +442,257 @@ function _getNextPageNumber(lastPage: IDocumentSkeletonPage) {
return lastPage.pageNumber + 1;
}
+interface IParagraphLineRef {
+ page: IDocumentSkeletonPage;
+ column: IDocumentSkeletonColumn;
+ line: IDocumentSkeletonPage['sections'][number]['columns'][number]['lines'][number];
+}
+
+function _getParagraphLineRefs(
+ pages: IDocumentSkeletonPage[],
+ paragraphIndex: number
+): IParagraphLineRef[] {
+ const refs: IParagraphLineRef[] = [];
+ for (const page of pages) {
+ for (const section of page.sections ?? []) {
+ for (const column of section.columns) {
+ for (const line of column.lines) {
+ if (line.paragraphIndex === paragraphIndex) {
+ refs.push({ page, column, line });
+ }
+ }
+ }
+ }
+ }
+ return refs;
+}
+
+function _hasPageContent(page: IDocumentSkeletonPage): boolean {
+ return (page.sections ?? []).some((section) =>
+ section.columns.some((column) => !isBlankColumn(column))
+ ) || (page.skeTables?.size ?? 0) > 0;
+}
+
+function _hasOnlyExplicitPageBoundaryMarkers(page: IDocumentSkeletonPage): boolean {
+ if ((page.skeTables?.size ?? 0) > 0) {
+ return false;
+ }
+ return (page.sections ?? []).every((section) =>
+ section.columns.every((column) =>
+ column.lines.every((line) =>
+ line.divides.every((divide) =>
+ divide.glyphGroup.every(({ raw, streamType }) =>
+ raw === DataStreamTreeTokenType.PARAGRAPH ||
+ streamType === DataStreamTreeTokenType.PARAGRAPH ||
+ raw === DataStreamTreeTokenType.PAGE_BREAK ||
+ streamType === DataStreamTreeTokenType.PAGE_BREAK
+ )
+ )
+ )
+ )
+ );
+}
+
+function _lineSpanHeight(lines: IParagraphLineRef['line'][]): number {
+ if (lines.length === 0) {
+ return 0;
+ }
+ const firstTop = Math.min(...lines.map((line) => line.top));
+ return Math.max(...lines.map((line) =>
+ line.top + line.lineHeight + Math.max(0, line.spaceBelowApply ?? 0)
+ )) - firstTop;
+}
+
+function _columnUsedHeight(column: IDocumentSkeletonColumn): number {
+ return _lineSpanHeight(column.lines);
+}
+
+function _reindexColumnLines(column: IDocumentSkeletonColumn): void {
+ column.lines.forEach((line, index) => {
+ line.lineIndex = index;
+ line.parent = column;
+ });
+}
+
+function _prependLines(
+ sourceColumn: IDocumentSkeletonColumn,
+ targetColumn: IDocumentSkeletonColumn,
+ lines: IParagraphLineRef['line'][]
+): number {
+ if (lines.length === 0 || lines.some((line) => !sourceColumn.lines.includes(line))) {
+ return 0;
+ }
+ const movedHeight = _lineSpanHeight(lines);
+ const targetHeight = targetColumn.parent?.height ?? Number.POSITIVE_INFINITY;
+ if (movedHeight + _columnUsedHeight(targetColumn) > targetHeight) {
+ return 0;
+ }
+
+ const firstTop = Math.min(...lines.map((line) => line.top));
+ const moved = lines.map((line) => {
+ line.top -= firstTop;
+ return line;
+ });
+ const movedSet = new Set(moved);
+ sourceColumn.lines = sourceColumn.lines.filter((line) => !movedSet.has(line));
+ for (const line of targetColumn.lines) {
+ line.top += movedHeight;
+ }
+ targetColumn.lines.unshift(...moved);
+ sourceColumn.isFull = false;
+ _reindexColumnLines(sourceColumn);
+ _reindexColumnLines(targetColumn);
+ return moved.length;
+}
+
+function _hasExplicitStructuralBreak(shapedTextList: IShapedText[]): boolean {
+ return shapedTextList.some(({ text, glyphs }) =>
+ _endsWithToken(text, glyphs, DataStreamTreeTokenType.PAGE_BREAK) ||
+ _endsWithToken(text, glyphs, DataStreamTreeTokenType.COLUMN_BREAK)
+ );
+}
+
+function _applyKeepLines(
+ pages: IDocumentSkeletonPage[],
+ paragraphIndex: number,
+ metrics: ILayoutContext['paginationMetrics']
+): number {
+ const refs = _getParagraphLineRefs(pages, paragraphIndex);
+ if (metrics) {
+ metrics.measuredLineCount += refs.length;
+ metrics.peakCheckpointLineCount = Math.max(metrics.peakCheckpointLineCount, refs.length);
+ }
+ const paragraphPages = [...new Set(refs.map(({ page }) => page))];
+ if (paragraphPages.length !== 2 ||
+ paragraphPages.some((page) => page.sections.some((section) => section.columns.length !== 1))) {
+ return 0;
+ }
+
+ const sourceRefs = refs.filter(({ page }) => page === paragraphPages[0]);
+ const targetRefs = refs.filter(({ page }) => page === paragraphPages[1]);
+ const sourceColumns = [...new Set(sourceRefs.map(({ column }) => column))];
+ const targetColumns = [...new Set(targetRefs.map(({ column }) => column))];
+ if (sourceColumns.length !== 1 || targetColumns.length !== 1) {
+ return 0;
+ }
+ const movedLineCount = _prependLines(
+ sourceColumns[0],
+ targetColumns[0],
+ sourceRefs.map(({ line }) => line)
+ );
+ if (metrics && movedLineCount > 0) {
+ metrics.retryCount += 1;
+ metrics.movedLineCount += movedLineCount;
+ }
+ return movedLineCount;
+}
+
+function _applyKeepNext(
+ pages: IDocumentSkeletonPage[],
+ originalPage: IDocumentSkeletonPage,
+ paragraphIndex: number,
+ paragraphConfigCache: Map<number, IParagraphConfig>,
+ metrics: ILayoutContext['paginationMetrics']
+): number {
+ const refs = _getParagraphLineRefs(pages, paragraphIndex);
+ if (metrics) {
+ metrics.measuredLineCount += refs.length;
+ metrics.peakCheckpointLineCount = Math.max(metrics.peakCheckpointLineCount, refs.length);
+ }
+ const targetPages = [...new Set(refs.map(({ page }) => page))];
+ if (refs.length === 0 || targetPages.length !== 1 || targetPages[0] === originalPage ||
+ targetPages[0].breakType === BreakType.PAGE ||
+ targetPages[0].sections.some((section) => section.columns.length !== 1)) {
+ return 0;
+ }
+
+ if (!originalPage.sections?.length) {
+ return 0;
+ }
+ const sourceSection = getLastSection(originalPage);
+ const sourceColumn = sourceSection?.columns.findLast((column) => column.lines.length > 0);
+ const targetColumn = refs[0].column;
+ if (!sourceColumn || refs.some(({ column }) => column !== targetColumn)) {
+ return 0;
+ }
+
+ let start = sourceColumn.lines.length;
+ let scannedParagraphs = 0;
+ while (start > 0 && scannedParagraphs < MAX_KEEP_NEXT_LOOKAHEAD) {
+ const paragraph = sourceColumn.lines[start - 1].paragraphIndex;
+ if (paragraphConfigCache.get(paragraph)?.paragraphStyle?.keepNext !== BooleanNumber.TRUE) {
+ break;
+ }
+ scannedParagraphs += 1;
+ const paragraphStart = sourceColumn.lines.findLastIndex((line, index) =>
+ index < start && line.paragraphIndex !== paragraph
+ ) + 1;
+ const pageRefs = _getParagraphLineRefs([originalPage], paragraph);
+ if (metrics) {
+ metrics.measuredLineCount += pageRefs.length;
+ metrics.peakCheckpointLineCount = Math.max(metrics.peakCheckpointLineCount, pageRefs.length);
+ }
+ const tailLineCount = start - paragraphStart;
+ if (pageRefs.length !== tailLineCount ||
+ pageRefs.some(({ column }) => column !== sourceColumn)) {
+ break;
+ }
+ start = paragraphStart;
+ }
+ if (metrics) {
+ metrics.keepNextScanCount += scannedParagraphs;
+ }
+ if (start === sourceColumn.lines.length) {
+ return 0;
+ }
+ const movedLineCount = _prependLines(sourceColumn, targetColumn, sourceColumn.lines.slice(start));
+ if (metrics && movedLineCount > 0) {
+ metrics.retryCount += 1;
+ metrics.movedLineCount += movedLineCount;
+ }
+ return movedLineCount;
+}
+
+function _applyWidowControl(
+ pages: IDocumentSkeletonPage[],
+ paragraphIndex: number,
+ metrics: ILayoutContext['paginationMetrics']
+): number {
+ const refs = _getParagraphLineRefs(pages, paragraphIndex);
+ if (metrics) {
+ metrics.measuredLineCount += refs.length;
+ metrics.peakCheckpointLineCount = Math.max(metrics.peakCheckpointLineCount, refs.length);
+ }
+ const paragraphPages = [...new Set(refs.map(({ page }) => page))];
+ if (paragraphPages.length < 2 ||
+ paragraphPages.some((page) => page.sections.some((section) => section.columns.length !== 1))) {
+ return 0;
+ }
+
+ const sourcePage = paragraphPages[paragraphPages.length - 2];
+ const targetPage = paragraphPages[paragraphPages.length - 1];
+ const sourceRefs = refs.filter(({ page }) => page === sourcePage);
+ const targetRefs = refs.filter(({ page }) => page === targetPage);
+ if (sourceRefs.length === 1 && targetRefs.length >= 2) {
+ const movedLineCount = _prependLines(sourceRefs[0].column, targetRefs[0].column, [sourceRefs[0].line]);
+ if (metrics && movedLineCount > 0) {
+ metrics.retryCount += 1;
+ metrics.movedLineCount += movedLineCount;
+ }
+ return movedLineCount;
+ }
+ if (targetRefs.length === 1 && sourceRefs.length >= 3) {
+ const line = sourceRefs[sourceRefs.length - 1];
+ const movedLineCount = _prependLines(line.column, targetRefs[0].column, [line.line]);
+ if (metrics && movedLineCount > 0) {
+ metrics.retryCount += 1;
+ metrics.movedLineCount += movedLineCount;
+ }
+ return movedLineCount;
+ }
+ return 0;
+}
+
export function lineBreaking(
ctx: ILayoutContext,
viewModel: DocumentViewModel,
@@ -454,7 +715,8 @@ export function lineBreaking(
const paragraph = viewModel.getParagraph(endIndex) || { startIndex: 0, paragraphId: 'para_render_fallback' };
const { paragraphStyle = {}, bullet } = paragraph;
- const documentStyle = viewModel.getSnapshot?.()?.documentStyle;
+ const documentSnapshot = viewModel.getSnapshot?.();
+ const documentStyle = documentSnapshot?.documentStyle;
const documentCompatibilityPolicy = sectionBreakConfig.documentCompatibilityPolicy ??
getDocumentCompatibilityPolicy(documentStyle?.documentFlavor);
const shouldApplyDocumentDefaults = documentCompatibilityPolicy.applyDocumentDefaultParagraphStyle;
@@ -479,7 +741,9 @@ export function lineBreaking(
paragraph,
paragraphStyle,
documentStyle,
- shouldApplyDocumentDefaults
+ shouldApplyDocumentDefaults,
+ documentSnapshot?.styles,
+ paragraph.styleId
);
const borderBottom = resolvedParagraphStyle.borderBottom;
@@ -567,6 +831,25 @@ export function lineBreaking(
segmentParagraphCache.set(endIndex, paragraphConfig);
let allPages = [curPage];
+ const explicitStructuralBreak = _hasExplicitStructuralBreak(shapedTextList);
+ const traditionalPagination = isTraditionalDocumentCompatibility(documentCompatibilityPolicy);
+ const forcePageBreakBefore =
+ traditionalPagination &&
+ resolvedParagraphStyle.pageBreakBefore === BooleanNumber.TRUE &&
+ _hasPageContent(curPage) &&
+ !_hasOnlyExplicitPageBoundaryMarkers(curPage);
+ if (forcePageBreakBefore) {
+ allPages.push(
+ createSkeletonPage(
+ ctx,
+ sectionBreakConfig,
+ skeletonResourceReference,
+ _getNextPageNumber(curPage),
+ BreakType.PAGE
+ )
+ );
+ ctx.paragraphsOpenNewPage.add(endIndex);
+ }
let isParagraphFirstShapedText = true; // First shaped text
let shapedTextOffset = 0;
for (const [_index, { text, glyphs, breakPointType }] of _mergeAdjacentCustomBlockShapedTexts(shapedTextList, paragraphNonInlineSkeDrawingsByBlockId).entries()) {
@@ -666,6 +949,64 @@ export function lineBreaking(
shapedTextOffset += textGlyphCount;
}
+ const needsPaginationCheckpoint =
+ forcePageBreakBefore ||
+ (
+ !explicitStructuralBreak &&
+ tableSkeleton == null &&
+ paragraphNonInlineSkeDrawingsByBlockId.size === 0 &&
+ (
+ resolvedParagraphStyle.keepLines === BooleanNumber.TRUE ||
+ (
+ allPages.length > 1 &&
+ (
+ resolvedParagraphStyle.widowControl === BooleanNumber.TRUE ||
+ segmentParagraphCache.size > 1
+ )
+ )
+ )
+ );
+ if (traditionalPagination && ctx.paginationMetrics) {
+ if (needsPaginationCheckpoint) {
+ ctx.paginationMetrics.constrainedParagraphs += 1;
+ } else {
+ ctx.paginationMetrics.noConstraintParagraphs += 1;
+ }
+ }
+
+ if (traditionalPagination &&
+ !explicitStructuralBreak &&
+ !forcePageBreakBefore &&
+ tableSkeleton == null &&
+ paragraphNonInlineSkeDrawingsByBlockId.size === 0) {
+ // Apply Word-compatible soft constraints from strongest to weakest.
+ // Each helper only relocates already-shaped local lines and remains bounded.
+ if (resolvedParagraphStyle.keepLines === BooleanNumber.TRUE &&
+ _applyKeepLines(allPages, endIndex, ctx.paginationMetrics) > 0) {
+ ctx.paragraphsOpenNewPage.add(endIndex);
+ }
+ const keepNextMoved = allPages.length > 1
+ ? _applyKeepNext(allPages, curPage, endIndex, segmentParagraphCache, ctx.paginationMetrics)
+ : 0;
+ if (keepNextMoved > 0) {
+ ctx.paragraphsOpenNewPage.add(endIndex);
+ }
+ let widowMoved = 0;
+ if (
+ allPages.length > 1 &&
+ resolvedParagraphStyle.widowControl === BooleanNumber.TRUE
+ ) {
+ widowMoved = _applyWidowControl(allPages, endIndex, ctx.paginationMetrics);
+ }
+ // A widow adjustment must not orphan a stronger keep-next predecessor.
+ // Re-check only when the first keep-next pass made no move.
+ if (widowMoved > 0 &&
+ keepNextMoved === 0 &&
+ _applyKeepNext(allPages, curPage, endIndex, segmentParagraphCache, ctx.paginationMetrics) > 0) {
+ ctx.paragraphsOpenNewPage.add(endIndex);
+ }
+ }
+
return allPages;
}
diff --git a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
index 83cbcf2d7d..1f64b05358 100644
--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
@@ -24,7 +24,7 @@ import type {
import type { IDocsConfig, INodeInfo, INodePosition, INodeSearch } from '../../../basics/interfaces';
import type { IViewportInfo, Vector2 } from '../../../basics/vector2';
import type { DocumentViewModel } from '../view-model/document-view-model';
-import type { ILayoutContext } from './tools';
+import type { IDocumentPaginationMetrics, ILayoutContext } from './tools';
import { DataStreamTreeTokenType, PRESET_LIST_TYPE, SectionType, Skeleton } from '@univerjs/core';
import { Subject } from 'rxjs';
import {
@@ -308,6 +308,8 @@ export class DocumentSkeleton extends Skeleton {
private _initialWidth = 0;
+ private _paginationMetrics: Nullable<IDocumentPaginationMetrics> = null;
+
constructor(
private _docViewModel: DocumentViewModel,
localeService: LocaleService
@@ -344,6 +346,7 @@ export class DocumentSkeleton extends Skeleton {
// const start = +new Date();
this._skeletonData = this._createSkeleton(ctx, bounds);
+ this._paginationMetrics = ctx.paginationMetrics ?? null;
// console.log('skeleton calculate cost', +new Date() - start);
this._dirty$.next(true);
}
@@ -352,6 +355,14 @@ export class DocumentSkeleton extends Skeleton {
return this._skeletonData;
}
+ /**
+ * Returns a cloned snapshot of the most recent layout's bounded pagination counters.
+ * These diagnostics describe renderer work and are not part of the document model.
+ */
+ getPaginationMetrics(): Nullable<IDocumentPaginationMetrics> {
+ return this._paginationMetrics == null ? null : { ...this._paginationMetrics };
+ }
+
resetInitialWidth() {
this._initialWidth = 0;
}
@@ -1317,6 +1328,15 @@ export class DocumentSkeleton extends Skeleton {
paragraphConfigCache: new Map(),
sectionBreakConfigCache: new Map(),
paragraphsOpenNewPage: new Set(),
+ paginationMetrics: {
+ constrainedParagraphs: 0,
+ noConstraintParagraphs: 0,
+ measuredLineCount: 0,
+ retryCount: 0,
+ movedLineCount: 0,
+ keepNextScanCount: 0,
+ peakCheckpointLineCount: 0,
+ },
hyphen: this._hyphen,
languageDetector: this._languageDetector,
};
diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.ts
index 2f69ee8b80..70dea21151 100644
--- a/packages/engine-render/src/components/docs/layout/tools.ts
+++ b/packages/engine-render/src/components/docs/layout/tools.ts
@@ -1618,6 +1618,23 @@ export interface IFloatObject {
// The context state of the layout process, which is used to store some cache and intermediate states in the typesetting process,
// as well as identifying information such as the pointer of the layout.
+export interface IDocumentPaginationMetrics {
+ /** Paragraphs that entered the Word-compatible pagination decision path. */
+ constrainedParagraphs: number;
+ /** Paragraphs that stayed on the no-constraint fast path. */
+ noConstraintParagraphs: number;
+ /** Already-shaped lines inspected by pagination checkpoints. */
+ measuredLineCount: number;
+ /** Bounded local pagination adjustments; at most one per paragraph or keep chain. */
+ retryCount: number;
+ /** Already-shaped lines moved by a pagination adjustment. */
+ movedLineCount: number;
+ /** Paragraphs inspected while walking backward through keep-next chains. */
+ keepNextScanCount: number;
+ /** Largest number of line references retained by one local checkpoint. */
+ peakCheckpointLineCount: number;
+}
+
export interface ILayoutContext {
// The view model of current layout document.
viewModel: DocumentViewModel;
@@ -1648,6 +1665,7 @@ export interface ILayoutContext {
paragraphConfigCache: Map<string, Map<number, IParagraphConfig>>;
sectionBreakConfigCache: Map<number, ISectionBreakConfig>;
paragraphsOpenNewPage: Set<number>;
+ paginationMetrics?: IDocumentPaginationMetrics;
// Use for hyphenation.
hyphen: Hyphen;
// Use for detect language for paragraph content.
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 bef56b2afd..657ce1cae1 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
@@ -381,5 +381,35 @@ describe('DocumentViewModel', () => {
expect(headerViewModel.getTableByStartIndex(0)?.tableSource).toBe(tableSource);
});
+
+ it('prefers a segment table source when its id also exists in the document body', () => {
+ const tableDataStream = `${DataStreamTreeTokenType.TABLE_START}${DataStreamTreeTokenType.TABLE_ROW_START}${DataStreamTreeTokenType.TABLE_CELL_START}F${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}${DataStreamTreeTokenType.TABLE_CELL_END}${DataStreamTreeTokenType.TABLE_ROW_END}${DataStreamTreeTokenType.TABLE_END}`;
+ const footerTableSource = { tableId: 'table-1', tableRows: [{ tableCells: [{ margin: {} }] }] };
+ const footerModel = createDocumentDataModel({
+ body: {
+ dataStream: `${tableDataStream}${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,
+ tables: [{ tableId: 'table-1', startIndex: 0, endIndex: tableDataStream.length }],
+ },
+ snapshot: {
+ tableSource: {
+ 'table-1': footerTableSource,
+ },
+ },
+ });
+ const bodyTableSource = { tableId: 'table-1', tableRows: [{ tableCells: [] }] };
+ const model = createDocumentDataModel({
+ snapshot: {
+ tableSource: {
+ 'table-1': bodyTableSource,
+ },
+ },
+ footerModelMap: new Map([['f1', footerModel]]),
+ });
+
+ const viewModel = new DocumentViewModel(model);
+ const footerViewModel = viewModel.getSelfOrHeaderFooterViewModel('f1');
+
+ expect(footerViewModel.getTableByStartIndex(0)?.tableSource).toBe(footerTableSource);
+ });
});
});
diff --git a/packages/engine-render/src/components/docs/view-model/document-view-model.ts b/packages/engine-render/src/components/docs/view-model/document-view-model.ts
index 6afdc38f47..92c4fa6556 100644
--- a/packages/engine-render/src/components/docs/view-model/document-view-model.ts
+++ b/packages/engine-render/src/components/docs/view-model/document-view-model.ts
@@ -601,14 +601,20 @@ export class DocumentViewModel implements IDisposable {
private _buildHeaderFooterViewModel() {
const { headerModelMap, footerModelMap } = this._documentDataModel;
const viewModels = [];
- const tableSource = this.getSnapshot().tableSource;
+ const rootTableSource = this.getSnapshot().tableSource;
for (const [headerId, headerModel] of headerModelMap) {
- this._headerTreeMap.set(headerId, new DocumentViewModel(headerModel, tableSource));
+ this._headerTreeMap.set(headerId, new DocumentViewModel(headerModel, {
+ ...rootTableSource,
+ ...headerModel.getSnapshot().tableSource,
+ }));
viewModels.push(this._headerTreeMap.get(headerId)!);
}
for (const [footerId, footerModel] of footerModelMap) {
- this._footerTreeMap.set(footerId, new DocumentViewModel(footerModel, tableSource));
+ this._footerTreeMap.set(footerId, new DocumentViewModel(footerModel, {
+ ...rootTableSource,
+ ...footerModel.getSnapshot().tableSource,
+ }));
viewModels.push(this._footerTreeMap.get(footerId)!);
}