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): improve DOCX floating drawing layout (#7123)
Univerdc8dd28ee59e
diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.tsindex f9fd477a7a..ea455f4092 100644--- a/packages/core/src/types/interfaces/i-document-data.ts+++ b/packages/core/src/types/interfaces/i-document-data.ts@@ -167,7 +167,7 @@ export enum DocStyleType {/*** Properties of doc footer*/-export interface IFooterData {+export interface IFooterData extends IReferenceSource {footerId: string;body: IDocumentBody;}@@ -175,7 +175,7 @@ export interface IFooterData {/*** Properties of doc header*/-export interface IHeaderData {+export interface IHeaderData extends IReferenceSource {headerId: string;body: IDocumentBody;}@@ -480,6 +480,12 @@ export enum GridType {export interface IDocumentStyle extends IDocStyleBase, IDocumentLayout, IHeaderAndFooterBase {textStyle?: ITextStyle; // default style for text+ background?: IDocumentBackground; // Page background image.+}++export interface IDocumentBackground {+ source?: string;+ sourceType?: ImageSourceType;}/**diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.tsindex 002e100e9a..4f4e1d810e 100644--- a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts@@ -14,11 +14,11 @@* limitations under the License.*/-import { BooleanNumber, PositionedObjectLayoutType } from '@univerjs/core';+import { AlignTypeH, AlignTypeV, BooleanNumber, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType } from '@univerjs/core';import { Liquid, setDocsTableRenderViewportProvider } from '@univerjs/engine-render';import { afterEach, describe, expect, it, vi } from 'vitest';import { getDocsTableCellAnchorContext } from '../../doc-drawing-transformer-update.controller';-import { DocDrawingTransformUpdateController, getDocsTableCellDrawingOffset } from '../doc-drawing-transform-update.controller';+import { DocDrawingTransformUpdateController, getDocsDrawingBehindText, getDocsDrawingClipPage, getDocsDrawingPageClipBounds, getDocsPageRelativeDrawingAnchorPage, getDocsPageRelativeDrawingLeft, getDocsPageRelativeDrawingTop, getDocsTableCellDrawingOffset } from '../doc-drawing-transform-update.controller';describe('DocDrawingTransformUpdateController', () => {afterEach(() => {@@ -134,6 +134,10 @@ describe('DocDrawingTransformUpdateController', () => {controller._context = context;controller._drawingManagerService = drawingManagerService;controller._liquid = new Liquid();+ const defaultDocTransform = {+ positionH: {},+ positionV: {},+ };const normalDrawing = {aLeft: 10,@@ -145,6 +149,7 @@ describe('DocDrawingTransformUpdateController', () => {drawingOrigin: {layoutType: PositionedObjectLayoutType.WRAP_NONE,behindDoc: BooleanNumber.TRUE,+ docTransform: defaultDocTransform,},};const headerDrawing = {@@ -156,6 +161,7 @@ describe('DocDrawingTransformUpdateController', () => {drawingId: 'header-drawing',drawingOrigin: {layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: defaultDocTransform,},};const tableCellDrawing = {@@ -167,6 +173,7 @@ describe('DocDrawingTransformUpdateController', () => {drawingId: 'cell-drawing',drawingOrigin: {layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: defaultDocTransform,},};const multiDrawingOnPage = {@@ -180,6 +187,7 @@ describe('DocDrawingTransformUpdateController', () => {layoutType: PositionedObjectLayoutType.WRAP_SQUARE,behindDoc: BooleanNumber.FALSE,isMultiTransform: BooleanNumber.TRUE,+ docTransform: defaultDocTransform,},};const multiDrawingInHeader = {@@ -237,16 +245,16 @@ describe('DocDrawingTransformUpdateController', () => {expect(drawingManagerService.refreshTransform).toHaveBeenCalledWith([expect.objectContaining({drawingId: 'header-drawing',- transform: { left: 19, top: 30, width: 9, height: 10, angle: 0 },+ transform: expect.objectContaining({ left: 19, top: 30, width: 9, height: 10, angle: 0 }),}),expect.objectContaining({drawingId: 'normal-drawing',behindText: true,- transform: { left: 26, top: 40, width: 30, height: 40, angle: 5 },+ transform: expect.objectContaining({ left: 26, top: 40, width: 30, height: 40, angle: 5 }),}),expect.objectContaining({drawingId: 'cell-drawing',- transform: { left: 56, top: 69, width: 11, height: 12, angle: 0 },+ transform: expect.objectContaining({ left: 56, top: 69, width: 11, height: 12, angle: 0 }),}),]);expect(drawingManagerService.removeNotification).toHaveBeenCalledWith([@@ -258,11 +266,155 @@ describe('DocDrawingTransformUpdateController', () => {drawingId: 'multi-drawing',isMultiTransform: BooleanNumber.TRUE,transforms: [- { left: 32, top: 44, width: 13, height: 14, angle: 2 },- { left: 22, top: 28, width: 13, height: 14, angle: 2 },+ expect.objectContaining({ left: 32, top: 44, width: 13, height: 14, angle: 2 }),+ expect.objectContaining({ left: 22, top: 28, width: 13, height: 14, angle: 2 }),],}),]);expect(transformer.setSelectedControl).toHaveBeenCalledWith(selectedShape);});++ it('projects a document page clip bound in scene coordinates before page padding is applied', () => {+ expect(getDocsDrawingPageClipBounds({+ docsLeft: 20,+ docsTop: 30,+ pageOffsetLeft: 100,+ pageOffsetTop: 200,+ page: {+ pageWidth: 793,+ pageHeight: 1122,+ marginLeft: 48,+ marginTop: 48,+ },+ } as never)).toEqual({+ left: 120,+ top: 230,+ width: 793,+ height: 1122,+ });+ });++ it('projects a table cell drawing clip bound through the cell offset', () => {+ expect(getDocsDrawingPageClipBounds({+ docsLeft: 20,+ docsTop: 30,+ pageOffsetLeft: 100,+ pageOffsetTop: 200,+ clipOffsetLeft: 138,+ clipOffsetTop: 98,+ page: {+ pageWidth: 321,+ pageHeight: 300,+ },+ })).toEqual({+ left: 258,+ top: 328,+ width: 321,+ height: 300,+ });+ });++ it('clips page-sized header background drawings to the host document page', () => {+ const headerPage = {+ pageWidth: 589,+ pageHeight: 476,+ };+ const hostPage = {+ pageWidth: 816,+ pageHeight: 1056,+ };++ expect(getDocsDrawingClipPage({+ drawing: {+ behindText: true,+ transform: {+ width: 815,+ height: 1055,+ },+ },+ hostPage,+ page: headerPage,+ })).toBe(hostPage);++ expect(getDocsDrawingClipPage({+ drawing: {+ behindText: true,+ transform: {+ width: 120,+ height: 40,+ },+ },+ hostPage,+ page: headerPage,+ })).toBe(headerPage);+ });++ it('positions page-sized header backgrounds against the host page width', () => {+ expect(getDocsPageRelativeDrawingLeft({+ hostPage: {+ pageWidth: 816,+ },+ positionH: {+ align: AlignTypeH.RIGHT,+ relativeFrom: ObjectRelativeFromH.PAGE,+ },+ width: 815,+ })).toBe(1);+ });++ it('positions page-sized header backgrounds against the host page height', () => {+ expect(getDocsPageRelativeDrawingTop({+ hostPage: {+ pageHeight: 1056,+ },+ positionV: {+ align: AlignTypeV.TOP,+ relativeFrom: ObjectRelativeFromV.PAGE,+ },+ height: 1055,+ })).toBe(0);++ expect(getDocsPageRelativeDrawingTop({+ hostPage: {+ pageHeight: 1056,+ },+ positionV: {+ align: AlignTypeV.BOTTOM,+ relativeFrom: ObjectRelativeFromV.PAGE,+ },+ height: 1055,+ })).toBe(1);+ });++ it('uses body pages as page-relative drawing anchors when no host page exists', () => {+ const bodyPage = {+ pageWidth: 816,+ pageHeight: 1056,+ };++ expect(getDocsPageRelativeDrawingAnchorPage({+ page: bodyPage,+ clipPage: bodyPage,+ })).toBe(bodyPage);+ });++ it('renders header and footer drawings in the host page behind-text layer', () => {+ expect(getDocsDrawingBehindText({+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: BooleanNumber.FALSE,+ },+ hostPage: {+ pageWidth: 816,+ pageHeight: 1056,+ },+ } as never)).toBe(true);++ expect(getDocsDrawingBehindText({+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: BooleanNumber.FALSE,+ },+ } as never)).toBe(false);+ });});diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-transform-update.controller.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-transform-update.controller.tsindex 597ccd6877..f1f460606f 100644--- a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-transform-update.controller.ts+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-transform-update.controller.ts@@ -18,6 +18,8 @@ import type { DocumentDataModel, ICommandInfo, IDrawingParam, ITransformState }import type { IRichTextEditingMutationParams } from '@univerjs/docs';import type { Documents, DocumentSkeleton, IDocsTableRenderViewport, IDocumentSkeletonHeaderFooter, IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonTable, Image, IRenderContext, IRenderModule } from '@univerjs/engine-render';import {+ AlignTypeH,+ AlignTypeV,BooleanNumber,Disposable,fromEventSubject,@@ -26,6 +28,8 @@ import {IUniverInstanceService,LifecycleService,LifecycleStages,+ ObjectRelativeFromH,+ ObjectRelativeFromV,PositionedObjectLayoutType,} from '@univerjs/core';import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';@@ -47,6 +51,149 @@ interface IDrawingParamsWithBehindText {isMultiTransform: BooleanNumber;}+interface IDrawingClipBounds {+ left: number;+ top: number;+ width: number;+ height: number;+}++interface IDrawingTransformStateWithClipBounds extends ITransformState {+ clipBounds?: IDrawingClipBounds;+}++export function getDocsDrawingPageClipBounds(config: {+ docsLeft: number;+ docsTop: number;+ pageOffsetLeft: number;+ pageOffsetTop: number;+ clipOffsetLeft?: number;+ clipOffsetTop?: number;+ page: Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'>;+}): IDrawingClipBounds | undefined {+ const { docsLeft, docsTop, pageOffsetLeft, pageOffsetTop, clipOffsetLeft = 0, clipOffsetTop = 0, page } = config;+ const { pageWidth, pageHeight } = page;+ if (!Number.isFinite(pageWidth) || !Number.isFinite(pageHeight) || pageWidth <= 0 || pageHeight <= 0) {+ return;+ }++ return {+ left: docsLeft + pageOffsetLeft + clipOffsetLeft,+ top: docsTop + pageOffsetTop + clipOffsetTop,+ width: pageWidth,+ height: pageHeight,+ };+}++export function getDocsDrawingClipPage(config: {+ drawing: Pick<IDrawingParamsWithBehindText, 'behindText'> & {+ transform?: Pick<ITransformState, 'width' | 'height'>;+ };+ hostPage?: Pick<IDocumentSkeletonPage, 'pageWidth' | 'pageHeight'>;+ page: Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'>;+}): Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'> {+ const { drawing, hostPage, page } = config;+ if (hostPage == null || drawing.behindText !== true || drawing.transform == null) {+ return page;+ }++ const { width, height } = drawing.transform;+ if (width == null || height == null) {+ return page;+ }++ const widthRatio = width / hostPage.pageWidth;+ const heightRatio = height / hostPage.pageHeight;+ if (widthRatio >= 0.8 && heightRatio >= 0.8) {+ return hostPage;+ }++ return page;+}++export function getDocsPageRelativeDrawingLeft(config: {+ hostPage: Pick<IDocumentSkeletonPage, 'pageWidth'>;+ positionH: {+ align?: AlignTypeH;+ posOffset?: number;+ relativeFrom?: ObjectRelativeFromH;+ };+ width: number;+}): number | undefined {+ const { hostPage, positionH, width } = config;+ if (positionH.relativeFrom !== ObjectRelativeFromH.PAGE) {+ return;+ }++ if (positionH.align === AlignTypeH.RIGHT) {+ return hostPage.pageWidth - width;+ }+ if (positionH.align === AlignTypeH.CENTER) {+ return hostPage.pageWidth / 2 - width / 2;+ }+ if (positionH.posOffset != null) {+ return positionH.posOffset;+ }++ return 0;+}++export function getDocsPageRelativeDrawingTop(config: {+ hostPage: Pick<IDocumentSkeletonPage, 'pageHeight'>;+ positionV: {+ align?: AlignTypeV;+ posOffset?: number;+ relativeFrom?: ObjectRelativeFromV;+ };+ height: number;+}): number | undefined {+ const { hostPage, positionV, height } = config;+ if (positionV.relativeFrom !== ObjectRelativeFromV.PAGE) {+ return;+ }++ if (positionV.align === AlignTypeV.BOTTOM) {+ return hostPage.pageHeight - height;+ }+ if (positionV.align === AlignTypeV.CENTER) {+ return hostPage.pageHeight / 2 - height / 2;+ }+ if (positionV.posOffset != null) {+ return positionV.posOffset;+ }++ return 0;+}++export function getDocsPageRelativeDrawingAnchorPage(config: {+ page: Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'>;+ clipPage: Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'>;+ hostPage?: Pick<IDocumentSkeletonPage, 'pageWidth' | 'pageHeight'>;+}): Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'> | undefined {+ const { page, clipPage, hostPage } = config;+ if (hostPage != null && hostPage === clipPage) {+ return hostPage;+ }+ if (hostPage == null && page === clipPage) {+ return page;+ }+}++export function getDocsDrawingBehindText(config: {+ drawingOrigin: {+ layoutType?: PositionedObjectLayoutType;+ behindDoc?: BooleanNumber;+ };+ hostPage?: Pick<IDocumentSkeletonPage, 'pageWidth' | 'pageHeight'>;+}): boolean {+ const { drawingOrigin, hostPage } = config;+ if (hostPage != null) {+ return true;+ }++ return drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_NONE && drawingOrigin.behindDoc === BooleanNumber.TRUE;+}+export function getDocsTableCellDrawingOffset(unitId: string,table: IDocumentSkeletonTable,@@ -175,6 +322,10 @@ export class DocDrawingTransformUpdateController extends Disposable implements I}const { left: docsLeft, top: docsTop, pageLayoutType, pageMarginLeft, pageMarginTop } = documentComponent;+ if (docsLeft <= -10000 || docsTop <= -10000) {+ return;+ }+const { pages, skeHeaders, skeFooters } = skeletonData;const updateDrawingMap: Record<string, IDrawingParamsWithBehindText> = {}; // IFloatingObjectManagerParam@@ -197,7 +348,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements IdocsTop,updateDrawingMap,headerPage.marginTop,- page.marginLeft+ page.marginLeft,+ page);this._calculateTableCellDrawingPositions(unitId,@@ -223,7 +375,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements IdocsTop,updateDrawingMap,footerTop,- page.marginLeft+ page.marginLeft,+ page);this._calculateTableCellDrawingPositions(unitId,@@ -299,9 +452,13 @@ export class DocDrawingTransformUpdateController extends Disposable implements IdocsTop: number,updateDrawingMap: Record<string, IDrawingParamsWithBehindText>,marginTop: number,- marginLeft: number+ marginLeft: number,+ hostPage?: IDocumentSkeletonPage,+ clipOffset?: { left: number; top: number }) {const { skeDrawings } = page;+ const pageOffsetLeft = this._liquid.x;+ const pageOffsetTop = this._liquid.y;this._liquid.translatePagePadding({marginTop,marginLeft,@@ -309,15 +466,56 @@ export class DocDrawingTransformUpdateController extends Disposable implements IskeDrawings.forEach((drawing) => {const { aLeft, aTop, height, width, angle, drawingId, drawingOrigin } = drawing;- const behindText = drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_NONE && drawingOrigin.behindDoc === BooleanNumber.TRUE;+ const behindText = getDocsDrawingBehindText({ drawingOrigin, hostPage });const { isMultiTransform = BooleanNumber.FALSE } = drawingOrigin;+ const clipDrawing = {+ behindText,+ transform: {+ width,+ height,+ },+ };+ const clipPage = getDocsDrawingClipPage({+ drawing: clipDrawing,+ hostPage,+ page,+ });+ const pageClipBounds = getDocsDrawingPageClipBounds({+ docsLeft,+ docsTop,+ pageOffsetLeft,+ pageOffsetTop,+ clipOffsetLeft: clipOffset?.left,+ clipOffsetTop: clipOffset?.top,+ page: clipPage,+ });+ const pageRelativeAnchorPage = getDocsPageRelativeDrawingAnchorPage({+ page,+ clipPage,+ hostPage,+ });+ const pageRelativeLeft = pageRelativeAnchorPage != null+ ? getDocsPageRelativeDrawingLeft({+ hostPage: pageRelativeAnchorPage,+ positionH: drawingOrigin.docTransform.positionH,+ width,+ })+ : undefined;+ const pageRelativeTop = pageRelativeAnchorPage != null+ ? getDocsPageRelativeDrawingTop({+ hostPage: pageRelativeAnchorPage,+ positionV: drawingOrigin.docTransform.positionV,+ height,+ })+ : undefined;const transform = {- left: aLeft + docsLeft + this._liquid.x,- top: aTop + docsTop + this._liquid.y,+ left: (pageRelativeLeft ?? aLeft) + docsLeft + (pageRelativeLeft == null ? this._liquid.x : pageOffsetLeft),+ top: (pageRelativeTop ?? aTop) + docsTop + (pageRelativeTop == null ? this._liquid.y : pageOffsetTop),width,height,angle,- };+ clipBounds: pageClipBounds,+ } as IDrawingTransformStateWithClipBounds;if (updateDrawingMap[drawingId] == null) {updateDrawingMap[drawingId] = {unitId,@@ -362,7 +560,9 @@ export class DocDrawingTransformUpdateController extends Disposable implements IdocsTop,updateDrawingMap,marginTop,- marginLeft+ marginLeft,+ undefined,+ { left: marginLeft, top: marginTop });this._calculateTableCellDrawingPositions(unitId,diff --git a/packages/docs-drawing/src/controllers/__tests__/doc-drawing.controller.spec.ts b/packages/docs-drawing/src/controllers/__tests__/doc-drawing.controller.spec.tsindex 53ea849e95..f32e7326dd 100644--- a/packages/docs-drawing/src/controllers/__tests__/doc-drawing.controller.spec.ts+++ b/packages/docs-drawing/src/controllers/__tests__/doc-drawing.controller.spec.ts@@ -68,9 +68,41 @@ describe('DocDrawingController', () => {expect(capturedResource.parseJson('')).toEqual({ data: {}, order: [] });expect(capturedResource.parseJson('{bad json')).toEqual({ data: {}, order: [] });- capturedResource.onLoad('doc-1', { data: { d2: { id: 'd2' } }, order: ['d2'] });+ capturedResource.onLoad('doc-1', {+ data: {+ d2: {+ id: 'd2',+ docTransform: {+ size: { width: 320, height: 180 },+ positionH: { posOffset: 12 },+ positionV: { posOffset: 34 },+ angle: 15,+ },+ },+ },+ order: ['d2'],+ });expect(registerDrawingData).toHaveBeenCalledWith('doc-1', expect.any(Object));expect(registerDrawingDataForManager).toHaveBeenCalledWith('doc-1', expect.any(Object));+ const loadedDrawingData = registerDrawingDataForManager.mock.calls.at(-1)?.[1];+ expect(loadedDrawingData).toMatchObject({+ 'doc-1': {+ unitId: 'doc-1',+ subUnitId: 'doc-1',+ data: {+ d2: expect.objectContaining({+ docTransform: {+ size: { width: 320, height: 180 },+ positionH: { posOffset: 12 },+ positionV: { posOffset: 34 },+ angle: 15,+ },+ }),+ },+ order: ['d2'],+ },+ });+ expect(loadedDrawingData?.['doc-1']?.data?.d2).not.toHaveProperty('transform');capturedResource.onUnLoad('doc-1');expect(registerDrawingData).toHaveBeenLastCalledWith('doc-1', {diff --git a/packages/docs-drawing/src/controllers/doc-drawing.controller.ts b/packages/docs-drawing/src/controllers/doc-drawing.controller.tsindex 931b302904..5dfe2a76c7 100644--- a/packages/docs-drawing/src/controllers/doc-drawing.controller.ts+++ b/packages/docs-drawing/src/controllers/doc-drawing.controller.ts@@ -109,14 +109,6 @@ export class DocDrawingController extends Disposable {// TODO@wzhudev: should move to docs-drawing.- Object.keys(drawingDataModels).forEach((drawingId) => {- const drawingDataModel = drawingDataModels[drawingId];- // const docTransform = drawingDataModel.docTransform;- // const transform = docDrawingPositionToTransform(docTransform);-- drawingDataModels[drawingId] = { ...drawingDataModel } as IDocDrawing;- });-const subDrawings = {[subUnitId]: {unitId,diff --git a/packages/drawing-ui/src/controllers/__tests__/drawing-update.controller.spec.ts b/packages/drawing-ui/src/controllers/__tests__/drawing-update.controller.spec.tsindex 47585769f6..1c0df20402 100644--- a/packages/drawing-ui/src/controllers/__tests__/drawing-update.controller.spec.ts+++ b/packages/drawing-ui/src/controllers/__tests__/drawing-update.controller.spec.ts@@ -18,9 +18,11 @@ import type { ICommandInfo } from '@univerjs/core';import type { IDrawingGroupUpdateParam } from '@univerjs/drawing';import { DrawingTypeEnum, UniverInstanceType } from '@univerjs/core';import { SetDrawingSelectedOperation } from '@univerjs/drawing';+import { DRAWING_OBJECT_LAYER_INDEX } from '@univerjs/engine-render';import { Subject } from 'rxjs';import { describe, expect, it, vi } from 'vitest';import { AlignType, SetDrawingAlignOperation } from '../../commands/operations/drawing-align.operation';+import { DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX } from '../../services/drawing-render.service';import { DrawingUpdateController } from '../drawing-update.controller';interface IDrawingNotification {@@ -68,7 +70,7 @@ function createHarness() {const zIndexShape = { setProps: vi.fn(), makeDirty: vi.fn() };const disposeShape = { dispose: vi.fn() };const showHideShape = { show: vi.fn(), hide: vi.fn() };- const transformShape = { transformByState: vi.fn() };+ const transformShape = { layer: { zIndex: DRAWING_OBJECT_LAYER_INDEX }, transformByState: vi.fn(), setClipBounds: vi.fn() };const scene = {getTransformerByCreate: vi.fn(() => transformer),@@ -86,6 +88,7 @@ function createHarness() {}),addObject: vi.fn(() => ({ attachTransformerTo: vi.fn() })),addObjects: vi.fn(),+ removeObject: vi.fn(),makeDirty: vi.fn(),};@@ -93,10 +96,11 @@ function createHarness() {getRenderById: vi.fn(() => ({ scene })),};- const drawingParams = new Map<string, { unitId: string; subUnitId: string; drawingId: string; drawingType: DrawingTypeEnum; transform: { left: number; top: number; width: number; height: number; angle: number } }>([+ const drawingParams = new Map<string, { unitId: string; subUnitId: string; drawingId: string; drawingType: DrawingTypeEnum; behindText?: boolean; transform: { left: number; top: number; width: number; height: number; angle: number; clipBounds?: { left: number; top: number; width: number; height: number } } }>([['drawing-a', { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-a', drawingType: DrawingTypeEnum.DRAWING_IMAGE, transform: { left: 0, top: 0, width: 10, height: 10, angle: 0 } }],['drawing-b', { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-b', drawingType: DrawingTypeEnum.DRAWING_IMAGE, transform: { left: 20, top: 0, width: 10, height: 10, angle: 0 } }],- ['drawing-transform', { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-transform', drawingType: DrawingTypeEnum.DRAWING_IMAGE, transform: { left: 1, top: 2, width: 3, height: 4, angle: 0 } }],+ ['drawing-transform', { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-transform', drawingType: DrawingTypeEnum.DRAWING_IMAGE, behindText: true, transform: { left: 1, top: 2, width: 3, height: 4, angle: 0, clipBounds: { left: 0, top: 0, width: 80, height: 120 } } }],+ ['drawing-refresh-missing', { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-refresh-missing', drawingType: DrawingTypeEnum.DRAWING_IMAGE, transform: { left: 4, top: 5, width: 6, height: 7, angle: 0 } }],]);const drawingManagerService = {@@ -116,6 +120,7 @@ function createHarness() {{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-a', drawingType: DrawingTypeEnum.DRAWING_IMAGE },{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-b', drawingType: DrawingTypeEnum.DRAWING_IMAGE },]),+ addNotification: vi.fn(),featurePluginUpdateNotification: vi.fn(),};@@ -216,6 +221,9 @@ describe('DrawingUpdateController', () => {harness.refreshTransform$.next([{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId }]);expect(harness.transformShape.transformByState).toHaveBeenCalledTimes(2);+ expect(harness.transformShape.setClipBounds).toHaveBeenCalledWith({ left: 0, top: 0, width: 80, height: 120 });+ expect(harness.scene.removeObject).toHaveBeenCalledWith(harness.transformShape);+ expect(harness.scene.addObject).toHaveBeenCalledWith(harness.transformShape, DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX);harness.visible$.next([{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-visible', visible: false }]);expect(harness.showHideShape.hide).toHaveBeenCalledTimes(1);@@ -228,4 +236,16 @@ describe('DrawingUpdateController', () => {harness.controller.dispose();});++ it('requests drawing insertion when a refreshed transform belongs to a missing scene object', () => {+ const harness = createHarness();++ harness.refreshTransform$.next([{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-refresh-missing' }]);++ expect(harness.drawingManagerService.addNotification).toHaveBeenCalledWith([+ { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-refresh-missing' },+ ]);++ harness.controller.dispose();+ });});diff --git a/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts b/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.tsindex c025e6db6c..be3c5c581d 100644--- a/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts+++ b/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts@@ -14,11 +14,12 @@* limitations under the License.*/-import { DrawingTypeEnum, UniverInstanceType } from '@univerjs/core';+import { DrawingTypeEnum, ImageSourceType, UniverInstanceType } from '@univerjs/core';import { SetDrawingSelectedOperation } from '@univerjs/drawing';import { Subject } from 'rxjs';import { afterEach, describe, expect, it, vi } from 'vitest';import { ImageResetSizeOperation } from '../../commands/operations/image-reset-size.operation';+import { DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX } from '../../services/drawing-render.service';import { ImageUpdateController } from '../image-update.controller';afterEach(() => {@@ -141,4 +142,68 @@ describe('ImageUpdateController', () => {expect(renderImages).toHaveBeenCalledTimes(1);expect(drawingManagerService.refreshTransform).toHaveBeenCalledWith([imageParam]);});++ it('applies refreshed transform, clip bounds, and behind-text layer to existing images', () => {+ const add$ = new Subject();+ const update$ = new Subject<Array<{ unitId: string; subUnitId: string; drawingId: string }>>();+ const transform = {+ angle: 0,+ clipBounds: { height: 120, left: 0, top: 0, width: 80 },+ height: 60,+ left: 10,+ top: 20,+ width: 100,+ };+ const imageParam = {+ behindText: true,+ drawingId: 'shape-3',+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ imageSourceType: ImageSourceType.BASE64,+ source: 'data:image/png;base64,Zm9v',+ srcRect: { bottom: 0, left: 0, right: 0, top: 0 },+ subUnitId: 'sheet-1',+ transform,+ unitId: 'book-1',+ };+ const imageShape = {+ changeSource: vi.fn(),+ layer: { zIndex: 4 },+ setClipBounds: vi.fn(),+ setPrstGeom: vi.fn(),+ setSrcRect: vi.fn(),+ transformByState: vi.fn(),+ };+ const scene = {+ addObject: vi.fn(),+ getObject: vi.fn(() => imageShape),+ getTransformerByCreate: vi.fn(),+ removeObject: vi.fn(),+ };+ const drawingManagerService = {+ add$,+ update$,+ getDrawingByParam: vi.fn(() => imageParam),+ };++ const controller = new ImageUpdateController(+ { onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })), syncExecuteCommand: vi.fn() } as never,+ {+ getRenderById: vi.fn(() => ({ scene })),+ } as never,+ drawingManagerService as never,+ {} as never,+ {} as never,+ { getUnit: vi.fn(() => createSheetUnit()), getFocusedUnit: vi.fn(() => createSheetUnit()) } as never,+ { renderImages: vi.fn() } as never+ );++ expect(controller).toBeTruthy();++ update$.next([{ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'shape-3' }]);++ expect(imageShape.transformByState).toHaveBeenCalledWith(transform);+ expect(imageShape.setClipBounds).toHaveBeenCalledWith(transform.clipBounds);+ expect(scene.removeObject).toHaveBeenCalledWith(imageShape);+ expect(scene.addObject).toHaveBeenCalledWith(imageShape, DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX);+ });});diff --git a/packages/drawing-ui/src/controllers/drawing-update.controller.ts b/packages/drawing-ui/src/controllers/drawing-update.controller.tsindex fc2f89895a..f59533aac1 100644--- a/packages/drawing-ui/src/controllers/drawing-update.controller.ts+++ b/packages/drawing-ui/src/controllers/drawing-update.controller.ts@@ -29,6 +29,7 @@ import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService, SetDrawingSeimport { DRAWING_OBJECT_LAYER_INDEX, DrawingGroupObject, Group, IRenderManagerService, RENDER_CLASS_TYPE } from '@univerjs/engine-render';import { AlignType, SetDrawingAlignOperation } from '../commands/operations/drawing-align.operation';import { CloseImageCropOperation } from '../commands/operations/image-crop.operation';+import { ensureDrawingRenderLayer } from '../services/drawing-render.service';import { getUpdateParams } from '../utils/get-update-params';import { getCurrentUnitInfo, insertGroupObject } from './utils';@@ -40,6 +41,10 @@ interface IDrawingTransformCache {transform: ITransformState;}+interface IDrawingTransformStateWithClipBounds extends ITransformState {+ clipBounds?: Nullable<{ left: number; top: number; width: number; height: number }>;+}+export class DrawingUpdateController extends Disposable {constructor(@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,@@ -676,6 +681,8 @@ export class DrawingUpdateController extends Disposable {}drawingShape.transformByState({ left, top, width, height, angle, flipX, flipY, skewX, skewY });+ (drawingShape as Image).setClipBounds?.((transform as IDrawingTransformStateWithClipBounds).clipBounds);+ ensureDrawingRenderLayer(scene, drawingShape, drawingParam);scene.getTransformer()?.debounceRefreshControls();});@@ -700,10 +707,15 @@ export class DrawingUpdateController extends Disposable {const { transform } = drawingParam;const { scene } = renderObject;+ if (transform == null) {+ return true;+ }+const drawingShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });const drawingShape = scene.getObject(drawingShapeKey);- if (drawingShape == null || transform == null) {+ if (drawingShape == null) {+ this._drawingManagerService.addNotification([{ unitId, subUnitId, drawingId }]);return true;}@@ -720,6 +732,8 @@ export class DrawingUpdateController extends Disposable {} = transform;drawingShape.transformByState({ left, top, width, height, angle, flipX, flipY, skewX, skewY });+ (drawingShape as Image).setClipBounds?.((transform as IDrawingTransformStateWithClipBounds).clipBounds);+ ensureDrawingRenderLayer(scene, drawingShape as BaseObject, drawingParam);});}));diff --git a/packages/drawing-ui/src/controllers/image-update.controller.ts b/packages/drawing-ui/src/controllers/image-update.controller.tsindex 5b7214a724..9af5394260 100644--- a/packages/drawing-ui/src/controllers/image-update.controller.ts+++ b/packages/drawing-ui/src/controllers/image-update.controller.ts@@ -31,7 +31,7 @@ import { CURSOR_TYPE, IRenderManagerService } from '@univerjs/engine-render';import { IDialogService } from '@univerjs/ui';import { bufferTime, filter, map } from 'rxjs';import { ImageResetSizeOperation } from '../commands/operations/image-reset-size.operation';-import { DrawingRenderService } from '../services/drawing-render.service';+import { DrawingRenderService, ensureDrawingRenderLayer } from '../services/drawing-render.service';import { getCurrentUnitInfo } from './utils';export class ImageUpdateController extends Disposable {@@ -247,6 +247,9 @@ export class ImageUpdateController extends Disposable {return true;}+ imageShape.transformByState(transform);+ (imageShape as Image & { setClipBounds?: (clipBounds?: unknown) => void }).setClipBounds?.((transform as { clipBounds?: unknown }).clipBounds);+ ensureDrawingRenderLayer(scene, imageShape, drawingParam);imageShape.setSrcRect(srcRect);imageShape.setPrstGeom(prstGeom);if (source != null && source.length > 0 && (imageSourceType === ImageSourceType.BASE64 || imageSourceType === ImageSourceType.URL)) {diff --git a/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts b/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.tsindex 78d6eccb68..f7a593fc5d 100644--- a/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts+++ b/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts@@ -37,7 +37,7 @@ import { IGalleryService } from '@univerjs/ui';import { Subject } from 'rxjs';import { describe, expect, it, vi } from 'vitest';import { DrawingImageClipService } from '../drawing-image-clip.service';-import { DrawingRenderService } from '../drawing-render.service';+import { DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX, DrawingRenderService } from '../drawing-render.service';const BASE_TRANSFORM = {left: 10,@@ -351,6 +351,9 @@ describe('DrawingRenderService', () => {it('uses cached native images instead of resolving the source again', async () => {const { service, scene, imageIoService } = createHarness();const nativeImage = document.createElement('img');+ Object.defineProperty(nativeImage, 'complete', { value: true });+ Object.defineProperty(nativeImage, 'naturalWidth', { value: 1 });+ Object.defineProperty(nativeImage, 'naturalHeight', { value: 1 });imageIoService.cache.set(cacheKey('image-source', ImageSourceType.BASE64), nativeImage);await service.renderImages(imageParam(), scene as unknown as Scene);@@ -527,4 +530,63 @@ describe('DrawingRenderService', () => {expect(galleryService.lastOpen?.images).toEqual(['preview-src']);expect(galleryService.closeCount).toBe(1);});++ it('renders incomplete cached images through url loading so onload can repaint', async () => {+ const { imageIoService, scene, service } = createHarness();+ const incompleteImage = document.createElement('img');+ Object.defineProperty(incompleteImage, 'complete', { value: false });+ imageIoService.cache.set(cacheKey('image-source', ImageSourceType.BASE64), incompleteImage);++ await service.renderImages(imageParam(), scene as unknown as Scene);++ const image = scene.addedObjects[0]?.object as Image;+ expect(image.getNative()).not.toBe(incompleteImage);+ expect(imageIoService.cacheWrites).toEqual([{ source: 'image-source', imageSourceType: ImageSourceType.BASE64, image: image.getNative() }]);+ });++ it('uses completed cached images directly', async () => {+ const { imageIoService, scene, service } = createHarness();+ const completeImage = document.createElement('img');+ Object.defineProperty(completeImage, 'complete', { value: true });+ Object.defineProperty(completeImage, 'naturalWidth', { value: 1 });+ Object.defineProperty(completeImage, 'naturalHeight', { value: 1 });+ imageIoService.cache.set(cacheKey('image-source', ImageSourceType.BASE64), completeImage);++ await service.renderImages(imageParam(), scene as unknown as Scene);++ const image = scene.addedObjects[0]?.object as Image;+ expect(image.getNative()).toBe(completeImage);+ expect(imageIoService.cacheWrites).toEqual([]);+ });++ it('reloads completed cached images without natural dimensions', async () => {+ const { imageIoService, scene, service } = createHarness();+ const brokenCompleteImage = document.createElement('img');+ Object.defineProperty(brokenCompleteImage, 'complete', { value: true });+ Object.defineProperty(brokenCompleteImage, 'naturalWidth', { value: 0 });+ Object.defineProperty(brokenCompleteImage, 'naturalHeight', { value: 0 });+ imageIoService.cache.set(cacheKey('image-source', ImageSourceType.BASE64), brokenCompleteImage);++ await service.renderImages(imageParam(), scene as unknown as Scene);++ const image = scene.addedObjects[0]?.object as Image;+ expect(image.getNative()).not.toBe(brokenCompleteImage);+ expect(imageIoService.cacheWrites).toEqual([{ source: 'image-source', imageSourceType: ImageSourceType.BASE64, image: image.getNative() }]);+ });++ it('renders docs behind-text images between page background and document text', async () => {+ const { scene, service } = createHarness();++ await service.renderImages(imageParam({ behindText: true } as never), scene as unknown as Scene);++ expect(scene.addedObjects[0]?.layerIndex).toBe(DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX);+ });++ it('keeps normal images on the regular drawing layer', async () => {+ const { scene, service } = createHarness();++ await service.renderImages(imageParam(), scene as unknown as Scene);++ expect(scene.addedObjects[0]?.layerIndex).toBe(DRAWING_OBJECT_LAYER_INDEX);+ });});diff --git a/packages/drawing-ui/src/services/drawing-render.service.ts b/packages/drawing-ui/src/services/drawing-render.service.tsindex 40af5aa93f..021068cd71 100644--- a/packages/drawing-ui/src/services/drawing-render.service.ts+++ b/packages/drawing-ui/src/services/drawing-render.service.ts@@ -14,10 +14,10 @@* limitations under the License.*/-import type { IDrawingSearch, Workbook } from '@univerjs/core';+import type { IDrawingParam, IDrawingSearch, Workbook } from '@univerjs/core';import type { IDocFloatDomData, IImageData } from '@univerjs/drawing';-import type { IImageProps, IRectProps, Scene } from '@univerjs/engine-render';-import { DrawingTypeEnum, Inject, IUniverInstanceService, IURLImageService, UniverInstanceType } from '@univerjs/core';+import type { BaseObject, IImageProps, IRectProps, Scene } from '@univerjs/engine-render';+import { BooleanNumber, DrawingTypeEnum, Inject, IUniverInstanceService, IURLImageService, UniverInstanceType } from '@univerjs/core';import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService, IImageIoService, ImageSourceType } from '@univerjs/drawing';import { DRAWING_OBJECT_LAYER_INDEX, Image, Rect } from '@univerjs/engine-render';import { IGalleryService } from '@univerjs/ui';@@ -26,6 +26,36 @@ import { DrawingImageClipService } from './drawing-image-clip.service';// const IMAGE_VIEWER_DROPDOWN_PADDING = 50;+interface IDrawingTransformStateWithClipBounds {+ clipBounds?: { left: number; top: number; width: number; height: number } | null;+}++type IDrawingParamWithBehindText = (Partial<IDrawingParam> | Partial<IImageData>) & {+ behindText?: boolean | BooleanNumber;+};++export const DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX = 1;++export function getDrawingRenderLayerIndex(param: IDrawingParamWithBehindText): number {+ return param.behindText === true || param.behindText === BooleanNumber.TRUE+ ? DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX+ : DRAWING_OBJECT_LAYER_INDEX;+}++export function ensureDrawingRenderLayer(scene: Scene, object: BaseObject, param: IDrawingParamWithBehindText): void {+ const layerIndex = getDrawingRenderLayerIndex(param);+ if (object.layer == null || object.layer.zIndex === layerIndex) {+ return;+ }++ scene.removeObject(object);+ scene.addObject(object, layerIndex);+}++function isRenderableImageCache(image: HTMLImageElement | null | undefined | void): image is HTMLImageElement {+ return image?.complete === true && image.naturalWidth > 0 && image.naturalHeight > 0;+}+export class DrawingRenderService {constructor(@IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,@@ -82,6 +112,8 @@ export class DrawingRenderService {const imageShape = scene.getObject(imageShapeKey);if (imageShape != null) {imageShape.transformByState({ left, top, width, height, angle, flipX, flipY, skewX, skewY });+ (imageShape as Image).setClipBounds?.((transform as IDrawingTransformStateWithClipBounds).clipBounds);+ ensureDrawingRenderLayer(scene, imageShape, imageParam as IDrawingParamWithBehindText);continue;}@@ -91,7 +123,7 @@ export class DrawingRenderService {const imageNativeCache = this._imageIoService.getImageSourceCache(source, imageSourceType);let shouldBeCache = false;- if (imageNativeCache != null) {+ if (isRenderableImageCache(imageNativeCache)) {imageConfig.image = imageNativeCache;} else {if (imageSourceType === ImageSourceType.UUID) {@@ -131,7 +163,7 @@ export class DrawingRenderService {this._imageIoService.addImageSourceCache(source, imageSourceType, image.getNative());}- scene.addObject(image, DRAWING_OBJECT_LAYER_INDEX);+ scene.addObject(image, getDrawingRenderLayerIndex(imageParam as IDrawingParamWithBehindText));if (this._drawingManagerService.getDrawingEditable()) {scene.attachTransformerTo(image);}diff --git a/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts b/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.tsindex e93cad7332..e279a1bb31 100644--- a/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts+++ b/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts@@ -130,7 +130,8 @@ describe('UnitDrawingService', () => {transform: { left: 1, top: 2 } as NonNullable<IDrawingParam['transform']>,transforms: [{ left: 3, top: 4 } as NonNullable<IDrawingParam['transform']>] as NonNullable<IDrawingParam['transforms']>,isMultiTransform: BooleanNumber.TRUE,- });+ behindText: true,+ } as Partial<IDrawingParam>);service.refreshTransform([transformed]);expect(refreshed).toEqual([[transformed]]);@@ -138,6 +139,7 @@ describe('UnitDrawingService', () => {transform: { left: 1, top: 2 },transforms: [{ left: 3, top: 4 }],isMultiTransform: BooleanNumber.TRUE,+ behindText: true,});service.visibleNotification([{ ...createSearch('a'), visible: false }]);diff --git a/packages/drawing/src/services/__tests__/image-io-impl.service.spec.ts b/packages/drawing/src/services/__tests__/image-io-impl.service.spec.tsindex c88bdbc728..46e407f9c8 100644--- a/packages/drawing/src/services/__tests__/image-io-impl.service.spec.ts+++ b/packages/drawing/src/services/__tests__/image-io-impl.service.spec.ts@@ -26,7 +26,17 @@ type MockLoadEvent = ProgressEvent<FileReader> & {};class MockImage {- src = '';+ onload: null | (() => void) = null;+ private _src = '';++ get src() {+ return this._src;+ }++ set src(value: string) {+ this._src = value;+ queueMicrotask(() => this.onload?.());+ }}class SuccessFileReader {@@ -87,6 +97,18 @@ describe('ImageIoService', () => {expect(counts).toEqual([2]);});+ it('should cache base64 images and emit after they load', async () => {+ const counts: number[] = [];+ service.change$.subscribe((count) => counts.push(count));++ const image = service.getImageSourceCache('data:image/png;base64,Zm9v', ImageSourceType.BASE64);+ const cached = service.getImageSourceCache('data:image/png;base64,Zm9v', ImageSourceType.BASE64);++ expect(cached).toBe(image);+ await Promise.resolve();+ expect(counts).toEqual([0]);+ });+it('should ignore invalid cache insertions and resolve image ids directly', async () => {service.addImageSourceCache('data:image/png;base64,Zm9v', ImageSourceType.BASE64, new MockImage() as unknown as HTMLImageElement);service.addImageSourceCache('https://example.com/image.png', ImageSourceType.URL, null);diff --git a/packages/drawing/src/services/drawing-manager-impl.service.ts b/packages/drawing/src/services/drawing-manager-impl.service.tsindex 204095132c..b1ca68acb9 100644--- a/packages/drawing/src/services/drawing-manager-impl.service.ts+++ b/packages/drawing/src/services/drawing-manager-impl.service.ts@@ -42,6 +42,10 @@ enum DrawingMapItemType {order = 'order',}+interface IDrawingRefreshMetadata {+ behindText?: unknown;+}+/*** unitId -> subUnitId -> drawingId -> drawingParam*/@@ -132,6 +136,10 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawingparam.transform = updateParam.transform;param.transforms = updateParam.transforms;param.isMultiTransform = updateParam.isMultiTransform;++ if ('behindText' in updateParam) {+ (param as T & IDrawingRefreshMetadata).behindText = (updateParam as T & IDrawingRefreshMetadata).behindText;+ }});this.refreshTransformNotification(updateParams);diff --git a/packages/drawing/src/services/image-io-impl.service.ts b/packages/drawing/src/services/image-io-impl.service.tsindex 0b0f446aa4..5914527ed6 100644--- a/packages/drawing/src/services/image-io-impl.service.ts+++ b/packages/drawing/src/services/image-io-impl.service.ts@@ -35,12 +35,19 @@ export class ImageIoService implements IImageIoService {private _imageSourceCache: Map<string, HTMLImageElement> = new Map();getImageSourceCache(source: string, imageSourceType: ImageSourceType) {+ const cachedImage = this._imageSourceCache.get(source);+ if (cachedImage != null) {+ return cachedImage;+ }if (imageSourceType === ImageSourceType.BASE64) {const image = new Image();+ image.onload = () => this._change$.next(this._waitCount);+ image.onerror = () => this._change$.next(this._waitCount);image.src = source;+ this._imageSourceCache.set(source, image);return image;}- return this._imageSourceCache.get(source);+ return undefined;}addImageSourceCache(source: string, imageSourceType: ImageSourceType, imageSource: Nullable<HTMLImageElement>) {diff --git a/packages/engine-render/src/basics/interfaces.ts b/packages/engine-render/src/basics/interfaces.tsindex eaf903aeb0..34ee3ea979 100644--- a/packages/engine-render/src/basics/interfaces.ts+++ b/packages/engine-render/src/basics/interfaces.ts@@ -128,6 +128,7 @@ export interface IParagraphTableCache {export interface IParagraphConfig {paragraphIndex: number;useWordStyleLineHeight?: boolean;+ docxFallbackAnchorLeft?: IParagraphStyle['indentStart'];paragraphNonInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>;paragraphInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>;skeTablesInParagraph?: IParagraphTableCache[];diff --git a/packages/engine-render/src/components/docs/__tests__/document.spec.ts b/packages/engine-render/src/components/docs/__tests__/document.spec.tsindex a935bfd826..8f94aec49f 100644--- a/packages/engine-render/src/components/docs/__tests__/document.spec.ts+++ b/packages/engine-render/src/components/docs/__tests__/document.spec.ts@@ -440,6 +440,50 @@ describe('documents render', () => {docBackground.dispose();});+ it('draws DOCX page background images on every traditional page', () => {+ const firstPage = createPage(DocumentSkeletonPageType.BODY, 'first');+ const secondPage = createPage(DocumentSkeletonPageType.BODY, 'second');+ const backgroundImage = { complete: true };+ vi.spyOn(document, 'createElement').mockReturnValue(backgroundImage as any);+ const skeleton = {+ getSkeletonData: () => ({ pages: [firstPage, secondPage] }),+ getViewModel: () => ({+ getDataModel: () => ({+ getSnapshot: () => ({+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ background: {+ source: 'data:image/png;base64,background',+ },+ },+ }),+ }),+ }),+ } as any;+ const docBackground = new DocBackground('docs-background-docx', skeleton, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 20,+ pageMarginTop: 20,+ });++ vi.spyOn(Rect, 'drawWith').mockImplementation(() => {});+ vi.spyOn(Path, 'drawWith').mockImplementation(() => {});+ const drawImage = vi.fn();++ docBackground.draw({+ restore: vi.fn(),+ save: vi.fn(),+ translate: vi.fn(),+ drawImage,+ } as any);++ expect(drawImage).toHaveBeenCalledTimes(2);+ expect(drawImage).toHaveBeenNthCalledWith(1, backgroundImage, 0, 0, 200, 420);+ expect(drawImage).toHaveBeenNthCalledWith(2, backgroundImage, 0, 0, 200, 420);++ docBackground.dispose();+ });+it('treats unspecified document flavor as traditional when drawing the page background', () => {const page = createPage(DocumentSkeletonPageType.BODY, '');const skeleton = {@@ -1042,6 +1086,7 @@ describe('documents render', () => {const headerPage = createPage(DocumentSkeletonPageType.HEADER, 'header-main');const footerPage = createPage(DocumentSkeletonPageType.FOOTER, 'footer-main');attachTable(bodyPage);+ attachTable(headerPage);const skeletonData = {pages: [bodyPage],@@ -1106,6 +1151,7 @@ describe('documents render', () => {const offsetConfig = documents.getOffsetConfig();expect(offsetConfig.pageMarginLeft).toBe(6);expect(documents.getEngine()).toBe(engine);+ const tableDraw = vi.spyOn(documents as any, '_drawTable');documents.draw(canvas.getContext(), {viewBound: { left: 0, top: 0, right: 900, bottom: 700 },@@ -1116,6 +1162,7 @@ describe('documents render', () => {expect(clearCache).toHaveBeenCalled();expect(lineDraw).toHaveBeenCalled();expect(spanDraw).toHaveBeenCalled();+ expect(tableDraw).toHaveBeenCalledTimes(2);documents.draw(canvas.getContext(), {viewBound: { left: 2000, top: 2000, right: 2200, bottom: 2200 },@@ -1133,6 +1180,59 @@ describe('documents render', () => {documents.dispose();});+ it('draws lower-page header content for DOCX page-relative header backgrounds', () => {+ const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');+ bodyPage.sections[0].columns[0].lines = [];+ bodyPage.skeTables.clear();++ const headerPage = createPage(DocumentSkeletonPageType.HEADER, 'header-main');+ const headerLine = createLine(LineType.PARAGRAPH, 260);+ headerLine.parent = headerPage.sections[0].columns[0];+ headerPage.sections[0].columns[0].lines = [headerLine];+ headerPage.skeTables.clear();++ const skeletonData = {+ pages: [bodyPage],+ skeHeaders: new Map([['header-main', new Map([[bodyPage.pageWidth, headerPage]])]]),+ skeFooters: new Map(),+ };+ bodyPage.parent = skeletonData;+ headerPage.parent = skeletonData;++ const documents = new Documents('docs-page-header-background', { getSkeletonData: () => skeletonData } as any, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ });+ documents.transformByState({+ left: 0,+ top: 0,+ width: 260,+ height: 480,+ });+ scene.addObject(documents, 1);++ const spanDraw = vi.fn();+ vi.spyOn(documents as any, 'getExtensionsByOrder').mockReturnValue([+ {+ uKey: 'DocsSpanExtension',+ type: DOCS_EXTENSION_TYPE.SPAN,+ extensionOffset: {},+ clearCache: vi.fn(),+ draw: spanDraw,+ },+ ] as any);++ documents.draw(canvas.getContext(), {+ viewBound: { left: 0, top: 0, right: 900, bottom: 700 },+ cacheBound: { left: 0, top: 0, right: 900, bottom: 700 },+ } as any);++ expect(spanDraw).toHaveBeenCalled();++ documents.dispose();+ });+it('merges adjacent glyph backgrounds with the same color into one draw per line', () => {const bodyPage = createPage(DocumentSkeletonPageType.BODY, '', '#d9eaf7');const skeletonData = {diff --git a/packages/engine-render/src/components/docs/doc-background.ts b/packages/engine-render/src/components/docs/doc-background.tsindex 2a76b77a6d..e739a75c32 100644--- a/packages/engine-render/src/components/docs/doc-background.ts+++ b/packages/engine-render/src/components/docs/doc-background.ts@@ -35,6 +35,8 @@ export class DocBackground extends DocComponent {private _pageFillColor?: string;private _pageStrokeColor?: string;private _marginStrokeColor?: string;+ private _pageBackgroundSource?: string;+ private _pageBackgroundImage?: HTMLImageElement;constructor(oKey: string, documentSkeleton?: DocumentSkeleton, config?: IDocumentsConfig) {super(oKey, documentSkeleton, config);@@ -77,7 +79,7 @@ export class DocBackground extends DocComponent {return;}- const { documentFlavor } = docDataModel.getSnapshot().documentStyle;+ const { documentFlavor, background } = docDataModel.getSnapshot().documentStyle;const workspaceFill = this._backgroundFillColor ?? (documentFlavor === DocumentFlavor.MODERN ? PAGE_FILL_COLOR : DOCS_WORKSPACE_FILL_COLOR);this._drawWorkspaceBackground(ctx, workspaceFill, bounds);@@ -125,6 +127,7 @@ export class DocBackground extends DocComponent {};Rect.drawWith(ctx, backgroundOptions);+ this._drawPageBackgroundImage(ctx, background?.source, pageWidth ?? width, pageHeight ?? height);const IDENTIFIER_WIDTH = 15;const marginIdentification: IPathProps = {@@ -205,6 +208,34 @@ export class DocBackground extends DocComponent {ctx.restore();}+ private _drawPageBackgroundImage(ctx: UniverRenderingContext, source: string | undefined, width: number, height: number) {+ if (!source || width <= 0 || height <= 0) {+ return;+ }++ const image = this._getPageBackgroundImage(source);+ if (!image.complete) {+ return;+ }++ ctx.drawImage(image, 0, 0, width, height);+ }++ private _getPageBackgroundImage(source: string) {+ if (this._pageBackgroundSource === source && this._pageBackgroundImage != null) {+ return this._pageBackgroundImage;+ }++ const image = document.createElement('img');+ image.crossOrigin = 'anonymous';+ image.onload = () => this.makeDirty(true);+ image.src = source;+ this._pageBackgroundSource = source;+ this._pageBackgroundImage = image;++ return image;+ }+changeSkeleton(newSkeleton: DocumentSkeleton) {this.setSkeleton(newSkeleton);diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.tsindex 973c047430..3886fb6270 100644--- a/packages/engine-render/src/components/docs/document.ts+++ b/packages/engine-render/src/components/docs/document.ts@@ -1029,9 +1029,25 @@ export class Documents extends DocComponent {if (this._drawLiquid == null) {return;}- const { sections } = page;+ const { sections, skeTables } = page;const { y: originY } = this._drawLiquid;+ if (skeTables.size > 0) {+ this._drawTable(+ ctx,+ page,+ skeTables,+ extensions,+ backgroundExtension,+ glyphExtensionsExcludeBackground,+ alignOffsetNoAngle,+ centerAngle,+ vertexAngle,+ renderConfig,+ parentScale+ );+ }+for (const section of sections) {const { columns } = section;@@ -1072,12 +1088,7 @@ export class Documents extends DocComponent {this._drawLiquid.translateLine(line, true, true);const { y } = this._drawLiquid;- if (isHeader) {- if ((y - originY + alignOffset.y) > (parentPage.pageHeight - 100) / 2) {- this._drawLiquid.translateRestore();- continue;- }- } else {+ if (!isHeader) {if ((y - originY + alignOffset.y + lineHeight) < (parentPage.pageHeight - 100) / 2 + 100) {this._drawLiquid.translateRestore();continue;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 728888ec90..e7867d4bdf 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@@ -14,7 +14,7 @@* limitations under the License.*/-import { ColumnSeparatorType, createDocumentModelWithStyle, LocaleService, Univer } from '@univerjs/core';+import { ColumnSeparatorType, createDocumentModelWithStyle, DocumentDataModel, DocumentFlavor, LocaleService, ObjectRelativeFromH, ObjectRelativeFromV, SectionType, TableSizeType, Univer } from '@univerjs/core';import { describe, expect, it, vi } from 'vitest';import { DocumentSkeletonPageType, GlyphType, PageLayoutType } from '../../../../basics/i-document-skeleton-cached';import { Vector2 } from '../../../../basics/vector2';@@ -383,4 +383,320 @@ describe('doc skeleton', () => {skeleton.dispose();univer.dispose();});++ it('creates an initial page when the first laid out section is continuous', () => {+ const univer = new Univer();+ const localeService = univer.__getInjector().get(LocaleService);++ const documentModel = new DocumentDataModel({+ id: 'continuous-doc',+ body: {+ dataStream: 'A\r\n',+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {},+ },+ ],+ paragraphs: [+ {+ startIndex: 1,+ paragraphId: 'para_continuous',+ },+ ],+ sectionBreaks: [+ {+ startIndex: 2,+ sectionType: SectionType.CONTINUOUS,+ },+ ],+ },+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ pageSize: {+ width: 160,+ height: 220,+ },+ },+ });++ const viewModel = new DocumentViewModel(documentModel);+ const skeleton = DocumentSkeleton.create(viewModel, localeService);++ expect(() => skeleton.calculate()).not.toThrow();+ expect(skeleton.getSkeletonData()?.pages.length).toBeGreaterThan(0);++ skeleton.dispose();+ univer.dispose();+ });++ it('lays out a traditional form document with header footer and long fields', () => {+ const univer = new Univer();+ const localeService = univer.__getInjector().get(LocaleService);+ const lines = [+ 'FORM AUTHORIZATION',+ '',+ 'Customer __________________________________',+ 'Identifier __________________________________',+ 'Agent',+ 'Name __________________________________',+ 'Identifier __________________________________',+ 'Permissions',+ 'review account history and invoices in the customer portal',+ 'create and close agreements',+ 'other',+ 'Valid until ________________________________',+ 'Signatures',+ '________________________________ (identifier __________-______)',+ '________________________________ (identifier __________-______)',+ '________________________________ (identifier __________-______)',+ '________________________________ (identifier __________-______)',+ ];+ const dataStream = `${lines.join('\r')}\r\n`;+ const paragraphs = Array.from(dataStream.matchAll(/\r/g)).map((match) => ({+ startIndex: match.index!,+ paragraphId: `p-${match.index}`,+ paragraphStyle: {+ spaceBelow: { v: 8 },+ },+ }));+ const documentModel = new DocumentDataModel({+ id: 'docx-form-doc',+ body: {+ dataStream,+ textRuns: [+ {+ st: 0,+ ed: dataStream.length - 2,+ ts: {},+ },+ ],+ paragraphs,+ sectionBreaks: [+ {+ startIndex: dataStream.length - 1,+ pageSize: {+ width: 793.7333333333332,+ height: 1122.5333333333333,+ },+ marginTop: 37.8,+ marginBottom: 61.6,+ marginLeft: 86.93333333333334,+ marginRight: 98.26666666666667,+ marginHeader: 37.8,+ marginFooter: 0,+ linePitch: 24,+ defaultHeaderId: 'header',+ defaultFooterId: 'footer',+ },+ ],+ },+ headers: {+ header: {+ headerId: 'header',+ body: {+ dataStream: '\x1A\x1B\x1C\b\r\n\x1D\x1C\r\n\x1D\x1C\r\n\x1D\x0E\x0F\r\r\n',+ paragraphs: [+ {+ startIndex: 4,+ paragraphId: 'header-p-1',+ },+ {+ startIndex: 8,+ paragraphId: 'header-p-2',+ },+ {+ startIndex: 12,+ paragraphId: 'header-p-3',+ },+ {+ startIndex: 18,+ paragraphId: 'header-p-4',+ },+ {+ startIndex: 19,+ paragraphId: 'header-p-5',+ },+ ],+ sectionBreaks: [+ {+ startIndex: 5,+ },+ {+ startIndex: 9,+ },+ {+ startIndex: 13,+ },+ {+ startIndex: 20,+ },+ ],+ tables: [+ {+ startIndex: 0,+ endIndex: 16,+ tableId: 'header-table',+ },+ ],+ },+ tableSource: {+ 'header-table': {+ tableId: 'header-table',+ align: 0,+ indent: {+ v: 0,+ },+ size: {+ type: 0,+ width: {+ v: 0,+ },+ },+ position: {+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 0 },+ },+ dist: {+ distT: 0,+ distB: 0,+ distL: 0,+ distR: 0,+ },+ tableRows: [+ {+ tableCells: [{}, {}, {}],+ trHeight: {+ val: { v: 0 },+ hRule: 0,+ },+ },+ ],+ tableColumns: [+ { size: { type: TableSizeType.SPECIFIED, width: { v: 356.8666666666666 } } },+ { size: { type: TableSizeType.SPECIFIED, width: { v: 264.59999999999997 } } },+ { size: { type: TableSizeType.SPECIFIED, width: { v: 56.73333333333333 } } },+ ],+ textWrap: 0,+ },+ },+ },+ },+ footers: {+ footer: {+ footerId: 'footer',+ body: {+ dataStream: '\x1A\x1B\x1CFooter company address\rFooter postal address\rFooter website\r\n\x1D\x1CFooter legal name\rBusiness id\r\n\x1D\x1CNetwork company\rBusiness id\r\n\x1D\x0E\x0F\r\r\n',+ paragraphs: [+ {+ startIndex: 22,+ paragraphId: 'footer-p-1',+ },+ {+ startIndex: 44,+ paragraphId: 'footer-p-2',+ },+ {+ startIndex: 59,+ paragraphId: 'footer-p-3',+ },+ {+ startIndex: 78,+ paragraphId: 'footer-p-4',+ },+ {+ startIndex: 90,+ paragraphId: 'footer-p-5',+ },+ {+ startIndex: 107,+ paragraphId: 'footer-p-6',+ },+ {+ startIndex: 119,+ paragraphId: 'footer-p-7',+ },+ {+ startIndex: 125,+ paragraphId: 'footer-p-8',+ },+ ],+ sectionBreaks: [+ {+ startIndex: 60,+ },+ {+ startIndex: 91,+ },+ {+ startIndex: 120,+ },+ {+ startIndex: 127,+ },+ ],+ tables: [+ {+ startIndex: 0,+ endIndex: 124,+ tableId: 'footer-table',+ },+ ],+ },+ tableSource: {+ 'footer-table': {+ tableId: 'footer-table',+ align: 0,+ indent: {+ v: 0,+ },+ size: {+ type: 0,+ width: {+ v: 0,+ },+ },+ position: {+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 0 },+ },+ dist: {+ distT: 0,+ distB: 0,+ distL: 0,+ distR: 0,+ },+ tableRows: [+ {+ tableCells: [{}, {}, {}],+ trHeight: {+ val: { v: 0 },+ hRule: 0,+ },+ },+ ],+ tableColumns: [+ { size: { type: TableSizeType.SPECIFIED, width: { v: 239.33333333333334 } } },+ { size: { type: TableSizeType.SPECIFIED, width: { v: 204.86666666666667 } } },+ { size: { type: TableSizeType.SPECIFIED, width: { v: 170.13333333333333 } } },+ ],+ textWrap: 0,+ },+ },+ },+ },+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ });++ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);++ expect(() => skeleton.calculate()).not.toThrow();+ expect(skeleton.getSkeletonData()?.pages.length).toBeGreaterThan(0);++ skeleton.dispose();+ univer.dispose();+ });});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 e28fc49124..c62bf38299 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@@ -24,6 +24,7 @@ import {ObjectRelativeFromH,ObjectRelativeFromV,SectionType,+ SpacingRule,} from '@univerjs/core';import { describe, expect, it, vi } from 'vitest';import { GlyphType } from '../../../../basics/i-document-skeleton-cached';@@ -172,6 +173,8 @@ describe('docs layout tools extra', () => {expect(isBlankPage({ sections: [{ columns: [{ lines: [blankLine] }] }] } as any)).toBe(true);expect(getNumberUnitValue(null, 100)).toBe(0);+ expect(getNumberUnitValue({} as any, 100)).toBe(0);+ expect(getNumberUnitValue({ v: Number.NaN } as any, 100)).toBe(0);expect(getNumberUnitValue({ v: 10, u: NumberUnitType.PIXEL } as any, 100)).toBe(10);expect(getNumberUnitValue({ v: 2, u: NumberUnitType.POINT } as any, 10)).toBe(2);@@ -209,6 +212,21 @@ describe('docs layout tools extra', () => {}));});+ it('defaults word-style docx paragraphs to snap when the section uses a document grid', () => {+ const lineCfg = getLineHeightConfig({+ linePitch: 30.46666666666667,+ gridType: GridType.LINES_AND_CHARS,+ } as any, {+ useWordStyleLineHeight: true,+ paragraphStyle: {+ lineSpacing: 26.666666666666668,+ spacingRule: SpacingRule.EXACT,+ },+ } as any);++ expect(lineCfg.snapToGrid).toBe(BooleanNumber.TRUE);+ });+it('updates block index values and iterates skeleton blocks', () => {const { page, column } = createPageSkeleton();updateBlockIndex([page] as any, -1);@@ -249,6 +267,21 @@ describe('docs layout tools extra', () => {posOffset: 50,} as any, column as any, page as any, 20)).toBe(60);+ expect(getPositionHorizon({+ relativeFrom: ObjectRelativeFromH.COLUMN,+ posOffset: 0,+ } as any, column as any, page as any, 20)).toBe(10);++ expect(getPositionHorizon({+ relativeFrom: ObjectRelativeFromH.MARGIN,+ posOffset: 50,+ } as any, column as any, page as any, 20)).toBe(70);++ expect(getPositionHorizon({+ relativeFrom: ObjectRelativeFromH.COLUMN,+ posOffset: -603.2,+ } as any, column as any, page as any, 1895.68)).toBeCloseTo(-593.2);+expect(getPositionHorizon({relativeFrom: ObjectRelativeFromH.PAGE,percent: 0.5,@@ -331,6 +364,15 @@ describe('docs layout tools extra', () => {{ paragraphStyle: {}, bullet: { listType: 'bullet' } } as any);expect(configWithBullet.textStyle.bl).toBe(1);++ const configWithMissingBulletList = getFontCreateConfig(+ 0,+ viewModel as any,+ paragraphNode as any,+ sectionBreakConfig as any,+ { paragraphStyle: {}, bullet: { listType: 'missing' } } as any+ );+ expect(configWithMissingBulletList.textStyle.bl).toBeUndefined();});it('creates default skeleton, prepares section config, and resolves page paths', () => {diff --git a/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.ts b/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.tsindex e19c389e72..9fcb66fb99 100644--- a/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.ts+++ b/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.ts@@ -253,6 +253,25 @@ describe('table utilities', () => {expect(() => rollbackListCache(listLevel, tableNode)).not.toThrow();});++ it('skips sparse paragraph list levels', () => {+ const paragraphList: IParagraphList = {+ bullet: {} as unknown as IParagraphList['bullet'],+ paragraph: { startIndex: 25 } as unknown as IParagraphList['paragraph'],+ };+ const paragraphLists = [] as unknown as IParagraphList[][];+ paragraphLists[2] = [paragraphList];+ const listLevel = new Map<string, IParagraphList[][]>([+ ['list1', paragraphLists],+ ]);+ const tableNode = {+ startIndex: 10,+ endIndex: 20,+ } as DataStreamTreeNode;++ expect(() => rollbackListCache(listLevel, tableNode)).not.toThrow();+ expect(listLevel.get('list1')![2]).toHaveLength(1);+ });});});diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.tsindex eede281bf3..cceb019fec 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.ts@@ -103,7 +103,7 @@ describe('language-ruler', () => {});describe('ArabicHandler', () => {- it('combines Arabic characters into one glyph in reverse order', () => {+ it('combines Arabic characters into one glyph in logical order', () => {const arabicText = '\u0645\u0631\u062D\u0628\u0627'; // 'مرحبا'const { viewModel } = createViewModel(arabicText);const paragraphNode = getParagraphNode(viewModel);@@ -113,8 +113,7 @@ describe('language-ruler', () => {const result = ArabicHandler(0, arabicText, viewModel, paragraphNode, sectionBreakConfig, paragraph);expect(result.step).toBe(5);expect(result.glyphGroup.length).toBe(1);- // Arabic characters are unshifted, so they should be in reverse order- expect(result.glyphGroup[0].content).toBe('\u0627\u0628\u062D\u0631\u0645'); // 'ابحرم'+ expect(result.glyphGroup[0].content).toBe(arabicText);});it('stops at non-Arabic characters', () => {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.tsindex 94bbd4c34b..7d5ebf08b1 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@@ -15,9 +15,10 @@*/import type { IParagraphConfig } from '../../../../../../basics/interfaces';-import { BooleanNumber, DataStreamTreeTokenType, GridType, SpacingRule } from '@univerjs/core';+import { BooleanNumber, DataStreamTreeTokenType, GridType, ObjectRelativeFromV, PositionedObjectLayoutType, SpacingRule, WrapTextType } from '@univerjs/core';import { describe, expect, it } from 'vitest';-import { getLineHeightMetrics, layoutParagraph, updateInlineDrawingPosition } from '../layout-ruler';+import { GlyphType, LineType } from '../../../../../../basics/i-document-skeleton-cached';+import { __testing, getLineHeightMetrics, layoutParagraph, updateInlineDrawingPosition } from '../layout-ruler';import { lineBreaking } from '../linebreaking';import { shaping } from '../shaping';import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';@@ -116,6 +117,194 @@ describe('layout-ruler', () => {expect(result.length).toBeGreaterThanOrEqual(1);});+ it('does not recurse indefinitely when floating drawings cover the available line width', () => {+ const { ctx, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('');+ curPage.skeDrawings = new Map(+ Array.from({ length: 4 }, (_, index) => [`float-${index}`, {+ drawingId: `float-${index}`,+ aTop: index,+ aLeft: 20,+ width: 280,+ height: 120,+ angle: 0,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ wrapText: WrapTextType.BOTH_SIDES,+ behindDoc: BooleanNumber.FALSE,+ distL: 0,+ distR: 0,+ distT: 0,+ distB: 0,+ docTransform: {+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH },+ },+ },+ }])+ ) as any;+ const paragraphConfig = {+ paragraphIndex: 0,+ paragraphStyle: {},+ } as unknown as IParagraphConfig;+ const glyphGroup = [{+ glyphType: GlyphType.WORD,+ content: 'Dense',+ count: 5,+ width: 80,+ left: 0,+ xOffset: 0,+ bBox: { ba: 8, bd: 4 },+ }] as any;++ expect(() =>+ layoutParagraph(ctx, glyphGroup, [curPage], sectionBreakConfig, paragraphConfig, true)+ ).not.toThrow(RangeError);+ });++ it('closes zero-width floating anchor lines without recursing through every divide', () => {+ const { ctx, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('');+ const column = curPage.sections[0].columns[0];+ const anchorGlyph = {+ glyphType: GlyphType.PLACEHOLDER,+ streamType: DataStreamTreeTokenType.CUSTOM_BLOCK,+ content: '',+ count: 1,+ width: 0,+ left: 0,+ xOffset: 0,+ drawingId: 'anchor',+ bBox: { ba: 0, bd: 0 },+ };+ const zeroWidthAnchorLine = {+ paragraphIndex: 0,+ type: LineType.PARAGRAPH,+ divides: Array.from({ length: 20_000 }, (_, index) => ({+ glyphGroup: index === 0 ? [anchorGlyph] : [],+ width: 100,+ left: index,+ paddingLeft: 0,+ isFull: false,+ st: 0,+ ed: 0,+ })),+ lineHeight: 0,+ contentHeight: 0,+ top: 0,+ lineIndex: 0,+ parent: column,+ } as any;+ column.lines.push(zeroWidthAnchorLine);+ const paragraphConfig = {+ paragraphIndex: 0,+ paragraphStyle: {},+ paragraphNonInlineSkeDrawings: new Map([['anchor', {+ drawingId: 'anchor',+ aTop: 0,+ aLeft: 0,+ width: 10,+ height: 10,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: BooleanNumber.FALSE,+ docTransform: {+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH },+ },+ },+ }]]),+ } as unknown as IParagraphConfig;+ const glyphGroup = [{+ glyphType: GlyphType.WORD,+ content: 'Text',+ count: 4,+ width: 40,+ left: 0,+ xOffset: 0,+ bBox: { ba: 8, bd: 4 },+ }] as any;++ expect(() =>+ layoutParagraph(ctx, glyphGroup, [curPage], sectionBreakConfig, paragraphConfig, false)+ ).not.toThrow(RangeError);+ });++ it('treats empty zero-size glyphs as ignorable in zero-width floating anchor lines', () => {+ const { ctx, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('');+ const column = curPage.sections[0].columns[0];+ const anchorGlyph = {+ glyphType: GlyphType.PLACEHOLDER,+ streamType: DataStreamTreeTokenType.CUSTOM_BLOCK,+ content: '',+ count: 1,+ width: 0,+ left: 0,+ xOffset: 0,+ drawingId: 'anchor',+ bBox: { ba: 0, bd: 0 },+ };+ const emptyGlyph = {+ glyphType: GlyphType.WORD,+ content: '',+ count: 0,+ width: 0,+ left: 0,+ xOffset: 0,+ bBox: { ba: 0, bd: 0 },+ };+ const divide = {+ glyphGroup: [anchorGlyph, emptyGlyph],+ width: 100,+ left: 0,+ paddingLeft: 0,+ isFull: false,+ st: 0,+ ed: 0,+ } as any;+ const zeroWidthAnchorLine = {+ paragraphIndex: 0,+ type: LineType.PARAGRAPH,+ divides: [divide],+ lineHeight: 0,+ contentHeight: 0,+ top: 0,+ lineIndex: 0,+ parent: column,+ } as any;+ divide.parent = zeroWidthAnchorLine;+ column.lines.push(zeroWidthAnchorLine);+ const paragraphConfig = {+ paragraphIndex: 0,+ paragraphStyle: {},+ paragraphNonInlineSkeDrawings: new Map([['anchor', {+ drawingId: 'anchor',+ aTop: 0,+ aLeft: 0,+ width: 10,+ height: 10,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: BooleanNumber.FALSE,+ docTransform: {+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH },+ },+ },+ }]]),+ } as unknown as IParagraphConfig;+ const glyphGroup = [{+ glyphType: GlyphType.WORD,+ content: 'Y',+ count: 1,+ width: 8,+ left: 0,+ xOffset: 0,+ bBox: { ba: 8, bd: 4 },+ }] as any;++ layoutParagraph(ctx, glyphGroup, [curPage], sectionBreakConfig, paragraphConfig, false);++ expect(column.lines).toHaveLength(2);+ expect(column.lines[0].divides.every((divide) => divide.isFull)).toBe(true);+ expect(column.lines[1].divides[0].glyphGroup).toEqual(glyphGroup);+ });+it('end-to-end: shapes and lays out text through lineBreaking', () => {const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Hello world');const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);@@ -133,6 +322,12 @@ describe('layout-ruler', () => {expect(getLineBoxHeight(metrics)).toBeCloseTo(24, 4);});+ it('does not multiply inline custom block height by auto line spacing', () => {+ const metrics = getLineHeightMetrics(624, 0, 15.6, GridType.LINES, 1.5, SpacingRule.AUTO, BooleanNumber.FALSE, true, false);++ expect(getLineBoxHeight(metrics)).toBeCloseTo(624, 4);+ });+it('keeps document-grid line pitch behavior when auto line spacing explicitly snaps to the grid', () => {const metrics = getLineHeightMetrics(16, 0, 15.6, GridType.LINES, 1.5, SpacingRule.AUTO, BooleanNumber.TRUE, true);@@ -154,6 +349,88 @@ describe('layout-ruler', () => {expect(metrics.contentHeight).toBeGreaterThan(getLineBoxHeight(metrics));});+ it('uses document grid line pitch as the minimum exact line box height for snapped docx paragraphs', () => {+ const metrics = getLineHeightMetrics(16, 0, 30.46666666666667, GridType.LINES_AND_CHARS, 26.666666666666668, SpacingRule.EXACT, BooleanNumber.TRUE, true);++ expect(getLineBoxHeight(metrics)).toBeCloseTo(30.46666666666667, 4);+ });++ it('stops dirty relayout after a floating object reaches the reposition limit', () => {+ const cachedPage: any = {+ segmentId: '',+ skeDrawings: new Map([['floating', {}]]),+ sections: [{ columns: [{ lines: [{ paragraphIndex: 1, top: 0, lineHeight: 20 }] }] }],+ };+ const page: any = {+ segmentId: '',+ sections: [{ columns: [] }],+ };+ const column: any = {+ width: 100,+ left: 0,+ lines: [{ paragraphIndex: 2, top: 0, lineHeight: 20 }],+ parent: { parent: page },+ };+ page.sections[0].columns = [column];+ const floatObject: any = {+ id: 'floating',+ top: 0,+ left: 0,+ width: 50,+ height: 50,+ angle: 0,+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH },+ };+ const ctx: any = {+ floatObjectsCache: new Map([['floating', { count: 5, floatObject, page: cachedPage }]]),+ isDirty: false,+ layoutStartPointer: { '': null },+ paragraphsOpenNewPage: new Set(),+ };++ __testing.reLayoutCheck(ctx, [floatObject], column, 9);++ expect(ctx.isDirty).toBe(false);+ expect(ctx.floatObjectsCache.has('floating')).toBe(true);+ expect(ctx.paragraphsOpenNewPage.has(9)).toBe(false);+ });++ it('does not dirty relayout for behind-doc floating objects', () => {+ const page: any = {+ segmentId: '',+ sections: [{ columns: [] }],+ };+ const column: any = {+ width: 100,+ left: 0,+ lines: [{ paragraphIndex: 2, top: 0, lineHeight: 20 }],+ parent: { parent: page },+ };+ page.sections[0].columns = [column];+ const floatObject: any = {+ id: 'behind-floating',+ top: 0,+ left: 0,+ width: 50,+ height: 50,+ angle: 0,+ behindDoc: BooleanNumber.TRUE,+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH },+ };+ const ctx: any = {+ floatObjectsCache: new Map(),+ isDirty: false,+ layoutStartPointer: { '': null },+ paragraphsOpenNewPage: new Set(),+ };++ __testing.reLayoutCheck(ctx, [floatObject], column, 9);++ expect(ctx.isDirty).toBe(false);+ expect(ctx.floatObjectsCache.has('behind-floating')).toBe(false);+ expect(ctx.paragraphsOpenNewPage.has(9)).toBe(false);+ });+it('keeps the legacy line-height behavior for embedded sheet documents', () => {const metrics = getLineHeightMetrics(16, 0, 15.6, GridType.LINES, 1.5, SpacingRule.AUTO, BooleanNumber.TRUE, false);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 ee18d24405..c2e9fc31ef 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@@ -14,11 +14,12 @@* limitations under the License.*/-import { DocumentBlockRangeType, DocumentFlavor } from '@univerjs/core';-import { describe, expect, it, vi } from 'vitest';+import { AlignTypeH, AlignTypeV, DataStreamTreeTokenType, DocumentBlockRangeType, DocumentFlavor, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType } from '@univerjs/core';+import { beforeEach, describe, expect, it, vi } from 'vitest';import { lineBreaking } from '../linebreaking';import { shaping } from '../shaping';-import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';+import { updateInlineDrawingCoordsAndBorder } from '../../../tools';+import { createParagraphLayoutTestBed, createSectionLayoutTestBed } from './create-paragraph-layout-test-bed';function createContext() {return {@@ -33,6 +34,24 @@ function createContext() {}describe('linebreaking', () => {+ beforeEach(() => {+ vi.stubGlobal('document', {+ createElement: () => ({+ getContext: () => ({+ font: '',+ textBaseline: 'alphabetic',+ measureText: (value: string) => ({+ width: value.length * 8,+ fontBoundingBoxAscent: 10,+ fontBoundingBoxDescent: 4,+ actualBoundingBoxAscent: 10,+ actualBoundingBoxDescent: 4,+ }),+ }),+ }),+ });+ });+it('lays out short text on a single page', () => {const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Hi');const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);@@ -94,6 +113,902 @@ describe('linebreaking', () => {expect(result.length).toBe(1);});+ it('ignores custom blocks that reference missing drawings', () => {+ const content = `A${DataStreamTreeTokenType.CUSTOM_BLOCK}B`;+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ body: {+ customBlocks: [{ startIndex: 1, blockId: 'missing' }],+ },+ drawings: {},+ });+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result.length).toBeGreaterThanOrEqual(1);+ });++ it('honors page breaks in paragraphs that only contain floating custom blocks', () => {+ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}${DataStreamTreeTokenType.CUSTOM_BLOCK}${DataStreamTreeTokenType.PAGE_BREAK}`;+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ body: {+ customBlocks: [+ { startIndex: 0, blockId: 'cover-background' },+ { startIndex: 1, blockId: 'cover-title' },+ ],+ },+ drawings: {+ 'cover-background': {+ drawingId: 'cover-background',+ layoutType: 1,+ docTransform: {+ size: { width: 400, height: 600 },+ positionH: {},+ positionV: {},+ },+ },+ 'cover-title': {+ layoutType: 1,+ docTransform: {+ size: { width: 200, height: 80 },+ positionH: {},+ positionV: {},+ },+ },+ },+ });+ vi.stubGlobal('document', {+ createElement: () => ({+ getContext: () => ({+ font: '',+ textBaseline: 'alphabetic',+ measureText: (value: string) => ({+ width: value.length * 8,+ fontBoundingBoxAscent: 10,+ fontBoundingBoxDescent: 4,+ actualBoundingBoxAscent: 10,+ actualBoundingBoxDescent: 4,+ }),+ }),+ }),+ });+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result).toHaveLength(2);+ expect(result[1].breakType).toBe(1);+ });++ it('keeps floating custom blocks after a page break on the next page', () => {+ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}${DataStreamTreeTokenType.PAGE_BREAK}${DataStreamTreeTokenType.CUSTOM_BLOCK}`;+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ body: {+ customBlocks: [+ { startIndex: 0, blockId: 'cover-background' },+ { startIndex: 2, blockId: 'checklist-panel' },+ ],+ },+ drawings: {+ 'cover-background': {+ drawingId: 'cover-background',+ layoutType: 1,+ docTransform: {+ size: { width: 400, height: 600 },+ positionH: {},+ positionV: {},+ },+ },+ 'checklist-panel': {+ drawingId: 'checklist-panel',+ layoutType: 1,+ docTransform: {+ size: { width: 200, height: 120 },+ positionH: {},+ positionV: {},+ },+ },+ },+ });+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result).toHaveLength(2);+ expect(result[0].skeDrawings.has('cover-background')).toBe(true);+ expect(result[0].skeDrawings.has('checklist-panel')).toBe(false);+ expect(result[1].skeDrawings.has('cover-background')).toBe(false);+ expect(result[1].skeDrawings.has('checklist-panel')).toBe(true);+ });++ it('keeps every floating custom block on its side of a page break', () => {+ const firstPageIds = Array.from({ length: 15 }, (_, index) => `cover-${index + 1}`);+ const secondPageIds = Array.from({ length: 14 }, (_, index) => `content-${index + 1}`);+ const drawingIds = [...firstPageIds, ...secondPageIds];+ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK.repeat(firstPageIds.length)}${DataStreamTreeTokenType.PAGE_BREAK}${DataStreamTreeTokenType.CUSTOM_BLOCK.repeat(secondPageIds.length)}`;+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ body: {+ customBlocks: drawingIds.map((blockId, startIndex) => ({ startIndex: startIndex < firstPageIds.length ? startIndex : startIndex + 1, blockId })),+ },+ drawings: Object.fromEntries(+ drawingIds.map((drawingId, index) => [+ drawingId,+ {+ drawingId,+ layoutType: 1,+ docTransform: {+ size: { width: 100 + index, height: 40 + index },+ positionH: { posOffset: 10 + index },+ positionV: { posOffset: 20 + index },+ angle: 0,+ },+ },+ ])+ ),+ });+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result).toHaveLength(2);+ expect([...result[0].skeDrawings.keys()].sort()).toEqual([...firstPageIds].sort());+ expect([...result[1].skeDrawings.keys()].sort()).toEqual([...secondPageIds].sort());+ });++ it('keeps inline custom blocks after adjacent floating blocks before a page break', () => {+ const content = `Intro${DataStreamTreeTokenType.CUSTOM_BLOCK.repeat(6)}${DataStreamTreeTokenType.PAGE_BREAK}`;+ const drawingIds = ['float-left', 'float-right', 'inline-map-left', 'float-frame-left', 'inline-map-right', 'float-frame-right'];+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ body: {+ customBlocks: drawingIds.map((blockId, index) => ({ startIndex: 5 + index, blockId })),+ },+ drawings: {+ 'float-left': {+ drawingId: 'float-left',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: {+ size: { width: 80, height: 40 },+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 10 },+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 120 },+ },+ },+ 'float-right': {+ drawingId: 'float-right',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: {+ size: { width: 80, height: 40 },+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 180 },+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 120 },+ },+ },+ 'inline-map-left': {+ drawingId: 'inline-map-left',+ layoutType: PositionedObjectLayoutType.INLINE,+ docTransform: {+ size: { width: 120, height: 90 },+ positionH: {},+ positionV: {},+ angle: 0,+ },+ },+ 'float-frame-left': {+ drawingId: 'float-frame-left',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: {+ size: { width: 120, height: 90 },+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 20 },+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 180 },+ },+ },+ 'inline-map-right': {+ drawingId: 'inline-map-right',+ layoutType: PositionedObjectLayoutType.INLINE,+ docTransform: {+ size: { width: 120, height: 90 },+ positionH: {},+ positionV: {},+ angle: 0,+ },+ },+ 'float-frame-right': {+ drawingId: 'float-frame-right',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: {+ size: { width: 120, height: 90 },+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 170 },+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 180 },+ },+ },+ },+ });+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);+ updateInlineDrawingCoordsAndBorder(ctx, result);++ const inlineMapLeft = result[0].skeDrawings.get('inline-map-left');+ const inlineMapRight = result[0].skeDrawings.get('inline-map-right');++ expect(inlineMapLeft).toMatchObject({ width: 120, height: 90 });+ expect(inlineMapRight).toMatchObject({ width: 120, height: 90 });+ expect(inlineMapRight?.lineTop).toBe(inlineMapLeft?.lineTop);+ expect(inlineMapRight?.aLeft).toBeGreaterThan(inlineMapLeft?.aLeft ?? 0);+ });++ it('does not move a zero-width wrap-none floating anchor to a new page at the page bottom', () => {+ const content = DataStreamTreeTokenType.CUSTOM_BLOCK;+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ body: {+ customBlocks: [{ startIndex: 0, blockId: 'behind-picture' }],+ },+ drawings: {+ 'behind-picture': {+ drawingId: 'behind-picture',+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: 1,+ docTransform: {+ size: { width: 120, height: 90 },+ positionH: { posOffset: 0 },+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },+ angle: 0,+ },+ },+ },+ });+ const column = curPage.sections[0].columns[0];+ const previousLine = {+ lineHeight: 0,+ top: curPage.sections[0].height - 0.1,+ paragraphIndex: 0,+ lineIndex: 0,+ divides: [],+ parent: column,+ };+ column.lines.push(previousLine as any);+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result).toHaveLength(1);+ expect(result[0].skeDrawings.has('behind-picture')).toBe(true);+ expect(result[0].skeDrawings.get('behind-picture')).toMatchObject({+ width: 120,+ height: 90,+ });+ const lines = result[0].sections[0].columns[0].lines;+ expect(lines[lines.length - 1].lineHeight).toBe(0);+ });++ it('keeps consecutive zero-width wrap-none floating anchors on a non-flow line', () => {+ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}${DataStreamTreeTokenType.CUSTOM_BLOCK}`;+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ body: {+ customBlocks: [+ { startIndex: 0, blockId: 'behind-picture-1' },+ { startIndex: 1, blockId: 'behind-picture-2' },+ ],+ },+ drawings: {+ 'behind-picture-1': {+ drawingId: 'behind-picture-1',+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: 1,+ docTransform: {+ size: { width: 120, height: 90 },+ positionH: { posOffset: 0 },+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },+ angle: 0,+ },+ },+ 'behind-picture-2': {+ drawingId: 'behind-picture-2',+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: 1,+ docTransform: {+ size: { width: 80, height: 60 },+ positionH: { posOffset: 40 },+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 20 },+ angle: 0,+ },+ },+ },+ });+ const [shapedText] = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);+ const firstGlyph = shapedText.glyphs[0];+ const secondGlyph = { ...firstGlyph, drawingId: 'behind-picture-2' };+ const shapedTextList = [+ { ...shapedText, text: DataStreamTreeTokenType.CUSTOM_BLOCK, glyphs: [firstGlyph] },+ { ...shapedText, text: DataStreamTreeTokenType.CUSTOM_BLOCK, glyphs: [secondGlyph] },+ ];++ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result).toHaveLength(1);+ expect(result[0].skeDrawings.has('behind-picture-1')).toBe(true);+ expect(result[0].skeDrawings.has('behind-picture-2')).toBe(true);+ expect(result[0].sections[0].columns[0].lines[0].lineHeight).toBe(0);+ });++ it('positions oversized behind-doc wrap-none anchors with negative Word offsets', () => {+ const content = DataStreamTreeTokenType.CUSTOM_BLOCK;+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ body: {+ customBlocks: [{ startIndex: 0, blockId: 'cover-background' }],+ },+ drawings: {+ 'cover-background': {+ drawingId: 'cover-background',+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: 1,+ docTransform: {+ size: { width: 1895.68, height: 1280.81 },+ positionH: { relativeFrom: ObjectRelativeFromH.COLUMN, posOffset: -603.2 },+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: -96.89 },+ angle: 0,+ },+ },+ },+ });+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result).toHaveLength(1);+ expect(result[0].skeDrawings.get('cover-background')).toMatchObject({+ width: 1895.68,+ height: 1280.81,+ aTop: expect.closeTo(-96.89, 2),+ });+ });++ it('positions page-relative full-page behind-doc anchors at the page origin', () => {+ const content = DataStreamTreeTokenType.CUSTOM_BLOCK;+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ body: {+ customBlocks: [{ startIndex: 0, blockId: 'cover-background' }],+ },+ drawings: {+ 'cover-background': {+ drawingId: 'cover-background',+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: 1,+ docTransform: {+ size: { width: 400, height: 600 },+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, align: AlignTypeH.CENTER },+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, align: AlignTypeV.TOP },+ angle: 0,+ },+ },+ },+ });+ curPage.pageWidth = 400;+ curPage.pageHeight = 600;+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result).toHaveLength(1);+ expect(result[0].skeDrawings.get('cover-background')).toMatchObject({+ aLeft: 0,+ aTop: 0,+ width: 400,+ height: 600,+ });+ });++ it('keeps DOCX manual line breaks in the same page instead of treating them as column breaks', () => {+ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}PROGRAM${DataStreamTreeTokenType.COLUMN_BREAK}SECOND`;+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ body: {+ customBlocks: [{ startIndex: 0, blockId: 'cover-background' }],+ },+ drawings: {+ 'cover-background': {+ drawingId: 'cover-background',+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: 1,+ docTransform: {+ size: { width: 400, height: 600 },+ positionH: { posOffset: 0 },+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },+ angle: 0,+ },+ },+ },+ });+ vi.stubGlobal('document', {+ createElement: () => ({+ getContext: () => ({+ font: '',+ textBaseline: 'alphabetic',+ measureText: (value: string) => ({+ width: value.length * 8,+ fontBoundingBoxAscent: 10,+ fontBoundingBoxDescent: 4,+ actualBoundingBoxAscent: 10,+ actualBoundingBoxDescent: 4,+ }),+ }),+ }),+ });+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result).toHaveLength(1);+ const renderedText = result[0].sections[0].columns[0].lines+ .flatMap((line) => line.divides)+ .flatMap((divide) => divide.glyphGroup)+ .map((glyph) => glyph.content)+ .join('');+ expect(renderedText).toContain('PROGRAM');+ expect(renderedText).toContain('SECOND');+ });++ it('treats marked DOCX column breaks as column breaks in traditional documents', () => {+ const content = `FIRST${DataStreamTreeTokenType.COLUMN_BREAK}SECOND`;+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ body: {+ customRanges: [{+ startIndex: 5,+ endIndex: 5,+ rangeId: 'docx-break-0',+ rangeType: 5,+ wholeEntity: true,+ properties: { docxBreakType: 'column' },+ }],+ sectionBreaks: [{+ startIndex: content.length + 1,+ columnProperties: [+ { width: 170, paddingEnd: 20 },+ { width: 170, paddingEnd: 0 },+ ],+ }],+ },+ });+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ const firstColumnText = result[0].sections[0].columns[0].lines+ .flatMap((line) => line.divides)+ .flatMap((divide) => divide.glyphGroup)+ .map((glyph) => glyph.content)+ .join('');+ const secondColumnText = result[0].sections[0].columns[1].lines+ .flatMap((line) => line.divides)+ .flatMap((divide) => divide.glyphGroup)+ .map((glyph) => glyph.content)+ .join('');++ expect(firstColumnText).toContain('FIRST');+ expect(firstColumnText).not.toContain('SECOND');+ expect(secondColumnText).toContain('SECOND');+ });++ it('starts normal text on a new flow line after a zero-width wrap-none floating anchor', () => {+ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}Hello`;+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ body: {+ customBlocks: [{ startIndex: 0, blockId: 'behind-picture' }],+ },+ drawings: {+ 'behind-picture': {+ drawingId: 'behind-picture',+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: 1,+ docTransform: {+ size: { width: 120, height: 90 },+ positionH: { posOffset: 0 },+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },+ angle: 0,+ },+ },+ },+ });+ vi.stubGlobal('document', {+ createElement: () => ({+ getContext: () => ({+ font: '',+ textBaseline: 'alphabetic',+ measureText: (value: string) => ({+ width: value.length * 8,+ fontBoundingBoxAscent: 10,+ fontBoundingBoxDescent: 4,+ actualBoundingBoxAscent: 10,+ actualBoundingBoxDescent: 4,+ }),+ }),+ }),+ });+ const shapedTexts = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);+ const allGlyphs = shapedTexts.flatMap(({ glyphs }) => glyphs);+ const anchorGlyph = allGlyphs.find((glyph) => glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK)!;+ const textGlyphs = allGlyphs+ .filter((glyph) => glyph.streamType !== DataStreamTreeTokenType.CUSTOM_BLOCK)+ .map((glyph) => ({+ ...glyph,+ width: glyph.content === 'H' || glyph.content === 'e' || glyph.content === 'l' || glyph.content === 'o' ? 8 : glyph.width,+ bBox: glyph.content === 'H' || glyph.content === 'e' || glyph.content === 'l' || glyph.content === 'o'+ ? { ...glyph.bBox, ba: 10, bd: 4 }+ : glyph.bBox,+ }));+ const shapedText = shapedTexts[0];+ const shapedTextList = [+ { ...shapedText, text: DataStreamTreeTokenType.CUSTOM_BLOCK, glyphs: [anchorGlyph] },+ { ...shapedText, text: 'Hello', glyphs: textGlyphs },+ ];++ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ const lines = result[0].sections[0].columns[0].lines;+ expect(result).toHaveLength(1);+ expect(result[0].skeDrawings.has('behind-picture')).toBe(true);+ expect(lines[0].lineHeight).toBe(0);+ expect(lines[0].divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.drawingId))).toContain('behind-picture');+ expect(lines[1].lineHeight).toBeGreaterThan(0);+ expect(lines[1].divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content)).join('')).toContain('Hello');+ });++ it('positions DOCX column-relative floating anchors from the paragraph indent origin', () => {+ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}Body`;+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ marginLeft: 0,+ },+ body: {+ customBlocks: [{ startIndex: 0, blockId: 'left-picture' }],+ paragraphs: [{+ startIndex: content.length,+ paragraphId: 'indented',+ paragraphStyle: {+ indentStart: { v: 737 },+ },+ }],+ },+ drawings: {+ 'left-picture': {+ drawingId: 'left-picture',+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: 1,+ docTransform: {+ size: { width: 120, height: 90 },+ positionH: { relativeFrom: ObjectRelativeFromH.COLUMN, posOffset: -616 },+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },+ angle: 0,+ },+ },+ },+ });+ const shapedTexts = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTexts, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result[0].skeDrawings.get('left-picture')).toMatchObject({+ aLeft: 121,+ });+ });++ it('positions DOCX floating anchors in empty paragraphs from the following text paragraph indent origin', () => {+ const floatingParagraph = DataStreamTreeTokenType.CUSTOM_BLOCK;+ const bodyParagraph = 'Body';+ const { viewModel, ctx, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed([floatingParagraph, bodyParagraph], {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ marginLeft: 0,+ },+ body: {+ customBlocks: [{ startIndex: 0, blockId: 'left-textbox' }],+ paragraphs: [+ {+ startIndex: floatingParagraph.length,+ paragraphId: 'floating-anchor',+ },+ {+ startIndex: floatingParagraph.length + 1 + bodyParagraph.length,+ paragraphId: 'indented-body',+ paragraphStyle: {+ indentStart: { v: 737 },+ },+ },+ ],+ },+ drawings: {+ 'left-textbox': {+ drawingId: 'left-textbox',+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: 1,+ docTransform: {+ size: { width: 120, height: 90 },+ positionH: { relativeFrom: ObjectRelativeFromH.COLUMN, posOffset: -616 },+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },+ angle: 0,+ },+ },+ },+ });+ curPage.sections[0].columns[0].left = 113;+ const paragraphNode = sectionNode.children.find((node) => node.blocks?.includes(1)) ?? sectionNode.children[0];+ const shapedTexts = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTexts, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result[0].skeDrawings.get('left-textbox')).toMatchObject({+ aLeft: 121,+ });+ });++ it('positions DOCX positive column-relative floating anchors from the following text paragraph indent origin', () => {+ const floatingParagraph = DataStreamTreeTokenType.CUSTOM_BLOCK;+ const bodyParagraph = 'Body';+ const { viewModel, ctx, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed([floatingParagraph, bodyParagraph], {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ marginLeft: 0,+ },+ body: {+ customBlocks: [{ startIndex: 0, blockId: 'scroll-picture' }],+ paragraphs: [+ {+ startIndex: floatingParagraph.length,+ paragraphId: 'floating-anchor',+ },+ {+ startIndex: floatingParagraph.length + 1 + bodyParagraph.length,+ paragraphId: 'indented-body',+ paragraphStyle: {+ indentStart: { v: 737 },+ },+ },+ ],+ },+ drawings: {+ 'scroll-picture': {+ drawingId: 'scroll-picture',+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: 1,+ docTransform: {+ size: { width: 120, height: 90 },+ positionH: { relativeFrom: ObjectRelativeFromH.COLUMN, posOffset: 33 },+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },+ angle: 0,+ },+ },+ },+ });+ curPage.sections[0].columns[0].left = 113;+ const paragraphNode = sectionNode.children.find((node) => node.blocks?.includes(1)) ?? sectionNode.children[0];+ const shapedTexts = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTexts, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result[0].skeDrawings.get('scroll-picture')).toMatchObject({+ aLeft: 770,+ });+ });++ it('subtracts page margin from DOCX paragraph-origin column anchors stored in the skeleton', () => {+ const floatingParagraph = DataStreamTreeTokenType.CUSTOM_BLOCK;+ const bodyParagraph = 'Body';+ const { viewModel, ctx, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed([floatingParagraph, bodyParagraph], {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ marginLeft: 113,+ },+ body: {+ customBlocks: [{ startIndex: 0, blockId: 'scroll-picture' }],+ paragraphs: [+ {+ startIndex: floatingParagraph.length,+ paragraphId: 'floating-anchor',+ },+ {+ startIndex: floatingParagraph.length + 1 + bodyParagraph.length,+ paragraphId: 'indented-body',+ paragraphStyle: {+ indentStart: { v: 737 },+ },+ },+ ],+ },+ drawings: {+ 'scroll-picture': {+ drawingId: 'scroll-picture',+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: 1,+ docTransform: {+ size: { width: 120, height: 90 },+ positionH: { relativeFrom: ObjectRelativeFromH.COLUMN, posOffset: 33 },+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },+ angle: 0,+ },+ },+ },+ });+ const paragraphNode = sectionNode.children.find((node) => node.blocks?.includes(1)) ?? sectionNode.children[0];+ const shapedTexts = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTexts, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result[0].skeDrawings.get('scroll-picture')).toMatchObject({+ aLeft: 657,+ });+ });++ it('does not borrow a distant following paragraph indent for DOCX column anchors', () => {+ const floatingParagraph = DataStreamTreeTokenType.CUSTOM_BLOCK;+ const bodyParagraph = 'Body';+ const signatureParagraph = 'Signature';+ const { viewModel, ctx, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed([floatingParagraph, bodyParagraph, signatureParagraph], {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ marginLeft: 113,+ },+ body: {+ customBlocks: [{ startIndex: 0, blockId: 'cover-picture' }],+ paragraphs: [+ {+ startIndex: floatingParagraph.length,+ paragraphId: 'floating-anchor',+ },+ {+ startIndex: floatingParagraph.length + 1 + bodyParagraph.length,+ paragraphId: 'body',+ },+ {+ startIndex: floatingParagraph.length + 1 + bodyParagraph.length + 1 + signatureParagraph.length,+ paragraphId: 'signature',+ paragraphStyle: {+ indentStart: { v: 330.4 },+ },+ },+ ],+ },+ drawings: {+ 'cover-picture': {+ drawingId: 'cover-picture',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ behindDoc: 0,+ docTransform: {+ size: { width: 795, height: 382 },+ positionH: { relativeFrom: ObjectRelativeFromH.COLUMN, posOffset: -75.6 },+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },+ angle: 0,+ },+ },+ },+ });+ const paragraphNode = sectionNode.children.find((node) => node.blocks?.includes(0)) ?? sectionNode.children[0];+ const shapedTexts = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTexts, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result[0].skeDrawings.get('cover-picture')).toMatchObject({+ aLeft: -75.6,+ });+ });++ it('keeps DOCX leading floating anchors in text paragraphs on their own column origin', () => {+ const floatingParagraph = `${DataStreamTreeTokenType.CUSTOM_BLOCK}Body`;+ const indentedContinuation = 'Continuation';+ const { viewModel, ctx, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed([floatingParagraph, indentedContinuation], {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ body: {+ customBlocks: [{ startIndex: 0, blockId: 'left-picture' }],+ paragraphs: [+ {+ startIndex: floatingParagraph.length,+ paragraphId: 'floating-with-text-anchor',+ },+ {+ startIndex: floatingParagraph.length + 1 + indentedContinuation.length,+ paragraphId: 'indented-continuation',+ paragraphStyle: {+ indentStart: { v: 737 },+ },+ },+ ],+ },+ drawings: {+ 'left-picture': {+ drawingId: 'left-picture',+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: 1,+ docTransform: {+ size: { width: 120, height: 90 },+ positionH: { relativeFrom: ObjectRelativeFromH.COLUMN, posOffset: -616 },+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },+ angle: 0,+ },+ },+ },+ });+ const paragraphNode = sectionNode.children[0];+ const shapedTexts = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const result = lineBreaking(ctx, viewModel, shapedTexts, curPage, paragraphNode, sectionBreakConfig, null);++ expect(result[0].skeDrawings.get('left-picture')).toMatchObject({+ aLeft: -616,+ });+ });++ it('starts normal text on a new flow line when the zero-width floating anchor line has paragraph terminators', () => {+ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}Hello`;+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ body: {+ customBlocks: [{ startIndex: 0, blockId: 'behind-picture' }],+ },+ drawings: {+ 'behind-picture': {+ drawingId: 'behind-picture',+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: 1,+ docTransform: {+ size: { width: 120, height: 90 },+ positionH: { posOffset: 0 },+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },+ angle: 0,+ },+ },+ },+ });+ const shapedTexts = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);+ const allGlyphs = shapedTexts.flatMap(({ glyphs }) => glyphs);+ const anchorGlyph = allGlyphs.find((glyph) => glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK)!;+ const terminatorGlyphs = allGlyphs.filter((glyph) =>+ glyph.streamType === DataStreamTreeTokenType.PARAGRAPH ||+ glyph.streamType === DataStreamTreeTokenType.SECTION_BREAK+ );+ const textGlyphs = allGlyphs+ .filter((glyph) => glyph.streamType !== DataStreamTreeTokenType.CUSTOM_BLOCK)+ .filter((glyph) => glyph.streamType !== DataStreamTreeTokenType.PARAGRAPH)+ .filter((glyph) => glyph.streamType !== DataStreamTreeTokenType.SECTION_BREAK)+ .map((glyph) => ({+ ...glyph,+ width: 8,+ bBox: { ...glyph.bBox, ba: 10, bd: 4 },+ }));+ const shapedText = shapedTexts[0];+ const shapedTextList = [+ { ...shapedText, text: DataStreamTreeTokenType.CUSTOM_BLOCK, glyphs: [anchorGlyph, ...terminatorGlyphs] },+ { ...shapedText, text: 'Hello', glyphs: textGlyphs },+ ];++ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ const lines = result[0].sections[0].columns[0].lines;+ expect(result).toHaveLength(1);+ expect(lines[0].lineHeight).toBe(0);+ expect(lines[0].divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.drawingId))).toContain('behind-picture');+ expect(lines[1].lineHeight).toBeGreaterThan(0);+ expect(lines[1].divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content)).join('')).toContain('Hello');+ });+it('applies callout outer spacing as a temporary layout style without mutating the paragraph model', () => {const ctx = createContext();const paragraphStyle = { indentStart: { v: 60 }, indentEnd: { v: 20 } };@@ -413,6 +1328,53 @@ describe('linebreaking', () => {expect(paragraphStyle).toEqual({});});+ it('keeps traditional documents on explicit paragraph spacing while using Word line height', () => {+ const ctx = createContext();+ const paragraphStyle = {};+ const paragraph = {+ startIndex: 3,+ paragraphStyle,+ };+ const viewModel = {+ getParagraph: vi.fn(() => paragraph),+ getBody: vi.fn(() => ({+ paragraphs: [paragraph],+ })),+ getSnapshot: vi.fn(() => ({+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ })),+ getCustomBlock: vi.fn(() => null),+ } as any;++ lineBreaking(+ ctx,+ viewModel,+ [],+ {+ segmentId: 'segment-1',+ pageNumber: 1,+ } as any,+ {+ endIndex: 3,+ startIndex: 0,+ blocks: [],+ children: [],+ } as any,+ {+ lists: [],+ localeService: {} as any,+ drawings: {},+ } as any,+ null+ );++ expect(ctx.paragraphConfigCache.get('segment-1')?.get(3)?.paragraphStyle).toEqual({});+ expect(ctx.paragraphConfigCache.get('segment-1')?.get(3)?.useWordStyleLineHeight).toBe(true);+ expect(paragraphStyle).toEqual({});+ });+it('keeps embedded sheet rich text documents without a flavor on their explicit paragraph style only', () => {const ctx = createContext();const paragraphStyle = {};diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.tsindex 07ce459c11..a8fa6e8ba0 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts@@ -96,6 +96,17 @@ describe('shaping', () => {expect(allGlyphs.length).toBeGreaterThan(0);});+ it('keeps Arabic glyph groups in logical order for canvas text shaping', () => {+ const arabicText = '\u0627\u0637\u0644\u0627\u0639\u064A\u0647';+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(arabicText);++ const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const allGlyphs = result.flatMap((r) => r.glyphs);+ expect(allGlyphs.some((glyph) => glyph.content === arabicText)).toBe(true);+ expect(allGlyphs.some((glyph) => glyph.content === '\u0647\u064A\u0639\u0627\u0644\u0637\u0627')).toBe(false);+ });+it('returns breakPointType for each shaped text', () => {const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('Hello world');@@ -174,6 +185,21 @@ describe('shaping', () => {expect(allGlyphs.length).toBeGreaterThan(0);});+ it('falls back when a custom block references a missing drawing', () => {+ const content = `A${DataStreamTreeTokenType.CUSTOM_BLOCK}B`;+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {+ body: {+ customBlocks: [{ startIndex: 1, blockId: 'missing' }],+ },+ drawings: {},+ });++ const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);++ const allGlyphs = result.flatMap((r) => r.glyphs);+ expect(allGlyphs.length).toBeGreaterThan(0);+ });+it('shapes inline custom block and splits shaped texts', () => {const content = `A${DataStreamTreeTokenType.CUSTOM_BLOCK}B`;const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.tsindex d38f727242..9bf5dc4331 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.ts@@ -80,7 +80,7 @@ export function ArabicHandler(for (let i = 0; i < charArray.length; i++) {const newChar = charArray[i];if (hasArabic(newChar)) {- glyph.unshift(newChar);+ glyph.push(newChar);step++;} else {break;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 cac5501bf1..df311c3c21 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@@ -30,7 +30,7 @@ import type {IFloatObject,ILayoutContext,} from '../../tools';-import { BooleanNumber, DataStreamTreeTokenType, GridType, NAMED_STYLE_SPACE_MAP, ObjectRelativeFromV, PositionedObjectLayoutType, SpacingRule, TableTextWrapType, WrapStrategy } from '@univerjs/core';+import { BooleanNumber, DataStreamTreeTokenType, GridType, NAMED_STYLE_SPACE_MAP, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType, SpacingRule, TableTextWrapType, WrapStrategy } from '@univerjs/core';import { GlyphType, LineType } from '../../../../../basics/i-document-skeleton-cached';import { BreakPointType } from '../../line-breaker/break';import { addGlyphToDivide, createSkeletonBulletGlyph } from '../../model/glyph';@@ -63,6 +63,9 @@ import {} from '../../tools';import { createTableSkeletons, rollbackListCache } from '../table';+const LINE_LAYOUT_OVERFLOW_TOLERANCE = 2;+const FLOAT_OBJECT_RELAYOUT_LIMIT = 5;+export function layoutParagraph(ctx: ILayoutContext,glyphGroup: IDocumentSkeletonGlyph[],@@ -217,7 +220,6 @@ function _divideOperator(const lastLeft = lastGlyph?.left || 0;const preOffsetLeft = lastWidth + lastLeft;const { hyphenationZone } = sectionBreakConfig;-if (preOffsetLeft + width > divide.width) {if (shouldKeepOverflowingTextOnLine(sectionBreakConfig)) {addGlyphToDivide(divide, glyphGroup, preOffsetLeft);@@ -345,7 +347,27 @@ function _divideOperator(const currentLine = divide.parent;const maxBox = __maxFontBoundingBoxByGlyphGroup(glyphGroup);- if (currentLine && maxBox && !__isNullLine(currentLine)) {+ if (+ currentLine &&+ __isZeroWidthNonFlowFloatingAnchorLine(__getGlyphGroupByLine(currentLine), paragraphConfig.paragraphNonInlineSkeDrawings) &&+ __hasFlowGlyph(glyphGroup)+ ) {+ for (const lineDivide of currentLine.divides) {+ updateDivideInfo(lineDivide, {+ isFull: true,+ });+ }+ _lineOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, false, breakPointType);+ return;+ }++ if (+ currentLine &&+ maxBox &&+ !__isNullLine(currentLine) &&+ __hasFlowGlyph(__getGlyphGroupByLine(currentLine)) &&+ !__isZeroWidthNonFlowFloatingAnchorLine(glyphGroup, paragraphConfig.paragraphNonInlineSkeDrawings)+ ) {const { paragraphLineGapDefault, linePitch, lineSpacing, spacingRule, snapToGrid, gridType } =getLineHeightConfig(sectionBreakConfig, paragraphConfig);const { boundingBoxAscent, boundingBoxDescent } = maxBox;@@ -361,7 +383,7 @@ function _divideOperator(paragraphConfig.useWordStyleLineHeight);- if (currentLine.contentHeight < contentHeight) {+ if (contentHeight - currentLine.contentHeight > LINE_LAYOUT_OVERFLOW_TOLERANCE) {// If the height of the new content exceeds the height of the line it joins, for mixed text and graphics layout, the entire line needs to be recalculated according to the new height// If the height of the new content exceeds the height of the added row,// the entire row needs to be recalculated according to the new height@@ -410,6 +432,23 @@ function _divideOperator(return;}}+ if (currentLine?.parent) {+ const anchorDrawings = __getZeroWidthNonFlowFloatingAnchorDrawings(glyphGroup, paragraphConfig.paragraphNonInlineSkeDrawings);+ if (anchorDrawings.length > 0) {+ const paragraphAnchorLeft = __getParagraphAnchorLeft(sectionBreakConfig, paragraphConfig, paragraphConfig.paragraphStyle?.indentStart);+ const drawings = __getDrawingPosition(+ currentLine.top,+ currentLine.lineHeight,+ currentLine.parent,+ true,+ paragraphConfig.pDrawingAnchor?.get(paragraphConfig.paragraphIndex)?.top,+ anchorDrawings,+ paragraphAnchorLeft+ );+ __updateDrawingPosition(currentLine.parent, drawings);+ }+ }+addGlyphToDivide(divide, glyphGroup, preOffsetLeft);updateDivideInfo(divide, { breakType: breakPointType });}@@ -463,6 +502,7 @@ function _lineOperator(pDrawingAnchor,paragraphIndex,} = paragraphConfig;+ const isZeroWidthNonFlowFloatingAnchorLine = __isZeroWidthNonFlowFloatingAnchorLine(glyphGroup, paragraphNonInlineSkeDrawings);const { namedStyleType } = originParagraphStyle;const namedStyle = namedStyleType !== undefined ? NAMED_STYLE_SPACE_MAP[namedStyleType] : null;const paragraphStyle = {@@ -493,7 +533,11 @@ function _lineOperator(paragraphConfig);- const { paddingTop, paddingBottom, contentHeight, lineSpacingApply } = getLineHeightMetrics(+ const hasInlineCustomBlock = glyphGroup.some((glyph) => glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width !== 0);+ const glyphGroupCustomBlockIds = new Set(glyphGroup+ .filter((glyph) => glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.drawingId != null)+ .map((glyph) => glyph.drawingId!));+ let { paddingTop, paddingBottom, contentHeight, lineSpacingApply } = getLineHeightMetrics(glyphLineHeight,paragraphLineGapDefault,linePitch,@@ -501,10 +545,11 @@ function _lineOperator(lineSpacing,spacingRule,snapToGrid,- paragraphConfig.useWordStyleLineHeight+ paragraphConfig.useWordStyleLineHeight,+ !hasInlineCustomBlock);- const { marginTop, spaceBelowApply } = __getParagraphSpace(+ let { marginTop, spaceBelowApply } = __getParagraphSpace(ctx,lineSpacingApply,spaceAbove,@@ -513,7 +558,19 @@ function _lineOperator(preLine);+ if (isZeroWidthNonFlowFloatingAnchorLine) {+ paddingTop = 0;+ paddingBottom = 0;+ contentHeight = 0;+ lineSpacingApply = 0;+ marginTop = 0;+ spaceBelowApply = 0;+ }+const lineHeight = marginTop + paddingTop + contentHeight + paddingBottom;+ const { charSpace, defaultTabStop } = getCharSpaceConfig(sectionBreakConfig, paragraphConfig);+ const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);+ const paragraphAnchorLeft = __getParagraphAnchorLeft(sectionBreakConfig, paragraphConfig, indentStart);let section = column.parent;if (!section) {@@ -546,11 +603,18 @@ function _lineOperator(}}+ let deferredInlineGroupAnchorDrawings: IDocumentSkeletonDrawing[] = [];+if (paragraphNonInlineSkeDrawings != null && paragraphNonInlineSkeDrawings.size > 0) {- const targetDrawings = [...paragraphNonInlineSkeDrawings.values()]+ let targetDrawings = [...paragraphNonInlineSkeDrawings.values()].filter((drawing) => drawing.drawingOrigin.docTransform.positionV.relativeFrom !== ObjectRelativeFromV.LINE);- __updateAndPositionDrawings(ctx, lineTop, lineHeight, column, targetDrawings, paragraphConfig.paragraphIndex, isParagraphFirstShapedText, pDrawingAnchor?.get(paragraphIndex)?.top);+ if (hasInlineCustomBlock) {+ deferredInlineGroupAnchorDrawings = targetDrawings.filter((drawing) => glyphGroupCustomBlockIds.has(drawing.drawingId));+ targetDrawings = targetDrawings.filter((drawing) => !glyphGroupCustomBlockIds.has(drawing.drawingId));+ }++ __updateAndPositionDrawings(ctx, lineTop, lineHeight, column, targetDrawings, paragraphConfig.paragraphIndex, isParagraphFirstShapedText, pDrawingAnchor?.get(paragraphIndex)?.top, paragraphAnchorLeft);}if (skeTablesInParagraph != null && skeTablesInParagraph.length > 0) {@@ -565,7 +629,9 @@ function _lineOperator(footerPage); // WRAP_TOP_AND_BOTTOM drawing and WRAP NONE table will change the starting top of the line- if ((lineHeight + newLineTop > section.height && column.lines.length > 0 && lastPage.sections.length > 0) || needOpenNewPageByTableLayout) {+ const lineOverflowsSection = lineHeight + newLineTop - section.height > LINE_LAYOUT_OVERFLOW_TOLERANCE;++ if ((lineOverflowsSection && column.lines.length > 0 && lastPage.sections.length > 0) || needOpenNewPageByTableLayout) {// Line height exceeds column height, and there is more than one line in the column, and there is more than one section;// console.log('_lineOperator', { glyphGroup, pages, lineHeight, newLineTop, sectionHeight: section.height, lastPage });setColumnFullState(column, true);@@ -599,8 +665,6 @@ 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;- const { charSpace, defaultTabStop } = getCharSpaceConfig(sectionBreakConfig, paragraphConfig);- const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);let { paddingLeft, paddingRight } = __getIndentPadding(indentFirstLine,hanging,@@ -643,6 +707,7 @@ function _lineOperator(column.lines.push(newLine);newLine.parent = column;createAndUpdateBlockAnchor(paragraphIndex, newLine, lineTop, pDrawingAnchor);+_divideOperator(ctx,glyphGroup,@@ -654,6 +719,10 @@ function _lineOperator(breakPointType,defaultGlyphLineHeight);++ if (deferredInlineGroupAnchorDrawings.length > 0) {+ __updateAndPositionDrawings(ctx, lineTop, lineHeight, column, deferredInlineGroupAnchorDrawings, paragraphConfig.paragraphIndex, isParagraphFirstShapedText, pDrawingAnchor?.get(paragraphIndex)?.top, paragraphAnchorLeft, true);+ }}function __updateAndPositionDrawings(@@ -664,7 +733,9 @@ function __updateAndPositionDrawings(targetDrawings: IDocumentSkeletonDrawing[],paragraphIndex: number,isParagraphFirstShapedText: boolean,- drawingAnchorTop?: number+ drawingAnchorTop?: number,+ drawingAnchorLeft = 0,+ skipRelayoutCheck = false) {if (targetDrawings.length === 0) {return;@@ -676,7 +747,8 @@ function __updateAndPositionDrawings(column,isParagraphFirstShapedText,drawingAnchorTop,- targetDrawings+ targetDrawings,+ drawingAnchorLeft);if (drawings == null || drawings.size === 0) {@@ -700,12 +772,15 @@ function __updateAndPositionDrawings(width,height,angle,+ behindDoc: drawingOrigin.behindDoc,type: FloatObjectType.IMAGE,positionV,};});- _reLayoutCheck(ctx, floatObjects, column, paragraphIndex);+ if (!skipRelayoutCheck) {+ _reLayoutCheck(ctx, floatObjects, column, paragraphIndex);+ }__updateDrawingPosition(column,@@ -910,6 +985,77 @@ function _getCustomBlockIdsInLine(line: IDocumentSkeletonLine) {return customBlockIds;}+function __isZeroWidthNonFlowFloatingAnchorLine(+ glyphGroup: IDocumentSkeletonGlyph[],+ paragraphNonInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>+) {+ return __getZeroWidthNonFlowFloatingAnchorDrawings(glyphGroup, paragraphNonInlineSkeDrawings).length > 0;+}++function __getZeroWidthNonFlowFloatingAnchorDrawings(+ glyphGroup: IDocumentSkeletonGlyph[],+ paragraphNonInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>+) {+ const drawings: IDocumentSkeletonDrawing[] = [];++ for (const glyph of glyphGroup) {+ if (__isStructuralTerminatorGlyph(glyph)) {+ continue;+ }++ if (__isIgnorableZeroSizeGlyph(glyph)) {+ continue;+ }++ if (glyph.streamType !== DataStreamTreeTokenType.CUSTOM_BLOCK || glyph.width !== 0 || glyph.drawingId == null) {+ return [];+ }++ const drawing = paragraphNonInlineSkeDrawings?.get(glyph.drawingId);+ const drawingOrigin = drawing?.drawingOrigin;+ if (drawing == null || drawingOrigin == null) {+ return [];+ }++ if (drawingOrigin.layoutType !== PositionedObjectLayoutType.WRAP_NONE && drawingOrigin.behindDoc !== BooleanNumber.TRUE) {+ return [];+ }++ drawings.push(drawing);+ }++ return drawings;+}++function __isIgnorableZeroSizeGlyph(glyph: IDocumentSkeletonGlyph) {+ return glyph.content === '' &&+ glyph.drawingId == null &&+ glyph.width === 0 &&+ glyph.bBox.ba + glyph.bBox.bd === 0;+}++function __isStructuralTerminatorGlyph(glyph: IDocumentSkeletonGlyph) {+ return (+ glyph.streamType === DataStreamTreeTokenType.PARAGRAPH ||+ glyph.streamType === DataStreamTreeTokenType.SECTION_BREAK ||+ glyph.streamType === DataStreamTreeTokenType.DOCS_END+ );+}++function __hasFlowGlyph(glyphGroup: IDocumentSkeletonGlyph[]) {+ return glyphGroup.some((glyph) => {+ if (__isStructuralTerminatorGlyph(glyph)) {+ return false;+ }++ if (glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK) {+ return glyph.width !== 0;+ }++ return glyph.content !== '' || glyph.width > 0 || glyph.bBox.ba + glyph.bBox.bd > 0;+ });+}+function _reLayoutCheck(ctx: ILayoutContext,floatObjects: IFloatObject[],@@ -917,19 +1063,23 @@ function _reLayoutCheck(paragraphIndex: number) {const page = column.parent?.parent;+ const flowAffectingFloatObjects = floatObjects.filter((floatObject) => floatObject.behindDoc !== BooleanNumber.TRUE);- if (floatObjects.length === 0 || page == null) {+ if (flowAffectingFloatObjects.length === 0 || page == null) {return;}let needBreakLineIterator = false;// Handle situations where an image anchor paragraph is squeezed to the next page.- for (const floatObject of floatObjects) {+ for (const floatObject of flowAffectingFloatObjects) {const floatObjectCache = ctx.floatObjectsCache.get(floatObject.id);if (floatObjectCache == null || floatObjectCache.page.segmentId !== page.segmentId) {continue;}+ if (floatObjectCache.count >= FLOAT_OBJECT_RELAYOUT_LIMIT) {+ continue;+ }// TODO: How to determine if drawing is on the same page???const cachePageStartParagraphIndex = floatObjectCache.page.sections[0]?.columns[0]?.lines[0]?.paragraphIndex;const startIndex = page.sections[0]?.columns[0]?.lines[0]?.paragraphIndex;@@ -969,7 +1119,7 @@ function _reLayoutCheck(return;}- for (const floatObject of floatObjects.values()) {+ for (const floatObject of flowAffectingFloatObjects.values()) {let targetObject = floatObject;if (ctx.floatObjectsCache.has(floatObject.id)) {@@ -1027,7 +1177,7 @@ function checkRelativeDrawingNeedRePosition(ctx: ILayoutContext, floatObject: IFconst { count, floatObject: prevObject } = drawingCache;// Floating elements can be positioned no more than 5 times,// and when the error is within 5 pixels, there is no need to re-layout- if (count < 5 && Math.abs(floatObject.top - prevObject.top) > 5) {+ if (count < FLOAT_OBJECT_RELAYOUT_LIMIT && Math.abs(floatObject.top - prevObject.top) > 5) {return true;}}@@ -1035,6 +1185,10 @@ function checkRelativeDrawingNeedRePosition(ctx: ILayoutContext, floatObject: IFreturn false;}+export const __testing = {+ reLayoutCheck: _reLayoutCheck,+};+function _columnOperator(ctx: ILayoutContext,glyphGroup: IDocumentSkeletonGlyph[],@@ -1145,6 +1299,25 @@ function __getParagraphSpace(};}+function __getParagraphAnchorLeft(+ sectionBreakConfig: ISectionBreakConfig,+ paragraphConfig: IParagraphConfig,+ indentStart: Nullable<INumberUnit>+) {+ const { paragraphStyle = {} } = paragraphConfig;+ const { snapToGrid = BooleanNumber.TRUE } = paragraphStyle;+ const { gridType = GridType.LINES } = sectionBreakConfig;+ const { charSpace, defaultTabStop } = getCharSpaceConfig(sectionBreakConfig, paragraphConfig);+ const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);+ const paragraphAnchorLeft = getNumberUnitValue(indentStart, charSpaceApply);++ if (paragraphAnchorLeft > 0) {+ return paragraphAnchorLeft;+ }++ return getNumberUnitValue(paragraphConfig.docxFallbackAnchorLeft, charSpaceApply);+}+export function getLineHeightMetrics(glyphLineHeight: number,paragraphLineGapDefault: number,@@ -1153,7 +1326,8 @@ export function getLineHeightMetrics(lineSpacing: number,spacingRule: SpacingRule,snapToGrid: BooleanNumber,- useWordStyleLineHeight = true+ useWordStyleLineHeight = true,+ scaleAutoLineSpacingByGlyphHeight = true) {if (!useWordStyleLineHeight) {let paddingTop = paragraphLineGapDefault;@@ -1204,7 +1378,11 @@ export function getLineHeightMetrics(&& gridType !== GridType.DEFAULT;if (spacingRule === SpacingRule.AUTO) {- const lineSpacingApply = usesDocumentGrid ? lineSpacing * linePitch : lineSpacing * glyphLineHeight;+ const lineSpacingApply = usesDocumentGrid+ ? lineSpacing * linePitch+ : scaleAutoLineSpacingByGlyphHeight+ ? lineSpacing * glyphLineHeight+ : glyphLineHeight;const padding = (lineSpacingApply - glyphLineHeight) / 2;return {@@ -1227,15 +1405,19 @@ export function getLineHeightMetrics(};}+ const exactLineSpacingApply = snapToGrid === BooleanNumber.TRUE && gridType !== GridType.DEFAULT+ ? Math.max(lineSpacing, linePitch)+ : lineSpacing;+// EXACT follows the requested line box height even when it is smaller than the glyph box.// Negative padding lets subsequent lines advance by the exact value, which is closer to Word.- const exactPadding = (lineSpacing - glyphLineHeight) / 2;+ const exactPadding = (exactLineSpacingApply - glyphLineHeight) / 2;return {paddingTop: exactPadding,paddingBottom: exactPadding,contentHeight: glyphLineHeight,- lineSpacingApply: lineSpacing,+ lineSpacingApply: exactLineSpacingApply,};}@@ -1304,7 +1486,8 @@ function __getDrawingPosition(column: IDocumentSkeletonColumn,isParagraphFirstShapedText: boolean,blockAnchorTop?: number,- needPositionDrawings: IDocumentSkeletonDrawing[] = []+ needPositionDrawings: IDocumentSkeletonDrawing[] = [],+ blockAnchorLeft = 0) {const page = column.parent?.parent;if (@@ -1333,7 +1516,15 @@ function __getDrawingPosition(const { positionH, positionV, size, angle } = docTransform;const { width = 0, height = 0 } = size;- drawing.aLeft = getPositionHorizon(positionH, column, page, width, isPageBreak) ?? 0;+ let aLeft = getPositionHorizon(positionH, column, page, width, isPageBreak) ?? 0;+ if (+ positionH.relativeFrom === ObjectRelativeFromH.COLUMN &&+ blockAnchorLeft > 0+ ) {+ const renderedColumnOrigin = isPageBreak ? 0 : (column.left || page.marginLeft);+ aLeft += blockAnchorLeft - renderedColumnOrigin;+ }+ drawing.aLeft = aLeft;drawing.aTop = getPositionVertical(positionV,page,@@ -1454,5 +1645,7 @@ function __getGlyphGroupByLine({ divides }: IDocumentSkeletonLine) {}function __isNullLine(line: IDocumentSkeletonLine) {- return !line.divides[0].glyphGroup[0];+ const glyphGroup = __getGlyphGroupByLine(line);++ return glyphGroup.every((glyph) => !glyph.content && !glyph.drawingId);}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 ce8dfc3f1b..5e4ccf5bd4 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@@ -15,7 +15,7 @@*/import type { IBullet, IDocDrawingBase, IDocumentBody, IDrawings, IParagraph, IParagraphStyle, Nullable } from '@univerjs/core';-import type { IDocumentSkeletonBullet, IDocumentSkeletonDrawing, IDocumentSkeletonPage, IDocumentSkeletonTable, IParagraphList } from '../../../../../basics/i-document-skeleton-cached';+import type { IDocumentSkeletonBullet, IDocumentSkeletonDrawing, IDocumentSkeletonGlyph, IDocumentSkeletonPage, IDocumentSkeletonTable, IParagraphList } from '../../../../../basics/i-document-skeleton-cached';import type { IParagraphConfig, ISectionBreakConfig } from '../../../../../basics/interfaces';import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../../../view-model/document-view-model';@@ -44,6 +44,51 @@ const BLOCK_LAYOUT_OUTER_SPACING_MAP = new Map([[DocumentBlockRangeType.QUOTE, 24],]);+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;+}++function _isMarkedDocxColumnBreak(viewModel: DocumentViewModel, absoluteIndex: number): boolean {+ const customRange = viewModel.getCustomRange(absoluteIndex);+ const properties = customRange?.properties as { docxBreakType?: unknown } | undefined;++ return properties?.docxBreakType === 'column';+}++function _glyphCount(glyphs: IDocumentSkeletonGlyph[]): number {+ return glyphs.reduce((count, glyph) => count + glyph.count, 0);+}++function _hasOnlyCustomBlockGlyphs(glyphs: IDocumentSkeletonGlyph[]): boolean {+ return glyphs.length > 0 && glyphs.every((glyph) => glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK);+}++function _mergeAdjacentCustomBlockShapedTexts(shapedTextList: IShapedText[]): IShapedText[] {+ const mergedShapedTextList: IShapedText[] = [];++ for (const shapedText of shapedTextList) {+ const lastShapedText = mergedShapedTextList[mergedShapedTextList.length - 1];++ if (+ lastShapedText &&+ _hasOnlyCustomBlockGlyphs(lastShapedText.glyphs) &&+ _hasOnlyCustomBlockGlyphs(shapedText.glyphs)+ ) {+ lastShapedText.text += shapedText.text;+ lastShapedText.glyphs.push(...shapedText.glyphs);+ lastShapedText.breakPointType = shapedText.breakPointType;+ continue;+ }++ mergedShapedTextList.push({+ ...shapedText,+ glyphs: [...shapedText.glyphs],+ });+ }++ return mergedShapedTextList;+}+function _getListLevelAncestors(bullet?: IBullet,listLevel?: Map<string, IParagraphList[][]>@@ -201,6 +246,16 @@ function _applyBlockRangeLayoutParagraphStyle(function _shouldApplyDocumentDefaultParagraphStyle(viewModel: DocumentViewModel): boolean {const snapshot = viewModel.getSnapshot?.();++ if (snapshot == null) {+ return true;+ }++ return snapshot.documentStyle.documentFlavor === DocumentFlavor.MODERN;+}++function _shouldUseWordStyleLineHeight(viewModel: DocumentViewModel): boolean {+ const snapshot = viewModel.getSnapshot?.();const documentFlavor = snapshot?.documentStyle.documentFlavor;if (snapshot == null) {@@ -210,6 +265,65 @@ function _shouldApplyDocumentDefaultParagraphStyle(viewModel: DocumentViewModel)return documentFlavor != null && documentFlavor !== DocumentFlavor.UNSPECIFIED;}+function _isTraditionalDoc(viewModel: DocumentViewModel): boolean {+ return viewModel.getSnapshot?.()?.documentStyle.documentFlavor === DocumentFlavor.TRADITIONAL;+}++function _isOnlyFloatingCustomBlockParagraph(+ viewModel: DocumentViewModel,+ paragraphNode: DataStreamTreeNode,+ drawings: IDrawings+): boolean {+ if (!paragraphNode.blocks?.length) {+ return false;+ }++ const content = paragraphNode.content ?? '';+ const hasOnlyCustomBlockContent = content.split('').every((char) =>+ char === DataStreamTreeTokenType.CUSTOM_BLOCK ||+ char === DataStreamTreeTokenType.PARAGRAPH ||+ char === DataStreamTreeTokenType.SECTION_BREAK+ );++ if (!hasOnlyCustomBlockContent) {+ return false;+ }++ return paragraphNode.blocks.every((charIndex) => {+ const customBlock = viewModel.getCustomBlock(charIndex);+ const drawing = customBlock == null ? null : drawings[customBlock.blockId];++ return drawing != null && drawing.layoutType !== PositionedObjectLayoutType.INLINE;+ });+}++function _getFollowingIndentedParagraphAnchorLeft(+ viewModel: DocumentViewModel,+ paragraph: IParagraph,+ paragraphNode: DataStreamTreeNode,+ drawings: IDrawings+): IParagraphStyle['indentStart'] | undefined {+ if (!_isTraditionalDoc(viewModel)) {+ return;+ }++ if ((paragraph.paragraphStyle?.indentStart?.v ?? 0) > 0) {+ return;+ }++ if (!_isOnlyFloatingCustomBlockParagraph(viewModel, paragraphNode, drawings)) {+ return;+ }++ const paragraphs = [...(viewModel.getBody?.()?.paragraphs ?? [])]+ .filter((item) => item.startIndex > paragraph.startIndex)+ .sort((left, right) => left.startIndex - right.startIndex);++ return (paragraphs[0]?.paragraphStyle?.indentStart?.v ?? 0) > 0+ ? paragraphs[0].paragraphStyle?.indentStart+ : undefined;+}+function _changeDrawingToSkeletonFormat(drawingIds: string[],drawings: IDrawings@@ -268,12 +382,15 @@ export function lineBreaking(const paragraph = viewModel.getParagraph(endIndex) || { startIndex: 0, paragraphId: 'para_render_fallback' };const { paragraphStyle = {}, bullet } = paragraph;- const useWordStyleLineHeight = _shouldApplyDocumentDefaultParagraphStyle(viewModel);+ const shouldApplyDocumentDefaults = _shouldApplyDocumentDefaultParagraphStyle(viewModel);+ const useWordStyleLineHeight = _shouldUseWordStyleLineHeight(viewModel);const { skeHeaders, skeFooters, skeListLevel, drawingAnchor } = skeletonResourceReference;const paragraphNonInlineSkeDrawings: Map<string, IDocumentSkeletonDrawing> = new Map();const paragraphInlineSkeDrawings: Map<string, IDocumentSkeletonDrawing> = new Map();+ const paragraphNonInlineSkeDrawingsByBlockId: Map<string, IDocumentSkeletonDrawing> = new Map();+ const paragraphInlineSkeDrawingsByBlockId: Map<string, IDocumentSkeletonDrawing> = new Map();let segmentDrawingAnchorCache = drawingAnchor?.get(segmentId);@@ -288,8 +405,9 @@ export function lineBreaking(viewModel.getBody?.() ?? null,paragraph,paragraphStyle,- useWordStyleLineHeight+ shouldApplyDocumentDefaults),+ docxFallbackAnchorLeft: _getFollowingIndentedParagraphAnchorLeft(viewModel, paragraph, paragraphNode, drawings),useWordStyleLineHeight,paragraphNonInlineSkeDrawings,paragraphInlineSkeDrawings,@@ -340,10 +458,14 @@ export function lineBreaking(const { blockId } = customBlock;const drawingOrigin = drawings[blockId];+ if (drawingOrigin == null) {+ continue;+ }+if (drawingOrigin.layoutType === PositionedObjectLayoutType.INLINE) {- paragraphInlineSkeDrawings.set(blockId, _getDrawingSkeletonFormat(drawingOrigin));+ paragraphInlineSkeDrawingsByBlockId.set(blockId, _getDrawingSkeletonFormat(drawingOrigin));} else {- paragraphNonInlineSkeDrawings.set(blockId, _getDrawingSkeletonFormat(drawingOrigin));+ paragraphNonInlineSkeDrawingsByBlockId.set(blockId, _getDrawingSkeletonFormat(drawingOrigin));}}@@ -351,26 +473,38 @@ export function lineBreaking(let allPages = [curPage];let isParagraphFirstShapedText = true; // First shaped text- for (const [_index, { text, glyphs, breakPointType }] of shapedTextList.entries()) {+ let shapedTextOffset = 0;+ for (const [_index, { text, glyphs, breakPointType }] of _mergeAdjacentCustomBlockShapedTexts(shapedTextList).entries()) {+ const textStartIndex = paragraphNode.startIndex + shapedTextOffset;+ const textGlyphCount = _glyphCount(glyphs);+ const textEndIndex = textStartIndex + textGlyphCount;const pushPending = () => {if (glyphs.length === 0) {return;}+ syncActiveParagraphDrawings(+ glyphs,+ paragraphNonInlineSkeDrawings,+ paragraphInlineSkeDrawings,+ paragraphNonInlineSkeDrawingsByBlockId,+ paragraphInlineSkeDrawingsByBlockId+ );+allPages = layoutParagraph(ctx,glyphs,allPages,sectionBreakConfig,paragraphConfig,- isParagraphFirstShapedText,+ isParagraphFirstShapedText || hasOnlyFloatingCustomBlockGlyphs(glyphs, paragraphNonInlineSkeDrawingsByBlockId),breakPointType);isParagraphFirstShapedText = false;};- if (text.endsWith(DataStreamTreeTokenType.PAGE_BREAK)) {+ if (_endsWithToken(text, glyphs, DataStreamTreeTokenType.PAGE_BREAK)) {pushPending();allPages.push(createSkeletonPage(@@ -382,9 +516,13 @@ export function lineBreaking());paragraphNonInlineSkeDrawings.clear();- paragraphInlineSkeDrawings.clear();+ isParagraphFirstShapedText = true;+ shapedTextOffset += textGlyphCount;continue;- } else if (text.endsWith(DataStreamTreeTokenType.COLUMN_BREAK)) {+ } else if (_endsWithToken(text, glyphs, DataStreamTreeTokenType.COLUMN_BREAK) && (+ viewModel.getDataModel().documentStyle.documentFlavor !== DocumentFlavor.TRADITIONAL ||+ _isMarkedDocxColumnBreak(viewModel, textEndIndex - 1)+ )) {pushPending();// Column break mark, still within the same sectionconst lastPage = allPages[allPages.length - 1];@@ -403,11 +541,49 @@ export function lineBreaking());}+ shapedTextOffset += textGlyphCount;continue;}pushPending();+ shapedTextOffset += textGlyphCount;}return allPages;}++function syncActiveParagraphDrawings(+ glyphs: IDocumentSkeletonGlyph[],+ paragraphNonInlineSkeDrawings: Map<string, IDocumentSkeletonDrawing>,+ paragraphInlineSkeDrawings: Map<string, IDocumentSkeletonDrawing>,+ paragraphNonInlineSkeDrawingsByBlockId: Map<string, IDocumentSkeletonDrawing>,+ paragraphInlineSkeDrawingsByBlockId: Map<string, IDocumentSkeletonDrawing>+) {+ for (const glyph of glyphs) {+ if (glyph.streamType !== DataStreamTreeTokenType.CUSTOM_BLOCK || glyph.drawingId == null) {+ continue;+ }++ const inlineDrawing = paragraphInlineSkeDrawingsByBlockId.get(glyph.drawingId);+ if (inlineDrawing != null) {+ paragraphInlineSkeDrawings.set(glyph.drawingId, inlineDrawing);+ continue;+ }++ const nonInlineDrawing = paragraphNonInlineSkeDrawingsByBlockId.get(glyph.drawingId);+ if (nonInlineDrawing != null) {+ paragraphNonInlineSkeDrawings.set(glyph.drawingId, nonInlineDrawing);+ }+ }+}++function hasOnlyFloatingCustomBlockGlyphs(+ glyphs: IDocumentSkeletonGlyph[],+ paragraphNonInlineSkeDrawingsByBlockId: Map<string, IDocumentSkeletonDrawing>+): boolean {+ return glyphs.length > 0 && glyphs.every((glyph) =>+ glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK &&+ glyph.drawingId != null &&+ paragraphNonInlineSkeDrawingsByBlockId.has(glyph.drawingId)+ );+}diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.tsindex ead379a396..be95ba5e44 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts@@ -218,7 +218,7 @@ export function shaping(if (customBlock != null) {const { blockId } = customBlock;const drawingOrigin = drawings[blockId];- if (drawingOrigin.layoutType === PositionedObjectLayoutType.INLINE) {+ if (drawingOrigin?.layoutType === PositionedObjectLayoutType.INLINE) {const { angle } = drawingOrigin.docTransform;const { width = 0, height = 0 } = drawingOrigin.docTransform.size;const top = 0;@@ -226,7 +226,7 @@ export function shaping(const boundingBox = getBoundingBox(angle, left, width, top, height);newGlyph = createSkeletonCustomBlockGlyph(config, boundingBox.width, boundingBox.height, drawingOrigin.drawingId);- } else {+ } else if (drawingOrigin != null) {newGlyph = createSkeletonCustomBlockGlyph(config, 0, 0, drawingOrigin.drawingId);}}diff --git a/packages/engine-render/src/components/docs/layout/block/table.ts b/packages/engine-render/src/components/docs/layout/block/table.tsindex ca61636750..7e6c480648 100644--- a/packages/engine-render/src/components/docs/layout/block/table.ts+++ b/packages/engine-render/src/components/docs/layout/block/table.ts@@ -151,6 +151,10 @@ export function rollbackListCache(listLevel: Map<string, IParagraphList[][]>, tafor (const paragraphLists of listLevel.values()) {for (const paragraphList of paragraphLists) {+ if (paragraphList == null) {+ continue;+ }+const paragraphListIndex = paragraphList.findIndex((p) => p.paragraph.startIndex > startIndex && p.paragraph.startIndex < endIndex);if (paragraphListIndex > -1) {diff --git a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-skeleton.tsindex 5d9dfddd91..4c010d4906 100644--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts@@ -1143,7 +1143,7 @@ export class DocumentSkeleton extends Skeleton {ctx.sectionBreakConfigCache.set(sectionNode.endIndex, sectionBreakConfig);- if (sectionType === SectionType.CONTINUOUS) {+ if (sectionType === SectionType.CONTINUOUS && curSkeletonPage != null) {updateBlockIndex(allSkeletonPages);this._addNewSectionByContinuous(curSkeletonPage, columnProperties!, columnSeparatorType!);isContinuous = true;diff --git a/packages/engine-render/src/components/docs/layout/model/__tests__/line.spec.ts b/packages/engine-render/src/components/docs/layout/model/__tests__/line.spec.tsindex aa33e0a60c..a06fb9d7d0 100644--- a/packages/engine-render/src/components/docs/layout/model/__tests__/line.spec.ts+++ b/packages/engine-render/src/components/docs/layout/model/__tests__/line.spec.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { PositionedObjectLayoutType, TableTextWrapType, WrapTextType } from '@univerjs/core';+import { BooleanNumber, PositionedObjectLayoutType, TableTextWrapType, WrapTextType } from '@univerjs/core';import { describe, expect, it } from 'vitest';import { LineType } from '../../../../../basics/i-document-skeleton-cached';import {@@ -191,6 +191,141 @@ describe('line model', () => {expect(line.divides.every((divide) => divide.parent === line)).toBe(true);});+ it('does not split line divides for behind-doc drawings', () => {+ const page = {+ skeDrawings: new Map([+ ['behind', {+ aTop: 0,+ aLeft: 0,+ width: 80,+ height: 20,+ angle: 0,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_TIGHT,+ behindDoc: BooleanNumber.TRUE,+ distL: 0,+ distR: 0,+ distT: 0,+ distB: 0,+ wrapText: WrapTextType.BOTH_SIDES,+ },+ }],+ ]),+ skeTables: new Map(),+ } as any;++ const line = createSkeletonLine(+ 1,+ LineType.PARAGRAPH,+ {+ lineHeight: 20,+ lineTop: 0,+ contentHeight: 14,+ },+ 100,+ 0,+ true,+ {} as any,+ page,+ null,+ null+ );++ expect(line.divides).toHaveLength(1);+ expect(line.divides[0].left).toBe(0);+ expect(line.divides[0].width).toBe(100);+ });++ it('does not split line divides for wrap-none drawings in front of text', () => {+ const page = {+ skeDrawings: new Map([+ ['front', {+ aTop: 0,+ aLeft: 0,+ width: 80,+ height: 20,+ angle: 0,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: BooleanNumber.FALSE,+ distL: 0,+ distR: 0,+ distT: 0,+ distB: 0,+ wrapText: WrapTextType.BOTH_SIDES,+ },+ }],+ ]),+ skeTables: new Map(),+ } as any;++ const line = createSkeletonLine(+ 1,+ LineType.PARAGRAPH,+ {+ lineHeight: 20,+ lineTop: 0,+ contentHeight: 14,+ },+ 100,+ 0,+ true,+ {} as any,+ page,+ null,+ null+ );++ expect(line.divides).toHaveLength(1);+ expect(line.divides[0].left).toBe(0);+ expect(line.divides[0].width).toBe(100);+ });++ it('falls back to a full-width divide when wrap drawings cover the whole line', () => {+ const page = {+ skeDrawings: new Map([+ ['cover', {+ aTop: 0,+ aLeft: 0,+ width: 100,+ height: 20,+ angle: 0,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ behindDoc: BooleanNumber.FALSE,+ distL: 0,+ distR: 0,+ distT: 0,+ distB: 0,+ wrapText: WrapTextType.BOTH_SIDES,+ },+ }],+ ]),+ skeTables: new Map(),+ } as any;++ const line = createSkeletonLine(+ 1,+ LineType.PARAGRAPH,+ {+ lineHeight: 20,+ lineTop: 0,+ contentHeight: 14,+ },+ 100,+ 0,+ true,+ {} as any,+ page,+ null,+ null+ );++ expect(line.divides).toHaveLength(1);+ expect(line.divides[0].left).toBe(0);+ expect(line.divides[0].width).toBe(100);+ });+it('calculates max line top with top-bottom drawings and no-wrap tables', () => {const page = {marginTop: 10,@@ -234,6 +369,78 @@ describe('line model', () => {expect(noOverlapTop).toBe(0);});+ it('pushes line top below wrap drawings that block the whole column', () => {+ const page = {+ skeDrawings: new Map([+ ['cover', {+ aTop: 10,+ aLeft: -20,+ width: 140,+ height: 40,+ angle: 0,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ behindDoc: BooleanNumber.FALSE,+ wrapText: WrapTextType.BOTH_SIDES,+ },+ }],+ ]),+ skeTables: new Map(),+ } as any;++ const top = calculateLineTopByDrawings(15, 0, page, null, null, 0, 100);++ expect(top).toBe(50);+ });++ it('pushes line top below full-column wrap drawings below the current line', () => {+ const page = {+ skeDrawings: new Map([+ ['cover', {+ aTop: 10,+ aLeft: -20,+ width: 140,+ height: 40,+ angle: 0,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ behindDoc: BooleanNumber.FALSE,+ wrapText: WrapTextType.BOTH_SIDES,+ },+ }],+ ]),+ skeTables: new Map(),+ } as any;++ const top = calculateLineTopByDrawings(5, 0, page, null, null, 0, 100);++ expect(top).toBe(50);+ });++ it('keeps line top for wrap drawings that leave side text space', () => {+ const page = {+ skeDrawings: new Map([+ ['side', {+ aTop: 10,+ aLeft: 30,+ width: 20,+ height: 40,+ angle: 0,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ behindDoc: BooleanNumber.FALSE,+ wrapText: WrapTextType.BOTH_SIDES,+ },+ }],+ ]),+ skeTables: new Map(),+ } as any;++ const top = calculateLineTopByDrawings(15, 0, page, null, null, 0, 100);++ expect(top).toBe(0);+ });+it('updates divide/line state and detects float object collision', () => {const divide = {glyphGroup: [],diff --git a/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts b/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.tsindex 45694ee834..389dc8de8f 100644--- a/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts+++ b/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts@@ -122,6 +122,8 @@ describe('page model', () => {expect(firstPage.footerId).toBe('f-first');expect(firstPage.pageWidth).toBe(200);expect(firstPage.pageHeight).toBe(300);+ expect(firstPage.marginTop).toBe(12);+ expect(firstPage.marginBottom).toBe(14);expect(firstPage.sections.length).toBeGreaterThan(0);expect(skeletonResourceReference.skeHeaders.get('h-first')?.has(200)).toBe(true);expect(skeletonResourceReference.skeFooters.get('f-first')?.has(200)).toBe(true);@@ -131,6 +133,71 @@ describe('page model', () => {expect(evenPage.footerId).toBe('f-even');});+ it('does not create negative-width columns for oversized single-column section properties', () => {+ const skeletonResourceReference = createSkeletonResourceReference();+ const ctx = {+ layoutStartPointer: {},+ skeletonResourceReference,+ isDirty: false,+ } as any;++ const page = createSkeletonPage(+ ctx,+ {+ pageNumberStart: 1,+ pageSize: { width: 816, height: 1056 },+ marginLeft: 120,+ marginRight: 120,+ marginTop: 96,+ marginBottom: 96,+ headerTreeMap: new Map(),+ footerTreeMap: new Map(),+ columnProperties: [{ width: 624, paddingEnd: 720 }],+ columnSeparatorType: ColumnSeparatorType.NONE,+ } as any,+ skeletonResourceReference,+ 1+ );++ expect(page.sections[0].columns.map((column) => column.width)).toEqual([576]);+ });++ it('keeps every oversized DOCX multi-column section usable after fitting gaps', () => {+ const skeletonResourceReference = createSkeletonResourceReference();+ const ctx = {+ layoutStartPointer: {},+ skeletonResourceReference,+ isDirty: false,+ } as any;++ const page = createSkeletonPage(+ ctx,+ {+ pageNumberStart: 1,+ pageSize: { width: 793.7333333333332, height: 1122.5333333333333 },+ marginLeft: 48,+ marginRight: 48,+ marginTop: 48,+ marginBottom: 48,+ headerTreeMap: new Map(),+ footerTreeMap: new Map(),+ columnProperties: [+ { width: 201.06666666666663, paddingEnd: 709 },+ { width: 201.06666666666663, paddingEnd: 709 },+ { width: 201.06666666666663, paddingEnd: 0 },+ ],+ columnSeparatorType: ColumnSeparatorType.NONE,+ } as any,+ skeletonResourceReference,+ 1+ );++ const columns = page.sections[0].columns;+ expect(columns).toHaveLength(3);+ expect(columns.every((column) => column.width > 0)).toBe(true);+ expect(columns.at(-1)!.left + columns.at(-1)!.width).toBeLessThanOrEqual(697.7333333333332);+ });+it('creates null cell page and skeleton cell pages', () => {dealWithSectionMock.mockImplementation((_ctx: any, _vm: any, _node: any, areaPage: any) => ({pages: [createDealPage(areaPage)],@@ -211,6 +278,39 @@ describe('page model', () => {expect(updateInlineDrawingCoordsAndBorderMock).toHaveBeenCalled();});+ it('shrinks default cell margins for extremely narrow table columns', () => {+ const ctx = {+ layoutStartPointer: {},+ skeletonResourceReference: createSkeletonResourceReference(),+ isDirty: false,+ } as any;+ const sectionBreakConfig = {+ lists: [],+ localeService: {} as any,+ drawings: {},+ pageSize: { width: 300, height: 200 },+ headerTreeMap: new Map(),+ footerTreeMap: new Map(),+ } as any;+ const tableConfig = {+ tableId: 'narrow-table',+ tableRows: [{ tableCells: [{}] }],+ tableColumns: [{ size: { width: { v: 0.8 } } }],+ } as any;++ const { page, sectionBreakConfig: cellSectionBreakConfig } = createNullCellPage(+ ctx,+ sectionBreakConfig,+ tableConfig,+ 0,+ 0+ );++ expect(page.pageWidth).toBe(0.8);+ expect(cellSectionBreakConfig.marginLeft! + cellSectionBreakConfig.marginRight!).toBeLessThan(page.pageWidth);+ expect(page.sections[0].columns[0].width).toBeGreaterThan(0);+ });+it('adds trailing block range spacing to table cell height when the block range is the last cell element', () => {dealWithSectionMock.mockImplementation((_ctx: any, _vm: any, _node: any, areaPage: any) => ({pages: [{diff --git a/packages/engine-render/src/components/docs/layout/model/line.ts b/packages/engine-render/src/components/docs/layout/model/line.tsindex c68134cd51..1e37aadc93 100644--- a/packages/engine-render/src/components/docs/layout/model/line.ts+++ b/packages/engine-render/src/components/docs/layout/model/line.ts@@ -27,7 +27,7 @@ import type {LineType,} from '../../../../basics/i-document-skeleton-cached';import type { IFloatObject } from '../tools';-import { PositionedObjectLayoutType, TableTextWrapType, WrapTextType } from '@univerjs/core';+import { BooleanNumber, PositionedObjectLayoutType, TableTextWrapType, WrapTextType } from '@univerjs/core';import { Path2 } from '../../../../basics/path2';import { Transform } from '../../../../basics/transform';import { Vector2 } from '../../../../basics/vector2';@@ -109,7 +109,11 @@ export function createSkeletonLine(lineSke.tableId = tableId;}- const affectSkeDrawings = new Map(Array.from(pageSkeDrawings).filter(([_, drawing]) => drawing.drawingOrigin.layoutType !== PositionedObjectLayoutType.INLINE));+ const affectSkeDrawings = new Map(Array.from(pageSkeDrawings).filter(([_, drawing]) =>+ drawing.drawingOrigin.layoutType !== PositionedObjectLayoutType.INLINE &&+ drawing.drawingOrigin.layoutType !== PositionedObjectLayoutType.WRAP_NONE &&+ drawing.drawingOrigin.behindDoc !== BooleanNumber.TRUE+ ));const wrapTypeTables = new Map(Array.from(pageSkeTables).filter(([_, table]) => table.tableSource.textWrap === TableTextWrapType.WRAP));lineSke.divides = _calculateDividesByDrawings(@@ -139,7 +143,9 @@ export function calculateLineTopByDrawings(lineTop: number = 0,page: IDocumentSkeletonPage,headerPage: Nullable<IDocumentSkeletonPage>,- footerPage: Nullable<IDocumentSkeletonPage>+ footerPage: Nullable<IDocumentSkeletonPage>,+ columnLeft: number = 0,+ columnWidth: number = 0) {let maxTop = lineTop;const pageSkeDrawings = page.skeDrawings;@@ -172,6 +178,10 @@ export function calculateLineTopByDrawings(if (top) {maxTop = Math.max(maxTop, top);}+ const blockingWrapTop = _getLineTopWithFullColumnWrap(drawing, lineHeight, lineTop, columnLeft, columnWidth);+ if (blockingWrapTop) {+ maxTop = Math.max(maxTop, blockingWrapTop);+ }});skeNonWrapTables?.forEach((table) => {@@ -184,6 +194,74 @@ export function calculateLineTopByDrawings(return maxTop;}+function _getLineTopWithFullColumnWrap(+ drawing: IDocumentSkeletonDrawing,+ lineHeight: number,+ lineTop: number,+ columnLeft: number,+ columnWidth: number+) {+ if (columnWidth <= 0) {+ return;+ }++ const { aTop, height, aLeft, width, angle = 0, drawingOrigin } = drawing;+ const { layoutType, behindDoc, distL = 0, distT = 0, distB = 0, distR = 0, wrapText } = drawingOrigin;++ if (+ behindDoc === BooleanNumber.TRUE ||+ layoutType === PositionedObjectLayoutType.INLINE ||+ layoutType === PositionedObjectLayoutType.WRAP_NONE ||+ layoutType === PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM+ ) {+ return;+ }++ let top = aTop;+ let drawingHeight = height;+ let left = aLeft - columnLeft;+ let drawingWidth = width;++ if (angle !== 0) {+ const boundingBox = getBoundingBox(angle, left, width, top, height);+ top = boundingBox.top ?? top;+ drawingHeight = boundingBox.height ?? drawingHeight;+ left = boundingBox.left ?? left;+ drawingWidth = boundingBox.width ?? drawingWidth;+ }++ const newTop = top - (layoutType === PositionedObjectLayoutType.WRAP_SQUARE ? distT : 0);+ const newHeight = drawingHeight + (layoutType === PositionedObjectLayoutType.WRAP_SQUARE ? distB + distT : 0);+ const bottom = newTop + newHeight;++ if (bottom <= lineTop) {+ return;+ }++ const split = __getSplitWidthNoAngle(+ top,+ drawingHeight,+ left,+ drawingWidth,+ newTop,+ Math.max(1, newHeight),+ columnWidth,+ { distL, distT, distB, distR },+ layoutType,+ wrapText+ );++ if (!split) {+ return;+ }++ if (split.left > 0 || split.left + split.width < columnWidth) {+ return;+ }++ return bottom;+}+function _getLineTopWidthWrapNone(table: IDocumentSkeletonTable, lineHeight: number, lineTop: number) {const { top, height } = table;@@ -197,9 +275,9 @@ function _getLineTopWidthWrapNone(table: IDocumentSkeletonTable, lineHeight: numfunction _getLineTopWidthWrapTopBottom(drawing: IDocumentSkeletonDrawing, lineHeight: number, lineTop: number) {const { aTop, height, aLeft, width, angle = 0, drawingOrigin } = drawing;- const { layoutType, distT = 0, distB = 0 } = drawingOrigin;+ const { layoutType, distT = 0, distB = 0, behindDoc } = drawingOrigin;- if (layoutType !== PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM) {+ if (layoutType !== PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM || behindDoc === BooleanNumber.TRUE) {return;}@@ -340,9 +418,10 @@ function _calculateSplit(columnWidth: number): Nullable<IDrawingsSplit> {const { aTop, height, aLeft, width, angle = 0, drawingOrigin } = drawing;- const { layoutType } = drawingOrigin;+ const { layoutType, behindDoc } = drawingOrigin;if (+ behindDoc === BooleanNumber.TRUE ||layoutType === PositionedObjectLayoutType.WRAP_NONE ||layoutType === PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM) {@@ -579,6 +658,10 @@ function _calculateDivideByDrawings(columnWidth: number, drawingSplit: IDrawings}}+ if (divideSkeleton.length === 0 && columnWidth > 0) {+ return [__getDivideSKe(0, columnWidth)];+ }+return divideSkeleton;}diff --git a/packages/engine-render/src/components/docs/layout/model/page.ts b/packages/engine-render/src/components/docs/layout/model/page.tsindex 2df0110220..8983cb8256 100644--- a/packages/engine-render/src/components/docs/layout/model/page.ts+++ b/packages/engine-render/src/components/docs/layout/model/page.ts@@ -299,7 +299,7 @@ export function createNullCellPage(const { cellMargin, tableRows, tableColumns, tableId } = tableConfig;const cellConfig = tableRows[row].tableCells[col];- const {+ let {start = { v: 10 },end = { v: 10 },top = { v: 5 },@@ -309,6 +309,14 @@ export function createNullCellPage(const pageWidth = tableColumns.slice(col, col + columnSpan).reduce((sum, column) => sum + column.size.width.v, 0);+ if (start.v + end.v >= pageWidth) {+ const marginWidth = start.v + end.v;+ const availableMarginWidth = Math.max(0, pageWidth - 1);+ const startRatio = marginWidth > 0 ? start.v / marginWidth : 0.5;++ start = { ...start, v: availableMarginWidth * startRatio };+ end = { ...end, v: availableMarginWidth - start.v };+ }const pageHeight = maxCellPageHeight;const cellSectionBreakConfig: ISectionBreakConfig = {@@ -439,16 +447,8 @@ function applyTrailingCellBlockRangeSpaceBelow(pages: IDocumentSkeletonPage[], bfunction _getVerticalMargin(marginTB: number,- headerOrFooter: Nullable<IDocumentSkeletonHeaderFooter>,- pageHeight: number+ _headerOrFooter: Nullable<IDocumentSkeletonHeaderFooter>,+ _pageHeight: number) {- if (!headerOrFooter || headerOrFooter.sections[0].columns[0].lines.length === 0) {- return marginTB;- }-- const HeaderFooterPageHeight = headerOrFooter.height + headerOrFooter.marginTop + headerOrFooter.marginBottom;- // Content height should be at least 100px.- const maxMargin = getHeaderFooterMaxHeight(pageHeight);-- return Math.min(maxMargin, Math.max(marginTB, HeaderFooterPageHeight));+ return marginTB;}diff --git a/packages/engine-render/src/components/docs/layout/model/section.ts b/packages/engine-render/src/components/docs/layout/model/section.tsindex f3bc2dc63b..5dc1d2297b 100644--- a/packages/engine-render/src/components/docs/layout/model/section.ts+++ b/packages/engine-render/src/components/docs/layout/model/section.ts@@ -34,21 +34,13 @@ export function createSkeletonSection(if (columnProperties.length === 0) {columns.push(_getSkeletonColumn(left, sectionWidth, 0, ColumnSeparatorType.NONE));} else {- for (let i = 0; i < columnProperties.length; i++) {- const { width, paddingEnd } = columnProperties[i];-+ for (const { width, paddingEnd } of _fitColumnProperties(columnProperties, sectionWidth)) {spaceWidth = paddingEnd;colWidth = width;columns.push(_getSkeletonColumn(left, colWidth, spaceWidth, columnSeparatorType));left += colWidth + spaceWidth;-- if (i === columnProperties.length - 1) {- colWidth = sectionWidth !== Number.POSITIVE_INFINITY ? sectionWidth - colWidth : width;- spaceWidth = 0;- columns.push(_getSkeletonColumn(left, colWidth, spaceWidth, columnSeparatorType));- }}}const newSection = {@@ -67,6 +59,60 @@ export function createSkeletonSection(return newSection;}+function _fitColumnProperties(+ columnProperties: ISectionColumnProperties[],+ sectionWidth: number+): ISectionColumnProperties[] {+ if (sectionWidth === Number.POSITIVE_INFINITY || columnProperties.length === 0) {+ return columnProperties;+ }++ const safeSectionWidth = Math.max(0, sectionWidth);+ const widths = columnProperties.map(({ width }) => Math.max(0, width));+ const spaces = columnProperties.map(({ paddingEnd }, index) =>+ index === columnProperties.length - 1 ? 0 : Math.max(0, paddingEnd)+ );+ const totalWidth = widths.reduce((sum, width) => sum + width, 0);++ if (safeSectionWidth === 0) {+ return columnProperties.map((columnProperty) => ({+ ...columnProperty,+ width: 0,+ paddingEnd: 0,+ }));+ }++ if (totalWidth <= 0) {+ const equalWidth = safeSectionWidth / columnProperties.length;+ return columnProperties.map((columnProperty, index) => ({+ ...columnProperty,+ width: equalWidth,+ paddingEnd: 0,+ }));+ }++ if (totalWidth > safeSectionWidth) {+ const scale = safeSectionWidth / totalWidth;+ return columnProperties.map((columnProperty, index) => ({+ ...columnProperty,+ width: widths[index] * scale,+ paddingEnd: 0,+ }));+ }++ const spaceBudget = safeSectionWidth - totalWidth;+ const totalSpace = spaces.reduce((sum, space) => sum + space, 0);+ const fittedSpaces = totalSpace > spaceBudget && totalSpace > 0+ ? spaces.map((space) => (space / totalSpace) * spaceBudget)+ : spaces;++ return columnProperties.map((columnProperty, index) => ({+ ...columnProperty,+ width: widths[index],+ paddingEnd: fittedSpaces[index],+ }));+}+export function setColumnFullState(column: IDocumentSkeletonColumn, state: boolean) {column.isFull = state;}diff --git a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/text-shaping-engine.spec.ts b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/text-shaping-engine.spec.tsindex 086cfa477e..d3b6d84ae9 100644--- a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/text-shaping-engine.spec.ts+++ b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/text-shaping-engine.spec.ts@@ -114,6 +114,22 @@ describe('text shaping runtime', () => {expect(h.parse).toHaveBeenCalledTimes(1);});+ it('keeps rtl text runs in logical order for canvas shaping', () => {+ const result = textShape({+ dataStream: 'ABC\r',+ textRuns: [{+ st: 0,+ ed: 3,+ ts: {+ ff: 'Arial',+ rtl: BooleanNumber.TRUE,+ },+ }],+ } as any);++ expect(result.slice(0, 3).map((glyph) => glyph.char)).toEqual(['A', 'B', 'C']);+ });+it('falls back to null glyph when no valid font family exists', () => {h.fontLibrary.getValidFontFamilies.mockReturnValueOnce([]);const result = textShape({diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.tsindex d3f7d5c8ee..33af9491ef 100644--- a/packages/engine-render/src/components/docs/layout/tools.ts+++ b/packages/engine-render/src/components/docs/layout/tools.ts@@ -253,6 +253,10 @@ export function getNumberUnitValue(unitValue: Nullable<INumberUnit>, benchMark:const { v: value, u: unit } = unitValue;+ if (typeof value !== 'number' || !Number.isFinite(value)) {+ return 0;+ }+if (!unit) {return value;}@@ -292,7 +296,8 @@ export function validationGrid(gridType = GridType.LINES, snapToGrid = BooleanNuexport function getLineHeightConfig(sectionBreakConfig: ISectionBreakConfig, paragraphConfig: IParagraphConfig) {const { paragraphStyle = {}, useWordStyleLineHeight = false } = paragraphConfig;const { linePitch = 15.6, gridType = GridType.LINES, paragraphLineGapDefault = 0 } = sectionBreakConfig;- const defaultSnapToGrid = useWordStyleLineHeight ? BooleanNumber.FALSE : BooleanNumber.TRUE;+ const hasDocumentGrid = gridType === GridType.LINES_AND_CHARS || gridType === GridType.SNAP_TO_CHARS;+ const defaultSnapToGrid = useWordStyleLineHeight && !hasDocumentGrid ? BooleanNumber.FALSE : BooleanNumber.TRUE;const { lineSpacing = 0, spacingRule = SpacingRule.AUTO, snapToGrid = defaultSnapToGrid } = paragraphStyle;// Flavored docs use Word-style single spacing by default.@@ -641,12 +646,9 @@ export function getPositionHorizon(return absoluteLeft;}}- } else if (posOffset) {- const { pageWidth, marginLeft, marginRight } = page;- const boundaryLeft = marginLeft;- const boundaryRight = pageWidth - marginRight;-+ } else if (posOffset != null) {let absoluteLeft = 0;+ const { marginLeft } = page;if (relativeFrom === ObjectRelativeFromH.COLUMN) {absoluteLeft = (isPageBreak ? 0 : column?.left || 0) + posOffset;} else if (relativeFrom === ObjectRelativeFromH.LEFT_MARGIN) {@@ -663,9 +665,6 @@ export function getPositionHorizon(absoluteLeft = posOffset;}- if (absoluteLeft + objectWidth > boundaryRight) {- absoluteLeft = boundaryRight - objectWidth;- }return absoluteLeft;} else if (percent) {const { pageWidth, marginLeft, marginRight } = page;@@ -827,7 +826,7 @@ function getBulletParagraphTextStyle(bullet: IBullet, viewModel: DocumentViewModconst { listType } = bullet;const lists = viewModel.getDataModel().getBulletPresetList();- return lists[listType].nestingLevel[0].paragraphProperties?.textStyle;+ return lists[listType]?.nestingLevel?.[0]?.paragraphProperties?.textStyle;}const DEFAULT_TEXT_RUN = { ts: {}, st: 0, ed: 0 };@@ -946,6 +945,7 @@ export interface IFloatObject {width: number;height: number;angle: number;+ behindDoc?: BooleanNumber;type: FloatObjectType;positionV: IObjectPositionV;}diff --git a/packages/engine-render/src/shape/__tests__/image.spec.ts b/packages/engine-render/src/shape/__tests__/image.spec.tsindex 96ac85983f..7e626bb18c 100644--- a/packages/engine-render/src/shape/__tests__/image.spec.ts+++ b/packages/engine-render/src/shape/__tests__/image.spec.ts@@ -126,4 +126,68 @@ describe('image extra', () => {expect(image.width).toBe(100);expect(image.height).toBe(60);});++ it('registers load handlers before assigning url image source', () => {+ const originalCreateElement = document.createElement.bind(document);+ const events: Array<{ hasOnload: boolean; value: string }> = [];+ let nativeSrc = '';+ const native = {+ crossOrigin: '',+ height: 60,+ onerror: undefined,+ onload: undefined,+ width: 100,+ get src() {+ return nativeSrc;+ },+ set src(value: string) {+ events.push({ hasOnload: typeof native.onload === 'function', value });+ nativeSrc = value;+ native.onload?.(new Event('load'));+ },+ } as unknown as HTMLImageElement;+ const createElement = vi.spyOn(document, 'createElement');+ createElement.mockImplementation((tagName: string) => {+ if (tagName === 'img') {+ return native;+ }+ return originalCreateElement(tagName);+ });+ const success = vi.fn();++ try {+ new Image('img-sync-load', {+ fail: vi.fn(),+ height: 60,+ left: 0,+ success,+ top: 0,+ url: 'data:image/png;base64,abc',+ width: 100,+ });+ } finally {+ createElement.mockRestore();+ }++ expect(events).toEqual([{ hasOnload: true, value: 'data:image/png;base64,abc' }]);+ expect(success).toHaveBeenCalled();+ });++ it('clips rendering to an absolute document page bound before applying image transform', () => {+ const image = new Image('img4', {+ image: createNativeImage(100, 60),+ left: -30,+ top: 10,+ width: 100,+ height: 60,+ clipBounds: { left: 0, top: 0, width: 80, height: 120 },+ });++ const ctx = createCtxMock();+ image.render(ctx);++ expect(ctx.rect).toHaveBeenCalledWith(0, 0, 80, 120);+ expect(ctx.clip).toHaveBeenCalledBefore(ctx.transform);+ expect(ctx.drawImage).toHaveBeenCalled();+ });});diff --git a/packages/engine-render/src/shape/image.ts b/packages/engine-render/src/shape/image.tsindex 62b4520399..7cacece6b4 100644--- a/packages/engine-render/src/shape/image.ts+++ b/packages/engine-render/src/shape/image.ts@@ -65,6 +65,8 @@ export interface IImageProps extends IShapeProps {adjustValues?: Nullable<Record<string, number>>;opacity?: number;++ clipBounds?: Nullable<IShapeClipBounds>;}export class Image extends Shape<IImageProps> {@@ -94,7 +96,6 @@ export class Image extends Shape<IImageProps> {this.makeDirty(true);} else if (config.url) {this._native = document.createElement('img');- this._native.src = config.url;this._native.crossOrigin = 'anonymous';this._native.onload = () => {config.success?.();@@ -110,6 +111,7 @@ export class Image extends Shape<IImageProps> {this.makeDirty(true);}};+ this._native.src = config.url;}this._init();@@ -127,11 +129,20 @@ export class Image extends Shape<IImageProps> {return this._props.opacity ?? 1;}+ get clipBounds() {+ return this._props.clipBounds;+ }+setOpacity(opacity: number) {this._props.opacity = opacity;this.makeDirty(true);}+ setClipBounds(clipBounds?: Nullable<IShapeClipBounds>) {+ this._props.clipBounds = clipBounds;+ this.makeDirty(true);+ }+setClipService(clipService: Nullable<IImageShapeClipService>) {this._clipService = clipService;}@@ -154,10 +165,10 @@ export class Image extends Shape<IImageProps> {if (this._native == null) {this._native = document.createElement('img');}- this._native.src = url;this._native.onload = () => {this.makeDirty(true);};+ this._native.src = url;}resetSize() {@@ -341,6 +352,12 @@ export class Image extends Shape<IImageProps> {const m = this.transform.getMatrix();mainCtx.save();+ const { clipBounds } = this;+ if (clipBounds) {+ mainCtx.beginPath();+ mainCtx.rect(clipBounds.left, clipBounds.top, clipBounds.width, clipBounds.height);+ mainCtx.clip();+ }// if (this.flipX || this.flipY) {// const centerX = this.left + this.width / 2;// const centerY = this.top + this.height / 2;