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(engine-render): preserve imported borders and distributed alignment (#7680)
wpxp1234564660b5094131
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.tsindex 7f6f229b63..1c35ad8669 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { HorizontalAlign } from '@univerjs/core';+import { DataStreamTreeTokenType, HorizontalAlign } from '@univerjs/core';import { describe, expect, it } from 'vitest';import { lineAdjustment } from '../line-adjustment';import { lineBreaking } from '../linebreaking';@@ -212,7 +212,9 @@ describe('line-adjustment', () => {const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);const pages = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);const divide = pages[0].sections[0].columns[0].lines[0].divides[0];- const visibleGlyphs = divide.glyphGroup.filter((glyph) => glyph.content !== '');+ const visibleGlyphs = divide.glyphGroup.filter((glyph) =>+ glyph.content !== '' && glyph.streamType !== DataStreamTreeTokenType.PARAGRAPH+ );const lastVisibleGlyph = visibleGlyphs[visibleGlyphs.length - 1];const initialLastGlyphLeft = lastVisibleGlyph.left;@@ -223,6 +225,26 @@ describe('line-adjustment', () => {expect(divide.paddingLeft).toBe(0);});+ it('distributes visible glyphs to both edges without counting the paragraph mark', () => {+ const lastVisibleGlyph = createGlyph('馆', 10);+ const paragraphMark = createGlyph(DataStreamTreeTokenType.PARAGRAPH, 10, {+ streamType: DataStreamTreeTokenType.PARAGRAPH,+ });+ const divide = {+ width: 100,+ isFull: false,+ paddingLeft: 0,+ glyphGroup: [createGlyph('重', 10), createGlyph('庆', 10), lastVisibleGlyph, paragraphMark],+ } as any;+ const context = createPagesWithLine(divide, HorizontalAlign.DISTRIBUTED);++ lineAdjustment(context.pages, context.viewModel, context.paragraphNode, context.sectionBreakConfig);++ expect(lastVisibleGlyph.left + lastVisibleGlyph.width).toBeCloseTo(divide.width, 1);+ expect(paragraphMark.left).toBeCloseTo(divide.width, 1);+ expect(divide.paddingLeft).toBe(0);+ });+it('handles line with only paragraph break', () => {const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('');const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.tsindex f6e7ff652b..07ca92b659 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.ts@@ -23,7 +23,7 @@ import type {import type { ISectionBreakConfig } from '../../../../../basics/interfaces';import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../../../view-model/document-view-model';-import { HorizontalAlign, WrapStrategy } from '@univerjs/core';+import { DataStreamTreeTokenType, HorizontalAlign, WrapStrategy } from '@univerjs/core';import { cjk } from '../../../../../basics/cjk-regexp';import {isCjkLeftAlignedPunctuation,@@ -126,14 +126,20 @@ function adjustGlyphsInDivide(divide: IDocumentSkeletonDivide, justificationRatisetGlyphGroupLeft(divide.glyphGroup);}-function distributeGlyphsInDivide(divide: IDocumentSkeletonDivide, remaining: number): boolean {- if (remaining <= 0) {+function distributeGlyphsInDivide(divide: IDocumentSkeletonDivide): boolean {+ const visibleGlyphs = divide.glyphGroup.filter((glyph) =>+ glyph.content !== '' &&+ glyph.width > 0 &&+ glyph.streamType !== DataStreamTreeTokenType.PARAGRAPH+ );++ if (visibleGlyphs.length < 2) {return false;}- const visibleGlyphs = divide.glyphGroup.filter((glyph) => glyph.content !== '' && glyph.width > 0);-- if (visibleGlyphs.length < 2) {+ const lastGlyph = visibleGlyphs[visibleGlyphs.length - 1];+ const remaining = divide.width - lastGlyph.left - lastGlyph.width;+ if (remaining <= 0) {return false;}@@ -254,7 +260,7 @@ function horizontalAlignHandler(const inkBounds = allowOverflowHorizontalOffset ? getGlyphGroupInkBounds(divide) : null;if (horizontalAlign === HorizontalAlign.DISTRIBUTED) {- if (distributeGlyphsInDivide(divide, width - glyphGroupWidth)) {+ if (distributeGlyphsInDivide(divide)) {glyphGroupWidth = getGlyphGroupWidth(divide);divide.glyphGroupWidth = glyphGroupWidth;}diff --git a/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.ts b/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.tsindex 90d15f2add..24f29caad8 100644--- a/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.ts+++ b/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.ts@@ -15,9 +15,21 @@*/import type { IWorkbookData, Workbook } from '@univerjs/core';-import { DocumentFlavor, LocaleType, Tools, Univer, UniverInstanceType } from '@univerjs/core';+import {+ BorderStyleTypes,+ DataStreamTreeTokenType,+ DocumentFlavor,+ HorizontalAlign,+ LocaleType,+ RANGE_TYPE,+ Tools,+ Univer,+ UniverInstanceType,+ WrapStrategy,+} from '@univerjs/core';import { afterEach, describe, expect, it, vi } from 'vitest';import { setupRenderTestEnv } from '../../../__tests__/render-test-utils';+import { BORDER_TYPE } from '../../../basics/const';import { FontCache } from '../../docs/layout/shaping-engine/font-cache';import { getGeneralNumberDisplayText, SpreadsheetSkeleton } from '../sheet.render-skeleton';@@ -84,6 +96,193 @@ describe('Rich-text render snapshot isolation', () => {);});+describe('Cell layout and merged styles', () => {+ it('renders justified plain text using the cell width', () => {+ const environment = setupRenderTestEnv();+ const univer = new Univer({ locale: LocaleType.EN_US });+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {+ id: 'justified-cell',+ styles: {+ justified: {+ ht: HorizontalAlign.JUSTIFIED,+ tb: WrapStrategy.WRAP,+ },+ },+ sheetOrder: ['sheet'],+ sheets: {+ sheet: {+ id: 'sheet',+ name: 'Sheet',+ rowCount: 10,+ columnCount: 10,+ defaultColumnWidth: 72,+ cellData: {+ 0: {+ 0: {+ v: 'one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen',+ s: 'justified',+ },+ },+ },+ },+ },+ });+ const worksheet = workbook.getActiveSheet()!;+ const skeleton = univer+ .__getInjector()+ .createInstance(SpreadsheetSkeleton, worksheet, workbook.getStyles());+ try {+ skeleton.calculate();+ const cell = worksheet.getCellRaw(0, 0)!;+ const style = worksheet.getComposedCellStyleByCellData(0, 0, cell);+ skeleton._setFontStylesCache(0, 0, cell, style, true);+ const documentSkeleton = skeleton.stylesCache.fontMatrix.getValue(0, 0)?.documentSkeleton;+ const lines = documentSkeleton?.getSkeletonData()?.pages[0].sections[0].columns[0].lines ?? [];+ const firstDivide = lines[0]?.divides[0];+ const visibleGlyphs = firstDivide?.glyphGroup.filter((glyph) => glyph.content !== '') ?? [];+ const lastGlyph = visibleGlyphs[visibleGlyphs.length - 1];++ expect(documentSkeleton).toBeDefined();+ expect(lines.length).toBeGreaterThan(1);+ expect(firstDivide?.isFull).toBe(true);+ expect(lastGlyph).toBeDefined();+ expect(lastGlyph!.left + lastGlyph!.width).toBeCloseTo(firstDivide!.width, 1);+ } finally {+ skeleton.dispose();+ univer.dispose();+ environment.restore();+ }+ });++ it('renders distributed plain text across the merged cell width', () => {+ const environment = setupRenderTestEnv();+ const univer = new Univer({ locale: LocaleType.EN_US });+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {+ id: 'distributed-merged-cell',+ styles: {+ distributed: {+ ht: HorizontalAlign.DISTRIBUTED,+ },+ },+ sheetOrder: ['sheet'],+ sheets: {+ sheet: {+ id: 'sheet',+ name: 'Sheet',+ rowCount: 10,+ columnCount: 10,+ defaultColumnWidth: 72,+ mergeData: [+ {+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 2,+ rangeType: RANGE_TYPE.NORMAL,+ },+ ],+ cellData: {+ 0: {+ 0: { v: '重庆市建设工程质量监督总站', s: 'distributed' },+ },+ },+ },+ },+ });+ const worksheet = workbook.getActiveSheet()!;+ const skeleton = univer+ .__getInjector()+ .createInstance(SpreadsheetSkeleton, worksheet, workbook.getStyles());+ try {+ skeleton.calculate();+ const cell = worksheet.getCellRaw(0, 0)!;+ const style = worksheet.getComposedCellStyleByCellData(0, 0, cell);+ skeleton._setFontStylesCache(0, 0, cell, style, true);+ const documentSkeleton = skeleton.stylesCache.fontMatrix.getValue(0, 0)?.documentSkeleton;+ const divide = documentSkeleton?.getSkeletonData()?.pages[0].sections[0].columns[0].lines[0].divides[0];+ const visibleGlyphs = divide?.glyphGroup.filter((glyph) =>+ glyph.content !== '' && glyph.streamType !== DataStreamTreeTokenType.PARAGRAPH+ ) ?? [];+ const lastGlyph = visibleGlyphs[visibleGlyphs.length - 1];++ expect(documentSkeleton).toBeDefined();+ expect(lastGlyph).toBeDefined();+ expect(lastGlyph!.left + lastGlyph!.width).toBeCloseTo(divide!.width, 1);+ expect(divide?.paddingLeft).toBe(0);+ } finally {+ skeleton.dispose();+ univer.dispose();+ environment.restore();+ }+ });++ it('renders a merged border stored only on an edge cell', () => {+ const environment = setupRenderTestEnv();+ const univer = new Univer({ locale: LocaleType.EN_US });+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {+ id: 'merged-cell-edge-border',+ styles: {+ rightBorder: {+ bd: {+ r: { s: BorderStyleTypes.THIN, cl: { rgb: '#000000' } },+ },+ },+ },+ sheetOrder: ['sheet'],+ sheets: {+ sheet: {+ id: 'sheet',+ name: 'Sheet',+ rowCount: 10,+ columnCount: 10,+ mergeData: [+ {+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 1,+ rangeType: RANGE_TYPE.NORMAL,+ },+ ],+ cellData: {+ 0: {+ 0: { v: 'merged' },+ 1: { s: 'rightBorder' },+ },+ },+ },+ },+ });+ const worksheet = workbook.getActiveSheet()!;+ const skeleton = univer+ .__getInjector()+ .createInstance(SpreadsheetSkeleton, worksheet, workbook.getStyles());+ try {+ skeleton.calculate();+ const cell = worksheet.getCellRaw(0, 0)!;+ const style = worksheet.getComposedCellStyleByCellData(0, 0, cell);+ skeleton._setBorderStylesCache(0, 0, style, {+ mergeRange: {+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 1,+ },+ });++ expect(skeleton.stylesCache.border?.getValue(0, 1)?.[BORDER_TYPE.RIGHT]).toEqual({+ type: BORDER_TYPE.RIGHT,+ style: BorderStyleTypes.THIN,+ color: '#000000',+ });+ } finally {+ skeleton.dispose();+ univer.dispose();+ environment.restore();+ }+ });+});+describe('General number display', () => {afterEach(() => {vi.restoreAllMocks();diff --git a/packages/engine-render/src/components/sheets/extensions/__tests__/font.spec.ts b/packages/engine-render/src/components/sheets/extensions/__tests__/font.spec.tsindex a0abbe2ead..cb59951590 100644--- a/packages/engine-render/src/components/sheets/extensions/__tests__/font.spec.ts+++ b/packages/engine-render/src/components/sheets/extensions/__tests__/font.spec.ts@@ -461,6 +461,54 @@ describe('font extension', () => {expect(documentSkeleton.calculate).not.toHaveBeenCalled();});+ it.each([HorizontalAlign.JUSTIFIED, HorizontalAlign.DISTRIBUTED])(+ 'keeps the cell width while rendering full-width alignment %s',+ (horizontalAlign) => {+ const font = new Font() as any;+ const ctx = createCtx();+ const overflow = new ObjectMatrix<any>();+ const spreadsheetSkeleton = createSpreadsheetSkeleton();+ const documentDataModel = {+ updateDocumentDataPageSize: vi.fn(),+ getBody: vi.fn(() => ({ paragraphs: [{}] })),+ getSnapshot: vi.fn(() => ({ documentStyle: {} })),+ };+ const documentSkeleton = {+ getViewModel: vi.fn(() => ({+ getDataModel: vi.fn(() => documentDataModel),+ })),+ calculate: vi.fn(),+ makeDirty: vi.fn(),+ };+ const documents = {+ resize: vi.fn(),+ changeSkeleton: vi.fn(() => documents),+ render: vi.fn(),+ };+ font.parent = {+ getDocuments: vi.fn(() => documents),+ };++ font._renderDocuments(ctx, 0, 0, {+ fontCache: createFontCache({+ documentSkeleton,+ horizontalAlign,+ wrapStrategy: WrapStrategy.OVERFLOW,+ vertexAngle: 0,+ }),+ startX: 10,+ startY: 0,+ endX: 110,+ endY: 20,+ spreadsheetSkeleton,+ }, overflow);++ expect(documentDataModel.updateDocumentDataPageSize).toHaveBeenCalledOnce();+ expect(documentDataModel.updateDocumentDataPageSize).toHaveBeenCalledWith(100);+ expect(documentSkeleton.calculate).toHaveBeenCalledOnce();+ }+ );+it('covers image rendering fallback branches', () => {const font = new Font() as any;const ctx = createCtx();diff --git a/packages/engine-render/src/components/sheets/extensions/font.ts b/packages/engine-render/src/components/sheets/extensions/font.tsindex 5c5ca157b3..e4825f6652 100644--- a/packages/engine-render/src/components/sheets/extensions/font.ts+++ b/packages/engine-render/src/components/sheets/extensions/font.ts@@ -47,7 +47,7 @@ import { clampRange, inViewRanges } from '../../../basics/tools';import { Text } from '../../../shape/text';import { SpreadsheetExtensionRegistry } from '../../extension';import { EXPAND_SIZE_FOR_RENDER_OVERFLOW, FONT_EXTENSION_Z_INDEX, shouldRenderRowText } from '../constants';-import { DEFAULT_PADDING_DATA, getDocsSkeletonPageSize } from '../sheet.render-skeleton';+import { DEFAULT_PADDING_DATA, FULL_WIDTH_HORIZONTAL_ALIGNMENTS, getDocsSkeletonPageSize } from '../sheet.render-skeleton';import { calculateCellImageRect } from '../util';import { SheetExtension } from './sheet-extension';@@ -684,7 +684,7 @@ export class Font extends SheetExtension {const { fontCache } = renderFontCtx;if (!fontCache) return;- const { documentSkeleton, vertexAngle = 0, wrapStrategy } = fontCache;+ const { documentSkeleton, vertexAngle = 0, wrapStrategy, horizontalAlign } = fontCache;if (!documentSkeleton) return;const documentDataModel = documentSkeleton.getViewModel().getDataModel();@@ -693,7 +693,10 @@ export class Font extends SheetExtension {const cellHeight = endY - startY;// WRAP means next line- if (wrapStrategy === WrapStrategy.WRAP && vertexAngle === 0) {+ if (+ vertexAngle === 0 &&+ (wrapStrategy === WrapStrategy.WRAP || FULL_WIDTH_HORIZONTAL_ALIGNMENTS.has(horizontalAlign))+ ) {documentDataModel.updateDocumentDataPageSize(endX - startX);documentSkeleton.calculate();} else {diff --git a/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts b/packages/engine-render/src/components/sheets/sheet.render-skeleton.tsindex 01911cc267..6da740c3a7 100644--- a/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts+++ b/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts@@ -95,6 +95,10 @@ export const RENDER_RAW_FORMULA_KEY = 'RENDER_RAW_FORMULA';const GENERAL_NUMBER_MAX_SIGNIFICANT_DIGITS = 15;const GENERAL_NUMBER_RESERVE_GLYPH = '0';+export const FULL_WIDTH_HORIZONTAL_ALIGNMENTS = new Set([+ HorizontalAlign.JUSTIFIED,+ HorizontalAlign.DISTRIBUTED,+]);export function getShrinkToFitScale(contentWidth: number, availableWidth: number, fontSize: number): number {if (contentWidth <= availableWidth || contentWidth <= 0 || availableWidth <= 0 || fontSize <= 0) {@@ -197,6 +201,12 @@ function setRenderTextCache(cacheItem: IFontCacheItem, cellData: Nullable<ICellD);}+function updateDocumentPageWidth(documentModel: DocumentDataModel, cellInfo: ICellWithCoord): void {+ const startX = cellInfo.isMergedMainCell ? cellInfo.mergeInfo.startX : cellInfo.startX;+ const endX = cellInfo.isMergedMainCell ? cellInfo.mergeInfo.endX : cellInfo.endX;+ documentModel.updateDocumentDataPageSize(endX - startX, Infinity);+}+function pushRowRange(ranges: IRange[], row: number, startColumn: number, endColumn: number): void {if (endColumn < startColumn) {return;@@ -1117,7 +1127,7 @@ export class SpreadsheetSkeleton extends SheetSkeleton {(wrapStrategy === WrapStrategy.OVERFLOW || wrapStrategy === WrapStrategy.UNSPECIFIED) &&cellValueType !== CellValueType.NUMBER &&cellValueType !== CellValueType.BOOLEAN &&- horizontalAlign !== HorizontalAlign.JUSTIFIED+ !FULL_WIDTH_HORIZONTAL_ALIGNMENTS.has(horizontalAlign)) {docsConfig.textFitsCurrentCell = false;// Merged cells do not support overflow.@@ -1348,20 +1358,20 @@ export class SpreadsheetSkeleton extends SheetSkeleton {if (!cacheItem.border) return;this._handleBorderMatrix.setValue(row, col, true);- if (style && style.bd) {- const mergeRange = options?.mergeRange;- if (mergeRange) {- this._setMergeBorderProps(BORDER_TYPE.TOP, this._stylesCache, mergeRange);- this._setMergeBorderProps(BORDER_TYPE.BOTTOM, this._stylesCache, mergeRange);- this._setMergeBorderProps(BORDER_TYPE.LEFT, this._stylesCache, mergeRange);- this._setMergeBorderProps(BORDER_TYPE.RIGHT, this._stylesCache, mergeRange);- } else if (!this.intersectMergeRange(row, col)) {- this._setBorderProps(row, col, BORDER_TYPE.TOP, style, this._stylesCache);- this._setBorderProps(row, col, BORDER_TYPE.BOTTOM, style, this._stylesCache);- this._setBorderProps(row, col, BORDER_TYPE.LEFT, style, this._stylesCache);- this._setBorderProps(row, col, BORDER_TYPE.RIGHT, style, this._stylesCache);- }+ const mergeRange = options?.mergeRange;+ if (mergeRange) {+ this._setMergeBorderProps(BORDER_TYPE.TOP, this._stylesCache, mergeRange);+ this._setMergeBorderProps(BORDER_TYPE.BOTTOM, this._stylesCache, mergeRange);+ this._setMergeBorderProps(BORDER_TYPE.LEFT, this._stylesCache, mergeRange);+ this._setMergeBorderProps(BORDER_TYPE.RIGHT, this._stylesCache, mergeRange);+ } else if (style && style.bd && !this.intersectMergeRange(row, col)) {+ this._setBorderProps(row, col, BORDER_TYPE.TOP, style, this._stylesCache);+ this._setBorderProps(row, col, BORDER_TYPE.BOTTOM, style, this._stylesCache);+ this._setBorderProps(row, col, BORDER_TYPE.LEFT, style, this._stylesCache);+ this._setBorderProps(row, col, BORDER_TYPE.RIGHT, style, this._stylesCache);+ }+ if (style && style.bd) {this._setBorderProps(row, col, BORDER_TYPE.TL_BR, style, this._stylesCache);this._setBorderProps(row, col, BORDER_TYPE.TL_BC, style, this._stylesCache);this._setBorderProps(row, col, BORDER_TYPE.TL_MR, style, this._stylesCache);@@ -1490,9 +1500,10 @@ export class SpreadsheetSkeleton extends SheetSkeleton {return;}const { vertexAngle, centerAngle } = convertTextRotation(style?.tr ?? { a: 0 });- const isRichText = cellData?.p || vertexAngle || centerAngle;+ const shouldUseDocumentLayout = Boolean(cellData?.p || vertexAngle || centerAngle) ||+ FULL_WIDTH_HORIZONTAL_ALIGNMENTS.has(style?.ht ?? HorizontalAlign.UNSPECIFIED);- const modelObject = isRichText ?+ const modelObject = shouldUseDocumentLayout ?this.worksheet.getCellDocumentModel(cellData, style, {isDeepClone: true,displayRawFormula: this._renderRawFormula,@@ -1503,6 +1514,9 @@ export class SpreadsheetSkeleton extends SheetSkeleton {const { documentModel } = modelObject;if (documentModel) {const { fontString, wrapStrategy, verticalAlign, horizontalAlign } = modelObject;+ if (FULL_WIDTH_HORIZONTAL_ALIGNMENTS.has(horizontalAlign)) {+ updateDocumentPageWidth(documentModel, this.getCellWithCoordByIndex(row, col, false));+ }const documentViewModel = new DocumentViewModel(documentModel);if (documentViewModel) {const documentSkeleton = DocumentSkeleton.create(documentViewModel, this._localeService);