Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(docs): improve DOCX drawing and table layout (#7124)

Univer3bb39fc3db2a
diff --git a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-notification.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-notification.controller.spec.ts
index bb199a41fc..21df1ccb22 100644
--- a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-notification.controller.spec.ts
+++ b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-notification.controller.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { UndoCommand } from '@univerjs/core';
+import { BooleanNumber, PositionedObjectLayoutType, UndoCommand } from '@univerjs/core';
import { RichTextEditingMutation } from '@univerjs/docs';
import { describe, expect, it, vi } from 'vitest';
import { DocDrawingAddRemoveController } from '../doc-drawing-notification.controller';
@@ -43,7 +43,21 @@ function createController() {
const controller = new DocDrawingAddRemoveController(
{
getCurrentUniverDocInstance: vi.fn(() => ({ getUnitId: () => 'doc-1' })),
- getUniverDocInstance: vi.fn(() => ({ getSnapshot: () => ({ drawingsOrder: ['drawing-2', 'drawing-1'] }) })),
+ getUniverDocInstance: vi.fn(() => ({
+ getSnapshot: () => ({
+ drawings: {
+ 'drawing-1': {
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ behindDoc: BooleanNumber.TRUE,
+ },
+ 'drawing-2': {
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ behindDoc: BooleanNumber.FALSE,
+ },
+ },
+ drawingsOrder: ['drawing-2', 'drawing-1'],
+ }),
+ })),
} as never,
{
beforeCommandExecuted: vi.fn((handler) => {
@@ -108,12 +122,12 @@ describe('DocDrawingAddRemoveController', () => {
});
executedHandlers[1]({ id: UndoCommand.id });
- expect(drawingManagerService.setDrawingOrder).toHaveBeenCalledWith('doc-1', 'doc-1', ['drawing-2', 'drawing-1']);
+ expect(drawingManagerService.setDrawingOrder).toHaveBeenCalledWith('doc-1', 'doc-1', ['drawing-1', 'drawing-2']);
expect(docDrawingService.setDrawingOrder).toHaveBeenCalledWith('doc-1', 'doc-1', ['drawing-2', 'drawing-1']);
expect(drawingManagerService.orderNotification).toHaveBeenCalledWith({
unitId: 'doc-1',
subUnitId: 'doc-1',
- drawingIds: ['drawing-2', 'drawing-1'],
+ drawingIds: ['drawing-1', 'drawing-2'],
});
expect(docDrawingService.orderNotification).toHaveBeenCalledWith({
unitId: 'doc-1',
diff --git a/packages/docs-drawing-ui/src/controllers/doc-drawing-notification.controller.ts b/packages/docs-drawing-ui/src/controllers/doc-drawing-notification.controller.ts
index 8d023e7d5a..c0da87642f 100644
--- a/packages/docs-drawing-ui/src/controllers/doc-drawing-notification.controller.ts
+++ b/packages/docs-drawing-ui/src/controllers/doc-drawing-notification.controller.ts
@@ -29,7 +29,7 @@ import {
UndoCommand,
} from '@univerjs/core';
import { RichTextEditingMutation } from '@univerjs/docs';
-import { IDocDrawingService } from '@univerjs/docs-drawing';
+import { getDocDrawingRenderOrder, IDocDrawingService } from '@univerjs/docs-drawing';
import { IDrawingManagerService } from '@univerjs/drawing';
import { IRenderManagerService } from '@univerjs/engine-render';
@@ -244,26 +244,31 @@ export class DocDrawingAddRemoveController extends Disposable {
return;
}
- const drawingsOrder = documentDataModel.getSnapshot().drawingsOrder;
+ const { drawings, drawingsOrder } = documentDataModel.getSnapshot();
if (drawingsOrder == null) {
return;
}
+ const renderOrder = getDocDrawingRenderOrder(drawingsOrder, drawings);
const drawingManagerService = this._drawingManagerService;
const docDrawingService = this._docDrawingService;
- drawingManagerService.setDrawingOrder(unitId, unitId, drawingsOrder);
+ drawingManagerService.setDrawingOrder(unitId, unitId, renderOrder);
docDrawingService.setDrawingOrder(unitId, unitId, drawingsOrder);
// FIXME: @Jocs, Only need to update the affected drawings.
const objects: IDrawingOrderMapParam = {
unitId,
subUnitId: unitId,
- drawingIds: drawingsOrder,
+ drawingIds: renderOrder,
};
drawingManagerService.orderNotification(objects);
- docDrawingService.orderNotification(objects);
+ docDrawingService.orderNotification({
+ unitId,
+ subUnitId: unitId,
+ drawingIds: drawingsOrder,
+ });
}
}
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.ts
index 299a39b919..4de57d6ab4 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
@@ -142,6 +142,10 @@ describe('DocDrawingTransformUpdateController', () => {
getDrawingData: vi.fn(() => ({
'multi-drawing': { drawingId: 'multi-drawing', isMultiTransform: BooleanNumber.TRUE },
'stale-multi': { drawingId: 'stale-multi', isMultiTransform: BooleanNumber.TRUE },
+ 'stale-normal': {
+ drawingId: 'stale-normal',
+ transform: { left: 0, top: 0, width: 100, height: 100, angle: 0 },
+ },
})),
removeNotification: vi.fn(),
addNotification: vi.fn(),
@@ -192,6 +196,18 @@ describe('DocDrawingTransformUpdateController', () => {
docTransform: defaultDocTransform,
},
};
+ const inlineDrawing = {
+ aLeft: 15,
+ aTop: 25,
+ width: 35,
+ height: 45,
+ angle: 0,
+ drawingId: 'inline-drawing',
+ drawingOrigin: {
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: defaultDocTransform,
+ },
+ };
const multiDrawingOnPage = {
aLeft: 6,
aTop: 8,
@@ -236,6 +252,7 @@ describe('DocDrawingTransformUpdateController', () => {
marginBottom: 17,
skeDrawings: new Map([
['normal-drawing', normalDrawing],
+ ['inline-drawing', inlineDrawing],
['multi-drawing', multiDrawingOnPage],
]),
skeTables: [table],
@@ -268,10 +285,19 @@ describe('DocDrawingTransformUpdateController', () => {
behindText: true,
transform: expect.objectContaining({ left: 26, top: 40, width: 30, height: 40, angle: 5 }),
}),
+ expect.objectContaining({
+ drawingId: 'inline-drawing',
+ transform: expect.objectContaining({ left: 31, top: 45, width: 35, height: 45, angle: 0 }),
+ }),
expect.objectContaining({
drawingId: 'cell-drawing',
transform: expect.objectContaining({ left: 56, top: 69, width: 11, height: 12, angle: 0 }),
}),
+ expect.objectContaining({
+ drawingId: 'stale-normal',
+ hidden: true,
+ transform: expect.objectContaining({ left: 0, top: 0, width: 100, height: 100, angle: 0 }),
+ }),
]);
expect(drawingManagerService.removeNotification).toHaveBeenCalledWith([
{ drawingId: 'multi-drawing', isMultiTransform: BooleanNumber.TRUE },
@@ -365,6 +391,29 @@ describe('DocDrawingTransformUpdateController', () => {
})).toBe(headerPage);
});
+ it('clips overflowing header cover drawings to the host document page', () => {
+ const headerPage = {
+ pageWidth: 601,
+ pageHeight: 510,
+ };
+ const hostPage = {
+ pageWidth: 794,
+ pageHeight: 1123,
+ };
+
+ expect(getDocsDrawingClipPage({
+ drawing: {
+ behindText: true,
+ transform: {
+ width: 803,
+ height: 682,
+ },
+ },
+ hostPage,
+ page: headerPage,
+ })).toBe(hostPage);
+ });
+
it('positions page-sized header backgrounds against the host page width', () => {
expect(getDocsPageRelativeDrawingLeft({
hostPage: {
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts
index fb52299f61..9bbbec8b1b 100644
--- a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts
@@ -26,6 +26,7 @@ import { DocDrawingUpdateRenderController } from '../doc-drawing-update.render-c
function createController(options: {
editArea?: DocumentEditArea;
drawings?: Record<string, unknown>;
+ isFocusing?: boolean;
} = {}) {
const featurePluginOrderUpdate$ = new Subject<any>();
const featurePluginGroupUpdate$ = new Subject<any>();
@@ -34,8 +35,11 @@ function createController(options: {
const changeEnd$ = new Subject<any>();
const editAreaChange$ = new Subject<void>();
const refreshDrawings$ = new Subject<unknown>();
+ const onFocus$ = new Subject<unknown>();
+ const onBlur$ = new Subject<unknown>();
const commandHandlers: Array<(command: { id: string }) => void> = [];
let editArea = options.editArea ?? DocumentEditArea.BODY;
+ let isFocusing = options.isFocusing ?? true;
const transformer = {
changeEnd$,
@@ -129,8 +133,13 @@ function createController(options: {
setContextValue: vi.fn(),
};
const docSelectionRenderService = {
+ get isFocusing() {
+ return isFocusing;
+ },
getActiveTextRange: vi.fn(() => null),
getSegment: vi.fn(() => ''),
+ onBlur$,
+ onFocus$,
setSegment: vi.fn(),
};
@@ -162,11 +171,16 @@ function createController(options: {
editAreaChange$,
focus$,
getShape: (drawingId: string) => shapeByDrawingId.get(drawingId),
+ onBlur$,
+ onFocus$,
refreshDrawings$,
scene,
setEditArea: (value: DocumentEditArea) => {
editArea = value;
},
+ setIsFocusing: (value: boolean) => {
+ isFocusing = value;
+ },
transformer,
};
}
@@ -259,4 +273,45 @@ describe('DocDrawingUpdateRenderController', () => {
expect(getShape('header-drawing').setOpacity).toHaveBeenLastCalledWith(1);
expect(getShape('body-drawing').setOpacity).toHaveBeenLastCalledWith(0.5);
});
+
+ it('keeps all drawings opaque while the document input is not focused', () => {
+ const bodyDrawing = {
+ drawingId: 'body-drawing',
+ isMultiTransform: BooleanNumber.FALSE,
+ };
+ const headerDrawing = {
+ drawingId: 'header-drawing',
+ isMultiTransform: BooleanNumber.TRUE,
+ };
+ const {
+ getShape,
+ onBlur$,
+ onFocus$,
+ scene,
+ setIsFocusing,
+ } = createController({
+ drawings: {
+ 'body-drawing': bodyDrawing,
+ 'header-drawing': headerDrawing,
+ },
+ isFocusing: false,
+ });
+
+ expect(scene.attachTransformerTo).not.toHaveBeenCalled();
+ expect(getShape('body-drawing').setOpacity).toHaveBeenLastCalledWith(1);
+ expect(getShape('header-drawing').setOpacity).toHaveBeenLastCalledWith(1);
+
+ setIsFocusing(true);
+ onFocus$.next({});
+
+ expect(scene.attachTransformerTo).toHaveBeenCalledWith(getShape('body-drawing'));
+ expect(getShape('body-drawing').setOpacity).toHaveBeenLastCalledWith(1);
+ expect(getShape('header-drawing').setOpacity).toHaveBeenLastCalledWith(0.5);
+
+ setIsFocusing(false);
+ onBlur$.next({});
+
+ expect(getShape('body-drawing').setOpacity).toHaveBeenLastCalledWith(1);
+ expect(getShape('header-drawing').setOpacity).toHaveBeenLastCalledWith(1);
+ });
});
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.ts
index f1f460606f..e8a034367c 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
@@ -44,6 +44,7 @@ interface IDrawingParamsWithBehindText {
subUnitId: string;
drawingId: string;
behindText: boolean;
+ hidden?: boolean;
transform: ITransformState;
transforms: ITransformState[];
// The same drawing render in different place, like image in header and footer.
@@ -102,6 +103,10 @@ export function getDocsDrawingClipPage(config: {
return page;
}
+ if (width > page.pageWidth || height > page.pageHeight) {
+ return hostPage;
+ }
+
const widthRatio = width / hostPage.pageWidth;
const heightRatio = height / hostPage.pageHeight;
if (widthRatio >= 0.8 && heightRatio >= 0.8) {
@@ -397,7 +402,14 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
const updateDrawings = Object.values(updateDrawingMap);
- const nonMultiDrawings = updateDrawings.filter((drawing) => !drawing.isMultiTransform);
+ for (const drawing of updateDrawings) {
+ drawing.hidden = false;
+ }
+
+ const staleNonMultiDrawings = this._getStaleNonMultiDrawings(unitId, updateDrawingMap);
+ const nonMultiDrawings = updateDrawings
+ .filter((drawing) => !drawing.isMultiTransform)
+ .concat(staleNonMultiDrawings);
const multiDrawings = updateDrawings.filter((drawing) => drawing.isMultiTransform);
if (nonMultiDrawings.length > 0) {
this._drawingManagerService.refreshTransform(nonMultiDrawings as unknown as IDrawingParam[]);
@@ -407,6 +419,27 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
this._handleMultiDrawingsTransform(multiDrawings as unknown as IDrawingParam[]);
}
+ private _getStaleNonMultiDrawings(
+ unitId: string,
+ updateDrawingMap: Record<string, IDrawingParamsWithBehindText>
+ ): IDrawingParamsWithBehindText[] {
+ const drawingData = this._drawingManagerService.getDrawingData(unitId, unitId) ?? {};
+
+ return Object.values(drawingData)
+ .filter((drawing) => drawing.isMultiTransform !== BooleanNumber.TRUE)
+ .filter((drawing) => updateDrawingMap[drawing.drawingId] == null)
+ .map((drawing) => ({
+ unitId,
+ subUnitId: unitId,
+ drawingId: drawing.drawingId,
+ behindText: false,
+ hidden: true,
+ transform: drawing.transform,
+ transforms: drawing.transforms ?? [],
+ isMultiTransform: drawing.isMultiTransform ?? BooleanNumber.FALSE,
+ } as IDrawingParamsWithBehindText));
+ }
+
private _handleMultiDrawingsTransform(multiDrawings: IDrawingParam[]) {
const { scene, unitId } = this._context;
const transformer = scene.getTransformerByCreate();
@@ -585,9 +618,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
return;
}
- this._refreshDrawing(skeleton);
-
this._drawingManagerService.initializeNotification(this._context.unitId);
+ this._refreshDrawing(skeleton);
};
if (this._lifecycleService.stage >= LifecycleStages.Rendered) {
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
index 5799c0e58f..84bcff8a67 100644
--- a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
@@ -357,6 +357,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
});
}
}
+ this._updateDrawingsEditStatus();
})
);
}
@@ -404,6 +405,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
const snapshot = docDataModel.getSnapshot();
const { drawings = {} } = snapshot;
const isEditBody = viewModel.getEditArea() === DocumentEditArea.BODY;
+ const isDocInputFocusing = this._docSelectionRenderService.isFocusing;
for (const key of Object.keys(drawings)) {
const drawing = drawings[key];
@@ -414,9 +416,12 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
for (const shape of drawingShapes) {
scene.detachTransformerFrom(shape);
try {
- (shape as Image).setOpacity(0.5);
+ (shape as Image).setOpacity(isDocInputFocusing ? 0.5 : 1);
} catch (e) {
}
+ if (!isDocInputFocusing) {
+ continue;
+ }
if (
(isEditBody && drawing.isMultiTransform !== BooleanNumber.TRUE)
|| (!isEditBody && drawing.isMultiTransform === BooleanNumber.TRUE)
@@ -454,6 +459,18 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
})
);
+ this.disposeWithMe(
+ this._docSelectionRenderService.onFocus$.subscribe(() => {
+ this._updateDrawingsEditStatus();
+ })
+ );
+
+ this.disposeWithMe(
+ this._docSelectionRenderService.onBlur$.subscribe(() => {
+ this._updateDrawingsEditStatus();
+ })
+ );
+
this.disposeWithMe(
this._docRefreshDrawingsService.refreshDrawings$.subscribe((skeleton) => {
if (skeleton == null) {
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.ts
index f32e7326dd..f78ca012fe 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
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { UniverInstanceType } from '@univerjs/core';
+import { BooleanNumber, PositionedObjectLayoutType, UniverInstanceType } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
import { DocDrawingController, DOCS_DRAWING_PLUGIN } from '../doc-drawing.controller';
@@ -70,6 +70,16 @@ describe('DocDrawingController', () => {
capturedResource.onLoad('doc-1', {
data: {
+ mask: {
+ id: 'mask',
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ behindDoc: BooleanNumber.FALSE,
+ },
+ photo: {
+ id: 'photo',
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ behindDoc: BooleanNumber.TRUE,
+ },
d2: {
id: 'd2',
docTransform: {
@@ -80,7 +90,7 @@ describe('DocDrawingController', () => {
},
},
},
- order: ['d2'],
+ order: ['mask', 'photo', 'd2'],
});
expect(registerDrawingData).toHaveBeenCalledWith('doc-1', expect.any(Object));
expect(registerDrawingDataForManager).toHaveBeenCalledWith('doc-1', expect.any(Object));
@@ -99,9 +109,11 @@ describe('DocDrawingController', () => {
},
}),
},
- order: ['d2'],
+ order: ['photo', 'mask', 'd2'],
},
});
+ const loadedDocDrawingData = registerDrawingData.mock.calls.at(-1)?.[1];
+ expect(loadedDocDrawingData?.['doc-1']?.order).toEqual(['mask', 'photo', 'd2']);
expect(loadedDrawingData?.['doc-1']?.data?.d2).not.toHaveProperty('transform');
capturedResource.onUnLoad('doc-1');
diff --git a/packages/docs-drawing/src/controllers/doc-drawing.controller.ts b/packages/docs-drawing/src/controllers/doc-drawing.controller.ts
index e8fae1ca91..3dd1f2fcdc 100644
--- a/packages/docs-drawing/src/controllers/doc-drawing.controller.ts
+++ b/packages/docs-drawing/src/controllers/doc-drawing.controller.ts
@@ -17,7 +17,7 @@
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
import type { IDrawingMapItem, IDrawingMapItemData } from '@univerjs/drawing';
import type { IDocDrawing } from '../services/doc-drawing.service';
-import { Disposable, IResourceManagerService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { BooleanNumber, Disposable, IResourceManagerService, IUniverInstanceService, PositionedObjectLayoutType, UniverInstanceType } from '@univerjs/core';
import { IDrawingManagerService } from '@univerjs/drawing';
import { IDocDrawingService } from '../services/doc-drawing.service';
@@ -27,6 +27,26 @@ export interface IDocDrawingModel {
drawingsOrder?: IDocumentData['drawingsOrder'];
};
+export function getDocDrawingRenderOrder(order: string[], drawings: IDocumentData['drawings'] = {}): string[] {
+ return order
+ .map((drawingId, index) => ({ drawingId, index }))
+ .sort((a, b) => {
+ const aBehind = isDocDrawingBehindText(drawings[a.drawingId]);
+ const bBehind = isDocDrawingBehindText(drawings[b.drawingId]);
+
+ if (aBehind !== bBehind) {
+ return aBehind ? -1 : 1;
+ }
+
+ return a.index - b.index;
+ })
+ .map(({ drawingId }) => drawingId);
+}
+
+function isDocDrawingBehindText(drawing: NonNullable<IDocumentData['drawings']>[string] | undefined): boolean {
+ return drawing?.layoutType === PositionedObjectLayoutType.WRAP_NONE && drawing.behindDoc === BooleanNumber.TRUE;
+}
+
export class DocDrawingController extends Disposable {
constructor(
@IDocDrawingService private readonly _docDrawingService: IDocDrawingService,
@@ -120,9 +140,15 @@ export class DocDrawingController extends Disposable {
order: drawingOrderModel,
},
};
+ const renderSubDrawings = {
+ [subUnitId]: {
+ ...subDrawings[subUnitId],
+ order: getDocDrawingRenderOrder(drawingOrderModel, drawingDataModels),
+ },
+ };
this._docDrawingService.registerDrawingData(unitId, subDrawings);
- this._drawingManagerService.registerDrawingData(unitId, subDrawings);
+ this._drawingManagerService.registerDrawingData(unitId, renderSubDrawings);
return true;
}
}
diff --git a/packages/docs-drawing/src/index.ts b/packages/docs-drawing/src/index.ts
index ae00c73edc..cf214e626e 100644
--- a/packages/docs-drawing/src/index.ts
+++ b/packages/docs-drawing/src/index.ts
@@ -15,7 +15,7 @@
*/
export type { IUniverDocsDrawingConfig } from './config/config';
-export { DOCS_DRAWING_PLUGIN } from './controllers/doc-drawing.controller';
+export { DOCS_DRAWING_PLUGIN, getDocDrawingRenderOrder } from './controllers/doc-drawing.controller';
export type { IDocDrawingModel } from './controllers/doc-drawing.controller';
export { DocDrawingController } from './controllers/doc-drawing.controller';
export { UniverDocsDrawingPlugin } from './plugin';
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.ts
index 1c0df20402..82a5c96aaf 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
@@ -29,6 +29,8 @@ interface IDrawingNotification {
unitId: string;
subUnitId: string;
drawingId: string;
+ behindText?: boolean;
+ hidden?: boolean;
}
interface IDrawingTransformObject {
@@ -70,7 +72,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 = { layer: { zIndex: DRAWING_OBJECT_LAYER_INDEX }, transformByState: vi.fn(), setClipBounds: vi.fn() };
+ const transformShape = { layer: { zIndex: DRAWING_OBJECT_LAYER_INDEX }, transformByState: vi.fn(), setClipBounds: vi.fn(), show: vi.fn(), hide: vi.fn() };
const scene = {
getTransformerByCreate: vi.fn(() => transformer),
@@ -96,10 +98,11 @@ function createHarness() {
getRenderById: vi.fn(() => ({ scene })),
};
- 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 } } }>([
+ const drawingParams = new Map<string, { unitId: string; subUnitId: string; drawingId: string; drawingType: DrawingTypeEnum; behindText?: boolean; hidden?: 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, behindText: true, transform: { left: 1, top: 2, width: 3, height: 4, angle: 0, clipBounds: { left: 0, top: 0, width: 80, height: 120 } } }],
+ ['drawing-transform', { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-transform', drawingType: DrawingTypeEnum.DRAWING_IMAGE, behindText: true, hidden: true, transform: { left: 1, top: 2, width: 3, height: 4, angle: 0, clipBounds: { left: 0, top: 0, width: 80, height: 120 } } }],
+ ['drawing-transform-refresh-hidden', { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-transform-refresh-hidden', drawingType: DrawingTypeEnum.DRAWING_IMAGE, 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 } }],
]);
@@ -217,11 +220,13 @@ describe('DrawingUpdateController', () => {
const drawingId = 'drawing-transform';
harness.update$.next([{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId }]);
expect(harness.transformShape.transformByState).toHaveBeenCalled();
+ expect(harness.transformShape.hide).toHaveBeenCalledTimes(1);
expect(harness.debounceRefreshControls).toHaveBeenCalledTimes(1);
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.transformShape.hide).toHaveBeenCalledTimes(2);
expect(harness.scene.removeObject).toHaveBeenCalledWith(harness.transformShape);
expect(harness.scene.addObject).toHaveBeenCalledWith(harness.transformShape, DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX);
@@ -248,4 +253,31 @@ describe('DrawingUpdateController', () => {
harness.controller.dispose();
});
+
+ it('uses refresh metadata to hide stale drawings without re-adding missing hidden shapes', () => {
+ const harness = createHarness();
+
+ harness.refreshTransform$.next([{
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'drawing-transform-refresh-hidden',
+ behindText: true,
+ hidden: true,
+ }]);
+
+ expect(harness.transformShape.hide).toHaveBeenCalledTimes(1);
+ expect(harness.scene.removeObject).toHaveBeenCalledWith(harness.transformShape);
+ expect(harness.scene.addObject).toHaveBeenCalledWith(harness.transformShape, DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX);
+
+ harness.refreshTransform$.next([{
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'drawing-refresh-missing',
+ hidden: true,
+ }]);
+
+ expect(harness.drawingManagerService.addNotification).not.toHaveBeenCalled();
+
+ harness.controller.dispose();
+ });
});
diff --git a/packages/drawing-ui/src/controllers/drawing-update.controller.ts b/packages/drawing-ui/src/controllers/drawing-update.controller.ts
index db1136b486..a98f4d09e6 100644
--- a/packages/drawing-ui/src/controllers/drawing-update.controller.ts
+++ b/packages/drawing-ui/src/controllers/drawing-update.controller.ts
@@ -62,6 +62,26 @@ interface IDrawingTransformStateWithClipBounds extends ITransformState {
clipBounds?: Nullable<{ left: number; top: number; width: number; height: number }>;
}
+function syncDrawingHiddenState(shape: BaseObject, drawingParam: IDrawingParam): void {
+ if (!('hidden' in drawingParam)) {
+ return;
+ }
+
+ drawingParam.hidden === true ? shape.hide() : shape.show();
+}
+
+function mergeRefreshMetadata(drawingParam: IDrawingParam, refreshParam: IDrawingSearch): IDrawingParam {
+ const metadata = refreshParam as Partial<IDrawingParam>;
+ if (!('hidden' in metadata) && !('behindText' in metadata)) {
+ return drawingParam;
+ }
+
+ return {
+ ...drawingParam,
+ ...metadata,
+ };
+}
+
export class DrawingUpdateController extends Disposable {
constructor(
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@@ -699,6 +719,7 @@ export class DrawingUpdateController extends Disposable {
drawingShape.transformByState({ left, top, width, height, angle, flipX, flipY, skewX, skewY });
(drawingShape as Image).setClipBounds?.((transform as IDrawingTransformStateWithClipBounds).clipBounds);
+ syncDrawingHiddenState(drawingShape, drawingParam);
ensureDrawingRenderLayer(scene, drawingShape, drawingParam);
scene.getTransformer()?.debounceRefreshControls();
@@ -730,8 +751,12 @@ export class DrawingUpdateController extends Disposable {
const drawingShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
const drawingShape = scene.getObject(drawingShapeKey);
+ const drawingParamWithRefreshMetadata = mergeRefreshMetadata(drawingParam, param);
if (drawingShape == null) {
+ if (drawingParamWithRefreshMetadata.hidden === true) {
+ return true;
+ }
this._drawingManagerService.addNotification([{ unitId, subUnitId, drawingId }]);
return true;
}
@@ -750,7 +775,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 as BaseObject, drawingParam);
+ syncDrawingHiddenState(drawingShape as BaseObject, drawingParamWithRefreshMetadata);
+ ensureDrawingRenderLayer(scene, drawingShape as BaseObject, drawingParamWithRefreshMetadata);
});
})
);
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.ts
index f7a593fc5d..29c592cf97 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
@@ -348,6 +348,25 @@ describe('DrawingRenderService', () => {
expect(imageIoService.cacheWrites).toEqual([{ source: 'image-source', imageSourceType: ImageSourceType.BASE64, image: image.getNative() }]);
});
+ it('syncs hidden state when an existing image shape is refreshed', async () => {
+ const { service, scene } = createHarness();
+ const key = drawingKey({ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1' });
+ const image = new Image(key, { ...BASE_TRANSFORM, url: 'existing-image' });
+ scene.objects.set(key, image);
+
+ await service.renderImages(imageParam({ hidden: true, transform: SECOND_TRANSFORM }), scene as unknown as Scene);
+
+ expect(image.visible).toBe(false);
+ expect(image.left).toBe(50);
+ expect(image.top).toBe(60);
+ expect(image.width).toBe(70);
+ expect(image.height).toBe(80);
+
+ await service.renderImages(imageParam({ hidden: false, transform: BASE_TRANSFORM }), scene as unknown as Scene);
+
+ expect(image.visible).toBe(true);
+ });
+
it('uses cached native images instead of resolving the source again', async () => {
const { service, scene, imageIoService } = createHarness();
const nativeImage = document.createElement('img');
diff --git a/packages/drawing-ui/src/services/drawing-render.service.ts b/packages/drawing-ui/src/services/drawing-render.service.ts
index c453eaef84..6a74b8aa48 100644
--- a/packages/drawing-ui/src/services/drawing-render.service.ts
+++ b/packages/drawing-ui/src/services/drawing-render.service.ts
@@ -125,6 +125,9 @@ export class DrawingRenderService {
if (imageShape != null) {
imageShape.transformByState({ left, top, width, height, angle, flipX, flipY, skewX, skewY });
(imageShape as Image).setClipBounds?.((transform as IDrawingTransformStateWithClipBounds).clipBounds);
+ if ('hidden' in imageParam) {
+ hidden ? imageShape.hide() : imageShape.show();
+ }
ensureDrawingRenderLayer(scene, imageShape, imageParam as IDrawingParamWithBehindText);
continue;
}
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.ts
index e279a1bb31..17c1f22b32 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
@@ -131,6 +131,7 @@ describe('UnitDrawingService', () => {
transforms: [{ left: 3, top: 4 } as NonNullable<IDrawingParam['transform']>] as NonNullable<IDrawingParam['transforms']>,
isMultiTransform: BooleanNumber.TRUE,
behindText: true,
+ hidden: true,
} as Partial<IDrawingParam>);
service.refreshTransform([transformed]);
@@ -140,6 +141,7 @@ describe('UnitDrawingService', () => {
transforms: [{ left: 3, top: 4 }],
isMultiTransform: BooleanNumber.TRUE,
behindText: true,
+ hidden: true,
});
service.visibleNotification([{ ...createSearch('a'), visible: false }]);
diff --git a/packages/drawing/src/services/drawing-manager-impl.service.ts b/packages/drawing/src/services/drawing-manager-impl.service.ts
index b1ca68acb9..e547d08be9 100644
--- a/packages/drawing/src/services/drawing-manager-impl.service.ts
+++ b/packages/drawing/src/services/drawing-manager-impl.service.ts
@@ -140,6 +140,9 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing
if ('behindText' in updateParam) {
(param as T & IDrawingRefreshMetadata).behindText = (updateParam as T & IDrawingRefreshMetadata).behindText;
}
+ if ('hidden' in updateParam) {
+ param.hidden = updateParam.hidden;
+ }
});
this.refreshTransformNotification(updateParams);
diff --git a/packages/engine-render/src/basics/i-document-skeleton-cached.ts b/packages/engine-render/src/basics/i-document-skeleton-cached.ts
index 5bcf36a6f7..5e74fd0448 100644
--- a/packages/engine-render/src/basics/i-document-skeleton-cached.ts
+++ b/packages/engine-render/src/basics/i-document-skeleton-cached.ts
@@ -18,6 +18,7 @@ import type {
BulletAlignment,
ColumnSeparatorType,
DataStreamTreeTokenType,
+ IColorStyle,
IDocDrawingBase,
IDocumentRenderConfig,
INestingLevel,
@@ -187,6 +188,7 @@ export interface IDocumentSkeletonLine {
tableId: string; // tableId if paragraph contains table, tableId is not empty, mainly used to calculate st\ed.
borderBottom?: IParagraphBorder; // borderBottom
+ backgroundColor?: IColorStyle; // backgroundColor
bullet?: IDocumentSkeletonBullet; // unordered and ordered list bullet
width?: number; // the actual width of a line
// dtId: string[]; // drawingTBIds element ids affecting rows, splitting divides, affecting top and bottom
diff --git a/packages/engine-render/src/basics/interfaces.ts b/packages/engine-render/src/basics/interfaces.ts
index 102e1f0f59..7f7a5b5bc6 100644
--- a/packages/engine-render/src/basics/interfaces.ts
+++ b/packages/engine-render/src/basics/interfaces.ts
@@ -30,6 +30,7 @@ import type {
LocaleService,
} from '@univerjs/core';
import type { DataStreamTreeNode } from '../components/docs/view-model/data-stream-tree-node';
+import type { IDocumentCompatibilityPolicy } from '../components/docs/document-compatibility';
import type { DocumentViewModel } from '../components/docs/view-model/document-view-model';
import type {
DocumentSkeletonPageType,
@@ -93,6 +94,7 @@ export interface IFontLocale {
export interface IDocsConfig extends IReferenceSource, IDocumentLayout {
localeService: LocaleService;
documentTextStyle?: ITextStyle;
+ documentCompatibilityPolicy?: IDocumentCompatibilityPolicy;
headerTreeMap: Map<string, DocumentViewModel>;
footerTreeMap: Map<string, DocumentViewModel>;
}
@@ -126,6 +128,7 @@ export interface IParagraphTableCache {
export interface IParagraphConfig {
paragraphIndex: number;
+ documentCompatibilityPolicy?: IDocumentCompatibilityPolicy;
useWordStyleLineHeight?: boolean;
docxFallbackAnchorLeft?: IParagraphStyle['indentStart'];
paragraphNonInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>;
@@ -147,6 +150,7 @@ export interface IFontCreateConfig {
textStyle: ITextStyle;
charSpace: number;
snapToGrid: BooleanNumber;
+ documentCompatibilityPolicy?: IDocumentCompatibilityPolicy;
gridType?: GridType;
pageWidth?: number;
}
diff --git a/packages/engine-render/src/components/docs/__tests__/document-compatibility.spec.ts b/packages/engine-render/src/components/docs/__tests__/document-compatibility.spec.ts
new file mode 100644
index 0000000000..25a7db1202
--- /dev/null
+++ b/packages/engine-render/src/components/docs/__tests__/document-compatibility.spec.ts
@@ -0,0 +1,51 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentSkeletonBoundingBox, IDocumentSkeletonFontStyle } from '../../../basics/i-document-skeleton-cached';
+import { DocumentFlavor } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { applyFontMetricCompatibility, getDocumentCompatibilityPolicy } from '../document-compatibility';
+
+const fontStyle = {
+ fontString: 'normal bold 24pt "Calibri", Arial',
+ fontSize: 24,
+ originFontSize: 24,
+ fontFamily: '"Calibri", Arial',
+ fontCache: 'normal bold 24pt "Calibri"',
+} as IDocumentSkeletonFontStyle;
+
+const bBox = {
+ width: 16,
+ ba: 30,
+ bd: 9,
+ aba: 30,
+ abd: 9,
+ sp: 0,
+ sbr: 0.6,
+ sbo: 1,
+ spr: 0.6,
+ spo: 1,
+} as IDocumentSkeletonBoundingBox;
+
+describe('document compatibility policy', () => {
+ it('applies traditional Word font metric width rules without changing modern documents', () => {
+ const traditional = getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL);
+ const modern = getDocumentCompatibilityPolicy(DocumentFlavor.MODERN);
+
+ expect(applyFontMetricCompatibility('5', fontStyle, bBox, traditional).width).toBeCloseTo(14.72);
+ expect(applyFontMetricCompatibility('5', fontStyle, bBox, modern).width).toBe(16);
+ });
+});
diff --git a/packages/engine-render/src/components/docs/__tests__/document.spec.ts b/packages/engine-render/src/components/docs/__tests__/document.spec.ts
index b91224f158..89d0f5b383 100644
--- a/packages/engine-render/src/components/docs/__tests__/document.spec.ts
+++ b/packages/engine-render/src/components/docs/__tests__/document.spec.ts
@@ -31,6 +31,7 @@ import { Viewport } from '../../../viewport';
import { DocBackground } from '../doc-background';
import { DOCS_EXTENSION_TYPE } from '../doc-extension';
import { Documents } from '../document';
+import { getDocumentCompatibilityPolicy } from '../document-compatibility';
import { setDocsTableRenderViewportProvider } from '../table-render-viewport';
function createGlyph(content: string, left: number, width = 16, backgroundColor?: string) {
@@ -992,6 +993,13 @@ describe('documents render', () => {
const documents = new Documents('docs-main', {
getSkeletonData: () => ({ pages: [bodyPage] }),
+ getViewModel: () => ({
+ getSnapshot: () => ({
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ },
+ }),
+ }),
} as any, {
pageLayoutType: PageLayoutType.VERTICAL,
pageMarginLeft: 0,
@@ -1033,6 +1041,65 @@ describe('documents render', () => {
documents.dispose();
});
+ it('does not clip DOCX tables that extend into margins while fitting the physical page', () => {
+ const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');
+ attachTable(bodyPage);
+ const table = bodyPage.skeTables.get('table-1')!;
+ table.left = -6;
+ table.width = 190;
+ table.tableSource = {
+ docxWidth: {
+ value: '2850',
+ type: 'dxa',
+ },
+ };
+ table.rows[0].cells[0].pageWidth = 190;
+
+ const documents = new Documents('docs-main', {
+ getSkeletonData: () => ({ pages: [bodyPage] }),
+ } as any, {
+ pageLayoutType: PageLayoutType.VERTICAL,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ });
+
+ const ctx = {
+ save: vi.fn(),
+ restore: vi.fn(),
+ getScale: vi.fn(() => ({ scaleX: 1, scaleY: 1 })),
+ beginPath: vi.fn(),
+ rect: vi.fn(),
+ fill: vi.fn(),
+ rectByPrecision: vi.fn(),
+ closePath: vi.fn(),
+ clip: vi.fn(),
+ set fillStyle(_value: string) {},
+ } as any;
+
+ vi.spyOn(documents as any, '_drawTableCell').mockImplementation(() => {});
+ vi.spyOn(documents as any, '_getDocumentCompatibilityPolicy').mockReturnValue(
+ getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL)
+ );
+
+ (documents as any)._drawTable(
+ ctx,
+ bodyPage,
+ bodyPage.skeTables,
+ [],
+ null,
+ [],
+ {} as any,
+ 0,
+ 0,
+ {},
+ { scaleX: 1, scaleY: 1 }
+ );
+
+ expect(ctx.clip).not.toHaveBeenCalled();
+
+ documents.dispose();
+ });
+
it('uses explicit table cell border width and skips no-border markers', () => {
const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;
const documents = new Documents('docs-border', skeleton, {
@@ -1285,4 +1352,49 @@ describe('documents render', () => {
documents.dispose();
});
+
+ it('draws paragraph background colors behind line text', () => {
+ const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');
+ const paragraphLine = createLine(LineType.PARAGRAPH, 24);
+ paragraphLine.backgroundColor = { rgb: '#ffffff' };
+ paragraphLine.parent = bodyPage.sections[0].columns[0];
+ bodyPage.sections[0].columns[0].lines = [paragraphLine];
+ bodyPage.skeTables.clear();
+
+ const skeletonData = {
+ pages: [bodyPage],
+ skeHeaders: new Map(),
+ skeFooters: new Map(),
+ };
+ bodyPage.parent = skeletonData;
+
+ const skeleton = {
+ getSkeletonData: () => skeletonData,
+ } as any;
+
+ const documents = new Documents('docs-paragraph-background', skeleton, {
+ pageLayoutType: PageLayoutType.VERTICAL,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ });
+ documents.transformByState({
+ left: 0,
+ top: 0,
+ width: 260,
+ height: 180,
+ });
+ scene.addObject(documents, 1);
+
+ const ctx = canvas.getContext();
+ const fillRect = vi.spyOn(ctx, 'fillRect');
+
+ documents.draw(ctx, {
+ viewBound: { left: 0, top: 0, right: 900, bottom: 700 },
+ cacheBound: { left: 0, top: 0, right: 900, bottom: 700 },
+ } as any);
+
+ expect(fillRect).toHaveBeenCalled();
+
+ documents.dispose();
+ });
});
diff --git a/packages/engine-render/src/components/docs/document-compatibility.ts b/packages/engine-render/src/components/docs/document-compatibility.ts
new file mode 100644
index 0000000000..63c682fc2e
--- /dev/null
+++ b/packages/engine-render/src/components/docs/document-compatibility.ts
@@ -0,0 +1,147 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ITable } from '@univerjs/core';
+import type {
+ IDocumentSkeletonBoundingBox,
+ IDocumentSkeletonFontStyle,
+} from '../../basics/i-document-skeleton-cached';
+import { DocumentFlavor } from '@univerjs/core';
+
+interface IFontMetricScaleRule {
+ fontFamily: RegExp;
+ minFontSize?: number;
+ fontString?: RegExp;
+ content?: RegExp;
+ widthScale?: number;
+}
+
+export interface IDocumentCompatibilityPolicy {
+ mode: 'modern' | 'traditional' | 'unspecified';
+ applyDocumentDefaultParagraphStyle: boolean;
+ useWordStyleLineHeight: boolean;
+ font: {
+ metricScaleRules: IFontMetricScaleRule[];
+ };
+ table: {
+ currentPageOverflowTolerance: number;
+ rowOverflowTolerance: number;
+ allowImportedTableMarginOverflow: boolean;
+ };
+}
+
+const MODERN_DOCUMENT_COMPATIBILITY_POLICY: IDocumentCompatibilityPolicy = {
+ mode: 'modern',
+ applyDocumentDefaultParagraphStyle: true,
+ useWordStyleLineHeight: true,
+ font: {
+ metricScaleRules: [],
+ },
+ table: {
+ currentPageOverflowTolerance: 0,
+ rowOverflowTolerance: 0,
+ allowImportedTableMarginOverflow: false,
+ },
+};
+
+const TRADITIONAL_DOCUMENT_COMPATIBILITY_POLICY: IDocumentCompatibilityPolicy = {
+ mode: 'traditional',
+ applyDocumentDefaultParagraphStyle: false,
+ useWordStyleLineHeight: true,
+ font: {
+ metricScaleRules: [
+ {
+ fontFamily: /^calibri$/i,
+ minFontSize: 20,
+ fontString: /\bbold\b/i,
+ content: /^[\d/]+$/u,
+ widthScale: 0.92,
+ },
+ ],
+ },
+ table: {
+ currentPageOverflowTolerance: 12,
+ rowOverflowTolerance: 4,
+ allowImportedTableMarginOverflow: true,
+ },
+};
+
+const UNSPECIFIED_DOCUMENT_COMPATIBILITY_POLICY: IDocumentCompatibilityPolicy = {
+ mode: 'unspecified',
+ applyDocumentDefaultParagraphStyle: false,
+ useWordStyleLineHeight: false,
+ font: {
+ metricScaleRules: [],
+ },
+ table: {
+ currentPageOverflowTolerance: 0,
+ rowOverflowTolerance: 0,
+ allowImportedTableMarginOverflow: false,
+ },
+};
+
+export function getDocumentCompatibilityPolicy(documentFlavor?: DocumentFlavor): IDocumentCompatibilityPolicy {
+ if (documentFlavor === DocumentFlavor.MODERN) {
+ return MODERN_DOCUMENT_COMPATIBILITY_POLICY;
+ }
+
+ if (documentFlavor === DocumentFlavor.TRADITIONAL) {
+ return TRADITIONAL_DOCUMENT_COMPATIBILITY_POLICY;
+ }
+
+ return UNSPECIFIED_DOCUMENT_COMPATIBILITY_POLICY;
+}
+
+export function applyFontMetricCompatibility(
+ content: string,
+ fontStyle: IDocumentSkeletonFontStyle,
+ bBox: IDocumentSkeletonBoundingBox,
+ policy: IDocumentCompatibilityPolicy
+): IDocumentSkeletonBoundingBox {
+ const fontFamilies = fontStyle.fontFamily
+ .split(',')
+ .map((item) => item.trim().replace(/^['"]|['"]$/g, ''));
+
+ const rule = policy.font.metricScaleRules.find((rule) =>
+ (rule.minFontSize == null || fontStyle.originFontSize >= rule.minFontSize) &&
+ (rule.fontString == null || rule.fontString.test(fontStyle.fontString)) &&
+ (rule.content == null || rule.content.test(content)) &&
+ fontFamilies.some((family) => rule.fontFamily.test(family))
+ );
+
+ if (rule?.widthScale == null) {
+ return bBox;
+ }
+
+ return {
+ ...bBox,
+ width: bBox.width * rule.widthScale,
+ };
+}
+
+export function isTraditionalDocumentCompatibility(policy: IDocumentCompatibilityPolicy): boolean {
+ return policy.mode === 'traditional';
+}
+
+export function shouldAllowImportedTableMarginOverflow(
+ policy: IDocumentCompatibilityPolicy,
+ tableSource: ITable | unknown
+): boolean {
+ return policy.table.allowImportedTableMarginOverflow &&
+ tableSource != null &&
+ typeof tableSource === 'object' &&
+ 'docxWidth' in tableSource;
+}
diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.ts
index 1d4014d535..f4ba002571 100644
--- a/packages/engine-render/src/components/docs/document.ts
+++ b/packages/engine-render/src/components/docs/document.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IDocumentRenderConfig, IScale, ITableCell, ITableCellBorder, Nullable } from '@univerjs/core';
+import type { DocumentFlavor, IDocumentRenderConfig, IScale, ITableCell, ITableCellBorder, Nullable } from '@univerjs/core';
import type {
IDocumentSkeletonGlyph,
IDocumentSkeletonLine,
@@ -42,6 +42,7 @@ import { DocumentsSpanAndLineExtensionRegistry } from '../extension';
import { DocComponent } from './doc-component';
import { DOCS_EXTENSION_TYPE } from './doc-extension';
import { collectBackgroundGlyphRuns } from './extensions/background-runs';
+import { getDocumentCompatibilityPolicy, shouldAllowImportedTableMarginOverflow } from './document-compatibility';
import { getTableIdAndSliceIndex } from './layout/block/table';
import { Liquid } from './liquid';
import { getDocsTableRenderViewport, hasDocsTableHorizontalViewport } from './table-render-viewport';
@@ -367,6 +368,7 @@ export class Documents extends DocComponent {
this._drawLiquid.translateLine(line, true, true);
rotateTranslateXListApply && this._drawLiquid.translate(rotateTranslateXListApply[i]); // x axis offset
+ this._drawLineBackground(ctx, page, line);
const divideLength = divides.length;
@@ -652,7 +654,10 @@ export class Documents extends DocComponent {
return null;
}
- const viewportWidth = Math.max(0, pageWidth - marginLeft - marginRight - tableSkeleton.left);
+ const compatibilityPolicy = this._getDocumentCompatibilityPolicy();
+ const viewportWidth = shouldAllowImportedTableMarginOverflow(compatibilityPolicy, tableSkeleton.tableSource)
+ ? Math.max(0, pageWidth - Math.max(0, marginLeft + tableSkeleton.left))
+ : Math.max(0, pageWidth - marginLeft - marginRight - tableSkeleton.left);
if (viewportWidth <= 0 || tableSkeleton.width <= viewportWidth) {
return null;
}
@@ -678,6 +683,53 @@ export class Documents extends DocComponent {
return dataModel?.getUnitId?.() ?? this.oKey;
}
+ private _getDocumentCompatibilityPolicy() {
+ const skeleton = this.getSkeleton() as {
+ getViewModel?: () => {
+ getSnapshot?: () => {
+ documentStyle?: {
+ documentFlavor?: DocumentFlavor;
+ };
+ };
+ };
+ } | undefined;
+ const documentFlavor = skeleton?.getViewModel?.()?.getSnapshot?.()?.documentStyle?.documentFlavor;
+
+ return getDocumentCompatibilityPolicy(documentFlavor);
+ }
+
+ private _drawLineBackground(
+ ctx: UniverRenderingContext,
+ page: IDocumentSkeletonPage,
+ line: IDocumentSkeletonLine,
+ left = 0,
+ top = 0
+ ) {
+ const color = line.backgroundColor?.rgb;
+ if (!color || this._drawLiquid == null) {
+ return;
+ }
+
+ let { x, y } = this._drawLiquid;
+ const { pageWidth, marginLeft, marginRight, marginTop } = page;
+
+ x += marginLeft + (left ?? 0);
+ y -= line.marginTop;
+ y -= line.paddingTop;
+ y += marginTop + top;
+
+ ctx.save();
+ ctx.fillStyle = color;
+ fillRectByPrecisionBounds(
+ ctx,
+ x,
+ y,
+ pageWidth - marginLeft - marginRight,
+ line.lineHeight
+ );
+ ctx.restore();
+ }
+
private _drawBorderBottom(
ctx: UniverRenderingContext,
page: IDocumentSkeletonPage,
@@ -813,6 +865,7 @@ export class Documents extends DocComponent {
} else {
this._drawLiquid.translateSave();
this._drawLiquid.translateLine(line, true, true);
+ this._drawLineBackground(ctx, cell, line, page.marginLeft, page.marginTop);
const divideLength = divides.length;
@@ -1099,6 +1152,7 @@ export class Documents extends DocComponent {
continue;
}
}
+ this._drawLineBackground(ctx, page, line, parentPage.marginLeft);
const divideLength = divides.length;
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.ts
index c62bf38299..e8b768d88d 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
@@ -18,6 +18,7 @@ import {
AlignTypeH,
AlignTypeV,
BooleanNumber,
+ DataStreamTreeTokenType,
DocumentFlavor,
GridType,
NumberUnitType,
@@ -65,6 +66,7 @@ import {
resetContext,
setPageParent,
updateBlockIndex,
+ updateInlineDrawingCoordsAndBorder,
validationGrid,
} from '../tools';
@@ -249,6 +251,40 @@ describe('docs layout tools extra', () => {
expect(columns.length).toBe(1);
});
+ it('copies paragraph background color to the rendered line', () => {
+ const { page, line1 } = createPageSkeleton();
+ const paragraphMark = {
+ streamType: DataStreamTreeTokenType.PARAGRAPH,
+ count: 1,
+ glyphType: GlyphType.WORD,
+ width: 0,
+ bBox: { ba: 0, bd: 0 },
+ xOffset: 0,
+ };
+ line1.divides = [{
+ glyphGroup: [paragraphMark],
+ }];
+ const ctx = {
+ paragraphConfigCache: new Map([[
+ undefined,
+ new Map([[
+ 0,
+ {
+ paragraphStyle: {
+ shading: {
+ backgroundColor: { rgb: '#ffffff' },
+ },
+ },
+ },
+ ]]),
+ ]]),
+ };
+
+ updateInlineDrawingCoordsAndBorder(ctx as any, [page] as any);
+
+ expect(line1.backgroundColor).toEqual({ rgb: '#ffffff' });
+ });
+
it('computes horizontal and vertical positioned object coordinates', () => {
const { page, column } = createPageSkeleton();
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.ts
index 70f3279788..a0fc6ac707 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
@@ -19,12 +19,14 @@ import type { IParagraphList } from '../../../../../basics/i-document-skeleton-c
import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';
import {
BooleanNumber,
+ DocumentFlavor,
TableAlignmentType,
TableRowHeightRule,
TableSizeType,
VerticalAlignmentType,
} from '@univerjs/core';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { getDocumentCompatibilityPolicy } from '../../../document-compatibility';
import {
createTableSkeleton,
createTableSkeletons,
@@ -148,6 +150,10 @@ function makeCellPage(width: number, height: number) {
};
}
+function useDocumentFlavor(sectionBreakConfig: Record<string, unknown>, documentFlavor: DocumentFlavor) {
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(documentFlavor);
+}
+
describe('table utilities', () => {
describe('getTableSliceId', () => {
it('concatenates tableId and sliceIndex with delimiter', () => {
@@ -408,6 +414,105 @@ describe('docs table layout', () => {
}
});
+ it('keeps a table on the current page when it only slightly overflows available height', () => {
+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();
+ useDocumentFlavor(sectionBreakConfig, DocumentFlavor.TRADITIONAL);
+ tableSource.tableRows = [
+ {
+ repeatHeaderRow: BooleanNumber.FALSE,
+ trHeight: {
+ hRule: TableRowHeightRule.AUTO,
+ val: { v: 16 },
+ },
+ cantSplit: BooleanNumber.FALSE,
+ tableCells: [
+ { vAlign: VerticalAlignmentType.TOP },
+ { vAlign: VerticalAlignmentType.TOP },
+ ],
+ },
+ ];
+ tableNode.children = [createRowNode(1, 20, 2) as any];
+ createSkeletonCellPagesMock.mockImplementation(() => [makeCellPage(60, 115)]);
+
+ const result = createTableSkeletons(ctx, curPage, viewModel, tableNode, sectionBreakConfig, 109);
+
+ expect(result.skeTables[0].height).toBe(117);
+ expect(result.fromCurrentPage).toBe(true);
+ });
+
+ it('opens a new table slice in modern documents when it overflows available height', () => {
+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();
+ useDocumentFlavor(sectionBreakConfig, DocumentFlavor.MODERN);
+ tableSource.tableRows = [
+ {
+ repeatHeaderRow: BooleanNumber.FALSE,
+ trHeight: {
+ hRule: TableRowHeightRule.AUTO,
+ val: { v: 16 },
+ },
+ cantSplit: BooleanNumber.FALSE,
+ tableCells: [
+ { vAlign: VerticalAlignmentType.TOP },
+ { vAlign: VerticalAlignmentType.TOP },
+ ],
+ },
+ ];
+ tableNode.children = [createRowNode(1, 20, 2) as any];
+ createSkeletonCellPagesMock.mockImplementation(() => [makeCellPage(60, 115)]);
+
+ const result = createTableSkeletons(ctx, curPage, viewModel, tableNode, sectionBreakConfig, 109);
+
+ expect(result.skeTables[0].height).toBe(117);
+ expect(result.fromCurrentPage).toBe(false);
+ });
+
+ it('lays out splittable auto rows against the remaining page height', () => {
+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();
+ tableSource.tableRows[0].repeatHeaderRow = BooleanNumber.FALSE;
+ tableSource.tableRows[0].trHeight = {
+ hRule: TableRowHeightRule.EXACT,
+ val: { v: 140 },
+ };
+ tableSource.tableRows[1].trHeight = {
+ hRule: TableRowHeightRule.AUTO,
+ val: { v: 0 },
+ };
+ tableSource.tableRows[1].cantSplit = BooleanNumber.FALSE;
+ createSkeletonCellPagesMock.mockImplementation(
+ (_ctx: unknown, _viewModel: unknown, _cellNode: unknown, _section: unknown, _table: unknown, row: number, _col: number) =>
+ row === 0 ? [makeCellPage(60, 20)] : [makeCellPage(60, 80)]
+ );
+
+ createTableSkeletons(ctx, curPage, viewModel, tableNode, sectionBreakConfig, 240);
+
+ const secondRowCall = createSkeletonCellPagesMock.mock.calls.find((call) => call[5] === 1 && call[6] === 0);
+ expect(secondRowCall?.[7]).toBe(100);
+ });
+
+ it('keeps a splittable auto row on the current page when its first slice slightly overflows', () => {
+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();
+ useDocumentFlavor(sectionBreakConfig, DocumentFlavor.TRADITIONAL);
+ tableSource.tableRows[0].repeatHeaderRow = BooleanNumber.FALSE;
+ tableSource.tableRows[0].trHeight = {
+ hRule: TableRowHeightRule.EXACT,
+ val: { v: 140 },
+ };
+ tableSource.tableRows[1].trHeight = {
+ hRule: TableRowHeightRule.AUTO,
+ val: { v: 0 },
+ };
+ tableSource.tableRows[1].cantSplit = BooleanNumber.FALSE;
+ createSkeletonCellPagesMock.mockImplementation(
+ (_ctx: unknown, _viewModel: unknown, _cellNode: unknown, _section: unknown, _table: unknown, row: number) =>
+ row === 0 ? [makeCellPage(60, 20)] : [makeCellPage(60, 100.5)]
+ );
+
+ const result = createTableSkeletons(ctx, curPage, viewModel, tableNode, sectionBreakConfig, 240);
+
+ expect(result.skeTables[0].rows.map((row) => row.index)).toEqual([0, 1]);
+ expect(result.skeTables[1]?.rows.map((row) => row.index) ?? []).not.toContain(1);
+ });
+
it('repeats multiple leading header rows on sliced table pages', () => {
const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();
tableSource.tableRows[1].repeatHeaderRow = BooleanNumber.TRUE;
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts
index 9d63c38212..7d90e5ddbb 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
@@ -24,7 +24,7 @@ import {
SpacingRule,
WrapTextType,
} from '@univerjs/core';
-import { describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { GlyphType, LineType } from '../../../../../../basics/i-document-skeleton-cached';
import { __testing, getLineHeightMetrics, layoutParagraph, updateInlineDrawingPosition } from '../layout-ruler';
import { lineBreaking } from '../linebreaking';
@@ -32,6 +32,24 @@ import { shaping } from '../shaping';
import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';
describe('layout-ruler', () => {
+ beforeEach(() => {
+ vi.stubGlobal('document', {
+ createElement: () => ({
+ getContext: () => ({
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText: (value: string) => ({
+ width: value.length * 8,
+ fontBoundingBoxAscent: 10,
+ fontBoundingBoxDescent: 4,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 4,
+ }),
+ }),
+ }),
+ });
+ });
+
function getLineBoxHeight(metrics: ReturnType<typeof getLineHeightMetrics>) {
return metrics.paddingTop + metrics.contentHeight + metrics.paddingBottom;
}
@@ -70,6 +88,43 @@ describe('layout-ruler', () => {
expect(result[0].sections.length).toBeGreaterThan(0);
});
+ it('keeps direct paragraph indents before bullet list defaults', () => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Item');
+ const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.viewModel, paragraphNode, sectionBreakConfig);
+ const bulletSkeleton = {
+ listId: 'list-1',
+ symbol: '-',
+ ts: { ff: 'Arial', fs: 9 },
+ startIndexItem: 1,
+ paragraphProperties: {
+ indentFirstLine: { v: 0 },
+ hanging: { v: 24 },
+ indentStart: { v: 48 },
+ },
+ };
+
+ const paragraphConfig = {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: {
+ hanging: { v: 12 },
+ indentStart: { v: 12 },
+ },
+ bulletSkeleton,
+ } as unknown as IParagraphConfig;
+
+ layoutParagraph(
+ ctx,
+ shapedTextList[0].glyphs,
+ [curPage],
+ sectionBreakConfig,
+ paragraphConfig,
+ true
+ );
+
+ expect(paragraphConfig.paragraphStyle?.indentStart).toEqual({ v: 12 });
+ expect(paragraphConfig.paragraphStyle?.hanging).toEqual({ v: 12 });
+ });
+
it('lays out first shaped text without bullet', () => {
const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Hello world');
const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.viewModel, paragraphNode, sectionBreakConfig);
@@ -461,6 +516,7 @@ describe('layout-ruler', () => {
const section = {
columns: [],
parent: page,
+ top: 126,
} as any;
const column = {
left: 40,
@@ -497,16 +553,44 @@ describe('layout-ruler', () => {
expect(page.skeDrawings.get('old-image')).toEqual({ drawingId: 'old-image' });
expect(page.skeDrawings.get('image-1')).toMatchObject({
- aLeft: 30,
- aTop: 104,
+ aLeft: 70,
+ aTop: 230,
width: 30,
height: 20,
angle: 15,
isPageBreak: false,
- lineTop: 100,
+ lineTop: 226,
columnLeft: 40,
- blockAnchorTop: 80,
+ blockAnchorTop: 206,
lineHeight: 24,
});
});
+
+ it('moves non-wrap tables into the usable area beside flow-affecting drawings', () => {
+ const table = {
+ top: 120,
+ left: 0,
+ width: 280,
+ height: 80,
+ } as any;
+ const page = {
+ skeDrawings: new Map([['left-wrap', {
+ aTop: 40,
+ aLeft: 10,
+ width: 90,
+ height: 220,
+ drawingOrigin: {
+ layoutType: PositionedObjectLayoutType.WRAP_TIGHT,
+ distR: 8,
+ },
+ }]]),
+ } as any;
+ const column = {
+ width: 420,
+ } as any;
+
+ __testing.avoidFlowAffectingDrawingsForTable(table, page, column);
+
+ expect(table.left).toBe(108);
+ });
});
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts
index 23930d3e0c..50508934a2 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
@@ -23,6 +23,7 @@ import {
ObjectRelativeFromH,
ObjectRelativeFromV,
PositionedObjectLayoutType,
+ WrapTextType,
} from '@univerjs/core';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { updateInlineDrawingCoordsAndBorder } from '../../../tools';
@@ -340,8 +341,55 @@ describe('linebreaking', () => {
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);
+ expect(inlineMapRight?.lineTop).toBeGreaterThanOrEqual(inlineMapLeft?.lineTop ?? 0);
+ if (inlineMapRight?.lineTop === inlineMapLeft?.lineTop) {
+ expect(inlineMapRight?.aLeft).toBeGreaterThan(inlineMapLeft?.aLeft ?? 0);
+ }
+ });
+
+ it('places an oversized inline custom block in the usable divide after a paragraph-relative wrap drawing', () => {
+ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}${DataStreamTreeTokenType.CUSTOM_BLOCK}`;
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ body: {
+ customBlocks: [
+ { startIndex: 0, blockId: 'inline-photo' },
+ { startIndex: 1, blockId: 'left-wrap' },
+ ],
+ },
+ drawings: {
+ 'inline-photo': {
+ drawingId: 'inline-photo',
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ size: { width: 120, height: 80 },
+ positionH: {},
+ positionV: {},
+ angle: 0,
+ },
+ },
+ 'left-wrap': {
+ drawingId: 'left-wrap',
+ layoutType: PositionedObjectLayoutType.WRAP_TIGHT,
+ behindDoc: 1,
+ wrapText: WrapTextType.BOTH_SIDES,
+ docTransform: {
+ size: { width: 50, height: 180 },
+ positionH: { relativeFrom: ObjectRelativeFromH.COLUMN, posOffset: 1.25 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 1.25 },
+ angle: 0,
+ },
+ },
+ },
+ });
+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+
+ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);
+ updateInlineDrawingCoordsAndBorder(ctx, result);
+
+ const inlinePhoto = result[0].skeDrawings.get('inline-photo');
+ const leftWrap = result[0].skeDrawings.get('left-wrap');
+
+ expect(inlinePhoto?.aLeft).toBeGreaterThanOrEqual((leftWrap?.aLeft ?? 0) + (leftWrap?.width ?? 0));
});
it('does not move a zero-width wrap-none floating anchor to a new page at the page bottom', () => {
@@ -1256,6 +1304,11 @@ describe('linebreaking', () => {
getBody: vi.fn(() => ({
paragraphs: [paragraph],
})),
+ getSnapshot: vi.fn(() => ({
+ documentStyle: {
+ documentFlavor: DocumentFlavor.MODERN,
+ },
+ })),
getCustomBlock: vi.fn(() => null),
} as any;
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts
index f73139cb49..dbfb429e33 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
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { INumberUnit, IParagraphProperties, IParagraphStyle, Nullable } from '@univerjs/core';
+import type { INumberUnit, IParagraphProperties, Nullable } from '@univerjs/core';
import type {
IDocumentSkeletonColumn,
IDocumentSkeletonDivide,
@@ -70,7 +70,6 @@ import {
getPositionVertical,
isColumnFull,
lineIterator,
- mergeByV,
} from '../../tools';
import { createTableSkeletons, rollbackListCache } from '../table';
@@ -98,8 +97,15 @@ export function layoutParagraph(
const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);
const bulletGlyph = createSkeletonBulletGlyph(glyphGroup[0], bulletSkeleton, charSpaceApply);
const paragraphProperties = bulletSkeleton.paragraphProperties || {};
-
- paragraphConfig.paragraphStyle = mergeByV<IParagraphStyle>(paragraphConfig.paragraphStyle, { ...paragraphProperties, hanging: { v: bulletGlyph.width } } as IParagraphProperties, 'max');
+ const bulletParagraphStyle = {
+ ...paragraphProperties,
+ hanging: paragraphProperties.hanging ?? { v: bulletGlyph.width },
+ } as IParagraphProperties;
+
+ paragraphConfig.paragraphStyle = {
+ ...bulletParagraphStyle,
+ ...paragraphConfig.paragraphStyle,
+ };
_lineOperator(ctx, [bulletGlyph, ...glyphGroup], pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType);
} else {
@@ -261,6 +267,27 @@ function _divideOperator(
divideInfo.isLast && !isGlyphGroupBeyondContentBox(glyphGroup, preOffsetLeft, divide.width) && isGlyphGroupEndWithWhiteSpaces(glyphGroup)
) {
addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
+ } else if (
+ !isLast &&
+ divide?.glyphGroup.length === 0 &&
+ glyphGroup.length === 1 &&
+ glyphGroup[0].streamType === DataStreamTreeTokenType.CUSTOM_BLOCK &&
+ glyphGroup[0].width > divide.width
+ ) {
+ updateDivideInfo(divide, {
+ isFull: true,
+ });
+ _divideOperator(
+ ctx,
+ glyphGroup,
+ pages,
+ sectionBreakConfig,
+ paragraphConfig,
+ isParagraphFirstShapedText,
+
+ breakPointType,
+ defaultSpanLineHeight
+ );
} else if (divide?.glyphGroup.length === 0) {
const sliceGlyphGroup: IDocumentSkeletonGlyph[] = [];
@@ -621,8 +648,11 @@ function _lineOperator(
.filter((drawing) => drawing.drawingOrigin.docTransform.positionV.relativeFrom !== ObjectRelativeFromV.LINE);
if (hasInlineCustomBlock) {
- deferredInlineGroupAnchorDrawings = targetDrawings.filter((drawing) => glyphGroupCustomBlockIds.has(drawing.drawingId));
- targetDrawings = targetDrawings.filter((drawing) => !glyphGroupCustomBlockIds.has(drawing.drawingId));
+ deferredInlineGroupAnchorDrawings = targetDrawings.filter((drawing) =>
+ glyphGroupCustomBlockIds.has(drawing.drawingId) &&
+ drawing.drawingOrigin.docTransform.positionV.relativeFrom === ObjectRelativeFromV.LINE
+ );
+ targetDrawings = targetDrawings.filter((drawing) => !deferredInlineGroupAnchorDrawings.includes(drawing));
}
__updateAndPositionDrawings(ctx, lineTop, lineHeight, column, targetDrawings, paragraphConfig.paragraphIndex, isParagraphFirstShapedText, pDrawingAnchor?.get(paragraphIndex)?.top, paragraphAnchorLeft);
@@ -784,6 +814,7 @@ function __updateAndPositionDrawings(
height,
angle,
behindDoc: drawingOrigin.behindDoc,
+ layoutType: drawingOrigin.layoutType,
type: FloatObjectType.IMAGE,
positionV,
};
@@ -864,6 +895,43 @@ function __getWrapTablePosition(
return { left, top };
}
+function __avoidFlowAffectingDrawingsForTable(
+ table: IDocumentSkeletonTable,
+ page: IDocumentSkeletonPage,
+ column: IDocumentSkeletonColumn
+) {
+ const tableTop = table.top;
+ const tableBottom = table.top + table.height;
+ const tableRight = table.left + table.width;
+
+ for (const drawing of page.skeDrawings.values()) {
+ const drawingOrigin = drawing.drawingOrigin;
+ if (
+ drawingOrigin == null ||
+ drawingOrigin.layoutType === PositionedObjectLayoutType.INLINE ||
+ drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_NONE ||
+ drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM
+ ) {
+ continue;
+ }
+
+ const drawingTop = drawing.aTop;
+ const drawingBottom = drawing.aTop + drawing.height;
+ if (drawingTop >= tableBottom || drawingBottom <= tableTop) {
+ continue;
+ }
+
+ const drawingRight = drawing.aLeft + drawing.width + (drawingOrigin.distR ?? 0);
+ if (drawing.aLeft >= tableRight || drawingRight <= table.left) {
+ continue;
+ }
+
+ if (drawingRight + table.width <= column.width) {
+ table.left = Math.max(table.left, drawingRight);
+ }
+ }
+}
+
function _updateAndPositionTable(
ctx: ILayoutContext,
lineTop: number,
@@ -894,6 +962,7 @@ function _updateAndPositionTable(
switch (tableSource.textWrap) {
case TableTextWrapType.NONE: {
table.top = lineTop;
+ __avoidFlowAffectingDrawingsForTable(table, page, column);
break;
}
case TableTextWrapType.WRAP: {
@@ -938,7 +1007,6 @@ function _updateAndPositionTable(
sectionBreakConfig,
availableHeight
);
-
// Reset the position of the first table.
skeTables.forEach((table, i) => {
table.top = i === 0 && fromCurrentPage ? top : 0;
@@ -1028,7 +1096,7 @@ function __getZeroWidthNonFlowFloatingAnchorDrawings(
return [];
}
- if (drawingOrigin.layoutType !== PositionedObjectLayoutType.WRAP_NONE && drawingOrigin.behindDoc !== BooleanNumber.TRUE) {
+ if (drawingOrigin.layoutType !== PositionedObjectLayoutType.WRAP_NONE) {
return [];
}
@@ -1074,7 +1142,13 @@ function _reLayoutCheck(
paragraphIndex: number
) {
const page = column.parent?.parent;
- const flowAffectingFloatObjects = floatObjects.filter((floatObject) => floatObject.behindDoc !== BooleanNumber.TRUE);
+ const flowAffectingFloatObjects = floatObjects.filter((floatObject) =>
+ floatObject.behindDoc !== BooleanNumber.TRUE ||
+ (
+ floatObject.layoutType != null &&
+ floatObject.layoutType !== PositionedObjectLayoutType.WRAP_NONE
+ )
+ );
if (flowAffectingFloatObjects.length === 0 || page == null) {
return;
@@ -1198,6 +1272,7 @@ function checkRelativeDrawingNeedRePosition(ctx: ILayoutContext, floatObject: IF
export const __testing = {
reLayoutCheck: _reLayoutCheck,
+ avoidFlowAffectingDrawingsForTable: __avoidFlowAffectingDrawingsForTable,
};
function _columnOperator(
@@ -1435,9 +1510,11 @@ export function getLineHeightMetrics(
export function updateInlineDrawingPosition(
line: IDocumentSkeletonLine,
paragraphInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>,
- blockAnchorTop?: number
+ blockAnchorTop?: number,
+ paragraphNonInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>
) {
const column = line.parent;
+ const section = column?.parent;
const page = line?.parent?.parent?.parent;
if (page == null || column == null) {
@@ -1448,6 +1525,8 @@ export function updateInlineDrawingPosition(
const drawings: Map<string, IDocumentSkeletonDrawing> = new Map();
const { top, lineHeight, marginBottom = 0 } = line;
+ const sectionTop = section?.top ?? 0;
+ const lineTop = sectionTop + top;
for (const divide of line.divides) {
for (const glyph of divide.glyphGroup) {
@@ -1472,15 +1551,43 @@ export function updateInlineDrawingPosition(
const { width = 0, height = 0 } = size;
const glyphHeight = glyph.bBox.bd + glyph.bBox.ba;
- drawing.aLeft = divide.left + divide.paddingLeft + glyph.left + 0.5 * glyph.width - 0.5 * width || 0;
- drawing.aTop = top + lineHeight - 0.5 * glyphHeight - 0.5 * height - marginBottom;
+ drawing.aLeft = column.left + divide.left + divide.paddingLeft + glyph.left + 0.5 * glyph.width - 0.5 * width || 0;
+ if (glyph.width > divide.width) {
+ for (const positionedDrawing of paragraphNonInlineSkeDrawings?.values() ?? []) {
+ const positionedOrigin = positionedDrawing.drawingOrigin;
+ if (
+ positionedOrigin == null ||
+ positionedOrigin.layoutType === PositionedObjectLayoutType.INLINE ||
+ positionedOrigin.layoutType === PositionedObjectLayoutType.WRAP_NONE ||
+ positionedOrigin.layoutType === PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM
+ ) {
+ continue;
+ }
+
+ const positionedBottom = positionedDrawing.aTop + positionedDrawing.height;
+ const lineBottom = lineTop + lineHeight;
+ if (positionedDrawing.aTop >= lineBottom || positionedBottom <= lineTop) {
+ continue;
+ }
+
+ const positionedRight = positionedDrawing.aLeft + positionedDrawing.width;
+ const drawingRight = drawing.aLeft + width;
+ if (positionedDrawing.aLeft < drawingRight && positionedRight > drawing.aLeft) {
+ drawing.aLeft = Math.max(
+ drawing.aLeft,
+ positionedDrawing.aLeft + positionedDrawing.width + (positionedOrigin.distR ?? 0)
+ );
+ }
+ }
+ }
+ drawing.aTop = lineTop + lineHeight - 0.5 * glyphHeight - 0.5 * height - marginBottom;
drawing.width = width;
drawing.height = height;
drawing.angle = angle;
drawing.isPageBreak = isPageBreak;
- drawing.lineTop = top;
+ drawing.lineTop = lineTop;
drawing.columnLeft = column.left;
- drawing.blockAnchorTop = blockAnchorTop ?? top;
+ drawing.blockAnchorTop = blockAnchorTop == null ? lineTop : sectionTop + blockAnchorTop;
drawing.lineHeight = line.lineHeight;
drawings.set(drawing.drawingId, drawing);
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts
index bc0a4848c4..59cc9286df 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
@@ -42,11 +42,11 @@ import {
DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE,
DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW,
DocumentBlockRangeType,
- DocumentFlavor,
PositionedObjectLayoutType,
Tools,
} from '@univerjs/core';
import { BreakType } from '../../../../../basics/i-document-skeleton-cached';
+import { getDocumentCompatibilityPolicy, isTraditionalDocumentCompatibility } from '../../../document-compatibility';
import { createSkeletonPage } from '../../model/page';
import { setColumnFullState } from '../../model/section';
import { getLastNotFullColumnInfo } from '../../tools';
@@ -259,31 +259,6 @@ function _applyBlockRangeLayoutParagraphStyle(
return style;
}
-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) {
- return true;
- }
-
- return documentFlavor != null && documentFlavor !== DocumentFlavor.UNSPECIFIED;
-}
-
-function _isTraditionalDoc(viewModel: DocumentViewModel): boolean {
- return viewModel.getSnapshot?.()?.documentStyle.documentFlavor === DocumentFlavor.TRADITIONAL;
-}
-
function _isOnlyFloatingCustomBlockParagraph(
viewModel: DocumentViewModel,
paragraphNode: DataStreamTreeNode,
@@ -316,9 +291,10 @@ function _getFollowingIndentedParagraphAnchorLeft(
viewModel: DocumentViewModel,
paragraph: IParagraph,
paragraphNode: DataStreamTreeNode,
- drawings: IDrawings
+ drawings: IDrawings,
+ isTraditionalDocument: boolean
): IParagraphStyle['indentStart'] | undefined {
- if (!_isTraditionalDoc(viewModel)) {
+ if (!isTraditionalDocument) {
return;
}
@@ -397,8 +373,10 @@ export function lineBreaking(
const paragraph = viewModel.getParagraph(endIndex) || { startIndex: 0, paragraphId: 'para_render_fallback' };
const { paragraphStyle = {}, bullet } = paragraph;
- const shouldApplyDocumentDefaults = _shouldApplyDocumentDefaultParagraphStyle(viewModel);
- const useWordStyleLineHeight = _shouldUseWordStyleLineHeight(viewModel);
+ const documentCompatibilityPolicy = sectionBreakConfig.documentCompatibilityPolicy ??
+ getDocumentCompatibilityPolicy(viewModel.getSnapshot?.()?.documentStyle.documentFlavor);
+ const shouldApplyDocumentDefaults = documentCompatibilityPolicy.applyDocumentDefaultParagraphStyle;
+ const useWordStyleLineHeight = documentCompatibilityPolicy.useWordStyleLineHeight;
const { skeHeaders, skeFooters, skeListLevel, drawingAnchor } = skeletonResourceReference;
@@ -416,13 +394,20 @@ export function lineBreaking(
const paragraphConfig: IParagraphConfig = {
paragraphIndex: endIndex,
+ documentCompatibilityPolicy,
paragraphStyle: _applyBlockRangeLayoutParagraphStyle(
viewModel.getBody?.() ?? null,
paragraph,
paragraphStyle,
shouldApplyDocumentDefaults
),
- docxFallbackAnchorLeft: _getFollowingIndentedParagraphAnchorLeft(viewModel, paragraph, paragraphNode, drawings),
+ docxFallbackAnchorLeft: _getFollowingIndentedParagraphAnchorLeft(
+ viewModel,
+ paragraph,
+ paragraphNode,
+ drawings,
+ isTraditionalDocumentCompatibility(documentCompatibilityPolicy)
+ ),
useWordStyleLineHeight,
paragraphNonInlineSkeDrawings,
paragraphInlineSkeDrawings,
@@ -534,10 +519,10 @@ export function lineBreaking(
isParagraphFirstShapedText = true;
shapedTextOffset += textGlyphCount;
continue;
- } else if (_endsWithToken(text, glyphs, DataStreamTreeTokenType.COLUMN_BREAK) && (
- viewModel.getDataModel().documentStyle.documentFlavor !== DocumentFlavor.TRADITIONAL ||
- _isMarkedDocxColumnBreak(viewModel, textEndIndex - 1)
- )) {
+ } else if (
+ _endsWithToken(text, glyphs, DataStreamTreeTokenType.COLUMN_BREAK) &&
+ (!isTraditionalDocumentCompatibility(documentCompatibilityPolicy) || _isMarkedDocxColumnBreak(viewModel, textEndIndex - 1))
+ ) {
pushPending();
// Column break mark, still within the same section
const lastPage = allPages[allPages.length - 1];
diff --git a/packages/engine-render/src/components/docs/layout/block/table.ts b/packages/engine-render/src/components/docs/layout/block/table.ts
index efb858d416..f4cf213914 100644
--- a/packages/engine-render/src/components/docs/layout/block/table.ts
+++ b/packages/engine-render/src/components/docs/layout/block/table.ts
@@ -26,6 +26,7 @@ import type { DataStreamTreeNode } from '../../view-model/data-stream-tree-node'
import type { DocumentViewModel } from '../../view-model/document-view-model';
import type { ILayoutContext } from '../tools';
import { BooleanNumber, TableAlignmentType, TableRowHeightRule, VerticalAlignmentType } from '@univerjs/core';
+import { getDocumentCompatibilityPolicy } from '../../document-compatibility';
import { createNullCellPage, createSkeletonCellPages } from '../model/page';
export function createTableSkeleton(
@@ -235,7 +236,9 @@ export function createTableSkeletons(
updateTableSkeletonsPosition(createCache, curPage, skeTables, table);
- const fromCurrentPage = skeTables[0].height <= availableHeight;
+ const documentCompatibilityPolicy = sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy();
+ const fromCurrentPage =
+ skeTables[0].height <= availableHeight + documentCompatibilityPolicy.table.currentPageOverflowTolerance;
return {
skeTables,
@@ -302,12 +305,13 @@ function dealWithTableRow(
) {
const pageContentHeight = getAvailableHeight(curPage, cache, false);
const availableHeight = getAvailableHeight(curPage, cache, true);
+ const documentCompatibilityPolicy = sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy();
const { children: cellNodes, startIndex, endIndex } = rowNode;
const rowSource = table.tableRows[row];
const { trHeight, cantSplit } = rowSource;
const rowSkeletons: IDocumentSkeletonRow[] = [];
const { hRule, val } = trHeight;
- const canRowSplit = cantSplit === BooleanNumber.TRUE && trHeight.hRule === TableRowHeightRule.AUTO;
+ const canRowSplit = cantSplit !== BooleanNumber.TRUE && trHeight.hRule === TableRowHeightRule.AUTO;
// If the remain height is less than 50 pixels, you can't fit the next line, so you can start typography directly from the second page.
const MAX_FONT_SIZE = 72;
const needOpenNewTable = cache.remainHeight <= MAX_FONT_SIZE;
@@ -345,7 +349,6 @@ function dealWithTableRow(
canRowSplit && !needOpenNewTable ? cache.remainHeight : availableHeight,
pageContentHeight
);
-
while (rowSkeletons.length < cellPageSkeletons.length) {
rowSkeletons.push(createNullRowSkeletonWithCells(
ctx,
@@ -421,8 +424,12 @@ function dealWithTableRow(
while (rowSkeletons.length > 0) {
const rowSkeleton = rowSkeletons.shift()!;
const lastRow = curTableSkeleton.rows[curTableSkeleton.rows.length - 1];
+ const rowOverflowHeight = rowSkeleton.height - cache.remainHeight;
+ const shouldOpenNewTable =
+ cache.remainHeight < MAX_FONT_SIZE ||
+ rowOverflowHeight > documentCompatibilityPolicy.table.rowOverflowTolerance;
- if (cache.remainHeight < MAX_FONT_SIZE || cache.remainHeight < rowSkeleton.height) {
+ if (shouldOpenNewTable) {
cache.remainHeight = getAvailableHeight(curPage, cache, row !== 0 && rowSkeleton.index !== lastRow.index);
cache.rowTop = 0;
diff --git a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
index 9f95006e52..0dd2eec96b 100644
--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
@@ -38,6 +38,7 @@ import { getDocsTableRenderViewport, hasDocsTableHorizontalViewport } from '../t
import { DocumentEditArea } from '../view-model/document-view-model';
import { dealWithSection } from './block/section';
import { getTableIdAndSliceIndex } from './block/table';
+import { getDocumentCompatibilityPolicy } from '../document-compatibility';
import { Hyphen } from './hyphenation/hyphen';
import { LanguageDetector } from './hyphenation/language-detector';
import { createSkeletonPage } from './model/page';
@@ -1059,6 +1060,7 @@ export class DocumentSkeleton extends Skeleton {
drawings,
localeService: this._localeService,
+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(documentStyle.documentFlavor),
paragraphLineGapDefault,
defaultTabStop,
documentTextStyle: textStyle,
diff --git a/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts b/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts
index a12b03f5a3..9b9bb26952 100644
--- a/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts
@@ -15,8 +15,10 @@
*/
import type { IDocumentSkeletonGlyph } from '../../../../../basics/i-document-skeleton-cached';
-import { describe, expect, it } from 'vitest';
-import { baseAdjustability, glyphShrinkLeft, glyphShrinkRight, isJustifiable, isSpace } from '../glyph';
+import { DocumentFlavor } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { getDocumentCompatibilityPolicy } from '../../../document-compatibility';
+import { baseAdjustability, createSkeletonLetterGlyph, glyphShrinkLeft, glyphShrinkRight, isJustifiable, isSpace } from '../glyph';
describe('Glyph utils test cases', () => {
describe('test baseAdjustability', () => {
@@ -133,4 +135,48 @@ describe('Glyph utils test cases', () => {
expect(glyph.xOffset).toBe(-5);
});
});
+
+ describe('test font compatibility policy', () => {
+ it('should apply traditional font metric width rules to letter glyphs only when enabled', () => {
+ vi.stubGlobal('document', {
+ createElement: () => ({
+ getContext: () => ({
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText: () => ({
+ width: 16,
+ fontBoundingBoxAscent: 30,
+ fontBoundingBoxDescent: 9,
+ actualBoundingBoxAscent: 30,
+ actualBoundingBoxDescent: 9,
+ }),
+ }),
+ }),
+ });
+ const config = {
+ fontStyle: {
+ fontString: 'normal bold 24pt "Calibri", Arial',
+ fontSize: 24,
+ originFontSize: 24,
+ fontFamily: '"Calibri", Arial',
+ fontCache: 'normal bold 24pt "Calibri"',
+ },
+ textStyle: {},
+ charSpace: 0,
+ snapToGrid: 0,
+ } as any;
+
+ const traditionalGlyph = createSkeletonLetterGlyph('5', {
+ ...config,
+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL),
+ });
+ const modernGlyph = createSkeletonLetterGlyph('5', {
+ ...config,
+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(DocumentFlavor.MODERN),
+ });
+
+ expect(traditionalGlyph.width).toBeCloseTo(14.72);
+ expect(modernGlyph.width).toBe(16);
+ });
+ });
});
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.ts
index a06fb9d7d0..2f29d0407d 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
@@ -191,7 +191,7 @@ describe('line model', () => {
expect(line.divides.every((divide) => divide.parent === line)).toBe(true);
});
- it('does not split line divides for behind-doc drawings', () => {
+ it('splits line divides for behind-doc drawings with wrap tight', () => {
const page = {
skeDrawings: new Map([
['behind', {
@@ -231,6 +231,51 @@ describe('line model', () => {
null
);
+ expect(line.divides).toHaveLength(1);
+ expect(line.divides[0].left).toBe(80);
+ expect(line.divides[0].width).toBe(20);
+ });
+
+ it('does not split line divides for behind-doc wrap-none drawings', () => {
+ const page = {
+ skeDrawings: new Map([
+ ['behind', {
+ aTop: 0,
+ aLeft: 0,
+ width: 80,
+ height: 20,
+ angle: 0,
+ drawingOrigin: {
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ 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);
diff --git a/packages/engine-render/src/components/docs/layout/model/glyph.ts b/packages/engine-render/src/components/docs/layout/model/glyph.ts
index d98d60d4aa..b56ad91fc5 100644
--- a/packages/engine-render/src/components/docs/layout/model/glyph.ts
+++ b/packages/engine-render/src/components/docs/layout/model/glyph.ts
@@ -35,6 +35,7 @@ import {
} from '../../../../basics/tools';
import { FontCache } from '../shaping-engine/font-cache';
import { validationGrid } from '../tools';
+import { applyFontMetricCompatibility, getDocumentCompatibilityPolicy } from '../../document-compatibility';
export function isSpace(char: string) {
const SPACE_CHARS = [' ', '\u{00A0}', ' '];
@@ -213,6 +214,12 @@ export function _createSkeletonWordOrLetter(
} else {
bBox = FontCache.getTextSize(content, fontStyle);
}
+ bBox = applyFontMetricCompatibility(
+ content,
+ fontStyle,
+ bBox,
+ config.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy()
+ );
const { width: contentWidth = 0 } = bBox;
let width = glyphWidth ?? contentWidth;
diff --git a/packages/engine-render/src/components/docs/layout/model/line.ts b/packages/engine-render/src/components/docs/layout/model/line.ts
index e5e69f3191..a7eabc617a 100644
--- a/packages/engine-render/src/components/docs/layout/model/line.ts
+++ b/packages/engine-render/src/components/docs/layout/model/line.ts
@@ -26,7 +26,7 @@ import type {
LineType,
} from '../../../../basics/i-document-skeleton-cached';
import type { IFloatObject } from '../tools';
-import { BooleanNumber, PositionedObjectLayoutType, TableTextWrapType, WrapTextType } from '@univerjs/core';
+import { PositionedObjectLayoutType, TableTextWrapType, WrapTextType } from '@univerjs/core';
import { Path2 } from '../../../../basics/path2';
import { Transform } from '../../../../basics/transform';
import { Vector2 } from '../../../../basics/vector2';
@@ -110,8 +110,7 @@ export function createSkeletonLine(
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
+ drawing.drawingOrigin.layoutType !== PositionedObjectLayoutType.WRAP_NONE
));
const wrapTypeTables = new Map(Array.from(pageSkeTables).filter(([_, table]) => table.tableSource.textWrap === TableTextWrapType.WRAP));
@@ -205,10 +204,9 @@ function _getLineTopWithFullColumnWrap(
}
const { aTop, height, aLeft, width, angle = 0, drawingOrigin } = drawing;
- const { layoutType, behindDoc, distL = 0, distT = 0, distB = 0, distR = 0, wrapText } = drawingOrigin;
+ const { layoutType, 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
@@ -274,9 +272,9 @@ function _getLineTopWidthWrapNone(table: IDocumentSkeletonTable, lineHeight: num
function _getLineTopWidthWrapTopBottom(drawing: IDocumentSkeletonDrawing, lineHeight: number, lineTop: number) {
const { aTop, height, aLeft, width, angle = 0, drawingOrigin } = drawing;
- const { layoutType, distT = 0, distB = 0, behindDoc } = drawingOrigin;
+ const { layoutType, distT = 0, distB = 0 } = drawingOrigin;
- if (layoutType !== PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM || behindDoc === BooleanNumber.TRUE) {
+ if (layoutType !== PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM) {
return;
}
@@ -417,10 +415,9 @@ function _calculateSplit(
columnWidth: number
): Nullable<IDrawingsSplit> {
const { aTop, height, aLeft, width, angle = 0, drawingOrigin } = drawing;
- const { layoutType, behindDoc } = drawingOrigin;
+ const { layoutType } = drawingOrigin;
if (
- behindDoc === BooleanNumber.TRUE ||
layoutType === PositionedObjectLayoutType.WRAP_NONE ||
layoutType === PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM
) {
diff --git a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts
index a2d147643d..09caa4347f 100644
--- a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts
@@ -139,6 +139,18 @@ describe('font cache', () => {
expect(byFont.ba).toBeCloseTo(9.6);
expect(byFont.abd).toBeCloseTo(1.8);
+ (FontCache as any)._context = {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText: vi.fn(() => ({
+ width: 12,
+ fontBoundingBoxAscent: 8,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 3,
+ })),
+ };
+
const byMeasure = FontCache.getTextSize('Z', {
fontString: '11px Other Font',
fontSize: 11,
diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.ts
index 0acb53ab4e..cebd93471e 100644
--- a/packages/engine-render/src/components/docs/layout/tools.ts
+++ b/packages/engine-render/src/components/docs/layout/tools.ts
@@ -26,6 +26,7 @@ import type {
ISectionBreak,
ITextStyle,
Nullable,
+ PositionedObjectLayoutType,
} from '@univerjs/core';
import type {
IDocumentSkeletonCached,
@@ -70,6 +71,7 @@ import {
import { DEFAULT_DOCUMENT_FONTSIZE } from '../../../basics/const';
import { GlyphType } from '../../../basics/i-document-skeleton-cached';
import { getFontStyleString, isFunction } from '../../../basics/tools';
+import { getDocumentCompatibilityPolicy } from '../document-compatibility';
import { updateInlineDrawingPosition } from './block/paragraph/layout-ruler';
import { getCustomDecorationStyle } from './style/custom-decoration';
import { getCustomRangeStyle } from './style/custom-range';
@@ -491,13 +493,19 @@ export function updateInlineDrawingCoordsAndBorder(ctx: ILayoutContext, pages: I
const paragraphConfig = ctx.paragraphConfigCache.get(segmentId)?.get(line.paragraphIndex);
const affectInlineDrawings = paragraphConfig?.paragraphInlineSkeDrawings;
+ const affectNonInlineDrawings = paragraphConfig?.paragraphNonInlineSkeDrawings;
const drawingAnchor = ctx.skeletonResourceReference?.drawingAnchor?.get(segmentId)?.get(line.paragraphIndex);
// Update inline drawings after the line is layout.
if (affectInlineDrawings && affectInlineDrawings.size > 0) {
- updateInlineDrawingPosition(line, affectInlineDrawings, drawingAnchor?.top);
+ updateInlineDrawingPosition(line, affectInlineDrawings, drawingAnchor?.top, affectNonInlineDrawings);
}
const paragraphStyle = paragraphConfig?.paragraphStyle;
+ const paragraphBackgroundColor = paragraphStyle?.shading?.backgroundColor;
+ if (paragraphBackgroundColor) {
+ line.backgroundColor = paragraphBackgroundColor;
+ }
+
if (line.divides.length > 0) {
const lastDivide = line.divides[line.divides.length - 1];
const lastGlyph = lastDivide.glyphGroup[lastDivide.glyphGroup.length - 1];
@@ -901,6 +909,7 @@ export function getFontCreateConfig(
charSpace,
gridType,
snapToGrid,
+ documentCompatibilityPolicy: sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy(),
pageWidth,
};
@@ -945,6 +954,7 @@ export interface IFloatObject {
height: number;
angle: number;
behindDoc?: BooleanNumber;
+ layoutType?: PositionedObjectLayoutType;
type: FloatObjectType;
positionV: IObjectPositionV;
}