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.

fix(docs): preserve shape text layout fidelity (#7245)

Univerd5197448c6f2
diff --git a/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/mergedCellsRenderingScrolling-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/mergedCellsRenderingScrolling-ci-chromium-linux.png
index 0bada8d0ba..7f2dee4395 100644
Binary files a/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/mergedCellsRenderingScrolling-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/mergedCellsRenderingScrolling-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/renderingAfterScrollByAPI-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/renderingAfterScrollByAPI-ci-chromium-linux.png
index e727dd6803..479a8ed06d 100644
Binary files a/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/renderingAfterScrollByAPI-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/renderingAfterScrollByAPI-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/mergedCellsRendering-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/mergedCellsRendering-ci-chromium-linux.png
index e5f31f1827..c003df1b80 100644
Binary files a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/mergedCellsRendering-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/mergedCellsRendering-ci-chromium-linux.png differ
diff --git a/packages/engine-render/src/basics/__tests__/tools.spec.ts b/packages/engine-render/src/basics/__tests__/tools.spec.ts
index ac2bdbcb89..ad89778f30 100644
--- a/packages/engine-render/src/basics/__tests__/tools.spec.ts
+++ b/packages/engine-render/src/basics/__tests__/tools.spec.ts
@@ -178,9 +178,14 @@ describe('tools extra', () => {
expect(fontStack.fontFamily).toBe('"SF Mono", "Cascadia Code", Consolas, monospace');
expect(fontStack.fontString).toContain('"SF Mono", "Cascadia Code", Consolas, monospace');
- const fractional = getFontStyleString({ fs: 10.5, ff: 'Arial' } as any);
- expect(fractional.originFontSize).toBe(10.5);
- expect(fractional.fontString).toContain('10.5pt');
+ const fractionalSize = getFontStyleString({
+ fs: 10.0125,
+ ff: 'Microsoft YaHei',
+ } as any);
+ expect(fractionalSize.originFontSize).toBe(10.0125);
+ expect(fractionalSize.fontSize).toBe(10.0125);
+ expect(fractionalSize.fontString).toContain('10.0125pt');
+ expect(fractionalSize.fontCache).toContain('10.0125pt');
const superscript = getFontStyleString({
fs: 12,
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/doc-no-wrap-measure.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/doc-no-wrap-measure.spec.ts
index bc378dee0c..b4b15bfaa0 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/doc-no-wrap-measure.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/doc-no-wrap-measure.spec.ts
@@ -16,7 +16,11 @@
import type { IDocumentData } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
-import { measureDocumentNoWrapTextWidth } from '../doc-no-wrap-measure';
+import {
+ measureDocumentNoWrapTextRangeWidth,
+ measureDocumentNoWrapTextWidth,
+ measureDocumentUnbreakableTextWidth,
+} from '../doc-no-wrap-measure';
import { FontCache } from '../shaping-engine/font-cache';
function createDocument(dataStream: string): IDocumentData {
@@ -58,4 +62,60 @@ describe('measureDocumentNoWrapTextWidth', () => {
measureSpy.mockRestore();
});
+
+ it('honors paragraph breaks that fall between text runs', () => {
+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
+ width: text.length * 10,
+ }) as never);
+ const document = createDocument('AA\rBBBB\r\n');
+ document.body!.textRuns = [
+ { st: 0, ed: 2, ts: { fs: 20 } },
+ { st: 3, ed: 7, ts: { fs: 20 } },
+ ];
+
+ expect(measureDocumentNoWrapTextWidth(document)).toBe(40);
+
+ measureSpy.mockRestore();
+ });
+});
+
+describe('measureDocumentUnbreakableTextWidth', () => {
+ it('uses the docs line-break policy for words, spaces, and CJK text', () => {
+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
+ width: Array.from(text).reduce((total, char) => total + (/[⺀-鿿豈-﫿]/u.test(char) ? 20 : 10), 0),
+ }) as never);
+
+ expect(measureDocumentUnbreakableTextWidth(createDocument('short longest 你好\r\n'))).toBe(70);
+
+ measureSpy.mockRestore();
+ });
+
+ it('preserves text-run styles while measuring a break segment', () => {
+ const measuredFonts = new Set<string>();
+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string, font: string) => {
+ measuredFonts.add(font);
+ return { width: text.length * 10 } as never;
+ });
+ const document = createDocument('ABCD E\r\n');
+ document.body!.textRuns = [
+ { st: 0, ed: 2, ts: { fs: 10 } },
+ { st: 2, ed: 4, ts: { fs: 20 } },
+ ];
+
+ expect(measureDocumentUnbreakableTextWidth(document)).toBe(40);
+ expect(measuredFonts.size).toBeGreaterThan(1);
+
+ measureSpy.mockRestore();
+ });
+
+ it('measures a styled document range without creating a temporary document', () => {
+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
+ width: text.length * 10,
+ }) as never);
+ const document = createDocument('First Second\r\n');
+
+ expect(measureDocumentNoWrapTextRangeWidth(document, 6, 12)).toBe(60);
+
+ measureSpy.mockRestore();
+ });
});
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts
index f35ab81c73..5fd36f8d44 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts
@@ -135,6 +135,16 @@ describe('layout-ruler', () => {
expect(result[0].sections.length).toBeGreaterThan(0);
});
+ it('uses trailing CJK punctuation shrinkability when deciding line overflow', () => {
+ const text = createGlyph('字', 10);
+ const punctuation = createGlyph(',', 10);
+ punctuation.adjustability.shrinkability = [0, 5];
+
+ expect(__testing.isGlyphGroupBeyondDivideWidth([text, punctuation], 85, 100)).toBe(false);
+ punctuation.adjustability.shrinkability = [0, 0];
+ expect(__testing.isGlyphGroupBeyondDivideWidth([text, punctuation], 85, 100)).toBe(true);
+ });
+
it('keeps direct paragraph indents before bullet list defaults', () => {
const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Item');
const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.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.ts
index 27b223e5f0..e86b00cb77 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
@@ -91,6 +91,17 @@ function isBeyondDivideWidth(width: number, divideWidth: number) {
return width - divideWidth > tolerance;
}
+function isGlyphGroupBeyondDivideWidth(
+ glyphGroup: IDocumentSkeletonGlyph[],
+ offsetLeft: number,
+ divideWidth: number
+) {
+ const width = __getGlyphGroupWidth(glyphGroup);
+ const trailingShrinkability = glyphGroup[glyphGroup.length - 1]?.adjustability?.shrinkability?.[1] ?? 0;
+
+ return isBeyondDivideWidth(offsetLeft + width - trailingShrinkability, divideWidth);
+}
+
export function layoutParagraph(
ctx: ILayoutContext,
glyphGroup: IDocumentSkeletonGlyph[],
@@ -245,14 +256,13 @@ function _divideOperator(
const lastPage = getLastPage(pages);
const divideInfo = getLastNotFullDivideInfo(lastPage); // Get the first divide in the latest line that is not full.
if (divideInfo) {
- const width = __getGlyphGroupWidth(glyphGroup);
const { divide, isLast } = divideInfo;
const lastGlyph = divide?.glyphGroup?.[divide.glyphGroup.length - 1];
const lastWidth = lastGlyph?.width || 0;
const lastLeft = lastGlyph?.left || 0;
const preOffsetLeft = lastWidth + lastLeft;
const { hyphenationZone } = sectionBreakConfig;
- if (isBeyondDivideWidth(preOffsetLeft + width, divide.width)) {
+ if (isGlyphGroupBeyondDivideWidth(glyphGroup, preOffsetLeft, divide.width)) {
if (
divide?.glyphGroup.length === 0 &&
glyphGroup.length > 0 &&
@@ -307,8 +317,7 @@ function _divideOperator(
while (glyphGroup.length) {
sliceGlyphGroup.push(glyphGroup.shift()!);
- const sliceGlyphGroupWidth = __getGlyphGroupWidth(sliceGlyphGroup);
- if (isBeyondDivideWidth(sliceGlyphGroupWidth, divide.width)) {
+ if (isGlyphGroupBeyondDivideWidth(sliceGlyphGroup, 0, divide.width)) {
// To avoid infinity loop when width is less than one char's width.
if (sliceGlyphGroup.length > 1) { // || (sliceGlyphGroup.length > 0 && sliceGlyphGroup[sliceGlyphGroup.length - 1].drawingId)) {
glyphGroup.unshift(sliceGlyphGroup.pop()!);
@@ -1375,6 +1384,7 @@ function checkRelativeDrawingNeedRePosition(ctx: ILayoutContext, floatObject: IF
export const __testing = {
reLayoutCheck: _reLayoutCheck,
avoidFlowAffectingDrawingsForTable: __avoidFlowAffectingDrawingsForTable,
+ isGlyphGroupBeyondDivideWidth,
};
function _columnOperator(
diff --git a/packages/engine-render/src/components/docs/layout/doc-no-wrap-measure.ts b/packages/engine-render/src/components/docs/layout/doc-no-wrap-measure.ts
index f1bbc96841..f5d2ddd0ea 100644
--- a/packages/engine-render/src/components/docs/layout/doc-no-wrap-measure.ts
+++ b/packages/engine-render/src/components/docs/layout/doc-no-wrap-measure.ts
@@ -14,16 +14,11 @@
* limitations under the License.
*/
-import type { IDocumentData, ITextStyle } from '@univerjs/core';
+import type { IDocumentData, ITextRun, ITextStyle } from '@univerjs/core';
import { getFontStyleString } from '../../../basics/tools';
+import { LineBreaker } from './line-breaker';
import { FontCache } from './shaping-engine/font-cache';
-interface IDocumentNoWrapTextRunLike {
- st?: number;
- ed?: number;
- ts?: ITextStyle;
-}
-
function splitDocumentNoWrapMeasureLines(text: string): string[] {
return text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n');
}
@@ -83,15 +78,17 @@ function measureDocumentNoWrapCJKLatinSpacing(
}
function measureDocumentNoWrapLineByStyle(text: string, textStyle: ITextStyle | undefined): number {
+ const visibleText = text.slice(0, getDocumentNoWrapMeasureTrailingWhitespaceStart(text));
const previous = { char: '', cjkWidth: 0 };
- return measureDocumentNoWrapTextByStyle(text, textStyle) +
- measureDocumentNoWrapCJKLatinSpacing(text, textStyle, previous);
+ return measureDocumentNoWrapTextByStyle(visibleText, textStyle) +
+ measureDocumentNoWrapCJKLatinSpacing(visibleText, textStyle, previous);
}
function measureDocumentNoWrapRunsWidth(
dataStream: string,
- textRuns: IDocumentNoWrapTextRunLike[]
+ textRuns: ITextRun[],
+ fallbackTextStyle: ITextStyle | undefined
): number {
let currentLineWidth = 0;
let maxLineWidth = 0;
@@ -128,23 +125,69 @@ function measureDocumentNoWrapRunsWidth(
previous.cjkWidth = 0;
};
- textRuns.forEach((run) => {
- const start = Math.max(0, run.st ?? 0);
- const end = Math.max(start, run.ed ?? start);
- const segments = splitDocumentNoWrapMeasureLines(dataStream.slice(start, end));
+ const appendRange = (text: string, textStyle: ITextStyle | undefined) => {
+ const segments = splitDocumentNoWrapMeasureLines(text);
segments.forEach((segment, index) => {
if (index > 0) {
finishLine();
}
- appendSegment(segment, run.ts);
+ appendSegment(segment, textStyle);
});
- });
+ };
+
+ let cursor = 0;
+ [...textRuns]
+ .sort((a, b) => a.st - b.st)
+ .forEach((run) => {
+ const start = Math.max(0, run.st);
+ const end = Math.max(start, run.ed);
+ if (start > cursor) {
+ appendRange(dataStream.slice(cursor, start), fallbackTextStyle);
+ }
+ const effectiveStart = Math.max(start, cursor);
+ if (end > effectiveStart) {
+ appendRange(dataStream.slice(effectiveStart, end), run.ts);
+ }
+ cursor = Math.max(cursor, end);
+ });
+ if (cursor < dataStream.length) {
+ appendRange(dataStream.slice(cursor), fallbackTextStyle);
+ }
return Math.max(maxLineWidth, currentLineWidth);
}
+export function measureDocumentNoWrapTextRangeWidth(documentData: IDocumentData, start: number, end: number): number {
+ const body = documentData.body;
+ const dataStream = body?.dataStream ?? '';
+ const rangeStart = Math.max(0, Math.min(dataStream.length, start));
+ const rangeEnd = Math.max(rangeStart, Math.min(dataStream.length, end));
+ const rangeText = dataStream.slice(rangeStart, rangeEnd);
+ const textRuns = (body?.textRuns ?? [])
+ .map((run): ITextRun | null => {
+ const runStart = Math.max(rangeStart, run.st);
+ const runEnd = Math.min(rangeEnd, run.ed);
+ if (runEnd <= runStart) {
+ return null;
+ }
+
+ return {
+ ...run,
+ st: runStart - rangeStart,
+ ed: runEnd - rangeStart,
+ };
+ })
+ .filter((run): run is ITextRun => run !== null);
+
+ if (textRuns.length) {
+ return measureDocumentNoWrapRunsWidth(rangeText, textRuns, documentData.documentStyle?.textStyle);
+ }
+
+ return measureDocumentNoWrapLineByStyle(rangeText, documentData.documentStyle?.textStyle);
+}
+
/**
* Measures the widest no-wrap line using the same text-width policy that docs
* layout relies on for lightweight shape/text-box autofit flows.
@@ -159,10 +202,14 @@ function measureDocumentNoWrapRunsWidth(
export function measureDocumentNoWrapTextWidth(documentData: IDocumentData | null | undefined): number {
const body = documentData?.body;
const dataStream = body?.dataStream ?? '';
- const textRuns = body?.textRuns as IDocumentNoWrapTextRunLike[] | undefined;
+ const textRuns = body?.textRuns;
if (textRuns?.length) {
- return measureDocumentNoWrapRunsWidth(dataStream, textRuns);
+ return measureDocumentNoWrapRunsWidth(
+ dataStream,
+ textRuns,
+ documentData?.documentStyle?.textStyle
+ );
}
const fallbackTextStyle = documentData?.documentStyle?.textStyle;
@@ -172,3 +219,28 @@ export function measureDocumentNoWrapTextWidth(documentData: IDocumentData | nul
...splitDocumentNoWrapMeasureLines(dataStream).map((line) => measureDocumentNoWrapLineByStyle(line, fallbackTextStyle))
);
}
+
+/**
+ * Measures the widest segment that docs line breaking keeps together. This is
+ * useful when a host may wrap normally but still needs enough width to avoid
+ * clipping an individual word, CJK glyph, or punctuation segment.
+ */
+export function measureDocumentUnbreakableTextWidth(documentData: IDocumentData | null | undefined): number {
+ const dataStream = documentData?.body?.dataStream ?? '';
+ if (!documentData || !dataStream) {
+ return 0;
+ }
+
+ const breaker = new LineBreaker(dataStream);
+ let start = 0;
+ let maxWidth = 0;
+ let breakPoint = breaker.nextBreakPoint();
+
+ while (breakPoint) {
+ maxWidth = Math.max(maxWidth, measureDocumentNoWrapTextRangeWidth(documentData, start, breakPoint.position));
+ start = breakPoint.position;
+ breakPoint = breaker.nextBreakPoint();
+ }
+
+ return maxWidth;
+}
diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.ts
index d9c9c7f29e..069ca3f9a9 100644
--- a/packages/engine-render/src/index.ts
+++ b/packages/engine-render/src/index.ts
@@ -26,7 +26,11 @@ export { Documents } from './components/docs/document';
export type { IPageRenderConfig } from './components/docs/document';
export type { IDocumentOffsetConfig } from './components/docs/document';
export { getTableIdAndSliceIndex } from './components/docs/layout/block/table';
-export { measureDocumentNoWrapTextWidth } from './components/docs/layout/doc-no-wrap-measure';
+export {
+ measureDocumentNoWrapTextRangeWidth,
+ measureDocumentNoWrapTextWidth,
+ measureDocumentUnbreakableTextWidth,
+} from './components/docs/layout/doc-no-wrap-measure';
export * from './components/docs/layout/doc-simple-skeleton';
export { DocumentSkeleton } from './components/docs/layout/doc-skeleton';
export type { IFindNodeRestrictions } from './components/docs/layout/doc-skeleton';