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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(docs): render paragraph borders (#7616)
wpxp123456a9e9e90a7852
diff --git a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.tsindex 57946849e2..b0ce98a176 100644--- a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts@@ -412,6 +412,42 @@ function createListParagraphDoc(): IDocumentData {function createHorizontalLineDoc(): IDocumentData {const doc = createMultiParagraphDoc();const body = doc.body!;+ return {+ ...doc,+ body: {+ ...body,+ dataStream: '\rBody\r\n',+ textRuns: [{ st: 0, ed: 5, ts: {} }],+ paragraphs: [+ {+ ...body.paragraphs![0],+ startIndex: 0,+ paragraphStyle: {+ borderBottom: {+ padding: 5,+ color: { rgb: '#CDD0D8' },+ width: 1,+ dashStyle: DashStyleType.SOLID,+ },+ },+ },+ {+ ...body.paragraphs![1],+ startIndex: 5,+ },+ ],+ sectionBreaks: [{+ ...body.sectionBreaks![0],+ startIndex: 6,+ }],+ },+ };+}++function createParagraphBorderDoc(): IDocumentData {+ const doc = createMultiParagraphDoc();+ const body = doc.body!;+return {...doc,body: {@@ -434,6 +470,50 @@ function createHorizontalLineDoc(): IDocumentData {};}+function createTableHorizontalLineDoc(): IDocumentData {+ const table = genEmptyTable(1, 1);+ const dataStream = `${table.dataStream}\r\n`;+ const doc = createBaseDoc(dataStream);+ const horizontalLineParagraph = table.paragraphs[0];++ return {+ ...doc,+ body: {+ ...doc.body!,+ paragraphs: [+ {+ ...horizontalLineParagraph,+ paragraphStyle: {+ ...horizontalLineParagraph.paragraphStyle,+ borderBottom: {+ padding: 5,+ color: { rgb: '#CDD0D8' },+ width: 1,+ dashStyle: DashStyleType.SOLID,+ },+ },+ },+ {+ paragraphId: 'para_after_table_horizontal_line',+ startIndex: table.dataStream.length,+ },+ ],+ sectionBreaks: [+ ...table.sectionBreaks,+ {+ sectionId: 'section_table_horizontal_line',+ startIndex: dataStream.length - 1,+ },+ ],+ tables: [{+ startIndex: 0,+ endIndex: table.dataStream.length,+ tableId: 'table-horizontal-line',+ }],+ },+ };+}+function createTableDoc(): IDocumentData {const table = genEmptyTable(2, 2);const prefix = 'AB';@@ -1103,7 +1183,7 @@ describe('misc document commands', () => {commandService = get(ICommandService);commandService.registerCommand(RemoveHorizontalLineCommand);commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);- setCollapsedSelection(6);+ setCollapsedSelection(1);const mutationParams = collectRichTextMutationParams();expect(await commandService.executeCommand(RemoveHorizontalLineCommand.id)).toBe(true);@@ -1196,6 +1276,42 @@ describe('misc document commands', () => {commandService.registerCommand(DeleteLeftCommand);commandService.registerCommand(RemoveHorizontalLineCommand);commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(1);++ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ skeletonManager.getSkeleton = () => useLinearSkeleton('\rBody\r\n');++ expect(await commandService.executeCommand(DeleteLeftCommand.id)).toBe(true);+ await awaitTime(0);++ expect(getBody()?.paragraphs?.[0].paragraphStyle?.borderBottom).toBeUndefined();+ });++ it('removes a horizontal line from the first paragraph inside a table cell', async () => {+ const doc = createTableHorizontalLineDoc();+ ({ univer, get } = createCommandTestBed(doc));+ commandService = get(ICommandService);+ commandService.registerCommand(DeleteLeftCommand);+ commandService.registerCommand(RemoveHorizontalLineCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(4);++ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ skeletonManager.getSkeleton = () => useLinearSkeleton(doc.body!.dataStream);++ expect(await commandService.executeCommand(DeleteLeftCommand.id)).toBe(true);+ await awaitTime(0);++ expect(getBody()?.paragraphs?.[0].paragraphStyle?.borderBottom).toBeUndefined();+ });++ it('merges a non-empty paragraph with a bottom border when Backspace is pressed at the next paragraph', async () => {+ ({ univer, get } = createCommandTestBed(createParagraphBorderDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(DeleteLeftCommand);+ commandService.registerCommand(MergeTwoParagraphCommand);+ commandService.registerCommand(RemoveHorizontalLineCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);setCollapsedSelection(6);const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };@@ -1204,7 +1320,8 @@ describe('misc document commands', () => {expect(await commandService.executeCommand(DeleteLeftCommand.id)).toBe(true);await awaitTime(0);- expect(getBody()?.paragraphs?.[0].paragraphStyle?.borderBottom).toBeUndefined();+ expect(getBody()?.dataStream).toBe('TitleBody\r\n');+ expect(getBody()?.paragraphs).toHaveLength(1);});it('turns a list paragraph into an indented paragraph when Backspace is pressed at its first glyph', async () => {diff --git a/packages/docs-ui/src/commands/commands/doc-delete.command.ts b/packages/docs-ui/src/commands/commands/doc-delete.command.tsindex a211626f15..8b288b4d9f 100644--- a/packages/docs-ui/src/commands/commands/doc-delete.command.ts+++ b/packages/docs-ui/src/commands/commands/doc-delete.command.ts@@ -24,6 +24,7 @@ import {DataStreamTreeTokenType,DeleteDirection,getBlockRangeInterval,+ getParagraphContentStartOffset,getRichTextEditPath,HorizontalAlign,ICommandService,@@ -47,6 +48,7 @@ import {} from '@univerjs/docs';import { getParagraphByGlyph, hasListGlyph, isFirstGlyph, isIndentByGlyph } from '@univerjs/engine-render';import { DocAutoFormatService } from '../../services/doc-auto-format.service';+import { isHorizontalLineParagraph } from '../../utils/horizontal-line';import { getCommandSkeleton } from '../util';import { CutContentCommand } from './clipboard.inner.command';import { getCurrentParagraph } from './util';@@ -571,10 +573,14 @@ export const DeleteLeftCommand: ICommand = {if (preGlyph == null) {return true;}- if (preGlyph.content === '\r') {+ if (preGlyph.content === DataStreamTreeTokenType.PARAGRAPH) {const paragraph = body.paragraphs?.find((p) => p.startIndex === startOffset - 1);+ const paragraphStart = paragraph == null ? 0 : getParagraphContentStartOffset(body, paragraph);+ const paragraphDataStream = paragraph == null+ ? ''+ : body.dataStream.slice(paragraphStart, paragraph.startIndex + 1);- if (paragraph?.paragraphStyle?.borderBottom) {+ if (isHorizontalLineParagraph(paragraphDataStream, paragraph)) {result = await commandService.executeCommand(RemoveHorizontalLineCommand.id);} else {result = await commandService.executeCommand(MergeTwoParagraphCommand.id, {diff --git a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts b/packages/docs-ui/src/services/doc-paragraph-menu.service.tsindex 02085c611b..7a99268c33 100644--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts@@ -23,6 +23,7 @@ import { canEditDocumentTargets, DocSelectionManagerService, DocSkeletonManagerSimport { DocumentEditArea } from '@univerjs/engine-render';import { BehaviorSubject, combineLatest, first, throttleTime } from 'rxjs';import { VIEWPORT_KEY } from '../basics/docs-view-key';+import { isHorizontalLineParagraph } from '../utils/horizontal-line';import {DOC_PARAGRAPH_MENU_COMPONENT_KEY,DOC_TABLE_BLOCK_MENU_COMPONENT_KEY,@@ -764,7 +765,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModuleconst paragraphDataStream = dataStream.slice(paragraph.paragraphStart, paragraph.paragraphEnd);const paragraphModel = body?.paragraphs?.find((item) => item.startIndex === paragraph.startIndex);const listIcon = getListIcon(paragraphModel?.bullet?.listType);- const isHorizontalRuleParagraph = paragraphDataStream.replace(/[\r\n]/g, '') === '' && !!paragraphModel?.paragraphStyle?.borderBottom;+ const isHorizontalRuleParagraph = isHorizontalLineParagraph(paragraphDataStream, paragraphModel);const customBlock = body?.customBlocks?.find((item) => item.startIndex >= paragraph.paragraphStart && item.startIndex <= paragraph.paragraphEnd);const isCustomBlockOnly = customBlock?.blockType === BlockType.CUSTOM && paragraphDataStream.replace(/[\b\r\n]/g, '') === '';if (customBlock && customBlock.blockType === BlockType.CUSTOM && isCustomBlockOnly) {diff --git a/packages/docs-ui/src/utils/horizontal-line.ts b/packages/docs-ui/src/utils/horizontal-line.tsnew file mode 100644index 0000000000..e6032bfbc8--- /dev/null+++ b/packages/docs-ui/src/utils/horizontal-line.ts@@ -0,0 +1,33 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IParagraph, Nullable } from '@univerjs/core';+import { DataStreamTreeTokenType } from '@univerjs/core';++export function isHorizontalLineParagraph(dataStream: string, paragraph: Nullable<IParagraph>) {+ const paragraphStyle = paragraph?.paragraphStyle;++ const isEmpty = Array.from(dataStream).every((token) =>+ token === DataStreamTreeTokenType.PARAGRAPH || token === DataStreamTreeTokenType.SECTION_BREAK+ );++ return isEmpty &&+ paragraphStyle?.borderBottom != null &&+ paragraphStyle.borderTop == null &&+ paragraphStyle.borderLeft == null &&+ paragraphStyle.borderRight == null &&+ paragraphStyle.borderBetween == null;+}diff --git a/packages/engine-render/src/basics/i-document-skeleton-cached.ts b/packages/engine-render/src/basics/i-document-skeleton-cached.tsindex b9ef30c0dd..0762601a2b 100644--- a/packages/engine-render/src/basics/i-document-skeleton-cached.ts+++ b/packages/engine-render/src/basics/i-document-skeleton-cached.ts@@ -48,6 +48,14 @@ export interface IParagraphList {paragraph: IParagraph;}+export interface IDocumentSkeletonParagraphBorders {+ borderTop?: IParagraphBorder;+ borderBottom?: IParagraphBorder;+ borderLeft?: IParagraphBorder;+ borderRight?: IParagraphBorder;+ borderBetween?: IParagraphBorder;+}+export interface ISkeletonResourceReference {skeHeaders: Map<string, Map<number, IDocumentSkeletonHeaderFooter>>; // id:{ width: IDocumentSkeletonHeaderFooter }skeFooters: Map<string, Map<number, IDocumentSkeletonHeaderFooter>>;@@ -231,7 +239,14 @@ export interface IDocumentSkeletonLine {isBehindTable: boolean; // In DataStream, if paragraph contains table, the first line isBehindTable is true and tableId is not empty, mainly used to calculate st\ed.tableId: string; // tableId if paragraph contains table, tableId is not empty, mainly used to calculate st\ed.+ borderBetween?: IParagraphBorder; // borderBetween+ borderTop?: IParagraphBorder; // borderTopborderBottom?: IParagraphBorder; // borderBottom+ borderLeft?: IParagraphBorder; // borderLeft+ borderRight?: IParagraphBorder; // borderRight+ paragraphBorders?: IDocumentSkeletonParagraphBorders;+ paragraphPaddingLeft?: number;+ paragraphPaddingRight?: number;backgroundColor?: IColorStyle; // backgroundColorbullet?: IDocumentSkeletonBullet; // unordered and ordered list bulletwidth?: number; // the actual width of a linediff --git a/packages/engine-render/src/components/docs/__tests__/document.spec.ts b/packages/engine-render/src/components/docs/__tests__/document.spec.tsindex 26103408c7..5ead2d950c 100644--- a/packages/engine-render/src/components/docs/__tests__/document.spec.ts+++ b/packages/engine-render/src/components/docs/__tests__/document.spec.ts@@ -854,7 +854,7 @@ describe('documents render', () => {documents.dispose();});- it('draws paragraph bottom borders with their configured width and dash style', () => {+ it('draws all paragraph borders with their own style, padding, and paragraph indentation', () => {const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;const documents = new Documents('docs-paragraph-border', skeleton, {pageLayoutType: PageLayoutType.VERTICAL,@@ -863,16 +863,35 @@ describe('documents render', () => {});const page = createPage(DocumentSkeletonPageType.BODY, '');const line = page.sections[0].columns[0].lines[1];+ line.paragraphPaddingLeft = 8;+ line.paragraphPaddingRight = 12;+ line.borderTop = {+ color: { rgb: 'auto' },+ width: 1,+ padding: 3,+ dashStyle: DashStyleType.DOT,+ };line.borderBottom = {- color: { rgb: '#ff0000' },- width: 2.5,+ color: { rgb: '#444444' },+ width: 4,+ padding: 6,+ dashStyle: DashStyleType.DASH,+ };+ line.borderLeft = {+ color: { rgb: '#222222' },+ width: 2,padding: 4,+ dashStyle: DashStyleType.SOLID,+ };+ line.borderRight = {+ color: { rgb: '#333333' },+ width: 3,+ padding: 5,dashStyle: DashStyleType.DASH,};- line.lineHeight += 6;- line.marginBottom = 6;(documents as any)._drawLiquid = { x: 0, y: 0 };+ const strokeStyles: string[] = [];const ctx = {save: vi.fn(),restore: vi.fn(),@@ -883,15 +902,23 @@ describe('documents render', () => {setLineDash: vi.fn(),stroke: vi.fn(),closePathByEnv: vi.fn(),- set strokeStyle(_value: string) {},+ set strokeStyle(value: string) {+ strokeStyles.push(value);+ },} as any;- (documents as any)._drawBorderBottom(ctx, page, line, 72);+ (documents as any)._drawParagraphBorders(ctx, page, line, 72);- expect(ctx.setLineWidthByPrecision).toHaveBeenCalledWith(2.5);- expect(ctx.setLineDash).toHaveBeenCalledWith([6]);- expect(ctx.lineToByPrecision).toHaveBeenCalledWith(82, 33);- expect(ctx.stroke).toHaveBeenCalledTimes(1);+ expect(ctx.setLineWidthByPrecision.mock.calls).toEqual([[1], [4], [2], [3]]);+ expect(ctx.setLineDash.mock.calls).toEqual([[[2]], [[6]], [[0]], [[6]]]);+ expect(ctx.lineToByPrecision.mock.calls).toEqual([+ [75, 7],+ [75, 35],+ [14, 35],+ [75, 35],+ ]);+ expect(strokeStyles).toEqual(['rgb(0,0,0)', '#444444', '#222222', '#333333']);+ expect(ctx.stroke).toHaveBeenCalledTimes(4);documents.dispose();});diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.tsindex ab56373a89..77958603d6 100644--- a/packages/engine-render/src/components/docs/document.ts+++ b/packages/engine-render/src/components/docs/document.ts@@ -14,7 +14,15 @@* limitations under the License.*/-import type { ICustomRange, IDocumentRenderConfig, IScale, ITableCell, ITableCellBorder, Nullable } from '@univerjs/core';+import type {+ ICustomRange,+ IDocumentRenderConfig,+ IParagraphBorder,+ IScale,+ ITableCell,+ ITableCellBorder,+ Nullable,+} from '@univerjs/core';import type {IDocumentSkeletonColumnGroup,IDocumentSkeletonColumnGroupColumn,@@ -35,7 +43,7 @@ import type { DocumentSkeleton } from './layout/doc-skeleton';import type { IDocsTableRenderViewport } from './table-render-viewport';import { CellValueType, ColumnSeparatorType, DashStyleType, DocumentFlavor, HorizontalAlign, VerticalAlign, WrapStrategy } from '@univerjs/core';import { Subject } from 'rxjs';-import { BORDER_TYPE as BORDER_LTRB, drawLineByBorderType } from '../../basics';+import { BORDER_TYPE, COLOR_BLACK_RGB, drawLineByBorderType } from '../../basics';import { calculateRectRotate, getRotateOffsetAndFarthestHypotenuse } from '../../basics/draw';import { LineType } from '../../basics/i-document-skeleton-cached';import { VERTICAL_ROTATE_ANGLE } from '../../basics/text-rotation';@@ -47,6 +55,7 @@ import { DOCS_EXTENSION_TYPE } from './doc-extension';import { getDocumentCompatibilityPolicy, shouldAllowImportedTableMarginOverflow } from './document-compatibility';import { collectBackgroundGlyphRuns } from './extensions/background-runs';import { getTableIdAndSliceIndex } from './layout/block/table';+import { getColorStyleForCanvas } from './layout/style/color';import { documentSkeletonTableIterator } from './layout/tools';import { Liquid } from './liquid';import { getDocsTableRenderViewport, getDocsTableViewportLeft, hasDocsTableHorizontalViewport } from './table-render-viewport';@@ -632,9 +641,7 @@ export class Documents extends DocComponent {this._drawLiquid.translateRestore();}- if (line.borderBottom) {- this._drawBorderBottom(ctx, page, line, column.width);- }+ this._drawParagraphBorders(ctx, page, line, column.width);this._drawLiquid.translateRestore();}}@@ -990,7 +997,7 @@ export class Documents extends DocComponent {ctx.restore();}- private _drawBorderBottom(+ private _drawParagraphBorders(ctx: UniverRenderingContext,page: IDocumentSkeletonPage,line: IDocumentSkeletonLine,@@ -998,7 +1005,11 @@ export class Documents extends DocComponent {left = 0,top = 0) {- if (this._drawLiquid == null) {+ const bottomBorder = line.borderBetween ?? line.borderBottom;+ if (+ this._drawLiquid == null ||+ (!line.borderTop && !bottomBorder && !line.borderLeft && !line.borderRight)+ ) {return;}let { x, y } = this._drawLiquid;@@ -1007,21 +1018,35 @@ export class Documents extends DocComponent {x += marginLeft + (left ?? 0);y -= line.marginTop;y -= line.paddingTop;- // Paragraph spacing is included in lineHeight, while border padding is measured from the text bottom.- y += marginTop + top + line.lineHeight - line.marginBottom + (line.borderBottom?.padding ?? 0);+ y += marginTop + top;- ctx.save();- const border = line.borderBottom;- ctx.setLineWidthByPrecision(Math.max(0, border?.width ?? 1));- ctx.strokeStyle = border?.color.rgb ?? '#CDD0D8';- setDocsBorderDash(ctx, border?.dashStyle);- drawLineByBorderType(ctx, BORDER_LTRB.BOTTOM, 0, {- startX: x,- startY: y,- endX: x + width,- endY: y,- });- ctx.restore();+ const startX = x + (line.paragraphPaddingLeft ?? 0) - (line.borderLeft?.padding ?? 0);+ const endX = x + width - (line.paragraphPaddingRight ?? 0) + (line.borderRight?.padding ?? 0);+ const startY = y + line.marginTop - (line.borderTop?.padding ?? 0);+ const endY = y + line.lineHeight - line.marginBottom + (bottomBorder?.padding ?? 0);+ const drawBorder = (border: IParagraphBorder, type: BORDER_TYPE) => {+ ctx.save();+ ctx.setLineWidthByPrecision(Math.max(0, border.width ?? 1));+ ctx.strokeStyle = border.color.rgb === 'auto'+ ? COLOR_BLACK_RGB+ : getColorStyleForCanvas(border.color) ?? COLOR_BLACK_RGB;+ setDocsBorderDash(ctx, border.dashStyle);+ drawLineByBorderType(ctx, type, 0, { startX, startY, endX, endY });+ ctx.restore();+ };++ if (line.borderTop) {+ drawBorder(line.borderTop, BORDER_TYPE.TOP);+ }+ if (bottomBorder) {+ drawBorder(bottomBorder, BORDER_TYPE.BOTTOM);+ }+ if (line.borderLeft) {+ drawBorder(line.borderLeft, BORDER_TYPE.LEFT);+ }+ if (line.borderRight) {+ drawBorder(line.borderRight, BORDER_TYPE.RIGHT);+ }}private _drawGlyphGroupBackgrounds(@@ -1316,9 +1341,14 @@ export class Documents extends DocComponent {this._drawLiquid.translateRestore();}- if (line.borderBottom) {- this._drawBorderBottom(ctx, nestedPage, line, column.width, parentPage.marginLeft, parentPage.marginTop);- }+ this._drawParagraphBorders(+ ctx,+ nestedPage,+ line,+ column.width,+ parentPage.marginLeft,+ parentPage.marginTop+ );this._drawLiquid.translateRestore();}@@ -1382,15 +1412,15 @@ export class Documents extends DocComponent {const rightCellSource = this._getTableCellSource(rowSke, index + 1);const bottomCellSource = tableSke ? this._getTableCellSource(tableSke.rows[rowIndex + 1], index) : undefined;- this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderRight, rightCellSource?.borderLeft), BORDER_LTRB.RIGHT, position);- this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderBottom, bottomCellSource?.borderTop), BORDER_LTRB.BOTTOM, position);+ this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderRight, rightCellSource?.borderLeft), BORDER_TYPE.RIGHT, position);+ this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderBottom, bottomCellSource?.borderTop), BORDER_TYPE.BOTTOM, position);if (rowIndex <= 0) {- this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderTop), BORDER_LTRB.TOP, position);+ this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderTop), BORDER_TYPE.TOP, position);}if (index <= 0) {- this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderLeft), BORDER_LTRB.LEFT, position);+ this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderLeft), BORDER_TYPE.LEFT, position);}}@@ -1427,7 +1457,7 @@ export class Documents extends DocComponent {private _drawTableCellBorder(ctx: UniverRenderingContext,border: Nullable<ITableCellBorder>,- type: BORDER_LTRB,+ type: BORDER_TYPE,position: { startX: number; startY: number; endX: number; endY: number }) {if (!border) {@@ -1632,9 +1662,7 @@ export class Documents extends DocComponent {this._drawLiquid.translateRestore();}- if (line.borderBottom) {- this._drawBorderBottom(ctx, page, line, column.width, parentPage.marginLeft);- }+ this._drawParagraphBorders(ctx, page, line, column.width, parentPage.marginLeft);this._drawLiquid.translateRestore();}diff --git a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.tsindex aa7763c097..fd1f600507 100644--- a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts+++ b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts@@ -19,6 +19,7 @@ import {BooleanNumber,ColumnSeparatorType,createDocumentModelWithStyle,+ DashStyleType,DataStreamTreeTokenType,DocumentDataModel,DocumentFlavor,@@ -1152,6 +1153,55 @@ describe('doc skeleton', () => {univer.dispose();});+ it('resolves matching paragraph borders across incrementally finalized page boundaries', () => {+ const univer = new Univer();+ const localeService = univer.__getInjector().get(LocaleService);+ const paragraphToken = DataStreamTreeTokenType.PARAGRAPH;+ const sectionToken = DataStreamTreeTokenType.SECTION_BREAK;+ let dataStream = '';+ const border = {+ color: { rgb: '#555555' },+ width: 2,+ padding: 1,+ dashStyle: DashStyleType.SOLID,+ };+ const paragraphs: IParagraph[] = Array.from({ length: 12 }, (_, index) => {+ dataStream += `Paragraph ${index}${paragraphToken}`;+ return {+ startIndex: dataStream.length - 1,+ paragraphId: `border-paragraph-${index}`,+ paragraphStyle: {+ lineSpacing: 20,+ spacingRule: SpacingRule.EXACT,+ borderTop: border,+ borderBottom: border,+ borderBetween: border,+ },+ };+ });+ dataStream += sectionToken;+ const snapshot = {+ id: 'incremental-paragraph-borders',+ body: {+ dataStream,+ paragraphs,+ sectionBreaks: [{ sectionId: 'body-section', startIndex: dataStream.length - 1 }],+ },+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ pageSize: { width: 180, height: 100 },+ marginTop: 10,+ marginBottom: 10,+ marginLeft: 10,+ marginRight: 10,+ },+ };++ expectIncrementalSkeletonToEqualSynchronous(snapshot, localeService);++ univer.dispose();+ });+it('keeps a paginated body table structurally identical after incremental layout', () => {const univer = new Univer();const localeService = univer.__getInjector().get(LocaleService);diff --git a/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.tsindex 675d97ae5e..c96cdecadc 100644--- a/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts+++ b/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts@@ -75,6 +75,7 @@ import {setPageParent,updateBlockIndex,updateInlineDrawingCoordsAndBorder,+ updateParagraphBorders,validationGrid,} from '../tools';@@ -420,6 +421,142 @@ describe('docs layout tools extra', () => {expect(line1.backgroundColor).toEqual({ rgb: '#ffffff' });});+ it('copies every paragraph border without relying on a terminal paragraph glyph', () => {+ const { page, line1 } = createPageSkeleton();+ line1.paragraphStart = true;+ line1.paragraphIndex = 10;+ line1.ed = 10;+ const paragraphStyle = {+ borderTop: { color: { rgb: '#111111' }, width: 1, padding: 1 },+ borderBottom: { color: { rgb: '#222222' }, width: 2, padding: 2 },+ borderLeft: { color: { rgb: '#333333' }, width: 3, padding: 3 },+ borderRight: { color: { rgb: '#444444' }, width: 4, padding: 4 },+ };+ const ctx = {+ paragraphConfigCache: new Map([[+ undefined,+ new Map([[10, { paragraphStyle }]]),+ ]]),+ };++ updateInlineDrawingCoordsAndBorder(ctx as any, [page] as any);++ expect(line1).toMatchObject(paragraphStyle);+ });++ it('uses the between border only between adjacent paragraphs with matching border sets', () => {+ const { page, line1, line2 } = createPageSkeleton();+ line1.paragraphStart = true;+ line1.paragraphIndex = 10;+ line1.ed = 10;+ line2.paragraphStart = true;+ line2.paragraphIndex = 20;+ line2.ed = 20;+ const paragraphStyle = {+ borderTop: { color: { rgb: '#111111' }, width: 1, padding: 1 },+ borderBottom: { color: { rgb: '#222222' }, width: 2, padding: 2 },+ borderLeft: { color: { rgb: '#333333' }, width: 3, padding: 3 },+ borderRight: { color: { rgb: '#444444' }, width: 4, padding: 4 },+ borderBetween: { color: { rgb: '#555555' }, width: 5, padding: 5 },+ };+ const ctx = {+ paragraphConfigCache: new Map([[+ undefined,+ new Map([+ [10, { paragraphStyle }],+ [20, { paragraphStyle }],+ ]),+ ]]),+ };++ updateInlineDrawingCoordsAndBorder(ctx as any, [page] as any);++ expect(line1.borderTop).toEqual(paragraphStyle.borderTop);+ expect(line1.borderBetween).toEqual(paragraphStyle.borderBetween);+ expect(line1.borderBottom).toBeUndefined();+ expect(line2.borderTop).toBeUndefined();+ expect(line2.borderBetween).toBeUndefined();+ expect(line2.borderBottom).toEqual(paragraphStyle.borderBottom);+ });++ it('uses cached border styles at retained and reused page boundaries', () => {+ const previous = createPageSkeleton();+ const current = createPageSkeleton();+ const next = createPageSkeleton();+ const pages = [previous, current, next].map(({ page, column, line1 }) => {+ column.lines = [line1];+ return page;+ });+ const lines = [previous.line1, current.line1, next.line1];+ const paragraphStyle = {+ borderTop: { color: { rgb: '#111111' }, width: 1, padding: 1 },+ borderBottom: { color: { rgb: '#222222' }, width: 2, padding: 2 },+ borderBetween: { color: { rgb: '#555555' }, width: 5, padding: 5 },+ };+ lines.forEach((line, index) => {+ line.paragraphStart = true;+ line.paragraphIndex = (index + 1) * 10;+ line.ed = line.paragraphIndex;+ line.paragraphBorders = paragraphStyle;+ });+ const ctx = {+ paragraphConfigCache: new Map([[+ undefined,+ new Map([[20, { paragraphStyle }]]),+ ]]),+ };++ updateParagraphBorders(ctx as any, pages as any);++ expect(previous.line1.borderTop).toEqual(paragraphStyle.borderTop);+ expect(previous.line1.borderBetween).toEqual(paragraphStyle.borderBetween);+ expect(current.line1.borderTop).toBeUndefined();+ expect(current.line1.borderBetween).toEqual(paragraphStyle.borderBetween);+ expect(next.line1.borderTop).toBeUndefined();+ expect(next.line1.borderBottom).toEqual(paragraphStyle.borderBottom);+ });++ it('updates only cross-boundary attachments on context pages', () => {+ const previous = createPageSkeleton();+ const current = createPageSkeleton();+ const next = createPageSkeleton();+ const pages = [previous, current, next].map(({ page, column, line1 }) => {+ column.lines = [line1];+ return page;+ });+ const lines = [previous.line1, current.line1, next.line1];+ const paragraphStyle = {+ borderTop: { color: { rgb: '#111111' }, width: 1, padding: 1 },+ borderBottom: { color: { rgb: '#222222' }, width: 2, padding: 2 },+ borderBetween: { color: { rgb: '#555555' }, width: 5, padding: 5 },+ };+ lines.forEach((line, index) => {+ line.paragraphStart = true;+ line.paragraphIndex = (index + 1) * 10;+ line.ed = line.paragraphIndex;+ line.paragraphBorders = paragraphStyle;+ });+ const previousTop = { color: { rgb: '#aaaaaa' }, width: 6, padding: 6 };+ const nextBottom = { color: { rgb: '#bbbbbb' }, width: 7, padding: 7 };+ previous.line1.borderTop = previousTop;+ next.line1.borderBottom = nextBottom;+ const ctx = {+ paragraphConfigCache: new Map([[+ undefined,+ new Map([[20, { paragraphStyle }]]),+ ]]),+ };++ updateParagraphBorders(ctx as any, pages as any, [current.page] as any);++ expect(previous.line1.borderTop).toBe(previousTop);+ expect(previous.line1.borderBetween).toEqual(paragraphStyle.borderBetween);+ expect(current.line1.borderTop).toBeUndefined();+ expect(current.line1.borderBetween).toEqual(paragraphStyle.borderBetween);+ expect(next.line1.borderTop).toBeUndefined();+ expect(next.line1.borderBottom).toBe(nextBottom);+ });+it('computes horizontal and vertical positioned object coordinates', () => {const { page, column } = createPageSkeleton();diff --git a/packages/engine-render/src/components/docs/layout/block/column.ts b/packages/engine-render/src/components/docs/layout/block/column.tsindex cebb818729..ef5527c928 100644--- a/packages/engine-render/src/components/docs/layout/block/column.ts+++ b/packages/engine-render/src/components/docs/layout/block/column.ts@@ -145,16 +145,21 @@ function createColumnContentPage(const page = createSkeletonPage(ctx, columnSectionBreakConfig, ctx.skeletonResourceReference);page.type = DocumentSkeletonPageType.CELL;- for (const paragraphNode of getColumnParagraphNodes(columnNode)) {- dealWidthParagraph(ctx, viewModel, paragraphNode, page, columnSectionBreakConfig);+ const paragraphNodes = getColumnParagraphNodes(columnNode);+ for (let index = 0; index < paragraphNodes.length; index++) {+ const paragraphNode = paragraphNodes[index];+ const nextParagraphNode = paragraphNodes[index + 1]?.nodeType === DataStreamTreeNodeType.PARAGRAPH+ ? paragraphNodes[index + 1]+ : undefined;+ dealWidthParagraph(ctx, viewModel, paragraphNode, page, columnSectionBreakConfig, nextParagraphNode);}- updateInlineDrawingCoordsAndBorder(ctx, [page]);updateBlockIndex([page],columnNode.startIndex,sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy());+ updateInlineDrawingCoordsAndBorder(ctx, [page]);applyTrailingBlockRangeSpaceBelow([page], ctx.dataModel?.getBody?.(), columnNode.endIndex);return page;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.tsindex fd62e9bda5..5cbc23f402 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@@ -1322,6 +1322,124 @@ describe('linebreaking', () => {expect(paragraphConfig?.paragraphStyle?.spaceBelow?.v).toBe(6);});+ it('reserves the larger border-between clearance below the paragraph', () => {+ const first = 'Rule';+ const second = 'Next';+ const content = `${first}${DataStreamTreeTokenType.PARAGRAPH}${second}`;+ const paragraphStyle = {+ spaceBelow: { v: 0 },+ borderBottom: {+ color: { rgb: '#cdd0d8' },+ padding: 1,+ width: 2,+ },+ borderBetween: {+ color: { rgb: '#cdd0d8' },+ padding: 8,+ width: 4,+ },+ };+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ body: {+ paragraphs: [+ { startIndex: first.length, paragraphStyle },+ { startIndex: content.length, paragraphStyle },+ ],+ },+ });+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ lineBreaking(+ ctx,+ viewModel,+ shapedTextList,+ curPage,+ paragraphNode,+ sectionBreakConfig,+ null,+ false,+ paragraphNode.parent?.children[1]+ );++ const paragraphConfig = ctx.paragraphConfigCache.get(curPage.segmentId)?.get(paragraphNode.endIndex);+ expect(paragraphConfig?.paragraphStyle?.spaceBelow?.v).toBe(10);+ });++ it('does not reserve border-between clearance when the next paragraph border set differs', () => {+ const first = 'Rule';+ const second = 'Next';+ const content = `${first}${DataStreamTreeTokenType.PARAGRAPH}${second}`;+ const firstParagraphStyle = {+ spaceBelow: { v: 0 },+ borderBottom: {+ color: { rgb: '#cdd0d8' },+ padding: 1,+ width: 2,+ },+ borderBetween: {+ color: { rgb: '#cdd0d8' },+ padding: 8,+ width: 4,+ },+ };+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ body: {+ paragraphs: [+ { startIndex: first.length, paragraphStyle: firstParagraphStyle },+ { startIndex: content.length, paragraphStyle: { ...firstParagraphStyle, borderBetween: undefined } },+ ],+ },+ });+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ lineBreaking(+ ctx,+ viewModel,+ shapedTextList,+ curPage,+ paragraphNode,+ sectionBreakConfig,+ null,+ false,+ paragraphNode.parent?.children[1]+ );++ const paragraphConfig = ctx.paragraphConfigCache.get(curPage.segmentId)?.get(paragraphNode.endIndex);+ expect(paragraphConfig?.paragraphStyle?.spaceBelow?.v).toBe(2);+ });++ it('reserves top-border clearance and caches paragraph indentation', () => {+ const content = 'Bordered';+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ body: {+ paragraphs: [{+ startIndex: content.length,+ paragraphStyle: {+ spaceAbove: { v: 0 },+ indentStart: { v: 18 },+ indentEnd: { v: 12 },+ borderTop: {+ color: { rgb: '#cdd0d8' },+ padding: 5,+ width: 2,+ },+ },+ }],+ },+ });+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const pages = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ const paragraphConfig = ctx.paragraphConfigCache.get(curPage.segmentId)?.get(paragraphNode.endIndex);+ const line = pages[0].sections[0].columns[0].lines[0];+ expect(paragraphConfig?.paragraphStyle?.spaceAbove?.v).toBe(6);+ expect(line).toMatchObject({+ paragraphPaddingLeft: 18,+ paragraphPaddingRight: 12,+ });+ });+it('lays out longer text that may span multiple lines', () => {const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('This is a longer text that should still fit within a reasonable page width for testing purposes');const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.tsindex cb05fa96fb..c61eb6b3e9 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts@@ -940,7 +940,7 @@ function _lineOperator(// Line does not exceed column height, or line exceeds column height but there is no other content in the column, or line exceeds page height but there is no other content on the page;const lineIndex = preLine ? preLine.lineIndex + 1 : 0;- let { paddingLeft, paddingRight } = __getIndentPadding(+ let { paddingLeft, paddingRight, paragraphPaddingLeft, paragraphPaddingRight } = __getIndentPadding(indentFirstLine,hanging,indentStart,@@ -956,6 +956,12 @@ function _lineOperator(paddingRight = column.width - paddingLeft - 0.5;}+ if (paragraphPaddingLeft + paragraphPaddingRight >= column.width) {+ const leftPercent = paragraphPaddingLeft / (paragraphPaddingLeft + paragraphPaddingRight);+ paragraphPaddingLeft = column.width * leftPercent - 0.5;+ paragraphPaddingRight = column.width - paragraphPaddingLeft - 0.5;+ }+const newLine = createSkeletonLine(paragraphIndex,LineType.PARAGRAPH,@@ -983,6 +989,8 @@ function _lineOperator(column.lines.push(newLine);newLine.parent = column;+ newLine.paragraphPaddingLeft = paragraphPaddingLeft;+ newLine.paragraphPaddingRight = paragraphPaddingRight;const blockAnchorTop = deferredTopBottomAnchorDrawings.length > 0 ? newLineTop : lineTop;createAndUpdateBlockAnchor(paragraphIndex, newLine, blockAnchorTop, pDrawingAnchor);if (deferredTopBottomAnchorDrawings.length > 0) {@@ -1652,6 +1660,8 @@ function __getIndentPadding(return {paddingLeft,paddingRight,+ paragraphPaddingLeft: indentStartNumber,+ paragraphPaddingRight: indentEndNumber,};}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.tsindex cf377cde8c..72bba5e88b 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@@ -53,7 +53,7 @@ import { BreakType, GlyphType } from '../../../../../basics/i-document-skeleton-import { getDocumentCompatibilityPolicy, isTraditionalDocumentCompatibility } from '../../../document-compatibility';import { createSkeletonPage } from '../../model/page';import { setColumnFullState } from '../../model/section';-import { getLastNotFullColumnInfo, getLastSection, isBlankColumn } from '../../tools';+import { getLastNotFullColumnInfo, getLastSection, hasSameParagraphBorderSet, isBlankColumn } from '../../tools';import { dealWithBullet } from './bullet';import { layoutParagraph } from './layout-ruler';@@ -753,7 +753,8 @@ export function lineBreaking(paragraphNode: DataStreamTreeNode,sectionBreakConfig: ISectionBreakConfig,tableSkeleton: Nullable<IDocumentSkeletonTable>,- tablePageBreakBefore = false+ tablePageBreakBefore = false,+ nextParagraphNode?: DataStreamTreeNode): IDocumentSkeletonPage[] {const { skeletonResourceReference } = ctx;const {@@ -789,8 +790,9 @@ export function lineBreaking(drawingAnchor?.set(segmentId, segmentDrawingAnchorCache);}+ const body = viewModel.getBody?.() ?? null;const resolvedParagraphStyle = _applyBlockRangeLayoutParagraphStyle(- viewModel.getBody?.() ?? null,+ body,paragraph,paragraphStyle,documentStyle,@@ -798,17 +800,44 @@ export function lineBreaking(documentSnapshot?.styles,paragraph.styleId);+ const borderTop = resolvedParagraphStyle.borderTop;const borderBottom = resolvedParagraphStyle.borderBottom;+ const borderBetween = resolvedParagraphStyle.borderBetween;+ const nextParagraph = borderBetween && nextParagraphNode+ ? viewModel.getParagraph(nextParagraphNode.endIndex)+ : undefined;+ const nextParagraphStyle = nextParagraph == null+ ? undefined+ : _applyBlockRangeLayoutParagraphStyle(+ body,+ nextParagraph,+ nextParagraph.paragraphStyle ?? {},+ documentStyle,+ shouldApplyDocumentDefaults,+ documentSnapshot?.styles,+ nextParagraph.styleId+ );- if (borderBottom) {- // Keep the stroke inside the paragraph's post-text region when spaceBelow is smaller.+ if (borderTop) {_withMinSpacing(resolvedParagraphStyle,- 'spaceBelow',- Math.max(0, borderBottom.padding ?? 0) + Math.max(0, borderBottom.width ?? 1) / 2+ 'spaceAbove',+ Math.max(0, borderTop.padding ?? 0) + Math.max(0, borderTop.width ?? 1) / 2);}+ const bottomBorder = borderBetween && nextParagraphStyle &&+ hasSameParagraphBorderSet(resolvedParagraphStyle, nextParagraphStyle)+ ? borderBetween+ : borderBottom;+ const bottomBorderClearance = bottomBorder+ ? Math.max(0, bottomBorder.padding ?? 0) + Math.max(0, bottomBorder.width ?? 1) / 2+ : 0;+ if (bottomBorderClearance > 0) {+ // Keep the stroke inside the paragraph's post-text region when spaceBelow is smaller.+ _withMinSpacing(resolvedParagraphStyle, 'spaceBelow', bottomBorderClearance);+ }+const paragraphConfig: IParagraphConfig = {paragraphIndex: endIndex,isInsideTable: _isInsideFlowTable(viewModel, endIndex),diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/paragraph-layout.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/paragraph-layout.tsindex af7e01dc1c..56bc2899d4 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/paragraph-layout.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/paragraph-layout.ts@@ -31,7 +31,8 @@ export function dealWidthParagraph(viewModel: DocumentViewModel,paragraphNode: DataStreamTreeNode,curPage: IDocumentSkeletonPage,- sectionBreakConfig: ISectionBreakConfig+ sectionBreakConfig: ISectionBreakConfig,+ nextParagraphNode?: DataStreamTreeNode): IDocumentSkeletonPage[] {clearFontCreateConfigCache();const { content = '', children } = paragraphNode;@@ -70,7 +71,8 @@ export function dealWidthParagraph(paragraphNode,sectionBreakConfig,tableSkeleton,- tablePageBreakBefore+ tablePageBreakBefore,+ nextParagraphNode);// Step 3: Line Adjustment.diff --git a/packages/engine-render/src/components/docs/layout/block/section.ts b/packages/engine-render/src/components/docs/layout/block/section.tsindex fff6d54cf1..4f67e5d3ad 100644--- a/packages/engine-render/src/components/docs/layout/block/section.ts+++ b/packages/engine-render/src/components/docs/layout/block/section.ts@@ -95,7 +95,10 @@ export function dealWithSection(viewModel,paragraphNode,currentPageCache,- sectionBreakConfig+ sectionBreakConfig,+ sectionNode.children[i + 1]?.nodeType === DataStreamTreeNodeType.PARAGRAPH+ ? sectionNode.children[i + 1]+ : undefined);}diff --git a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-skeleton.tsindex 3804e5486c..43e743d6a8 100644--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts@@ -61,6 +61,7 @@ import {setPageParent,updateBlockIndex,updateInlineDrawingCoordsAndBorder,+ updateParagraphBorders,} from './tools';function getEffectiveSectionType(sectionType: SectionType | undefined): SectionType {@@ -2090,6 +2091,23 @@ export class DocumentSkeleton extends Skeleton {const startIndex = ctx.skeleton.pages[state.finalizedPageCount - 1]?.ed ?? -1;updateBlockIndex(pages, startIndex, ctx.docsConfig.documentCompatibilityPolicy);updateInlineDrawingCoordsAndBorder(ctx, pages);+ const previousPageIndex = state.finalizedPageCount - 1;+ if (previousPageIndex >= 0 && previousPageIndex < state.stablePageCount) {+ const previousPage = clonePageFlowForPublish(ctx.skeleton.pages[previousPageIndex]);+ previousPage.parent = ctx.skeleton;+ ctx.skeleton.pages[previousPageIndex] = previousPage;+ }+ updateParagraphBorders(+ ctx,+ ctx.skeleton.pages.slice(+ Math.max(0, state.finalizedPageCount - 1),+ Math.min(ctx.skeleton.pages.length, endPageIndex + 1)+ ),+ pages+ );+ }+ if (state.complete && publishedPageCount >= ctx.skeleton.pages.length) {+ updateParagraphBorders(ctx, ctx.skeleton.pages);}state.finalizedPageCount = state.reusedTail? publishedPageCountdiff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.tsindex 9e90f71283..459f355be5 100644--- a/packages/engine-render/src/components/docs/layout/tools.ts+++ b/packages/engine-render/src/components/docs/layout/tools.ts@@ -23,6 +23,7 @@ import type {IObjectPositionH,IObjectPositionV,IParagraph,+ IParagraphBorder,IParagraphStyle,ISectionBreak,ITextStyle,@@ -37,6 +38,7 @@ import type {IDocumentSkeletonGlyph,IDocumentSkeletonLine,IDocumentSkeletonPage,+ IDocumentSkeletonParagraphBorders,IDocumentSkeletonRow,IDocumentSkeletonSection,IDocumentSkeletonTable,@@ -642,6 +644,36 @@ function collapseRedundantColumnBreakOverflow(section: IDocumentSkeletonSection)section.columns.splice(expectedColumnCount);}+function isParagraphEnd(line: IDocumentSkeletonLine) {+ const lastDivide = line.divides[line.divides.length - 1];+ const lastGlyph = lastDivide?.glyphGroup[lastDivide.glyphGroup.length - 1];++ return line.ed >= line.paragraphIndex || lastGlyph?.streamType === DataStreamTreeTokenType.PARAGRAPH;+}++function isSameParagraphBorder(first?: IParagraphBorder, second?: IParagraphBorder) {+ if (first === second) {+ return true;+ }+ if (!first || !second) {+ return false;+ }++ return first.color.rgb === second.color.rgb &&+ first.color.th === second.color.th &&+ first.width === second.width &&+ first.padding === second.padding &&+ first.dashStyle === second.dashStyle;+}++export function hasSameParagraphBorderSet(first: IDocumentSkeletonParagraphBorders, second: IDocumentSkeletonParagraphBorders) {+ return isSameParagraphBorder(first.borderTop, second.borderTop) &&+ isSameParagraphBorder(first.borderBottom, second.borderBottom) &&+ isSameParagraphBorder(first.borderLeft, second.borderLeft) &&+ isSameParagraphBorder(first.borderRight, second.borderRight) &&+ isSameParagraphBorder(first.borderBetween, second.borderBetween);+}+export function updateInlineDrawingCoordsAndBorder(ctx: ILayoutContext, pages: IDocumentSkeletonPage[]) {lineIterator(pages, (line, _, __, page) => {const { segmentId } = page;@@ -666,13 +698,100 @@ export function updateInlineDrawingCoordsAndBorder(ctx: ILayoutContext, pages: Iif (paragraphBackgroundColor) {line.backgroundColor = paragraphBackgroundColor;}+ });- if (line.divides.length > 0) {- const lastDivide = line.divides[line.divides.length - 1];- const lastGlyph = lastDivide.glyphGroup[lastDivide.glyphGroup.length - 1];+ updateParagraphBorders(ctx, pages);+}++export function updateParagraphBorders(+ ctx: ILayoutContext,+ pages: IDocumentSkeletonPage[],+ targetPages: IDocumentSkeletonPage[] = pages+) {+ const targetPageSet = new Set(targetPages);+ const renderLines: Array<{+ line: IDocumentSkeletonLine;+ paragraphBorders?: IDocumentSkeletonParagraphBorders;+ segmentId?: string;+ target: boolean;+ }> = [];+ const bordersByParagraphStyle = new Map<IParagraphStyle, IDocumentSkeletonParagraphBorders>();- if (lastGlyph?.streamType === DataStreamTreeTokenType.PARAGRAPH && paragraphStyle?.borderBottom) {- line.borderBottom = paragraphStyle.borderBottom;+ lineIterator(pages, (line, _, __, page) => {+ const { segmentId } = page;+ const paragraphConfig = ctx.paragraphConfigCache.get(segmentId)?.get(line.paragraphIndex);+ const paragraphStyle = paragraphConfig?.paragraphStyle;+ let paragraphBorders = paragraphStyle == null ? undefined : bordersByParagraphStyle.get(paragraphStyle);+ if (paragraphStyle && !paragraphBorders && (paragraphStyle.borderTop ||+ paragraphStyle.borderBottom ||+ paragraphStyle.borderLeft ||+ paragraphStyle.borderRight ||+ paragraphStyle.borderBetween)) {+ paragraphBorders = {+ borderTop: paragraphStyle.borderTop,+ borderBottom: paragraphStyle.borderBottom,+ borderLeft: paragraphStyle.borderLeft,+ borderRight: paragraphStyle.borderRight,+ borderBetween: paragraphStyle.borderBetween,+ };+ bordersByParagraphStyle.set(paragraphStyle, paragraphBorders);+ }+ const target = targetPageSet.has(page);+ if (target && paragraphConfig) {+ line.paragraphBorders = paragraphBorders;+ }++ renderLines.push({+ line,+ paragraphBorders: paragraphConfig ? paragraphBorders : line.paragraphBorders,+ segmentId,+ target,+ });+ });++ renderLines.forEach(({ line, paragraphBorders, segmentId, target }, index) => {+ const previous = renderLines[index - 1];+ const next = renderLines[index + 1];+ const updateTop = target || previous?.target === true;+ const updateBottom = target || next?.target === true;+ if (!target && !updateTop && !updateBottom) {+ return;+ }++ const hasMatchingPrevious = line.paragraphStart &&+ previous != null &&+ previous.segmentId === segmentId &&+ previous.line.paragraphIndex !== line.paragraphIndex &&+ previous.paragraphBorders != null &&+ paragraphBorders != null &&+ isParagraphEnd(previous.line) &&+ hasSameParagraphBorderSet(previous.paragraphBorders, paragraphBorders);+ const hasMatchingNext = isParagraphEnd(line) &&+ next != null &&+ next.segmentId === segmentId &&+ next.line.paragraphIndex !== line.paragraphIndex &&+ next.paragraphBorders != null &&+ paragraphBorders != null &&+ hasSameParagraphBorderSet(paragraphBorders, next.paragraphBorders);++ if (updateTop) {+ line.borderTop = line.paragraphStart && !hasMatchingPrevious+ ? paragraphBorders?.borderTop+ : undefined;+ }+ if (target) {+ line.borderLeft = paragraphBorders?.borderLeft;+ line.borderRight = paragraphBorders?.borderRight;+ }+ if (updateBottom) {+ line.borderBetween = undefined;+ line.borderBottom = undefined;+ if (isParagraphEnd(line)) {+ if (hasMatchingNext && paragraphBorders?.borderBetween) {+ line.borderBetween = paragraphBorders.borderBetween;+ } else if (paragraphBorders?.borderBottom) {+ line.borderBottom = paragraphBorders.borderBottom;+ }}}});