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): respect layout fragment geometry (#7287)

Univer23029b582966
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/data-stream-change.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/data-stream-change.spec.ts
index c3e7f9d185..ec4a1fb0b3 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/data-stream-change.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/data-stream-change.spec.ts
@@ -46,6 +46,27 @@ describe('getSingleDataStreamChange', () => {
});
});
+ it('anchors a deleted block before an adjacent identical start sentinel', () => {
+ const T = DataStreamTreeTokenType;
+ const previousBody: IDocumentBody = {
+ dataStream: `${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_END}${T.BLOCK_START}B${T.PARAGRAPH}${T.BLOCK_END}`,
+ blockRanges: [
+ { blockId: 'code-1', blockType: DocumentBlockRangeType.CODE, startIndex: 0, endIndex: 3 },
+ { blockId: 'quote-1', blockType: DocumentBlockRangeType.QUOTE, startIndex: 4, endIndex: 7 },
+ ],
+ };
+ const nextBody: IDocumentBody = {
+ dataStream: `${T.BLOCK_START}B${T.PARAGRAPH}${T.BLOCK_END}`,
+ blockRanges: [{ blockId: 'quote-1', blockType: DocumentBlockRangeType.QUOTE, startIndex: 0, endIndex: 3 }],
+ };
+
+ expect(getSingleDataStreamChange(previousBody, nextBody)).toEqual({
+ start: 0,
+ deleteLength: 4,
+ insertLength: 0,
+ });
+ });
+
it('falls back to the minimal contiguous text change', () => {
expect(getSingleDataStreamChange(
{ dataStream: 'Alpha\r' },
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/data-stream-change.ts b/packages/core/src/docs/data-model/text-x/build-utils/data-stream-change.ts
index 3a3458f0ac..e7835feab1 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/data-stream-change.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/data-stream-change.ts
@@ -23,10 +23,10 @@ export interface IDataStreamChange {
}
/**
- * Finds one contiguous dataStream change. Pure structural insertions are
- * anchored by their new stable ids before falling back to string comparison.
+ * Finds one contiguous dataStream change. Pure structural insertions and deletions
+ * are anchored by their stable ids before falling back to string comparison.
* This prevents an adjacent identical sentinel from being mistaken for an
- * unchanged prefix and keeps the inserted structure metadata in the TextX body.
+ * unchanged prefix and keeps the structure metadata aligned with the TextX body.
*/
export function getSingleDataStreamChange(
previousBody: IDocumentBody | undefined,
@@ -54,6 +54,17 @@ export function getSingleDataStreamChange(
if (structuralInsertion) {
return structuralInsertion;
}
+ } else if (insertedLength < 0) {
+ const structuralDeletion = findStructuralDeletion(
+ previousBody,
+ nextBody,
+ previousDataStream,
+ nextDataStream,
+ -insertedLength
+ );
+ if (structuralDeletion) {
+ return structuralDeletion;
+ }
}
let start = 0;
@@ -83,6 +94,25 @@ export function getSingleDataStreamChange(
};
}
+function findStructuralDeletion(
+ previousBody: IDocumentBody,
+ nextBody: IDocumentBody,
+ previousDataStream: string,
+ nextDataStream: string,
+ deletedLength: number
+): IDataStreamChange | null {
+ for (const start of collectNewStructuralStartOffsets(nextBody, previousBody)) {
+ if (
+ previousDataStream.slice(0, start) === nextDataStream.slice(0, start) &&
+ previousDataStream.slice(start + deletedLength) === nextDataStream.slice(start)
+ ) {
+ return { start, deleteLength: deletedLength, insertLength: 0 };
+ }
+ }
+
+ return null;
+}
+
function findStructuralInsertion(
previousBody: IDocumentBody,
nextBody: IDocumentBody,
diff --git a/packages/core/src/types/interfaces/i-document-data-interceptor.ts b/packages/core/src/types/interfaces/i-document-data-interceptor.ts
index d21c94e177..7d414449f9 100644
--- a/packages/core/src/types/interfaces/i-document-data-interceptor.ts
+++ b/packages/core/src/types/interfaces/i-document-data-interceptor.ts
@@ -18,6 +18,8 @@ import type { ICustomDecoration, ICustomRange, IParagraph } from './i-document-d
export interface ICustomRangeForInterceptor extends ICustomRange {
active?: boolean;
+ glyphAscentEm?: number;
+ glyphDescentEm?: number;
glyphWidthEm?: number;
show?: boolean;
}
diff --git a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts
index 0e3ff62270..478f59e9d8 100644
--- a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts
+++ b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts
@@ -899,6 +899,7 @@ describe('docs drawing commands integration', () => {
skeFooters: new Map(),
}),
} as never);
+ const refreshDrawings = vi.spyOn(testBed.get(DocRefreshDrawingsService), 'refreshDrawings');
expect(await testBed.commandService.executeCommand(UpdateDocDrawingWrappingStyleCommand.id, {
unitId: 'test-doc',
@@ -923,6 +924,7 @@ describe('docs drawing commands integration', () => {
relativeFrom: ObjectRelativeFromV.PARAGRAPH,
posOffset: 5,
});
+ expect(refreshDrawings).toHaveBeenCalledWith(skeletonManager.getSkeleton());
testBed.univer.dispose();
});
@@ -1037,6 +1039,9 @@ describe('docs drawing commands integration', () => {
it('transforms a non-inline drawing and persists position, size and angle changes', async () => {
const testBed = setupDrawingTestBed(createDrawingDocData());
+ const skeleton = {} as never;
+ vi.spyOn(testBed.get(DocSkeletonManagerService), 'getSkeleton').mockReturnValue(skeleton);
+ const refreshDrawings = vi.spyOn(testBed.get(DocRefreshDrawingsService), 'refreshDrawings');
expect(await testBed.commandService.executeCommand(ITransformNonInlineDrawingCommand.id, {
unitId: 'test-doc',
@@ -1084,6 +1089,7 @@ describe('docs drawing commands integration', () => {
angle: 15,
});
expect(testBed.refreshControls).toHaveBeenCalled();
+ expect(refreshDrawings).toHaveBeenCalledWith(skeleton);
testBed.univer.dispose();
});
diff --git a/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.ts
index 0aa3303b53..e3540cceaf 100644
--- a/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.ts
+++ b/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.ts
@@ -459,7 +459,7 @@ export const ITransformNonInlineDrawingCommand: ICommand = {
const renderObject = renderManagerService.getRenderUnitById(unitId);
const scene = renderObject?.scene;
- if (scene == null || docSelectionRenderService == null) {
+ if (renderObject == null || scene == null || docSelectionRenderService == null) {
return false;
}
@@ -546,6 +546,8 @@ export const ITransformNonInlineDrawingCommand: ICommand = {
IRichTextEditingMutationParams
>(doMutation.id, doMutation.params);
+ const skeleton = renderObject.with(DocSkeletonManagerService).getSkeleton();
+ accessor.get(DocRefreshDrawingsService).refreshDrawings(skeleton);
transformer.refreshControls();
return Boolean(result);
diff --git a/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.ts b/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.ts
index 8ae49210c0..ce6f065216 100644
--- a/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.ts
+++ b/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.ts
@@ -505,7 +505,7 @@ export class DocDrawingTransformerController extends Disposable {
let glyphAnchor: Nullable<IDocumentSkeletonGlyph> = null;
let segmentId = '';
let segmentPage = -1;
- const isBack = false;
+ const isBack = true;
const docTransform = {
...drawing.docTransform,
size: {
@@ -546,6 +546,7 @@ export class DocDrawingTransformerController extends Disposable {
const line = glyphAnchor.parent?.parent;
const column = line?.parent;
+ const sectionTop = column?.parent?.top ?? 0;
const paragraphStartLine = column?.lines.find((l) => l.paragraphIndex === line?.paragraphIndex && l.paragraphStart) ?? column?.lines[0];
const page = column?.parent?.parent;
@@ -650,11 +651,11 @@ export class DocDrawingTransformerController extends Disposable {
break;
}
case ObjectRelativeFromV.LINE: {
- docTransform.positionV.posOffset = top - this._liquid.y - docsTop - line.top;
+ docTransform.positionV.posOffset = top - this._liquid.y - docsTop - sectionTop - line.top;
break;
}
case ObjectRelativeFromV.PARAGRAPH: {
- docTransform.positionV.posOffset = top - this._liquid.y - docsTop - paragraphStartLine.top;
+ docTransform.positionV.posOffset = top - this._liquid.y - docsTop - sectionTop - paragraphStartLine.top;
break;
}
}
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 8c870dbd84..ccc62fe1f3 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
@@ -172,6 +172,36 @@ describe('DocDrawingTransformUpdateController', () => {
docTransform: defaultDocTransform,
},
};
+ const pageRelativeDrawing = {
+ ...normalDrawing,
+ drawingId: 'page-relative-drawing',
+ drawingOrigin: {
+ ...normalDrawing.drawingOrigin,
+ docTransform: {
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 99 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 88 },
+ },
+ },
+ };
+ const squareDrawing = {
+ ...normalDrawing,
+ drawingId: 'square-drawing',
+ drawingOrigin: {
+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,
+ behindDoc: BooleanNumber.FALSE,
+ docTransform: pageRelativeDrawing.drawingOrigin.docTransform,
+ },
+ };
+ const topBottomDrawing = {
+ ...squareDrawing,
+ aLeft: 12,
+ aTop: 22,
+ drawingId: 'top-bottom-drawing',
+ drawingOrigin: {
+ ...squareDrawing.drawingOrigin,
+ layoutType: PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM,
+ },
+ };
const headerDrawing = {
aLeft: 3,
aTop: 4,
@@ -256,6 +286,9 @@ describe('DocDrawingTransformUpdateController', () => {
marginBottom: 17,
skeDrawings: new Map([
['normal-drawing', normalDrawing],
+ ['page-relative-drawing', pageRelativeDrawing],
+ ['square-drawing', squareDrawing],
+ ['top-bottom-drawing', topBottomDrawing],
['inline-drawing', inlineDrawing],
['multi-drawing', multiDrawingOnPage],
]),
@@ -289,6 +322,19 @@ describe('DocDrawingTransformUpdateController', () => {
behindText: true,
transform: expect.objectContaining({ left: 26, top: 40, width: 30, height: 40, angle: 5 }),
}),
+ expect.objectContaining({
+ drawingId: 'page-relative-drawing',
+ behindText: true,
+ transform: expect.objectContaining({ left: 104, top: 95, width: 30, height: 40, angle: 5 }),
+ }),
+ expect.objectContaining({
+ drawingId: 'square-drawing',
+ transform: expect.objectContaining({ left: 26, top: 40, width: 30, height: 40, angle: 5 }),
+ }),
+ expect.objectContaining({
+ drawingId: 'top-bottom-drawing',
+ transform: expect.objectContaining({ left: 28, top: 42, width: 30, height: 40, angle: 5 }),
+ }),
expect.objectContaining({
drawingId: 'inline-drawing',
transform: expect.objectContaining({ left: 31, top: 45, width: 35, height: 45, angle: 0 }),
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 9e728a22b2..fa57c0b24b 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
@@ -523,13 +523,13 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
clipOffsetTop: clipOffset?.top,
page: clipPage,
});
- const pageRelativeAnchorPage = drawingOrigin.layoutType === PositionedObjectLayoutType.INLINE
- ? undefined
- : getDocsPageRelativeDrawingAnchorPage({
+ const pageRelativeAnchorPage = drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_NONE
+ ? getDocsPageRelativeDrawingAnchorPage({
page,
clipPage,
hostPage,
- });
+ })
+ : undefined;
const pageRelativeLeft = pageRelativeAnchorPage != null
? getDocsPageRelativeDrawingLeft({
hostPage: pageRelativeAnchorPage,
diff --git a/packages/docs-ui/src/basics/paragraph.ts b/packages/docs-ui/src/basics/paragraph.ts
index b3ebab39a2..131031022f 100644
--- a/packages/docs-ui/src/basics/paragraph.ts
+++ b/packages/docs-ui/src/basics/paragraph.ts
@@ -15,6 +15,19 @@
*/
import type { ICustomDecoration, ICustomRange, ICustomTable, IDocumentBody, IParagraph, ITextRun, ITextStyle, Nullable } from '@univerjs/core';
+import { DataStreamTreeTokenType } from '@univerjs/core';
+
+export function isTopLevelStructuralGap(dataStream: string, offset: number): boolean {
+ const previousToken = dataStream[offset - 1];
+ const nextToken = dataStream[offset];
+
+ return previousToken === DataStreamTreeTokenType.BLOCK_END ||
+ previousToken === DataStreamTreeTokenType.TABLE_END ||
+ previousToken === DataStreamTreeTokenType.COLUMN_GROUP_END ||
+ nextToken === DataStreamTreeTokenType.BLOCK_START ||
+ nextToken === DataStreamTreeTokenType.TABLE_START ||
+ nextToken === DataStreamTreeTokenType.COLUMN_GROUP_START;
+}
export function hasParagraphInTable(paragraph: IParagraph, tables: ICustomTable[]) {
return tables.some((table) => paragraph.startIndex > table.startIndex && paragraph.startIndex < table.endIndex);
diff --git a/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts
index eaad8cc476..5fc44048b3 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts
@@ -53,6 +53,8 @@ class TestDocClipboardService {
readonly copies: Array<{ sliceType?: SliceBodyType; ranges?: ITextRangeWithStyle[] }> = [];
readonly cuts: Array<{ ranges?: ITextRangeWithStyle[] }> = [];
readonly pastes: ClipboardItem[][] = [];
+ memoryPasteResult = false;
+ memoryPastes = 0;
async copy(sliceType?: SliceBodyType, ranges?: ITextRangeWithStyle[]): Promise<boolean> {
this.copies.push({ sliceType, ranges });
@@ -64,7 +66,12 @@ class TestDocClipboardService {
return true;
}
- async paste(items: ClipboardItem[]): Promise<boolean> {
+ async paste(items?: ClipboardItem[]): Promise<boolean> {
+ if (!items?.length) {
+ this.memoryPastes++;
+ return this.memoryPasteResult;
+ }
+
this.pastes.push(items);
return true;
}
@@ -80,15 +87,20 @@ class TestDocClipboardService {
class TestClipboardInterfaceService {
items: ClipboardItem[] = [{ types: ['text/plain'] } as unknown as ClipboardItem];
+ supported = true;
+ reads = 0;
get supportClipboard(): boolean {
- return true;
+ return this.supported;
}
async writeText(): Promise<void> {}
async write(): Promise<void> {}
async readText(): Promise<string> { return ''; }
- async read(): Promise<ClipboardItem[]> { return this.items; }
+ async read(): Promise<ClipboardItem[]> {
+ this.reads++;
+ return this.items;
+ }
}
function getDocumentData() {
@@ -690,5 +702,16 @@ describe('test cases in clipboard', () => {
expect(docClipboardService.pastes).toEqual([clipboardInterfaceService.items]);
});
+
+ it('Should paste the internal copy when browser clipboard reads are unsupported', async () => {
+ const docClipboardService = get(IDocClipboardService) as unknown as TestDocClipboardService;
+ const clipboardInterfaceService = get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;
+ docClipboardService.memoryPasteResult = true;
+ clipboardInterfaceService.supported = false;
+
+ expect(await commandService.executeCommand(DocPasteCommand.id)).toBe(true);
+ expect(docClipboardService.memoryPastes).toBe(1);
+ expect(clipboardInterfaceService.reads).toBe(0);
+ });
});
});
diff --git a/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts
index 88f0bb44f8..4785dbf3b4 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts
@@ -567,9 +567,16 @@ describe('doc table create command helpers', () => {
const tableFixture = createTableFixture();
const tableTestBed = createTableCommandBed(tableFixture);
commandService = tableTestBed.get(ICommandService);
- setActiveTableRange(tableTestBed, tableFixture.cellRanges[4].startIndex + 1);
-
- expect(await commandService.executeCommand(DocTableDeleteTableCommand.id)).toBe(true);
+ setActiveTableRange(tableTestBed, tableFixture.tableRange.endIndex + 2);
+
+ expect(await commandService.executeCommand(DocTableDeleteTableCommand.id, {
+ targetRange: {
+ startOffset: tableFixture.tableRange.startIndex,
+ endOffset: tableFixture.tableRange.endIndex,
+ collapsed: false,
+ segmentId: '',
+ },
+ })).toBe(true);
await awaitTime(0);
expect(tableTestBed.doc.getBody()?.dataStream).toBe(TABLE_SUFFIX);
expect(testBedSnapshotTableIds(tableTestBed)).toEqual([]);
diff --git a/packages/docs-ui/src/commands/commands/break-line.command.ts b/packages/docs-ui/src/commands/commands/break-line.command.ts
index adcca70bae..80fc72a253 100644
--- a/packages/docs-ui/src/commands/commands/break-line.command.ts
+++ b/packages/docs-ui/src/commands/commands/break-line.command.ts
@@ -18,7 +18,7 @@ import type { DocumentDataModel, ICommand, IDocumentBody, IMutationInfo, IParagr
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import { BuildTextUtils, CommandType, DataStreamTreeTokenType, getRichTextEditPath, ICommandService, IUniverInstanceService, JSONX, PresetListType, TextX, TextXActionType, UniverInstanceType, UpdateDocsAttributeType } from '@univerjs/core';
import { DocSelectionManagerService, generateParagraphs, RichTextEditingMutation } from '@univerjs/docs';
-import { getTextRunAtPosition } from '../../basics/paragraph';
+import { getTextRunAtPosition, isTopLevelStructuralGap } from '../../basics/paragraph';
import { DocMenuStyleService } from '../../services/doc-menu-style.service';
export { generateParagraphs };
@@ -208,15 +208,3 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {
return Boolean(result);
},
};
-
-function isTopLevelStructuralGap(dataStream: string, offset: number): boolean {
- const previousToken = dataStream[offset - 1];
- const nextToken = dataStream[offset];
-
- return previousToken === DataStreamTreeTokenType.BLOCK_END ||
- previousToken === DataStreamTreeTokenType.TABLE_END ||
- previousToken === DataStreamTreeTokenType.COLUMN_GROUP_END ||
- nextToken === DataStreamTreeTokenType.BLOCK_START ||
- nextToken === DataStreamTreeTokenType.TABLE_START ||
- nextToken === DataStreamTreeTokenType.COLUMN_GROUP_START;
-}
diff --git a/packages/docs-ui/src/commands/commands/clipboard.command.ts b/packages/docs-ui/src/commands/commands/clipboard.command.ts
index 70e4387652..d5791accf2 100644
--- a/packages/docs-ui/src/commands/commands/clipboard.command.ts
+++ b/packages/docs-ui/src/commands/commands/clipboard.command.ts
@@ -111,10 +111,9 @@ export const DocPasteCommand: IMultiCommand = {
handler: async (accessor: IAccessor) => {
const docClipboardService = accessor.get(IDocClipboardService);
const clipboardInterfaceService = accessor.get(IClipboardInterfaceService);
- const clipboardItems = await clipboardInterfaceService.read();
- if (clipboardItems.length === 0) {
- return false;
- }
+ const clipboardItems = clipboardInterfaceService.supportClipboard
+ ? await clipboardInterfaceService.read()
+ : [];
return docClipboardService.paste(clipboardItems);
},
diff --git a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
index fb6d4f5699..509017b6a6 100644
--- a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
+++ b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
@@ -29,7 +29,7 @@ import type {
} from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { DocumentViewModel, IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';
-import type { IDocClipboardPasteCustomBlockMapping } from '../../services/clipboard/doc-paste-mutation-adapter.service';
+import type { IDocClipboardPasteBlockRangeMapping, IDocClipboardPasteCustomBlockMapping } from '../../services/clipboard/doc-paste-mutation-adapter.service';
import {
BuildTextUtils,
CommandType,
@@ -117,6 +117,7 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
const hasTable = !!body.tables?.length;
const hasCustomBlock = !!body.customBlocks?.length;
+ const hasBlockRange = !!body.blockRanges?.length;
// TODO: @JOCS A feature that has not yet been implemented,
// and it is currently not possible to paste tables in the header and footer.
@@ -142,6 +143,16 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
const len = startOffset - memoryCursor.cursor;
const cloneBody = Tools.deepClone(body);
+ const blockRangeMappings: IDocClipboardPasteBlockRangeMapping[] = [];
+ const customBlockMappings: IDocClipboardPasteCustomBlockMapping[] = [];
+
+ if (hasBlockRange) {
+ cloneBody.blockRanges!.forEach((targetBlockRange, index) => {
+ const sourceBlockRange = body.blockRanges![index];
+ targetBlockRange.blockId = generateRandomId(6);
+ blockRangeMappings.push({ sourceBlockRange, targetBlockRange });
+ });
+ }
if (hasTable) {
for (const t of cloneBody.tables!) {
@@ -161,7 +172,6 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
if (hasCustomBlock && drawings) {
const drawingLen = docDataModel.getSnapshot().drawingsOrder?.length ?? 0;
- const customBlockMappings: IDocClipboardPasteCustomBlockMapping[] = [];
for (const block of cloneBody.customBlocks!) {
const { blockId } = block;
@@ -182,23 +192,6 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
});
}
- if (customBlockMappings.length > 0 && pasteAdapterService) {
- const mutationInfos = pasteAdapterService.getPasteMutationInfos({
- unitId,
- segmentId,
- doc,
- sourceBody: body,
- targetBody: cloneBody,
- customBlockMappings,
- });
-
- if (mutationInfos.redoMutations.length > 0 || mutationInfos.undoMutations.length > 0) {
- resourceRedoMutations.push(...mutationInfos.redoMutations);
- resourceUndoMutations.push(...mutationInfos.undoMutations);
- resourceMutationGroups.push(mutationInfos);
- }
- }
-
customBlockMappings.forEach(({ targetBlockId, targetDrawing }) => {
const action = jsonX.insertOp(['drawings', targetBlockId], targetDrawing);
const orderAction = jsonX.insertOp(['drawingsOrder', drawingLen], targetBlockId);
@@ -208,6 +201,24 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
});
}
+ if ((blockRangeMappings.length > 0 || customBlockMappings.length > 0) && pasteAdapterService) {
+ const mutationInfos = pasteAdapterService.getPasteMutationInfos({
+ unitId,
+ segmentId,
+ doc,
+ sourceBody: body,
+ targetBody: cloneBody,
+ blockRangeMappings,
+ customBlockMappings,
+ });
+
+ if (mutationInfos.redoMutations.length > 0 || mutationInfos.undoMutations.length > 0) {
+ resourceRedoMutations.push(...mutationInfos.redoMutations);
+ resourceUndoMutations.push(...mutationInfos.undoMutations);
+ resourceMutationGroups.push(mutationInfos);
+ }
+ }
+
const customRange = getCustomRangeAtPosition(originBody.customRanges ?? [], endOffset, UNITS.includes(unitId));
const customDecorations = getCustomDecorationAtPosition(originBody.customDecorations ?? [], endOffset);
if (customRange) {
diff --git a/packages/docs-ui/src/commands/commands/table/doc-table-delete.command.ts b/packages/docs-ui/src/commands/commands/table/doc-table-delete.command.ts
index d2a10ee2bf..dda00d64e8 100644
--- a/packages/docs-ui/src/commands/commands/table/doc-table-delete.command.ts
+++ b/packages/docs-ui/src/commands/commands/table/doc-table-delete.command.ts
@@ -239,13 +239,15 @@ export const DocTableDeleteColumnsCommand: ICommand<IDocTableDeleteColumnsComman
},
};
-export interface IDocTableDeleteTableCommandParams {}
+export interface IDocTableDeleteTableCommandParams {
+ targetRange?: ITextRangeWithStyle;
+}
export const DocTableDeleteTableCommand: ICommand<IDocTableDeleteTableCommandParams> = {
id: 'doc.table.delete-table',
type: CommandType.COMMAND,
// eslint-disable-next-line max-lines-per-function
- handler: async (accessor) => {
+ handler: async (accessor, params) => {
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
@@ -253,7 +255,10 @@ export const DocTableDeleteTableCommand: ICommand<IDocTableDeleteTableCommandPar
const activeRectRanges = docSelectionManagerService.getRectRanges();
const activeTextRange = docSelectionManagerService.getActiveTextRange();
- const rangeInfo = getRangeInfoFromRanges(activeTextRange, activeRectRanges);
+ const rangeInfo = getRangeInfoFromRanges(
+ params?.targetRange ?? activeTextRange,
+ params?.targetRange ? [] : activeRectRanges
+ );
if (rangeInfo == null) {
return false;
diff --git a/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
index a54ac956c9..89c594750e 100644
--- a/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
@@ -295,6 +295,34 @@ describe('doc render controller', () => {
expect((context.components.get(DOCS_VIEW_KEY.BACKGROUND) as { width: number }).width).toBe(960);
});
+ it('keeps modern doc width anchored to page width when a floating drawing extends past the page', () => {
+ const { context, skeletonManager } = createControllerFixture({
+ documentFlavor: DocumentFlavor.MODERN,
+ pages: [{
+ pageWidth: 960,
+ pageHeight: Number.POSITIVE_INFINITY,
+ width: 826.6666666666667,
+ height: 640,
+ marginLeft: 66.66666666666667,
+ marginRight: 66.66666666666667,
+ marginTop: 72,
+ marginBottom: 72,
+ skeDrawings: new Map([['drawing-1', {
+ aLeft: 1051.6084250425697,
+ aTop: 82.39,
+ width: 160,
+ height: 96,
+ }]]),
+ skeTables: new Map(),
+ }],
+ });
+
+ skeletonManager.currentSkeletonBefore$.next(skeletonManager.getSkeleton());
+
+ expect(context.mainComponent?.width).toBe(960);
+ expect((context.components.get(DOCS_VIEW_KEY.BACKGROUND) as { width: number }).width).toBe(960);
+ });
+
it('keeps internal editor doc background transparent before the render config is registered', () => {
const { canvasElement, context, skeletonManager } = createControllerFixture({
documentFlavor: DocumentFlavor.UNSPECIFIED,
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
index ac82de6f3f..ae38f32c7c 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
@@ -361,15 +361,13 @@ function getPageSizeInModernMode(page: IDocumentSkeletonPage) {
pageHeight = page.height + marginTop + marginBottom;
}
+ // Keep the modern page horizontally anchored to its configured width.
+ // Overflow drawings and tables may extend its height, but must not recenter the document.
for (const drawing of skeDrawings.values()) {
- pageWidth = Math.max(pageWidth, drawing.aLeft + drawing.width + marginLeft + marginRight);
pageHeight = Math.max(pageHeight, drawing.aTop + drawing.height + marginTop + marginBottom);
}
for (const table of skeTables.values()) {
- // Keep the modern document page anchored to its configured width. Tables
- // may render beyond the text column, but they should not widen the whole
- // document and recenter the page during column resize.
pageHeight = Math.max(pageHeight, table.top + table.height + marginTop + marginBottom);
}
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index 2f8646e13b..3c69e337a1 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -193,12 +193,14 @@ export { menuSchema as DocsUIMenuSchema } from './menu/schema';
export { UniverDocsUIPlugin } from './plugin';
export * from './services';
export { IDocClipboardService } from './services/clipboard/clipboard.service';
+export type { IDocClipboardHook } from './services/clipboard/clipboard.service';
export {
DocClipboardPasteAdapterService,
IDocClipboardPasteAdapterService,
} from './services/clipboard/doc-paste-mutation-adapter.service';
export type {
IDocClipboardPasteAdapter,
+ IDocClipboardPasteBlockRangeMapping,
IDocClipboardPasteCustomBlockMapping,
IDocClipboardPasteMutationInfoParams,
IDocClipboardPasteMutationInfos,
diff --git a/packages/docs-ui/src/menu/menu.ts b/packages/docs-ui/src/menu/menu.ts
index 2366e09b12..e5a13cf877 100644
--- a/packages/docs-ui/src/menu/menu.ts
+++ b/packages/docs-ui/src/menu/menu.ts
@@ -54,7 +54,7 @@ import {
HEADING_LIST,
MenuItemType,
} from '@univerjs/ui';
-import { combineLatest, map, Observable } from 'rxjs';
+import { combineLatest, distinctUntilChanged, map, Observable, shareReplay } from 'rxjs';
import { OpenHeaderFooterPanelCommand } from '../commands/commands/doc-header-footer.command';
import { HorizontalLineCommand } from '../commands/commands/doc-horizontal-line.command';
import {
@@ -1240,7 +1240,10 @@ export function AlignMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<Loc
calc();
return disposable.dispose;
- });
+ }).pipe(
+ distinctUntilChanged(),
+ shareReplay({ bufferSize: 1, refCount: true })
+ );
return {
id: AlignOperationCommand.id,
diff --git a/packages/docs-ui/src/menu/schema.ts b/packages/docs-ui/src/menu/schema.ts
index 0a97543197..31768e1af1 100644
--- a/packages/docs-ui/src/menu/schema.ts
+++ b/packages/docs-ui/src/menu/schema.ts
@@ -681,6 +681,13 @@ export const menuSchema: MenuSchemaType = {
menuItemFactory: InsertDefaultTableMenuFactory,
},
},
+ format: {
+ order: 3,
+ [DocPasteCommand.id]: {
+ order: 0,
+ menuItemFactory: PasteMenuFactory,
+ },
+ },
},
[DOC_PARAGRAPH_T_INSERT_BELOW_MENU_ID]: {
quickTop: {
@@ -809,8 +816,12 @@ export const menuSchema: MenuSchemaType = {
order: 1,
menuItemFactory: CopyCurrentParagraphMenuItemFactory,
},
- [DeleteCurrentParagraphCommand.id]: {
+ [DocPasteCommand.id]: {
order: 2,
+ menuItemFactory: PasteMenuFactory,
+ },
+ [DeleteCurrentParagraphCommand.id]: {
+ order: 3,
menuItemFactory: DeleteCurrentParagraphMenuItemFactory,
},
},
diff --git a/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts
index 1f7ce9a979..71784c57ab 100644
--- a/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts
@@ -24,6 +24,7 @@ import {
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
DocumentBlockRangeType,
DocumentDataModel,
+ FOCUSING_COMMON_DRAWINGS,
ICommandService,
IConfigService,
IContextService,
@@ -322,6 +323,82 @@ describe('DocFloatMenuService', () => {
expect(popupService.ranges).toEqual([]);
});
+ it('does not show the text toolbar while a drawing is focused', () => {
+ const unitId = 'doc-drawing-menu';
+ const { injector, popupService, selectionManager, service } = createActiveFloatMenuHarness(unitId, {
+ dataStream: 'Drawing anchor\r\n',
+ paragraphs: [{ paragraphId: 'para_docs_ui_float_menu_drawing', startIndex: 14 }],
+ sectionBreaks: [],
+ customRanges: [],
+ tables: [],
+ textRuns: [],
+ });
+ injector.get(IContextService).setContextValue(FOCUSING_COMMON_DRAWINGS, true);
+
+ selectionManager.__replaceTextRangesWithNoRefresh({
+ textRanges: [{
+ startOffset: 0,
+ endOffset: 1,
+ collapsed: false,
+ }],
+ rectRanges: [],
+ segmentId: '',
+ segmentPage: -1,
+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ isEditing: true,
+ }, { unitId, subUnitId: unitId });
+
+ expect(service.floatMenu).toBeNull();
+ expect(popupService.ranges).toEqual([]);
+ });
+
+ it('hides and suppresses the text toolbar while another floating menu is active', () => {
+ const unitId = 'doc-suppressed-menu';
+ const { popupService, selectionManager, service } = createActiveFloatMenuHarness(unitId, {
+ dataStream: 'Suppressed menu\r\n',
+ paragraphs: [{ paragraphId: 'para_docs_ui_float_menu_suppressed', startIndex: 15 }],
+ sectionBreaks: [],
+ customRanges: [],
+ tables: [],
+ textRuns: [],
+ });
+ selectionManager.__replaceTextRangesWithNoRefresh({
+ textRanges: [{
+ startOffset: 0,
+ endOffset: 10,
+ collapsed: false,
+ }],
+ rectRanges: [],
+ segmentId: '',
+ segmentPage: -1,
+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ isEditing: true,
+ }, { unitId, subUnitId: unitId });
+
+ expect(service.floatMenu).toMatchObject({ start: 0, end: 10 });
+
+ service.setSuppressed(true);
+
+ expect(service.floatMenu).toBeNull();
+ expect(popupService.disposedCount).toBe(1);
+
+ selectionManager.__replaceTextRangesWithNoRefresh({
+ textRanges: [{
+ startOffset: 1,
+ endOffset: 10,
+ collapsed: false,
+ }],
+ rectRanges: [],
+ segmentId: '',
+ segmentPage: -1,
+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ isEditing: true,
+ }, { unitId, subUnitId: unitId });
+
+ expect(service.floatMenu).toBeNull();
+ expect(popupService.ranges).toEqual(['0:10']);
+ });
+
it('places the floating toolbar below a forward selection that spans multiple lines', () => {
const unitId = 'doc-direction-menu';
const { popupService, selectionManager, service } = createActiveFloatMenuHarness(unitId, {
diff --git a/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts b/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts
index b34e061591..237ce8af94 100644
--- a/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts
+++ b/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts
@@ -20,9 +20,11 @@ import {
BooleanNumber,
DataStreamTreeTokenType,
DOC_RANGE_TYPE,
+ DocumentBlockRangeType,
ICommandService,
ImageSourceType,
IUniverInstanceService,
+ SliceBodyType,
UniverInstanceType,
} from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
@@ -53,6 +55,12 @@ class TestClipboardInterfaceService {
async read(): Promise<ClipboardItem[]> { return []; }
}
+class RejectingClipboardInterfaceService extends TestClipboardInterfaceService {
+ override async write(): Promise<void> {
+ throw new Error('clipboard write failed');
+ }
+}
+
describe('DocClipboardService table copy helpers', () => {
it('should keep table metadata when copying an entire selected docs table', () => {
const tokens = DataStreamTreeTokenType;
@@ -179,6 +187,37 @@ describe('DocClipboardService table copy helpers', () => {
testBed.univer.dispose();
});
+ it('returns false when writing copied content to the clipboard fails', async () => {
+ const documentData: IDocumentData = {
+ id: 'failed-copy-doc',
+ body: {
+ dataStream: 'Alpha\r\n',
+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_failed_copy', startIndex: 5 }],
+ sectionBreaks: [],
+ customBlocks: [],
+ textRuns: [],
+ },
+ documentStyle: {},
+ };
+ const testBed = createCommandTestBed(documentData, [
+ [IClipboardInterfaceService, { useClass: RejectingClipboardInterfaceService }],
+ [IDocClipboardService, { useClass: DocClipboardService }],
+ ]);
+ const selectionManager = testBed.get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'failed-copy-doc', subUnitId: '' });
+ selectionManager.__TEST_ONLY_add([{
+ startOffset: 0,
+ endOffset: 5,
+ collapsed: false,
+ isActive: true,
+ segmentId: '',
+ }]);
+
+ expect(await testBed.get(IDocClipboardService).copy()).toBe(false);
+
+ testBed.univer.dispose();
+ });
+
it('copies multiple selected text ranges in document order', async () => {
const documentData: IDocumentData = {
id: 'multi-copy-doc',
@@ -346,6 +385,118 @@ describe('DocClipboardService table copy helpers', () => {
testBed.univer.dispose();
});
+ it('keeps plain text pasted after a block range separate from the following paragraph', async () => {
+ const tokens = DataStreamTreeTokenType;
+ const blockStream = `${tokens.BLOCK_START}Callout${tokens.PARAGRAPH}${tokens.BLOCK_END}`;
+ const documentData: IDocumentData = {
+ id: 'block-boundary-paste-doc',
+ body: {
+ dataStream: `${blockStream}Quote${tokens.PARAGRAPH}${tokens.SECTION_BREAK}`,
+ paragraphs: [
+ { paragraphId: 'para_docs_ui_clipboard_fixture_block', startIndex: blockStream.length - 2 },
+ { paragraphId: 'para_docs_ui_clipboard_fixture_quote', startIndex: blockStream.length + 5 },
+ ],
+ blockRanges: [{
+ blockId: 'callout-1',
+ blockType: DocumentBlockRangeType.CALLOUT,
+ startIndex: 0,
+ endIndex: blockStream.length - 1,
+ }],
+ sectionBreaks: [],
+ customBlocks: [],
+ textRuns: [],
+ },
+ documentStyle: {},
+ };
+ const testBed = createCommandTestBed(documentData, [
+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],
+ [IDocClipboardService, { useClass: DocClipboardService }],
+ ]);
+ const commandService = testBed.get(ICommandService);
+ commandService.registerCommand(InnerPasteCommand);
+ commandService.registerCommand(RichTextEditingMutation);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ const selectionManager = testBed.get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'block-boundary-paste-doc', subUnitId: '' });
+ selectionManager.__TEST_ONLY_add([{
+ startOffset: blockStream.length,
+ endOffset: blockStream.length,
+ collapsed: true,
+ isActive: true,
+ segmentId: '',
+ }]);
+
+ expect(await testBed.get(IDocClipboardService).legacyPaste({ text: 'Pasted', files: [] })).toBe(true);
+
+ const documentModel = testBed.get(IUniverInstanceService).getUnit<DocumentDataModel>('block-boundary-paste-doc', UniverInstanceType.UNIVER_DOC)!;
+ expect(documentModel.getBody()?.dataStream).toBe(`${blockStream}Pasted${tokens.PARAGRAPH}Quote${tokens.PARAGRAPH}${tokens.SECTION_BREAK}`);
+
+ testBed.univer.dispose();
+ });
+
+ it('copies and pastes a complete block range after itself', async () => {
+ const tokens = DataStreamTreeTokenType;
+ const blockStream = `${tokens.BLOCK_START}Callout${tokens.PARAGRAPH}${tokens.BLOCK_END}`;
+ const clipboard = new TestClipboardInterfaceService();
+ const documentData: IDocumentData = {
+ id: 'block-copy-paste-doc',
+ body: {
+ dataStream: `${blockStream}After${tokens.PARAGRAPH}${tokens.SECTION_BREAK}`,
+ paragraphs: [
+ { paragraphId: 'para_docs_ui_clipboard_fixture_source_block', startIndex: blockStream.length - 2 },
+ { paragraphId: 'para_docs_ui_clipboard_fixture_after_block', startIndex: blockStream.length + 5 },
+ ],
+ blockRanges: [{
+ blockId: 'callout-1',
+ blockType: DocumentBlockRangeType.CALLOUT,
+ startIndex: 0,
+ endIndex: blockStream.length - 1,
+ }],
+ sectionBreaks: [],
+ customBlocks: [],
+ textRuns: [],
+ },
+ documentStyle: {},
+ };
+ const testBed = createCommandTestBed(documentData, [
+ [IClipboardInterfaceService, { useValue: clipboard }],
+ [IDocClipboardService, { useClass: DocClipboardService }],
+ ]);
+ const commandService = testBed.get(ICommandService);
+ commandService.registerCommand(InnerPasteCommand);
+ commandService.registerCommand(RichTextEditingMutation);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ const selectionManager = testBed.get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'block-copy-paste-doc', subUnitId: '' });
+ const service = testBed.get(IDocClipboardService);
+
+ expect(await service.copy(SliceBodyType.copy, [{
+ startOffset: 0,
+ endOffset: blockStream.length,
+ collapsed: false,
+ segmentId: '',
+ }])).toBe(true);
+
+ selectionManager.__TEST_ONLY_add([{
+ startOffset: blockStream.length,
+ endOffset: blockStream.length,
+ collapsed: true,
+ isActive: true,
+ segmentId: '',
+ }]);
+
+ expect(await service.paste()).toBe(true);
+
+ const documentModel = testBed.get(IUniverInstanceService).getUnit<DocumentDataModel>('block-copy-paste-doc', UniverInstanceType.UNIVER_DOC)!;
+ expect(documentModel.getBody()?.dataStream).toBe(`${blockStream}${blockStream}After${tokens.PARAGRAPH}${tokens.SECTION_BREAK}`);
+ const blockRanges = documentModel.getBody()?.blockRanges ?? [];
+ expect(blockRanges).toHaveLength(2);
+ expect(blockRanges[0].blockId).toBe('callout-1');
+ expect(blockRanges[1].blockId).not.toBe('callout-1');
+
+ testBed.univer.dispose();
+ });
+
it('pastes Univer internal clipboard data with document styles preserved', async () => {
const documentData: IDocumentData = {
id: 'internal-paste-doc',
diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
index b9714e39ad..fa087bed79 100644
--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
@@ -20,6 +20,7 @@ import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-
import {
BuildTextUtils,
createIdentifier,
+ createParagraphId,
DataStreamTreeTokenType,
Disposable,
DOC_RANGE_TYPE,
@@ -38,6 +39,7 @@ import {
PositionedObjectLayoutType,
SliceBodyType,
toDisposable,
+ Tools,
UniverInstanceType,
} from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
@@ -50,6 +52,7 @@ import {
IClipboardInterfaceService,
PLAIN_TEXT_CLIPBOARD_MIME_TYPE,
} from '@univerjs/ui';
+import { isTopLevelStructuralGap } from '../../basics/paragraph';
import { CutContentCommand, InnerPasteCommand } from '../../commands/commands/clipboard.inner.command';
import { getCursorWhenDelete } from '../../commands/commands/doc-delete.command';
import { copyContentCache, extractId } from './copy-content-cache';
@@ -91,7 +94,7 @@ export interface IDocClipboardHook {
export interface IDocClipboardService {
copy(sliceType?: SliceBodyType, ranges?: ITextRangeWithStyle[]): Promise<boolean>;
cut(ranges?: ITextRangeWithStyle[]): Promise<boolean>;
- paste(items: ClipboardItem[]): Promise<boolean>;
+ paste(items?: ClipboardItem[]): Promise<boolean>;
legacyPaste(options: { html?: string; text?: string; internalJson?: string; files: File[] }): Promise<boolean>;
addClipboardHook(hook: IDocClipboardHook): IDisposable;
}
@@ -149,6 +152,7 @@ export const IDocClipboardService = createIdentifier<IDocClipboardService>('doc.
export class DocClipboardService extends Disposable implements IDocClipboardService {
private _clipboardHooks: IDocClipboardHook[] = [];
+ private _memoryClipboardData: Partial<IDocumentData> | null = null;
private _htmlToUDM = new HtmlToUDMService();
private readonly _umdToHtml: UDMToHtmlService;
@@ -175,7 +179,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
try {
const isCopyInHeaderFooter = !!allRanges?.[0]?.segmentId;
- this._setClipboardData(newSnapshotList, !isCopyInHeaderFooter && needCache);
+ await this._setClipboardData(newSnapshotList, !isCopyInHeaderFooter && needCache);
} catch (e) {
this._logService.error('[DocClipboardService] copy failed', e);
return false;
@@ -188,7 +192,11 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
return this._cut(ranges);
}
- async paste(items: ClipboardItem[]): Promise<boolean> {
+ async paste(items?: ClipboardItem[]): Promise<boolean> {
+ if (!items?.length) {
+ return this._memoryClipboardData ? this._paste(Tools.deepClone(this._memoryClipboardData)) : false;
+ }
+
const partDocData = await this._genDocDataFromClipboardItems(items);
return this._paste(partDocData);
@@ -295,8 +303,8 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
let body = normalizeBody(_body);
- const unitId = this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC)?.getUnitId();
- if (!unitId) {
+ const currentDocument = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ if (!currentDocument) {
return false;
}
@@ -327,6 +335,11 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
return false;
}
+ const originBody = segmentId == null ? null : currentDocument.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+ if (originBody) {
+ ensureParagraphAtStructuralGap(body, originBody, ranges);
+ }
+
try {
// When doc has multiple selections, the cursor moves to the last pasted content's end.
let cursor = activeEndOffset;
@@ -406,7 +419,8 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
html = wrapClipboardHtml(html);
- return this._clipboardInterfaceService.write(text, html, internalJson ? { [DOC_INTERNAL_FRAGMENT_MIME]: internalJson } : undefined);
+ await this._clipboardInterfaceService.write(text, html, internalJson ? { [DOC_INTERNAL_FRAGMENT_MIME]: internalJson } : undefined);
+ this._memoryClipboardData = Tools.deepClone(internalDocData);
}
addClipboardHook(hook: IDocClipboardHook): IDisposable {
@@ -681,6 +695,33 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
}
}
+function endsAtDocumentBoundary(dataStream: string): boolean {
+ const lastToken = dataStream[dataStream.length - 1];
+
+ return lastToken === DataStreamTreeTokenType.PARAGRAPH ||
+ lastToken === DataStreamTreeTokenType.SECTION_BREAK ||
+ lastToken === DataStreamTreeTokenType.BLOCK_END ||
+ lastToken === DataStreamTreeTokenType.TABLE_END ||
+ lastToken === DataStreamTreeTokenType.COLUMN_GROUP_END;
+}
+
+function ensureParagraphAtStructuralGap(body: IDocumentBody, originBody: IDocumentBody, ranges: readonly ITextRangeWithStyle[]): void {
+ if (
+ endsAtDocumentBoundary(body.dataStream) ||
+ !ranges.every((range) => range.collapsed && isTopLevelStructuralGap(originBody.dataStream, range.startOffset))
+ ) {
+ return;
+ }
+
+ const paragraphIndex = body.dataStream.length;
+ const paragraphIds = new Set(body.paragraphs?.map((paragraph) => paragraph.paragraphId) ?? []);
+ body.dataStream += DataStreamTreeTokenType.PARAGRAPH;
+ body.paragraphs = [
+ ...(body.paragraphs ?? []),
+ { startIndex: paragraphIndex, paragraphId: createParagraphId(paragraphIds) },
+ ];
+}
+
function dataUrlToFile(dataUrl: string, fallbackName: string): File {
const match = /^data:([^;,]+)(;base64)?,(.*)$/i.exec(dataUrl);
if (!match) {
diff --git a/packages/docs-ui/src/services/clipboard/doc-paste-mutation-adapter.service.ts b/packages/docs-ui/src/services/clipboard/doc-paste-mutation-adapter.service.ts
index 8c531f6cc1..60f7b06d7a 100644
--- a/packages/docs-ui/src/services/clipboard/doc-paste-mutation-adapter.service.ts
+++ b/packages/docs-ui/src/services/clipboard/doc-paste-mutation-adapter.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IDisposable, IDocumentBody, IDocumentData, IDrawingParam, IMutationInfo } from '@univerjs/core';
+import type { IDisposable, IDocumentBlockRange, IDocumentBody, IDocumentData, IDrawingParam, IMutationInfo } from '@univerjs/core';
import { createIdentifier, toDisposable } from '@univerjs/core';
export interface IDocClipboardPasteCustomBlockMapping {
@@ -24,12 +24,18 @@ export interface IDocClipboardPasteCustomBlockMapping {
targetDrawing: IDrawingParam;
}
+export interface IDocClipboardPasteBlockRangeMapping {
+ sourceBlockRange: IDocumentBlockRange;
+ targetBlockRange: IDocumentBlockRange;
+}
+
export interface IDocClipboardPasteMutationInfoParams {
unitId: string;
segmentId: string;
doc: Partial<IDocumentData>;
sourceBody: IDocumentBody;
targetBody: IDocumentBody;
+ blockRangeMappings: IDocClipboardPasteBlockRangeMapping[];
customBlockMappings: IDocClipboardPasteCustomBlockMapping[];
}
diff --git a/packages/docs-ui/src/services/float-menu.service.ts b/packages/docs-ui/src/services/float-menu.service.ts
index 8e10323518..13e277eeb7 100644
--- a/packages/docs-ui/src/services/float-menu.service.ts
+++ b/packages/docs-ui/src/services/float-menu.service.ts
@@ -21,6 +21,8 @@ import {
deepCompare,
Disposable,
DocumentBlockRangeType,
+ FOCUSING_COMMON_DRAWINGS,
+ IContextService,
Inject,
isInternalEditorID,
IUniverInstanceService,
@@ -49,13 +51,15 @@ const SKIP_SYMBOLS: string[] = [
export class DocFloatMenuService extends Disposable implements IRenderModule {
private _floatMenu: Nullable<{ disposable: IDisposable; start: number; end: number }> = null;
+ private _suppressed = false;
constructor(
private _context: IRenderContext<DocumentDataModel>,
@Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService,
@Inject(DocCanvasPopManagerService) private readonly _docCanvasPopManagerService: DocCanvasPopManagerService,
@Inject(IUniverInstanceService) private readonly _univerInstanceService: IUniverInstanceService,
- @Inject(DocSelectionRenderService) private readonly _docSelectionRenderService: DocSelectionRenderService
+ @Inject(DocSelectionRenderService) private readonly _docSelectionRenderService: DocSelectionRenderService,
+ @IContextService private readonly _contextService: IContextService
) {
super();
@@ -77,6 +81,17 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {
this._hideFloatMenu();
}
+ setSuppressed(suppressed: boolean): void {
+ if (this._suppressed === suppressed) {
+ return;
+ }
+
+ this._suppressed = suppressed;
+ if (suppressed) {
+ this._hideFloatMenu();
+ }
+ }
+
private _initSelectionChange() {
this.disposeWithMe(this._docSelectionRenderService.onSelectionStart$.subscribe(() => {
this._hideFloatMenu();
@@ -88,6 +103,11 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {
return;
}
+ if (this._suppressed || this._contextService.getContextValue(FOCUSING_COMMON_DRAWINGS)) {
+ this._hideFloatMenu();
+ return;
+ }
+
const range = (textRanges.length > 0) && textRanges.find((range) => !range.collapsed);
if (range) {
if (range.startOffset === this._floatMenu?.start && range.endOffset === this._floatMenu?.end) {
diff --git a/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts b/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts
index 76f3a62c6f..aeb314242d 100644
--- a/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts
+++ b/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts
@@ -15,7 +15,7 @@
*/
import type { INodePosition } from '@univerjs/engine-render';
-import { DataStreamTreeTokenType } from '@univerjs/core';
+import { DataStreamTreeTokenType, PositionedObjectLayoutType } from '@univerjs/core';
import { DocumentSkeletonPageType, setDocsTableRenderViewportProvider } from '@univerjs/engine-render';
import { afterEach, describe, expect, it } from 'vitest';
import {
@@ -648,9 +648,51 @@ describe('selection convert text range helpers', () => {
expect(result.borderBoxPointGroup).toHaveLength(0);
expect(result.contentBoxPointGroup).toHaveLength(0);
});
+
+ it('does not draw text selection rectangles for floating drawings', () => {
+ const { position, skeleton } = createEmbedCustomBlockCursorHarness({
+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,
+ });
+ const convertor = new NodePositionConvertToCursor({
+ docsLeft: 0,
+ docsTop: 0,
+ pageLayoutType: 0,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ } as never, skeleton as never);
+
+ const result = convertor.getRangePointData(
+ { ...position, isBack: true },
+ { ...position, isBack: false }
+ );
+
+ expect(result.borderBoxPointGroup).toHaveLength(0);
+ expect(result.contentBoxPointGroup).toHaveLength(0);
+ });
+
+ it('keeps text selection rectangles for inline drawings', () => {
+ const { position, skeleton } = createEmbedCustomBlockCursorHarness({
+ layoutType: PositionedObjectLayoutType.INLINE,
+ });
+ const convertor = new NodePositionConvertToCursor({
+ docsLeft: 0,
+ docsTop: 0,
+ pageLayoutType: 0,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ } as never, skeleton as never);
+
+ const result = convertor.getRangePointData(
+ { ...position, isBack: true },
+ { ...position, isBack: false }
+ );
+
+ expect(result.borderBoxPointGroup).toHaveLength(1);
+ expect(result.contentBoxPointGroup).toHaveLength(1);
+ });
});
-function createEmbedCustomBlockCursorHarness() {
+function createEmbedCustomBlockCursorHarness(drawing?: Record<string, unknown>) {
const drawingId = 'embed-block-1';
const glyph = {
bBox: { ba: 480, bd: 0 },
@@ -702,12 +744,14 @@ function createEmbedCustomBlockCursorHarness() {
getSnapshot: () => ({
drawings: {
[drawingId]: {
- data: {
- version: 1,
- embedId: 'embed-1',
- hostAnchorId: drawingId,
- interactionMode: 'block',
- },
+ ...(drawing ?? {
+ data: {
+ version: 1,
+ embedId: 'embed-1',
+ hostAnchorId: drawingId,
+ interactionMode: 'block',
+ },
+ }),
},
},
}),
diff --git a/packages/docs-ui/src/services/selection/convert-text-range.ts b/packages/docs-ui/src/services/selection/convert-text-range.ts
index 9e5369e21d..6be0cfc881 100644
--- a/packages/docs-ui/src/services/selection/convert-text-range.ts
+++ b/packages/docs-ui/src/services/selection/convert-text-range.ts
@@ -29,7 +29,7 @@ import type {
INodePosition,
IPoint,
} from '@univerjs/engine-render';
-import { DataStreamTreeTokenType } from '@univerjs/core';
+import { DataStreamTreeTokenType, PositionedObjectLayoutType } from '@univerjs/core';
import { shouldUseInlineTextSelectionForDocsCustomBlockDrawing } from '@univerjs/docs';
import {
compareDocumentSkeletonNestedPagePathOrder,
@@ -317,9 +317,9 @@ export class NodePositionConvertToCursor {
const rawAnchorGlyph = isStartBack ? (preGlyph ?? firstGlyph) : firstGlyph;
const anchorGlyph = this._getCaretGlyph(rawAnchorGlyph, glyphGroup, start_sp);
const selectedGlyphs = glyphGroup.slice(start_sp, end_sp + 1);
- const isSelectionOnlyNonInlineEmbedBlock = !collapsed &&
+ const isSelectionOnlyNonInlineDrawing = !collapsed &&
selectedGlyphs.length > 0 &&
- selectedGlyphs.every((glyph) => this._isNonInlineEmbedCustomBlockGlyph(glyph));
+ selectedGlyphs.every((glyph) => this._isNonInlineDrawingGlyph(glyph));
const borderBoxStartY = startY;
const borderBoxEndY = contentHeight == null
? startY + lineHeight - marginTop - marginBottom
@@ -360,10 +360,10 @@ export class NodePositionConvertToCursor {
const clippedBorderBoxPosition = clipPositionToHorizontalRange(borderBoxPosition, this._horizontalClip);
const clippedContentBoxPosition = clipPositionToHorizontalRange(contentBoxPosition, this._horizontalClip);
- if (clippedBorderBoxPosition && !isSelectionOnlyNonInlineEmbedBlock) {
+ if (clippedBorderBoxPosition && !isSelectionOnlyNonInlineDrawing) {
borderBoxPointGroup.push(pushToPoints(clippedBorderBoxPosition));
}
- if (clippedContentBoxPosition && !isSelectionOnlyNonInlineEmbedBlock) {
+ if (clippedContentBoxPosition && !isSelectionOnlyNonInlineDrawing) {
contentBoxPointGroup.push(pushToPoints(clippedContentBoxPosition));
}
@@ -386,7 +386,7 @@ export class NodePositionConvertToCursor {
glyphGroup: IDocumentSkeletonGlyph[],
glyphIndex: number
): IDocumentSkeletonGlyph {
- if (!glyph || !this._isNonInlineEmbedCustomBlockGlyph(glyph)) {
+ if (!glyph || !this._isNonInlineDrawingGlyph(glyph)) {
return glyph!;
}
@@ -402,7 +402,7 @@ export class NodePositionConvertToCursor {
private _findTextLikeGlyph(glyphGroup: IDocumentSkeletonGlyph[], startIndex: number, step: 1 | -1): IDocumentSkeletonGlyph | undefined {
for (let index = startIndex; index >= 0 && index < glyphGroup.length; index += step) {
const glyph = glyphGroup[index];
- if (!this._isNonInlineEmbedCustomBlockGlyph(glyph)) {
+ if (!this._isNonInlineDrawingGlyph(glyph)) {
return glyph;
}
}
@@ -410,13 +410,15 @@ export class NodePositionConvertToCursor {
return undefined;
}
- private _isNonInlineEmbedCustomBlockGlyph(glyph: IDocumentSkeletonGlyph | undefined): boolean {
+ private _isNonInlineDrawingGlyph(glyph: IDocumentSkeletonGlyph | undefined): boolean {
if (!glyph?.drawingId || glyph.streamType !== DataStreamTreeTokenType.CUSTOM_BLOCK) {
return false;
}
const drawing = this._docSkeleton.getViewModel?.().getDataModel?.().getSnapshot?.().drawings?.[glyph.drawingId];
- return !shouldUseInlineTextSelectionForDocsCustomBlockDrawing(drawing);
+ return drawing?.layoutType == null
+ ? !shouldUseInlineTextSelectionForDocsCustomBlockDrawing(drawing)
+ : drawing.layoutType !== PositionedObjectLayoutType.INLINE;
}
private _isValidPosition(startOrigin: INodePosition, endOrigin: INodePosition) {
diff --git a/packages/docs-ui/src/views/ParagraphMenu.tsx b/packages/docs-ui/src/views/ParagraphMenu.tsx
index 0c939df79e..bc02a7b17a 100644
--- a/packages/docs-ui/src/views/ParagraphMenu.tsx
+++ b/packages/docs-ui/src/views/ParagraphMenu.tsx
@@ -39,7 +39,6 @@ import { DocBlockMoveValidatorService, DocContentInsertService, DocSelectionMana
import { IRenderManagerService } from '@univerjs/engine-render';
import {
ContextMenuPanel,
- IClipboardInterfaceService,
IconManager,
ILayoutService,
RectPopup,
@@ -317,6 +316,7 @@ const PARAGRAPH_MENU_BLOCK_RANGE_COMMAND_IDS = new Set(
);
const PARAGRAPH_MENU_SELECTION_COMMAND_IDS = new Set([
+ DocPasteCommand.id,
BulletListCommand.id,
OrderListCommand.id,
CheckListCommand.id,
@@ -471,6 +471,10 @@ export function getParagraphMenuHiddenItemIds(
const hiddenIds = [...getParagraphMenuHiddenHeadingCommandIds(namedStyleType)];
const blockType = target?.kind === 'blockRange' ? target.blockRange?.blockType : undefined;
+ if (target?.kind !== 'blockRange') {
+ hiddenIds.push(DocPasteCommand.id);
+ }
+
if (blockType === DocumentBlockRangeType.CALLOUT) {
hiddenIds.push(
getParagraphMenuBlockRangeCommandId(DocumentBlockRangeType.CODE)!,
@@ -796,6 +800,10 @@ export function getParagraphMenuCommandTargetRange(
targetRange?: ITextRangeWithStyle | null,
formattingRange?: ITextRangeWithStyle | null
): ITextRangeWithStyle | null | undefined {
+ if (commandId === DocPasteCommand.id) {
+ return targetRange;
+ }
+
if (commandId && PARAGRAPH_MENU_SELECTION_COMMAND_IDS.has(commandId)) {
return formattingRange ?? targetRange;
}
@@ -831,6 +839,31 @@ function getBlockSelectionRange(target: IDocBlockMenuTarget | null | undefined,
};
}
+export function getBlockRangeClipboardTargetRange(
+ commandId: string,
+ target: IDocBlockMenuTarget | null | undefined,
+ paragraph?: IMutiPageParagraphBound | null | void
+): ITextRangeWithStyle | null {
+ if (target?.kind !== 'blockRange') {
+ return null;
+ }
+
+ if (commandId === DocPasteCommand.id) {
+ return {
+ startOffset: target.moveRange.endOffset,
+ endOffset: target.moveRange.endOffset,
+ collapsed: true,
+ segmentId: paragraph?.segmentId,
+ };
+ }
+
+ if (commandId === DocCopyCurrentParagraphCommand.id || commandId === DocCutCurrentParagraphCommand.id) {
+ return getBlockSelectionRange(target, paragraph ?? undefined);
+ }
+
+ return null;
+}
+
function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; tableBlockOnly?: boolean }) {
const [visible, setVisible] = useState(false);
const [openMode, setOpenMode] = useState<ParagraphMenuOpenMode>('pointer');
@@ -850,7 +883,6 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
const docClipboardService = useDependency(IDocClipboardService);
const docContentInsertService = useDependency(DocContentInsertService);
const docBlockMoveValidatorService = useDependency(DocBlockMoveValidatorService);
- const clipboardInterfaceService = useDependency(IClipboardInterfaceService);
const layoutService = useDependency(ILayoutService);
const iconManager = useDependency(IconManager);
const anchorRef = useRef<HTMLDivElement>(null);
@@ -1105,6 +1137,20 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
if (latestTarget?.kind === 'blockRange') {
const currentBlockCommandId = getParagraphMenuBlockRangeCommandId(latestTarget.blockRange?.blockType);
+ const clipboardRange = getBlockRangeClipboardTargetRange(commandId, latestTarget, activeParagraphBound);
+
+ if (clipboardRange) {
+ if (commandId === DocCopyCurrentParagraphCommand.id) {
+ await docClipboardService.copy(SliceBodyType.copy, [clipboardRange]);
+ } else if (commandId === DocCutCurrentParagraphCommand.id) {
+ await docClipboardService.cut([clipboardRange]);
+ } else {
+ replaceSelection(clipboardRange);
+ await executeResolvedCommand(option, clipboardRange);
+ }
+ finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ return;
+ }
if (commandId === currentBlockCommandId) {
await unwrapActiveBlockRange();
@@ -1427,8 +1473,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
if (commandId === DocPasteCommand.id) {
docSelectionManagerService.replaceTextRanges([afterTableRange], false);
- const clipboardItems = await clipboardInterfaceService.read();
- await docClipboardService.paste(clipboardItems);
+ await commandService.executeCommand(DocPasteCommand.id);
finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
return;
}
@@ -1440,7 +1485,9 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
}
if (commandService && commandId) {
- commandService.executeCommand(commandId, commandParams);
+ commandService.executeCommand(commandId, commandId === DocTableDeleteTableCommand.id
+ ? { ...commandParams, targetRange: tableRange }
+ : commandParams);
}
finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
diff --git a/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts b/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
index c24b94a7a9..6c6c44cf17 100644
--- a/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
+++ b/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
@@ -22,6 +22,11 @@ import type { IDocBlockMenuTarget } from '../../services/doc-paragraph-menu.serv
import { DataStreamTreeTokenType, DocumentBlockRangeType, DocumentBlockType, JSONX, NamedStyleType } from '@univerjs/core';
import { DocBlockMoveValidatorService } from '@univerjs/docs';
import { describe, expect, it } from 'vitest';
+import {
+ DocCopyCurrentParagraphCommand,
+ DocCutCurrentParagraphCommand,
+ DocPasteCommand,
+} from '../../commands/commands/clipboard.command';
import { DeleteCurrentParagraphCommand } from '../../commands/commands/doc-delete.command';
import { HorizontalLineCommand } from '../../commands/commands/doc-horizontal-line.command';
import { BulletListCommand } from '../../commands/commands/list.command';
@@ -30,6 +35,7 @@ import { H2HeadingCommand, SetParagraphNamedStyleCommand } from '../../commands/
import { DOC_PARAGRAPH_T_EDIT_MENU_ID, INSERT_BELLOW_MENU_ID } from '../../menu/paragraph-menu';
import {
buildUnwrapBlockRangeActions,
+ getBlockRangeClipboardTargetRange,
getParagraphFormattingRange,
getParagraphMenuCommandParams,
getParagraphMenuCommandTargetRange,
@@ -171,6 +177,18 @@ describe('ParagraphMenu command behavior', () => {
});
});
+ it('pastes at the hovered paragraph cursor instead of selecting the paragraph', () => {
+ const caretRange: ITextRangeWithStyle = {
+ startOffset: 14,
+ endOffset: 14,
+ collapsed: true,
+ segmentId: 'header-left',
+ };
+ const paragraphRange = getParagraphFormattingRange(undefined, paragraphBound());
+
+ expect(getParagraphMenuCommandTargetRange(DocPasteCommand.id, caretRange, paragraphRange)).toBe(caretRange);
+ });
+
it('targets the whole block and hides incompatible block conversions', () => {
const paragraph = paragraphBound();
const target = blockTarget({
@@ -189,6 +207,34 @@ describe('ParagraphMenu command behavior', () => {
expect(getParagraphMenuHiddenItemIds(DOC_PARAGRAPH_T_EDIT_MENU_ID, target)).toContain('docs-callout.command.insert');
expect(getParagraphMenuHiddenItemIds(DOC_PARAGRAPH_T_EDIT_MENU_ID, target)).not.toContain('docs-quote.command.insert');
+ expect(getParagraphMenuHiddenItemIds(DOC_PARAGRAPH_T_EDIT_MENU_ID, target)).not.toContain(DocPasteCommand.id);
+ expect(getParagraphMenuHiddenItemIds(DOC_PARAGRAPH_T_EDIT_MENU_ID, undefined)).toContain(DocPasteCommand.id);
+ });
+
+ it('uses the whole block for copy and cut and places paste after it', () => {
+ const paragraph = paragraphBound();
+ const target = blockTarget({
+ blockId: 'quote-1',
+ blockType: DocumentBlockRangeType.QUOTE,
+ startIndex: 20,
+ endIndex: 45,
+ } as IDocumentBlockRange);
+
+ const blockRange = {
+ startOffset: 20,
+ endOffset: 46,
+ collapsed: false,
+ segmentId: 'header-left',
+ };
+
+ expect(getBlockRangeClipboardTargetRange(DocCopyCurrentParagraphCommand.id, target, paragraph)).toEqual(blockRange);
+ expect(getBlockRangeClipboardTargetRange(DocCutCurrentParagraphCommand.id, target, paragraph)).toEqual(blockRange);
+ expect(getBlockRangeClipboardTargetRange(DocPasteCommand.id, target, paragraph)).toEqual({
+ startOffset: 46,
+ endOffset: 46,
+ collapsed: true,
+ segmentId: 'header-left',
+ });
});
it('adds block range context to current paragraph delete commands', () => {
diff --git a/packages/docs/src/facade/__tests__/f-document.spec.ts b/packages/docs/src/facade/__tests__/f-document.spec.ts
index 0f7390c6db..7f7dc4ca9c 100644
--- a/packages/docs/src/facade/__tests__/f-document.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document.spec.ts
@@ -380,5 +380,6 @@ describe('FDocument', () => {
width: 1,
color: { rgb: '#CDD0D8' },
});
+ expect(rule?.getInfo().paragraph.paragraphStyle?.spaceBelow).toEqual({ v: 10 });
});
});
diff --git a/packages/docs/src/utils/paragraphs.ts b/packages/docs/src/utils/paragraphs.ts
index 54650d4912..0121b95f1a 100644
--- a/packages/docs/src/utils/paragraphs.ts
+++ b/packages/docs/src/utils/paragraphs.ts
@@ -54,6 +54,7 @@ export function generateParagraphs(
if (borderBottom) {
paragraph.paragraphStyle ??= {};
paragraph.paragraphStyle.borderBottom = Tools.deepClone(borderBottom);
+ paragraph.paragraphStyle.spaceBelow = { v: 10 };
}
}
diff --git a/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts b/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts
index 3bc8c13cee..0e5ad76c7e 100644
--- a/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts
+++ b/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts
@@ -252,7 +252,17 @@ describe('ImageUpdateController', () => {
update$.next([{ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'shape-3' }]);
- expect(imageShape.transformByState).toHaveBeenCalledWith(transform);
+ expect(imageShape.transformByState).toHaveBeenCalledWith({
+ angle: 0,
+ flipX: false,
+ flipY: false,
+ height: 60,
+ left: 10,
+ skewX: 0,
+ skewY: 0,
+ top: 20,
+ width: 100,
+ });
expect(imageShape.setClipBounds).toHaveBeenCalledWith(transform.clipBounds);
expect(scene.removeObject).toHaveBeenCalledWith(imageShape);
expect(scene.addObject).toHaveBeenCalledWith(imageShape, DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX);
diff --git a/packages/drawing-ui/src/controllers/image-update.controller.ts b/packages/drawing-ui/src/controllers/image-update.controller.ts
index 0c12b77e35..0975f722be 100644
--- a/packages/drawing-ui/src/controllers/image-update.controller.ts
+++ b/packages/drawing-ui/src/controllers/image-update.controller.ts
@@ -239,7 +239,7 @@ export class ImageUpdateController extends Disposable {
if (renderObject == null) {
return;
}
- const { scene, transformer } = renderObject;
+ const { scene } = renderObject;
if (transform == null) {
return true;
@@ -253,7 +253,9 @@ export class ImageUpdateController extends Disposable {
return true;
}
- imageShape.transformByState(transform);
+ const { left = 0, top = 0, width = 0, height = 0, angle = 0, flipX = false, flipY = false, skewX = 0, skewY = 0 } = transform;
+
+ imageShape.transformByState({ left, top, width, height, angle, flipX, flipY, skewX, skewY });
(imageShape as Image & { setClipBounds?: (clipBounds?: unknown) => void }).setClipBounds?.((transform as { clipBounds?: unknown }).clipBounds);
ensureDrawingRenderLayer(scene, imageShape, drawingParam);
imageShape.setSrcRect(srcRect);
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 12df7d4d08..19dbc58465 100644
--- a/packages/engine-render/src/components/docs/__tests__/document.spec.ts
+++ b/packages/engine-render/src/components/docs/__tests__/document.spec.ts
@@ -745,6 +745,8 @@ describe('documents render', () => {
padding: 4,
dashStyle: DashStyleType.DASH,
};
+ line.lineHeight += 6;
+ line.marginBottom = 6;
(documents as any)._drawLiquid = { x: 0, y: 0 };
const ctx = {
@@ -760,15 +762,43 @@ describe('documents render', () => {
set strokeStyle(_value: string) {},
} as any;
- (documents as any)._drawBorderBottom(ctx, page, line);
+ (documents as any)._drawBorderBottom(ctx, page, line, 72);
expect(ctx.setLineWidthByPrecision).toHaveBeenCalledWith(2.5);
expect(ctx.setLineDash).toHaveBeenCalledWith([6]);
+ expect(ctx.lineToByPrecision).toHaveBeenCalledWith(82, 33);
expect(ctx.stroke).toHaveBeenCalledTimes(1);
documents.dispose();
});
+ it('limits paragraph backgrounds to the current column width', () => {
+ const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;
+ const documents = new Documents('docs-paragraph-background', skeleton, {
+ pageLayoutType: PageLayoutType.VERTICAL,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ });
+ const page = createPage(DocumentSkeletonPageType.BODY, '');
+ const line = page.sections[0].columns[0].lines[1];
+ line.backgroundColor = { rgb: '#ffeecc' };
+ (documents as any)._drawLiquid = { x: 0, y: 0 };
+
+ const ctx = {
+ save: vi.fn(),
+ restore: vi.fn(),
+ fillRect: vi.fn(),
+ getScale: () => ({ scaleX: 1, scaleY: 1 }),
+ set fillStyle(_value: string) {},
+ } as any;
+
+ (documents as any)._drawLineBackground(ctx, page, line, 72);
+
+ expect(ctx.fillRect).toHaveBeenCalledWith(10, 9, 72, 20);
+
+ documents.dispose();
+ });
+
it('draws each physical table grid line only once', () => {
const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;
const documents = new Documents('docs-border-canonical', skeleton, {
@@ -1701,6 +1731,47 @@ describe('documents render', () => {
documents.dispose();
});
+ it('restores the section offset before advancing to the next page', () => {
+ const firstPage = createPage(DocumentSkeletonPageType.BODY, 'first');
+ const secondPage = createPage(DocumentSkeletonPageType.BODY, 'second');
+ firstPage.sections.push({
+ columns: [],
+ height: 80,
+ top: 90,
+ } as any);
+ secondPage.pageNumber = 2;
+ attachTable(secondPage);
+
+ const skeletonData = {
+ pages: [firstPage, secondPage],
+ skeFooters: new Map(),
+ skeHeaders: new Map(),
+ };
+ const documents = new Documents('docs-section-page-offset', { getSkeletonData: () => skeletonData } as any, {
+ pageLayoutType: PageLayoutType.VERTICAL,
+ pageMarginLeft: 0,
+ pageMarginTop: 8,
+ });
+ const tableOrigins: Array<{ x: number; y: number }> = [];
+
+ vi.spyOn(documents as any, 'getExtensionsByOrder').mockReturnValue([]);
+ vi.spyOn(documents as any, '_drawTable').mockImplementation(() => {
+ tableOrigins.push({
+ x: (documents as any)._drawLiquid.x,
+ y: (documents as any)._drawLiquid.y,
+ });
+ });
+
+ documents.draw(canvas.getContext());
+
+ expect(tableOrigins).toEqual([{
+ x: 0,
+ y: firstPage.pageHeight + 8,
+ }]);
+
+ documents.dispose();
+ });
+
it('draws lower-page header content for DOCX page-relative header backgrounds', () => {
const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');
bodyPage.sections[0].columns[0].lines = [];
diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.ts
index 7e99b5025f..fb9f177ab9 100644
--- a/packages/engine-render/src/components/docs/document.ts
+++ b/packages/engine-render/src/components/docs/document.ts
@@ -262,6 +262,7 @@ export class Documents extends DocComponent {
for (const section of sections) {
const { columns } = section;
+ this._drawLiquid.translateSave();
this._drawLiquid.translateSection(section);
for (const column of columns) {
@@ -371,7 +372,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);
+ this._drawLineBackground(ctx, page, line, column.width);
const divideLength = divides.length;
@@ -447,7 +448,7 @@ export class Documents extends DocComponent {
}
if (line.borderBottom) {
- this._drawBorderBottom(ctx, page, line);
+ this._drawBorderBottom(ctx, page, line, column.width);
}
this._drawLiquid.translateRestore();
}
@@ -455,6 +456,8 @@ export class Documents extends DocComponent {
this._drawLiquid.translateRestore();
}
+
+ this._drawLiquid.translateRestore();
}
if (skeColumnGroups.size > 0) {
@@ -766,6 +769,7 @@ export class Documents extends DocComponent {
ctx: UniverRenderingContext,
page: IDocumentSkeletonPage,
line: IDocumentSkeletonLine,
+ width = page.pageWidth - page.marginLeft - page.marginRight,
left = 0,
top = 0
) {
@@ -775,7 +779,7 @@ export class Documents extends DocComponent {
}
let { x, y } = this._drawLiquid;
- const { pageWidth, marginLeft, marginRight, marginTop } = page;
+ const { marginLeft, marginTop } = page;
x += marginLeft + (left ?? 0);
y -= line.marginTop;
@@ -788,7 +792,7 @@ export class Documents extends DocComponent {
ctx,
x,
y,
- pageWidth - marginLeft - marginRight,
+ width,
line.lineHeight
);
ctx.restore();
@@ -798,6 +802,7 @@ export class Documents extends DocComponent {
ctx: UniverRenderingContext,
page: IDocumentSkeletonPage,
line: IDocumentSkeletonLine,
+ width = page.pageWidth - page.marginLeft - page.marginRight,
left = 0,
top = 0
) {
@@ -805,12 +810,13 @@ export class Documents extends DocComponent {
return;
}
let { x, y } = this._drawLiquid;
- const { pageWidth, marginLeft, marginRight, marginTop } = page;
+ const { marginLeft, marginTop } = page;
x += marginLeft + (left ?? 0);
y -= line.marginTop;
y -= line.paddingTop;
- y += marginTop + top + line.lineHeight + (line.borderBottom?.padding ?? 0);
+ // Paragraph spacing is included in lineHeight, while border padding is measured from the text bottom.
+ y += marginTop + top + line.lineHeight - line.marginBottom + (line.borderBottom?.padding ?? 0);
ctx.save();
const border = line.borderBottom;
@@ -820,7 +826,7 @@ export class Documents extends DocComponent {
drawLineByBorderType(ctx, BORDER_LTRB.BOTTOM, 0, {
startX: x,
startY: y,
- endX: x + pageWidth - marginLeft - marginRight,
+ endX: x + width,
endY: y,
});
ctx.restore();
@@ -999,7 +1005,7 @@ export class Documents extends DocComponent {
} else {
this._drawLiquid.translateSave();
this._drawLiquid.translateLine(line, true, true);
- this._drawLineBackground(ctx, nestedPage, line);
+ this._drawLineBackground(ctx, nestedPage, line, column.width);
const divideLength = divides.length;
@@ -1073,7 +1079,7 @@ export class Documents extends DocComponent {
}
if (line.borderBottom) {
- this._drawBorderBottom(ctx, nestedPage, line, parentPage.marginLeft, parentPage.marginTop);
+ this._drawBorderBottom(ctx, nestedPage, line, column.width, parentPage.marginLeft, parentPage.marginTop);
}
this._drawLiquid.translateRestore();
@@ -1293,7 +1299,7 @@ export class Documents extends DocComponent {
continue;
}
}
- this._drawLineBackground(ctx, page, line, parentPage.marginLeft);
+ this._drawLineBackground(ctx, page, line, column.width, parentPage.marginLeft);
const divideLength = divides.length;
@@ -1367,7 +1373,7 @@ export class Documents extends DocComponent {
}
if (line.borderBottom) {
- this._drawBorderBottom(ctx, page, line, parentPage.marginLeft);
+ this._drawBorderBottom(ctx, page, line, column.width, parentPage.marginLeft);
}
this._drawLiquid.translateRestore();
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
index 4ed7e2b263..c00ec0d26c 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
@@ -23,9 +23,11 @@ import {
LocaleService,
ObjectRelativeFromH,
ObjectRelativeFromV,
+ PositionedObjectLayoutType,
SectionType,
TableSizeType,
Univer,
+ WrapTextType,
} from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
import { DocumentSkeletonPageType, GlyphType, PageLayoutType } from '../../../../basics/i-document-skeleton-cached';
@@ -692,6 +694,129 @@ describe('doc skeleton', () => {
expect(noNode).toBeUndefined();
});
+ it('restores a truncated continuous section in place for incremental layout', () => {
+ const body = createPage(DocumentSkeletonPageType.BODY, 0);
+ body.page.pageHeight = 300;
+ body.section.top = 80;
+ body.section.height = 60;
+ body.section.colCount = 2;
+ const retainedColumn = body.section.columns[0];
+ const docViewModel = {
+ getDataModel: () => ({
+ documentStyle: {
+ pageSize: { width: 200, height: 300 },
+ },
+ }),
+ dispose: vi.fn(),
+ } as any;
+ const skeleton = new DocumentSkeleton(docViewModel, {} as any);
+
+ (skeleton as any)._restoreContinuousSection(
+ body.page,
+ [
+ { width: 80, paddingEnd: 10 },
+ { width: 80, paddingEnd: 0 },
+ ],
+ ColumnSeparatorType.BETWEEN_EACH_COLUMN
+ );
+
+ expect(body.page.sections).toHaveLength(1);
+ expect(body.section.top).toBe(80);
+ expect(body.section.height).toBe(200);
+ expect(body.section.columns).toHaveLength(2);
+ expect(body.section.columns[0]).toBe(retainedColumn);
+ expect(body.section.columns[1].left).toBe(90);
+ expect(body.section.columns[1].parent).toBe(body.section);
+
+ (skeleton as any)._restoreContinuousSection(
+ body.page,
+ [
+ { width: 80, paddingEnd: 10 },
+ { width: 80, paddingEnd: 0 },
+ ],
+ ColumnSeparatorType.BETWEEN_EACH_COLUMN
+ );
+ expect(body.section.columns).toHaveLength(2);
+ });
+
+ it('does not restore a later continuous section into the anchored title section', () => {
+ const firstTitleParagraph = `First title${DataStreamTreeTokenType.PARAGRAPH}`;
+ const secondTitleParagraph = `Second title${DataStreamTreeTokenType.PARAGRAPH}`;
+ const anchoredTitleParagraph = `Anchor${DataStreamTreeTokenType.CUSTOM_BLOCK}${DataStreamTreeTokenType.PARAGRAPH}`;
+ const title = `${firstTitleParagraph}${secondTitleParagraph}${anchoredTitleParagraph}${DataStreamTreeTokenType.SECTION_BREAK}`;
+ const bodyText = `${'Body text '.repeat(80)}${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`;
+ const documentModel = new DocumentDataModel({
+ id: 'continuous-section-after-anchored-title',
+ body: {
+ dataStream: `${title}${bodyText}`,
+ paragraphs: [
+ { startIndex: firstTitleParagraph.length - 1, paragraphId: 'title-1' },
+ { startIndex: firstTitleParagraph.length + secondTitleParagraph.length - 1, paragraphId: 'title-2' },
+ { startIndex: title.length - 2, paragraphId: 'title-anchor' },
+ { startIndex: title.length + bodyText.length - 2, paragraphId: 'body' },
+ ],
+ sectionBreaks: [
+ { sectionId: 'title-section', startIndex: title.length - 1 },
+ {
+ sectionId: 'body-section',
+ startIndex: title.length + bodyText.length - 1,
+ sectionType: SectionType.CONTINUOUS,
+ columnProperties: [
+ { width: 120, paddingEnd: 10 },
+ { width: 120, paddingEnd: 0 },
+ ],
+ },
+ ],
+ customBlocks: [{ startIndex: firstTitleParagraph.length + secondTitleParagraph.length + 6, blockId: 'title-shape' }],
+ },
+ drawings: {
+ 'title-shape': {
+ unitId: 'continuous-section-after-anchored-title',
+ subUnitId: 'continuous-section-after-anchored-title',
+ drawingId: 'title-shape',
+ drawingType: 1,
+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,
+ wrapText: WrapTextType.BOTH_SIDES,
+ docTransform: {
+ angle: 0,
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 40 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: -30 },
+ size: { width: 150, height: 100 },
+ },
+ },
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 320, height: 400 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ });
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const viewModel = new DocumentViewModel(documentModel);
+ const skeleton = DocumentSkeleton.create(viewModel, localeService);
+ const createSkeletonSpy = vi.spyOn(skeleton as any, '_createSkeleton');
+ const restoreContinuousSectionSpy = vi.spyOn(skeleton as any, '_restoreContinuousSection');
+
+ skeleton.calculate();
+
+ expect(createSkeletonSpy.mock.calls.length).toBeGreaterThan(1);
+ expect(restoreContinuousSectionSpy).not.toHaveBeenCalled();
+ const firstPageSections = skeleton.getSkeletonData()?.pages[0]?.sections ?? [];
+ expect(firstPageSections).toHaveLength(2);
+ expect(firstPageSections[0].colCount).toBe(1);
+ expect(firstPageSections[0].columns).toHaveLength(1);
+ expect(firstPageSections[1].colCount).toBe(2);
+ expect(firstPageSections[1].columns).toHaveLength(2);
+ expect(firstPageSections[0].columns[0].width).toBeGreaterThan(firstPageSections[1].columns[0].width);
+
+ skeleton.dispose();
+ univer.dispose();
+ });
+
it('calculates real skeleton layout from document view model', () => {
const univer = new Univer();
const localeService = univer.__getInjector().get(LocaleService);
diff --git a/packages/engine-render/src/components/docs/layout/block/__tests__/section.spec.ts b/packages/engine-render/src/components/docs/layout/block/__tests__/section.spec.ts
index fb961d11dd..dbff74d2e7 100644
--- a/packages/engine-render/src/components/docs/layout/block/__tests__/section.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/__tests__/section.spec.ts
@@ -112,11 +112,26 @@ describe('section', () => {
createSectionLayoutTestBed(['Hello', 'World']);
// Mark the second paragraph to open a new page.
- ctx.paragraphsOpenNewPage.add(sectionNode.children[1].endIndex);
+ const paragraphEndIndex = sectionNode.children[1].endIndex;
+ ctx.paragraphsOpenNewPage.add(paragraphEndIndex);
const result = dealWithSection(ctx, viewModel, sectionNode, curPage, sectionBreakConfig, null);
// Should have two pages because the second paragraph starts on a new page.
expect(result.pages.length).toBeGreaterThanOrEqual(2);
+ expect(ctx.paragraphsOpenNewPage.has(paragraphEndIndex)).toBe(false);
+ });
+
+ it('reuses an empty rollback page when opening the anchor paragraph', () => {
+ const { ctx, viewModel, sectionNode, curPage, sectionBreakConfig } =
+ createSectionLayoutTestBed(['Hello']);
+ const paragraphEndIndex = sectionNode.children[0].endIndex;
+ ctx.paragraphsOpenNewPage.add(paragraphEndIndex);
+
+ const result = dealWithSection(ctx, viewModel, sectionNode, curPage, sectionBreakConfig, null);
+
+ expect(result.pages).toHaveLength(1);
+ expect(result.pages[0].pageNumber).toBe(curPage.pageNumber);
+ expect(ctx.paragraphsOpenNewPage.has(paragraphEndIndex)).toBe(false);
});
it('lays out column group blocks into page skeleton columns', () => {
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 a0fc6ac707..ec1d302745 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
@@ -32,6 +32,7 @@ import {
createTableSkeletons,
getNullTableSkeleton,
getTableIdAndSliceIndex,
+ getTableLeft,
getTableSliceId,
rollbackListCache,
} from '../table';
@@ -155,6 +156,13 @@ function useDocumentFlavor(sectionBreakConfig: Record<string, unknown>, document
}
describe('table utilities', () => {
+ describe('getTableLeft', () => {
+ it('centers a table within the supplied column width', () => {
+ expect(getTableLeft(243, 243, TableAlignmentType.CENTER)).toBe(0);
+ expect(261 + getTableLeft(243, 120, TableAlignmentType.CENTER)).toBe(322.5);
+ });
+ });
+
describe('getTableSliceId', () => {
it('concatenates tableId and sliceIndex with delimiter', () => {
expect(getTableSliceId('table1', 0)).toBe('table1#-#0');
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.ts
index b5b0791b39..459ba15912 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.ts
@@ -101,13 +101,15 @@ describe('language-ruler', () => {
expect(result.glyphGroup.length).toBe(2);
});
- it('uses runtime custom range width for placeholder glyphs', () => {
+ it('uses runtime custom range metrics for placeholder glyphs', () => {
const { viewModel } = createViewModel('i');
const paragraphNode = getParagraphNode(viewModel);
const paragraph = getParagraph(viewModel);
const sectionBreakConfig = createSectionBreakConfig();
vi.spyOn(viewModel, 'getCustomRange').mockReturnValue({
endIndex: 0,
+ glyphAscentEm: 1.5,
+ glyphDescentEm: 0.5,
glyphWidthEm: 3,
rangeId: 'formula-1',
startIndex: 0,
@@ -115,8 +117,11 @@ describe('language-ruler', () => {
const result = otherHandler(0, 'i', viewModel, paragraphNode, sectionBreakConfig, paragraph);
const glyph = result.glyphGroup[0];
+ const emSize = glyph.fontStyle!.originFontSize / 0.75;
- expect(glyph.width).toBeCloseTo(glyph.fontStyle!.originFontSize * 3);
+ expect(glyph.width).toBeCloseTo(emSize * 3);
+ expect(glyph.bBox.ba).toBeCloseTo(emSize * 1.5);
+ expect(glyph.bBox.bd).toBeCloseTo(emSize * 0.5);
});
});
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 5fd36f8d44..16ab3c3a4c 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
@@ -25,6 +25,8 @@ import {
ObjectRelativeFromV,
PositionedObjectLayoutType,
SpacingRule,
+ TableAlignmentType,
+ TableTextWrapType,
WrapTextType,
} from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -547,6 +549,72 @@ describe('layout-ruler', () => {
expect(ctx.paragraphsOpenNewPage.has(9)).toBe(false);
});
+ it('does not mistake another continuous-section fragment for a new page', () => {
+ const cachedLine: any = { paragraphIndex: 1, top: 0, lineHeight: 20 };
+ const cachedColumn: any = { width: 100, left: 0, lines: [cachedLine] };
+ const cachedPage: any = {
+ pageNumber: 1,
+ segmentId: '',
+ skeDrawings: new Map([['floating', {}]]),
+ sections: [{ top: 20, columns: [cachedColumn] }],
+ };
+ cachedLine.parent = cachedColumn;
+ cachedColumn.parent = { top: 20, parent: cachedPage };
+ const page: any = {
+ pageNumber: 1,
+ segmentId: '',
+ sections: [{ columns: [] }],
+ };
+ const column: any = {
+ width: 100,
+ left: 0,
+ lines: [{ paragraphIndex: 2, top: 0, lineHeight: 20 }],
+ parent: { top: 20, parent: page },
+ };
+ page.sections[0].columns = [column];
+ const floatObject: any = {
+ id: 'floating',
+ top: 20,
+ left: 0,
+ width: 50,
+ height: 50,
+ angle: 0,
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH },
+ };
+ const ctx: any = {
+ floatObjectsCache: new Map([['floating', { count: 1, floatObject, page: cachedPage }]]),
+ isDirty: false,
+ layoutStartPointer: { '': null },
+ paragraphsOpenNewPage: new Set(),
+ };
+
+ __testing.reLayoutCheck(ctx, [floatObject], column, 9);
+
+ expect(ctx.isDirty).toBe(false);
+ expect(ctx.floatObjectsCache.has('floating')).toBe(true);
+ expect(ctx.paragraphsOpenNewPage.has(9)).toBe(false);
+
+ page.pageNumber = 2;
+ __testing.reLayoutCheck(ctx, [floatObject], column, 9);
+
+ expect(ctx.isDirty).toBe(true);
+ expect(ctx.floatObjectsCache.has('floating')).toBe(false);
+ expect(ctx.paragraphsOpenNewPage.has(9)).toBe(true);
+ });
+
+ it('does not treat the first paragraph of a continuous section as a page break', () => {
+ const page: any = { sections: [{}] };
+ const section: any = { columns: [], parent: page };
+ const column: any = { lines: [], parent: section };
+ section.columns.push(column);
+ page.sections.push(section);
+
+ expect(__testing.checkPageBreak(column)).toBe(false);
+
+ page.sections = [section];
+ expect(__testing.checkPageBreak(column)).toBe(true);
+ });
+
it('does not dirty relayout for behind-doc floating objects', () => {
const page: any = {
segmentId: '',
@@ -658,14 +726,14 @@ describe('layout-ruler', () => {
it('moves non-wrap tables into the usable area beside flow-affecting drawings', () => {
const table = {
top: 120,
- left: 0,
+ left: 261,
width: 280,
height: 80,
} as any;
const page = {
skeDrawings: new Map([['left-wrap', {
aTop: 40,
- aLeft: 10,
+ aLeft: 271,
width: 90,
height: 220,
drawingOrigin: {
@@ -675,12 +743,62 @@ describe('layout-ruler', () => {
}]]),
} as any;
const column = {
+ left: 261,
width: 420,
} as any;
__testing.avoidFlowAffectingDrawingsForTable(table, page, column);
- expect(table.left).toBe(108);
+ expect(table.left).toBe(369);
+ });
+
+ it('positions a sliced table continuation in its current column', () => {
+ const table = {
+ tableId: 'table#-#1',
+ tableSource: {
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ },
+ top: 0,
+ left: 0,
+ width: 243,
+ height: 114,
+ } as any;
+ const page = {
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ } as any;
+ const section = {
+ top: 40,
+ height: 678,
+ } as any;
+ const column = {
+ left: 261,
+ width: 243,
+ } as any;
+ const cache = [{
+ table,
+ tableId: table.tableId,
+ hasPositioned: false,
+ isSlideTable: true,
+ tableNode: {},
+ }] as any;
+
+ __testing.updateAndPositionTable(
+ {} as any,
+ 0,
+ 14,
+ page,
+ column,
+ section,
+ cache,
+ 0,
+ {} as any
+ );
+
+ expect(table).toMatchObject({ left: 261, top: 40 });
+ expect(page.skeTables.get(table.tableId)).toBe(table);
});
it('stores custom block render viewport on inline skeleton drawings', () => {
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 4230f57cb6..e4bfbf3bc0 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
@@ -21,6 +21,7 @@ import {
DataStreamTreeTokenType,
DocumentBlockRangeType,
DocumentFlavor,
+ HorizontalAlign,
ObjectRelativeFromH,
ObjectRelativeFromV,
PositionedObjectLayoutType,
@@ -77,6 +78,31 @@ describe('linebreaking', () => {
expect(result[0].sections.length).toBeGreaterThan(0);
});
+ it('reserves bottom-border clearance when paragraph spacing is smaller', () => {
+ const content = 'Rule';
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ body: {
+ paragraphs: [{
+ startIndex: content.length,
+ paragraphStyle: {
+ spaceBelow: { v: 0 },
+ borderBottom: {
+ color: { rgb: '#cdd0d8' },
+ padding: 5,
+ width: 2,
+ },
+ },
+ }],
+ },
+ });
+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+
+ lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);
+
+ const paragraphConfig = ctx.paragraphConfigCache.get(curPage.segmentId)?.get(paragraphNode.endIndex);
+ expect(paragraphConfig?.paragraphStyle?.spaceBelow?.v).toBe(6);
+ });
+
it('lays out longer text that may span multiple lines', () => {
const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('This is a longer text that should still fit within a reasonable page width for testing purposes');
const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
@@ -164,6 +190,84 @@ describe('linebreaking', () => {
expect(drawing?.height).toBe(120);
});
+ it('does not multiply an inline drawing height when it follows text', () => {
+ const content = `Before${DataStreamTreeTokenType.CUSTOM_BLOCK}after`;
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ body: {
+ customBlocks: [{ startIndex: 6, blockId: 'inline-shape' }],
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.MODERN,
+ },
+ drawings: {
+ 'inline-shape': {
+ drawingId: 'inline-shape',
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ angle: 0,
+ positionH: {},
+ positionV: {},
+ size: { width: 100, height: 96 },
+ },
+ },
+ },
+ });
+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+
+ lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);
+
+ const line = curPage.sections[0].columns[0].lines[0];
+ expect(line.contentHeight).toBeCloseTo(96);
+ expect(line.lineHeight).toBeCloseTo(96);
+ });
+
+ it.each([
+ PositionedObjectLayoutType.WRAP_SQUARE,
+ PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM,
+ ])('starts flow text after a positioned-only anchor line for layout %s', (layoutType) => {
+ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}Hello world`;
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ body: {
+ customBlocks: [{ startIndex: 0, blockId: 'b1' }],
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.MODERN,
+ },
+ drawings: {
+ b1: {
+ drawingId: 'b1',
+ layoutType,
+ wrapText: WrapTextType.BOTH_SIDES,
+ docTransform: {
+ angle: 0,
+ positionH: { relativeFrom: ObjectRelativeFromH.COLUMN, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ size: { width: 100, height: 120 },
+ },
+ },
+ },
+ });
+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+
+ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);
+ const lines = result.flatMap((page) => page.sections)
+ .flatMap((section) => section.columns)
+ .flatMap((column) => column.lines);
+ const anchorLine = lines.find((line) => line.divides.some((divide) =>
+ divide.glyphGroup.some((glyph) => glyph.drawingId === 'b1')
+ ));
+ const textLine = lines.find((line) => line.divides
+ .flatMap((divide) => divide.glyphGroup)
+ .map((glyph) => glyph.content)
+ .join('')
+ .includes('Hello'));
+
+ expect(anchorLine).toBeDefined();
+ expect(textLine).toBeDefined();
+ expect(textLine).not.toBe(anchorLine);
+ expect(textLine!.contentHeight).toBeGreaterThan(0.01);
+ });
+
it('uses measured custom block viewport height to push following paragraphs', () => {
setDocsCustomBlockRenderViewportProvider(() => ({
contentHeight: 240,
@@ -740,6 +844,112 @@ describe('linebreaking', () => {
expect(secondColumnText).toContain('SECOND');
});
+ it('wraps second-column text around a drawing anchored below a preceding section', () => {
+ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}FIRST${DataStreamTreeTokenType.COLUMN_BREAK}ments without duplicating content in the body`;
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ },
+ body: {
+ customBlocks: [{ startIndex: 0, blockId: 'cross-column' }],
+ paragraphs: [{
+ startIndex: content.length,
+ paragraphId: 'cross-column-wrap-paragraph',
+ paragraphStyle: { horizontalAlign: HorizontalAlign.JUSTIFIED },
+ }],
+ customRanges: [{
+ startIndex: 6,
+ endIndex: 6,
+ rangeId: 'cross-column-break',
+ rangeType: 5,
+ wholeEntity: true,
+ properties: { docxBreakType: 'column' },
+ }],
+ sectionBreaks: [{
+ sectionId: 'section_fixture_cross_column_wrap',
+ startIndex: content.length + 1,
+ columnProperties: [
+ { width: 170, paddingEnd: 20 },
+ { width: 170, paddingEnd: 0 },
+ ],
+ }],
+ },
+ drawings: {
+ 'cross-column': {
+ drawingId: 'cross-column',
+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,
+ wrapText: WrapTextType.BOTH_SIDES,
+ docTransform: {
+ angle: 0,
+ positionH: { relativeFrom: ObjectRelativeFromH.COLUMN, posOffset: 8 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ size: { width: 100, height: 96 },
+ },
+ },
+ },
+ });
+ curPage.sections[0].top = 70;
+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+
+ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);
+ const secondColumn = result[0].sections[0].columns[1];
+ const textDivides = secondColumn.lines
+ .flatMap((line) => line.divides)
+ .filter((divide) => divide.glyphGroup.some((glyph) => glyph.content && glyph.content !== DataStreamTreeTokenType.PARAGRAPH));
+
+ expect(result[0].skeDrawings.get('cross-column')).toMatchObject({ aLeft: 198, aTop: 70, width: 100 });
+ expect(textDivides.length).toBeGreaterThan(0);
+ expect(textDivides.every((divide) => divide.width > 8)).toBe(true);
+ expect(textDivides.map((divide) => divide.glyphGroup.map((glyph) => glyph.content).join('')).join(''))
+ .toContain('ments without duplicating content in the body');
+ });
+
+ it('relayouts an earlier column covered by a top-bottom drawing anchored in a later column', () => {
+ const content = `LEFT${DataStreamTreeTokenType.COLUMN_BREAK}${DataStreamTreeTokenType.CUSTOM_BLOCK}`;
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ },
+ body: {
+ customBlocks: [{ startIndex: 5, blockId: 'cross-column-top-bottom' }],
+ customRanges: [{
+ startIndex: 4,
+ endIndex: 4,
+ rangeId: 'cross-column-top-bottom-break',
+ rangeType: 5,
+ wholeEntity: true,
+ properties: { docxBreakType: 'column' },
+ }],
+ sectionBreaks: [{
+ sectionId: 'section_fixture_cross_column_top_bottom',
+ startIndex: content.length + 1,
+ columnProperties: [
+ { width: 170, paddingEnd: 20 },
+ { width: 170, paddingEnd: 0 },
+ ],
+ }],
+ },
+ drawings: {
+ 'cross-column-top-bottom': {
+ drawingId: 'cross-column-top-bottom',
+ layoutType: PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM,
+ docTransform: {
+ angle: 0,
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 20 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ size: { width: 100, height: 96 },
+ },
+ },
+ },
+ });
+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+
+ lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);
+
+ expect(ctx.isDirty).toBe(true);
+ expect(ctx.layoutStartPointer['']).toBe(paragraphNode.endIndex);
+ });
+
it('starts normal text on a new flow line after a zero-width wrap-none floating anchor', () => {
const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}Hello`;
const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.ts
index 4ab9da2fc2..e4b2875a42 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.ts
@@ -27,7 +27,7 @@ import {
startWithEmoji,
} from '../../../../../basics/tools';
import { createSkeletonLetterGlyph, createSkeletonWordGlyph } from '../../model/glyph';
-import { getCustomRangeGlyphWidth, getFontCreateConfig } from '../../tools';
+import { getCustomRangeGlyphMetrics, getFontCreateConfig } from '../../tools';
// Handle English word, English punctuation, number characters.
// https://en.wikipedia.org/wiki/CJK_characters
@@ -55,7 +55,7 @@ export function otherHandler(
}
const config = getFontCreateConfig(index + step, viewModel, paragraphNode, sectionBreakConfig, paragraph);
- const glyph = createSkeletonLetterGlyph(char, config, getCustomRangeGlyphWidth(index + step, viewModel, paragraphNode, config));
+ const glyph = createSkeletonLetterGlyph(char, config, getCustomRangeGlyphMetrics(index + step, viewModel, paragraphNode, config));
glyphGroup.push(glyph);
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 e86b00cb77..aa9ee5b7fd 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
@@ -74,7 +74,7 @@ import {
isColumnFull,
lineIterator,
} from '../../tools';
-import { createTableSkeletons, rollbackListCache } from '../table';
+import { createTableSkeletons, getTableLeft, rollbackListCache } from '../table';
const LINE_LAYOUT_OVERFLOW_TOLERANCE = 2;
const FLOAT_OBJECT_RELAYOUT_LIMIT = 5;
@@ -82,6 +82,11 @@ const MIN_LINE_WIDTH_TOLERANCE = 1;
const MAX_LINE_WIDTH_TOLERANCE = 3;
const RELATIVE_LINE_WIDTH_TOLERANCE = 0.01;
+interface IDefaultSpanMetrics {
+ lineHeight: number;
+ hasInlineCustomBlock: boolean;
+}
+
function isBeyondDivideWidth(width: number, divideWidth: number) {
const tolerance = Math.min(
MAX_LINE_WIDTH_TOLERANCE,
@@ -251,7 +256,7 @@ function _divideOperator(
paragraphConfig: IParagraphConfig,
isParagraphFirstShapedText: boolean,
breakPointType = BreakPointType.Normal,
- defaultSpanLineHeight?: number
+ defaultSpanMetrics?: IDefaultSpanMetrics
) {
const lastPage = getLastPage(pages);
const divideInfo = getLastNotFullDivideInfo(lastPage); // Get the first divide in the latest line that is not full.
@@ -311,6 +316,20 @@ function _divideOperator(
) {
addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
updateDivideInfo(divide, { breakType: breakPointType });
+ } else if (!isLast && divide?.glyphGroup.length === 0) {
+ // A wrap drawing can leave a sliver before another usable divide.
+ // Preserve the shaped word and try the next divide instead of
+ // forcing a single glyph into that sliver.
+ _divideOperator(
+ ctx,
+ glyphGroup,
+ pages,
+ sectionBreakConfig,
+ paragraphConfig,
+ isParagraphFirstShapedText,
+ breakPointType,
+ defaultSpanMetrics
+ );
} else if (divide?.glyphGroup.length === 0) {
const sliceGlyphGroup: IDocumentSkeletonGlyph[] = [];
@@ -341,7 +360,7 @@ function _divideOperator(
false,
breakPointType,
- defaultSpanLineHeight
+ defaultSpanMetrics
);
}
} else if (hyphenLineCount > consecutiveHyphenLimit) {
@@ -364,7 +383,7 @@ function _divideOperator(
isParagraphFirstShapedText,
breakPointType,
- defaultSpanLineHeight
+ defaultSpanMetrics
);
} else {
_divideOperator(
@@ -376,7 +395,7 @@ function _divideOperator(
isParagraphFirstShapedText,
breakPointType,
- defaultSpanLineHeight
+ defaultSpanMetrics
);
}
} else if ( // Determine if first word slice appears inside the hyphenation zone.
@@ -400,7 +419,7 @@ function _divideOperator(
isParagraphFirstShapedText,
breakPointType,
- defaultSpanLineHeight
+ defaultSpanMetrics
);
} else {
// w does not exceed divide width, add it to divide
@@ -409,7 +428,7 @@ function _divideOperator(
if (
currentLine &&
- __isZeroWidthNonFlowFloatingAnchorLine(__getGlyphGroupByLine(currentLine), paragraphConfig.paragraphNonInlineSkeDrawings) &&
+ __isPositionedCustomBlockOnlyLine(__getGlyphGroupByLine(currentLine), paragraphConfig.paragraphNonInlineSkeDrawings) &&
__hasFlowGlyph(glyphGroup)
) {
for (const lineDivide of currentLine.divides) {
@@ -472,7 +491,12 @@ function _divideOperator(
lineIsStart,
breakPointType,
- boundingBoxAscent + boundingBoxDescent
+ {
+ lineHeight: boundingBoxAscent + boundingBoxDescent,
+ hasInlineCustomBlock: glyphGroup.some((glyph) =>
+ glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width !== 0
+ ),
+ }
);
for (let i = startIndex; i < spanGroupCached.length; i++) {
@@ -519,7 +543,7 @@ function _divideOperator(
updateDivideInfo(divide, { breakType: breakPointType });
}
} else {
- _lineOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType, defaultSpanLineHeight);
+ _lineOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType, defaultSpanMetrics);
}
}
@@ -531,7 +555,7 @@ function _lineOperator(
paragraphConfig: IParagraphConfig,
isParagraphFirstShapedText: boolean,
breakPointType: BreakPointType = BreakPointType.Normal,
- defaultGlyphLineHeight?: number
+ defaultSpanMetrics?: IDefaultSpanMetrics
) {
let lastPage = getLastPage(pages);
let columnInfo = getLastNotFullColumnInfo(lastPage);
@@ -570,7 +594,7 @@ function _lineOperator(
const ascent = Math.max(...glyphGroup.map((glyph) => glyph.bBox.ba));
const descent = Math.max(...glyphGroup.map((glyph) => glyph.bBox.bd));
- const glyphLineHeight = defaultGlyphLineHeight || (ascent + descent);
+ const glyphLineHeight = defaultSpanMetrics?.lineHeight || (ascent + descent);
const {
paragraphStyle: originParagraphStyle = {},
@@ -612,7 +636,8 @@ function _lineOperator(
paragraphConfig
);
- const hasInlineCustomBlock = glyphGroup.some((glyph) => glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width !== 0);
+ const hasInlineCustomBlock = defaultSpanMetrics?.hasInlineCustomBlock ||
+ glyphGroup.some((glyph) => glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width !== 0);
const positionedCustomBlockOnly = glyphGroup.length > 0 &&
paragraphNonInlineSkeDrawings != null &&
paragraphNonInlineSkeDrawings.size > 0 &&
@@ -743,7 +768,10 @@ function _lineOperator(
lineTop,
lastPage,
headerPage,
- footerPage
+ footerPage,
+ column.left,
+ column.width,
+ section.top
); // WRAP_TOP_AND_BOTTOM drawing and WRAP NONE table will change the starting top of the line
const previousTopBottomCustomBlockFlowBottom = deferredTopBottomAnchorDrawings.length > 0
? paragraphConfig.topBottomCustomBlockFlowBottom
@@ -766,7 +794,7 @@ function _lineOperator(
paragraphConfig,
isParagraphFirstShapedText,
breakPointType,
- defaultGlyphLineHeight
+ defaultSpanMetrics
);
if (isParagraphFirstShapedText && paragraphNonInlineSkeDrawings && paragraphNonInlineSkeDrawings.size > 0) {
@@ -824,7 +852,9 @@ function _lineOperator(
paragraphConfig,
lastPage,
headerPage,
- footerPage
+ footerPage,
+ column.left,
+ section.top
);
column.lines.push(newLine);
@@ -832,8 +862,8 @@ function _lineOperator(
const blockAnchorTop = deferredTopBottomAnchorDrawings.length > 0 ? newLineTop : lineTop;
createAndUpdateBlockAnchor(paragraphIndex, newLine, blockAnchorTop, pDrawingAnchor);
if (deferredTopBottomAnchorDrawings.length > 0) {
- __updateAndPositionDrawings(ctx, newLineTop, lineHeight, column, deferredTopBottomAnchorDrawings, paragraphConfig.paragraphIndex, isParagraphFirstShapedText, blockAnchorTop, paragraphAnchorLeft, true, true);
- __updateTopBottomCustomBlockFlowBottom(paragraphConfig, deferredTopBottomAnchorDrawings);
+ __updateAndPositionDrawings(ctx, newLineTop, lineHeight, column, deferredTopBottomAnchorDrawings, paragraphConfig.paragraphIndex, isParagraphFirstShapedText, blockAnchorTop, paragraphAnchorLeft, false, true);
+ __updateTopBottomCustomBlockFlowBottom(paragraphConfig, deferredTopBottomAnchorDrawings, section.top);
}
_divideOperator(
@@ -845,7 +875,7 @@ function _lineOperator(
isParagraphFirstShapedText,
breakPointType,
- defaultGlyphLineHeight
+ defaultSpanMetrics
);
if (deferredInlineGroupAnchorDrawings.length > 0) {
@@ -963,6 +993,7 @@ function __getWrapTablePosition(
drawingAnchorTop?: number
) {
const page = column.parent?.parent;
+ const sectionTop = column.parent?.top ?? 0;
if (page == null) {
return;
}
@@ -975,10 +1006,10 @@ function __getWrapTablePosition(
const top = getPositionVertical(
positionV,
page,
- lineTop,
+ sectionTop + lineTop,
lineHeight,
height,
- drawingAnchorTop,
+ drawingAnchorTop == null ? undefined : sectionTop + drawingAnchorTop,
isPageBreak
) ?? 0;
@@ -990,6 +1021,7 @@ function __avoidFlowAffectingDrawingsForTable(
page: IDocumentSkeletonPage,
column: IDocumentSkeletonColumn
) {
+ const columnLeft = column.left ?? 0;
const tableTop = table.top;
const tableBottom = table.top + table.height;
const tableRight = table.left + table.width;
@@ -1016,7 +1048,7 @@ function __avoidFlowAffectingDrawingsForTable(
continue;
}
- if (drawingRight + table.width <= column.width) {
+ if (drawingRight + table.width <= columnLeft + column.width) {
table.left = Math.max(table.left, drawingRight);
}
}
@@ -1048,10 +1080,11 @@ function _updateAndPositionTable(
const { tableId, table } = firstUnPositionedTable;
const { tableSource } = table;
- if (firstUnPositionedTable.isSlideTable === false) {
+ if (firstUnPositionedTable.isSlideTable === false || tableSource.textWrap === TableTextWrapType.NONE) {
switch (tableSource.textWrap) {
case TableTextWrapType.NONE: {
- table.top = lineTop;
+ table.top = section.top + lineTop;
+ table.left = column.left + getTableLeft(column.width, table.width, tableSource.align, tableSource.indent);
__avoidFlowAffectingDrawingsForTable(table, page, column);
break;
}
@@ -1075,10 +1108,11 @@ function _updateAndPositionTable(
const { top, left, height } = table;
- if (!ctx.isDirty && top + height > section.height && firstUnPositionedTable.isSlideTable === false) {
+ const localTop = top - section.top;
+ if (!ctx.isDirty && localTop + height > section.height && firstUnPositionedTable.isSlideTable === false) {
// Need split table.
skeTablesInParagraph.pop();
- const availableHeight = section.height - top;
+ const availableHeight = section.height - localTop;
// TODO: handle nested table.
const { segmentId } = page;
const viewModel = ctx.viewModel.getSelfOrHeaderFooterViewModel(segmentId);
@@ -1156,7 +1190,8 @@ function _getCustomBlockIdsInLine(line: IDocumentSkeletonLine) {
function __updateTopBottomCustomBlockFlowBottom(
paragraphConfig: IParagraphConfig,
- drawings: IDocumentSkeletonDrawing[]
+ drawings: IDocumentSkeletonDrawing[],
+ sectionTop: number
) {
for (const drawing of drawings) {
const { drawingOrigin } = drawing;
@@ -1167,7 +1202,7 @@ function __updateTopBottomCustomBlockFlowBottom(
continue;
}
- const bottom = drawing.aTop + drawing.height + (drawingOrigin.distB ?? 0);
+ const bottom = drawing.aTop + drawing.height + (drawingOrigin.distB ?? 0) - sectionTop;
paragraphConfig.topBottomCustomBlockFlowBottom = Math.max(
paragraphConfig.topBottomCustomBlockFlowBottom ?? Number.NEGATIVE_INFINITY,
bottom
@@ -1182,6 +1217,32 @@ function __isZeroWidthNonFlowFloatingAnchorLine(
return __getZeroWidthNonFlowFloatingAnchorDrawings(glyphGroup, paragraphNonInlineSkeDrawings).length > 0;
}
+function __isPositionedCustomBlockOnlyLine(
+ glyphGroup: IDocumentSkeletonGlyph[],
+ paragraphNonInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>
+) {
+ let hasPositionedCustomBlock = false;
+
+ for (const glyph of glyphGroup) {
+ if (__isStructuralTerminatorGlyph(glyph) || __isIgnorableZeroSizeGlyph(glyph)) {
+ continue;
+ }
+
+ if (glyph.streamType !== DataStreamTreeTokenType.CUSTOM_BLOCK || glyph.drawingId == null) {
+ return false;
+ }
+
+ const drawingOrigin = paragraphNonInlineSkeDrawings?.get(glyph.drawingId)?.drawingOrigin;
+ if (drawingOrigin == null || drawingOrigin.layoutType === PositionedObjectLayoutType.INLINE) {
+ return false;
+ }
+
+ hasPositionedCustomBlock = true;
+ }
+
+ return hasPositionedCustomBlock;
+}
+
function __getZeroWidthNonFlowFloatingAnchorDrawings(
glyphGroup: IDocumentSkeletonGlyph[],
paragraphNonInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>
@@ -1276,16 +1337,12 @@ function _reLayoutCheck(
if (floatObjectCache.count >= FLOAT_OBJECT_RELAYOUT_LIMIT) {
continue;
}
- // TODO: How to determine if drawing is on the same page???
- const cachePageStartParagraphIndex = floatObjectCache.page.sections[0]?.columns[0]?.lines[0]?.paragraphIndex;
- const startIndex = page.sections[0]?.columns[0]?.lines[0]?.paragraphIndex;
-
- if (floatObjectCache.page && cachePageStartParagraphIndex && startIndex && cachePageStartParagraphIndex !== startIndex) {
+ if (floatObjectCache.page.pageNumber !== page.pageNumber) {
floatObjectCache.page.skeDrawings.delete(floatObject.id);
ctx.floatObjectsCache.delete(floatObject.id);
lineIterator([floatObjectCache.page], (line) => {
- const { lineHeight, top } = line;
+ const { lineHeight } = line;
const column = line.parent;
if (needBreakLineIterator || column == null) {
@@ -1293,6 +1350,7 @@ function _reLayoutCheck(
}
const { width: columnWidth, left: columnLeft } = column;
+ const top = (column.parent?.top ?? 0) + line.top;
const collision = collisionDetection(floatObjectCache.floatObject, lineHeight, top, columnLeft, columnWidth);
if (collision) {
// No need to loop next line.
@@ -1308,13 +1366,16 @@ function _reLayoutCheck(
needBreakLineIterator = false;
lineIterator([page], (line) => {
- const { lineHeight, top } = line;
- const { width: columnWidth, left: columnLeft } = column;
+ const { lineHeight } = line;
+ const lineColumn = line.parent;
- if (needBreakLineIterator) {
+ if (needBreakLineIterator || lineColumn == null) {
return;
}
+ const { width: columnWidth, left: columnLeft } = lineColumn;
+ const top = (lineColumn.parent?.top ?? 0) + line.top;
+
for (const floatObject of flowAffectingFloatObjects.values()) {
let targetObject = floatObject;
@@ -1385,6 +1446,8 @@ export const __testing = {
reLayoutCheck: _reLayoutCheck,
avoidFlowAffectingDrawingsForTable: __avoidFlowAffectingDrawingsForTable,
isGlyphGroupBeyondDivideWidth,
+ checkPageBreak: __checkPageBreak,
+ updateAndPositionTable: _updateAndPositionTable,
};
function _columnOperator(
@@ -1395,15 +1458,15 @@ function _columnOperator(
paragraphConfig: IParagraphConfig,
isParagraphFirstShapedText: boolean,
breakPointType = BreakPointType.Normal,
- defaultSpanLineHeight?: number
+ defaultSpanMetrics?: IDefaultSpanMetrics
) {
const lastPage = getLastPage(pages);
const columnIsFull = isColumnFull(lastPage);
if (columnIsFull === true) {
- _pageOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType, defaultSpanLineHeight);
+ _pageOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType, defaultSpanMetrics);
} else {
- _lineOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType, defaultSpanLineHeight);
+ _lineOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType, defaultSpanMetrics);
}
}
@@ -1415,13 +1478,13 @@ function _pageOperator(
paragraphConfig: IParagraphConfig,
isParagraphFirstShapedText: boolean,
breakPointType = BreakPointType.Normal,
- defaultSpanLineHeight?: number
+ defaultSpanMetrics?: IDefaultSpanMetrics
) {
const curSkeletonPage: IDocumentSkeletonPage = getLastPage(pages);
const { skeHeaders, skeFooters } = paragraphConfig;
pages.push(createSkeletonPage(ctx, sectionBreakConfig, { skeHeaders, skeFooters }, curSkeletonPage?.pageNumber + 1));
- _columnOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType, defaultSpanLineHeight);
+ _columnOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType, defaultSpanMetrics);
}
/**
@@ -1764,6 +1827,9 @@ function __getDrawingPosition(
const drawings: Map<string, IDocumentSkeletonDrawing> = new Map();
const isPageBreak = __checkPageBreak(column);
+ const sectionTop = column.parent?.top ?? 0;
+ const absoluteLineTop = sectionTop + lineTop;
+ const absoluteBlockAnchorTop = blockAnchorTop == null ? undefined : sectionTop + blockAnchorTop;
// TODO: @jocs In paragraph cross-page scenario (one paragraph across two pages), default to placing drawing on the previous page, and do not process drawing on the next page?
if (isPageBreak && !isParagraphFirstShapedText) {
@@ -1813,10 +1879,10 @@ function __getDrawingPosition(
drawing.aTop = getPositionVertical(
positionV,
page,
- lineTop,
+ absoluteLineTop,
lineHeight,
drawingHeight,
- blockAnchorTop,
+ absoluteBlockAnchorTop,
isPageBreak
) ?? 0;
drawing.width = drawingWidth;
@@ -1834,10 +1900,10 @@ function __getDrawingPosition(
: undefined;
drawing.initialState = true;
drawing.columnLeft = column.left;
- drawing.lineTop = lineTop;
+ drawing.lineTop = absoluteLineTop;
drawing.lineHeight = lineHeight;
drawing.isPageBreak = isPageBreak;
- drawing.blockAnchorTop = blockAnchorTop ?? lineTop;
+ drawing.blockAnchorTop = absoluteBlockAnchorTop ?? absoluteLineTop;
drawings.set(drawing.drawingId, drawing);
}
@@ -1885,6 +1951,12 @@ function __checkPageBreak(column: IDocumentSkeletonColumn) {
if (!section) {
return false;
}
+
+ const pageSections = section.parent?.sections;
+ if (pageSections && pageSections[0] !== section) {
+ return false;
+ }
+
const columns = section?.columns;
if (!columns) {
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.ts
index 081755e423..5ba8bef75a 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.ts
@@ -190,6 +190,13 @@ function horizontalAlignHandler(
for (let i = 0; i < divides.length; i++) {
const divide = divides[i];
const { width } = divide;
+
+ if (divide.glyphGroup.length === 0) {
+ divide.glyphGroupWidth = 0;
+ divide.paddingLeft = 0;
+ continue;
+ }
+
let glyphGroupWidth = getGlyphGroupWidth(divide);
divide.glyphGroupWidth = glyphGroupWidth;
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 1284006d0b..ebfe5ff7f7 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
@@ -474,16 +474,28 @@ export function lineBreaking(
drawingAnchor?.set(segmentId, segmentDrawingAnchorCache);
}
+ const resolvedParagraphStyle = _applyBlockRangeLayoutParagraphStyle(
+ viewModel.getBody?.() ?? null,
+ paragraph,
+ paragraphStyle,
+ documentStyle,
+ shouldApplyDocumentDefaults
+ );
+ const borderBottom = resolvedParagraphStyle.borderBottom;
+
+ if (borderBottom) {
+ // Keep the stroke inside the paragraph's post-text region when spaceBelow is smaller.
+ _withMinSpacing(
+ resolvedParagraphStyle,
+ 'spaceBelow',
+ Math.max(0, borderBottom.padding ?? 0) + Math.max(0, borderBottom.width ?? 1) / 2
+ );
+ }
+
const paragraphConfig: IParagraphConfig = {
paragraphIndex: endIndex,
documentCompatibilityPolicy,
- paragraphStyle: _applyBlockRangeLayoutParagraphStyle(
- viewModel.getBody?.() ?? null,
- paragraph,
- paragraphStyle,
- documentStyle,
- shouldApplyDocumentDefaults
- ),
+ paragraphStyle: resolvedParagraphStyle,
docxFallbackAnchorLeft: _getFollowingIndentedParagraphAnchorLeft(
viewModel,
paragraph,
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts
index 3bfa306e3b..ef5934d9a0 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts
@@ -48,7 +48,7 @@ import { getBoundingBox } from '../../model/line';
import { fontLibrary } from '../../shaping-engine/font-library';
import { textShape } from '../../shaping-engine/text-shaping';
import { prepareParagraphBody } from '../../shaping-engine/utils';
-import { getCharSpaceApply, getCustomRangeGlyphWidth, getFontCreateConfig } from '../../tools';
+import { getCharSpaceApply, getCustomRangeGlyphMetrics, getFontCreateConfig } from '../../tools';
import { ArabicHandler, emojiHandler, otherHandler, ThaiHandler, TibetanHandler } from './language-ruler';
// Now we apply consecutive punctuation adjustment, specified in Chinese Layout
@@ -212,7 +212,7 @@ export function shaping(
const newSpan = createSkeletonLetterGlyph(
char,
config,
- getCustomRangeGlyphWidth(start, viewModel, paragraphNode, config),
+ getCustomRangeGlyphMetrics(start, viewModel, paragraphNode, config),
glyphInfo
);
shapedGlyphs.push(newSpan);
@@ -285,7 +285,7 @@ export function shaping(
newGlyph = createSkeletonLetterGlyph(
char,
config,
- getCustomRangeGlyphWidth(i, viewModel, paragraphNode, config)
+ getCustomRangeGlyphMetrics(i, viewModel, paragraphNode, config)
);
}
} else {
diff --git a/packages/engine-render/src/components/docs/layout/block/section.ts b/packages/engine-render/src/components/docs/layout/block/section.ts
index d35b3fd606..b927470a53 100644
--- a/packages/engine-render/src/components/docs/layout/block/section.ts
+++ b/packages/engine-render/src/components/docs/layout/block/section.ts
@@ -66,7 +66,12 @@ export function dealWithSection(
if (paragraphNode.nodeType === DataStreamTreeNodeType.PARAGRAPH) {
// Paragraph
- if (ctx.paragraphsOpenNewPage.has(paragraphNode.endIndex)) {
+ // Opening the anchor paragraph on a new page is a one-shot relayout instruction.
+ // Keeping it would advance the paragraph by one more page on every dirty-layout retry.
+ if (
+ ctx.paragraphsOpenNewPage.delete(paragraphNode.endIndex) &&
+ currentPageCache.sections.some((section) => section.columns.some((column) => column.lines.length > 0))
+ ) {
currentPageCache = createSkeletonPage(
ctx,
sectionBreakConfig,
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 f4cf213914..35c07bbfc0 100644
--- a/packages/engine-render/src/components/docs/layout/block/table.ts
+++ b/packages/engine-render/src/components/docs/layout/block/table.ts
@@ -148,7 +148,7 @@ export function createTableSkeleton(
const { pageWidth, marginLeft = 0, marginRight = 0 } = curPage;
- tableSkeleton.left = _getTableLeft(pageWidth - marginLeft - marginRight, tableWidth, table.align, table.indent);
+ tableSkeleton.left = getTableLeft(pageWidth - marginLeft - marginRight, tableWidth, table.align, table.indent);
return tableSkeleton;
}
@@ -254,7 +254,7 @@ function updateTableSkeletonsPosition(
) {
const { pageWidth, marginLeft = 0, marginRight = 0 } = curPage;
const { tableWidth } = cache;
- const tableLeft = _getTableLeft(pageWidth - marginLeft - marginRight, tableWidth, table.align, table.indent);
+ const tableLeft = getTableLeft(pageWidth - marginLeft - marginRight, tableWidth, table.align, table.indent);
let tableIndex = 0;
for (const tableSkeleton of skeTables) {
@@ -663,7 +663,7 @@ function isCoveredTableCell(cellConfig: ITableCell | undefined): boolean {
return cellConfig?.rowSpan === 0 || cellConfig?.columnSpan === 0;
}
-function _getTableLeft(pageWidth: number, tableWidth: number, align: TableAlignmentType, indent: INumberUnit = { v: 0 }) {
+export function getTableLeft(pageWidth: number, tableWidth: number, align: TableAlignmentType, indent: INumberUnit = { v: 0 }) {
switch (align) {
case TableAlignmentType.START: {
return indent.v;
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 a7eef9d676..3b621e9b22 100644
--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
@@ -1365,7 +1365,11 @@ export class DocumentSkeleton extends Skeleton {
if (sectionType === SectionType.CONTINUOUS && curSkeletonPage != null) {
updateBlockIndex(allSkeletonPages, -1, ctx.docsConfig.documentCompatibilityPolicy);
- this._addNewSectionByContinuous(curSkeletonPage, columnProperties!, columnSeparatorType!);
+ if (layoutAnchor != null && layoutAnchor >= sectionNode.startIndex && layoutAnchor <= sectionNode.endIndex) {
+ this._restoreContinuousSection(curSkeletonPage, columnProperties!, columnSeparatorType!);
+ } else {
+ this._addNewSectionByContinuous(curSkeletonPage, columnProperties!, columnSeparatorType!);
+ }
isContinuous = true;
} else if (layoutAnchor == null || curSkeletonPage == null) {
curSkeletonPage = createSkeletonPage(
@@ -1466,6 +1470,35 @@ export class DocumentSkeleton extends Skeleton {
sections.push(newSection);
}
+ private _restoreContinuousSection(
+ curSkeletonPage: IDocumentSkeletonPage,
+ columnProperties: ISectionColumnProperties[],
+ columnSeparatorType: ColumnSeparatorType
+ ) {
+ const section = curSkeletonPage.sections[curSkeletonPage.sections.length - 1];
+ if (section == null) {
+ return;
+ }
+
+ const pageContentWidth = curSkeletonPage.pageWidth - curSkeletonPage.marginLeft - curSkeletonPage.marginRight;
+ const pageContentHeight = curSkeletonPage.pageHeight - curSkeletonPage.marginTop - curSkeletonPage.marginBottom;
+ const restoredSection = createSkeletonSection(
+ columnProperties,
+ columnSeparatorType,
+ section.top,
+ 0,
+ pageContentWidth,
+ pageContentHeight - section.top
+ );
+
+ for (const column of restoredSection.columns.slice(section.columns.length)) {
+ column.parent = section;
+ section.columns.push(column);
+ }
+ section.colCount = restoredSection.colCount;
+ section.height = restoredSection.height;
+ }
+
private _findNodeByIndex(charIndex: number, segmentId = '', segmentPageIndex = -1) {
const skeletonData = this.getSkeletonData();
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 2f29d0407d..704767f355 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
@@ -236,6 +236,94 @@ describe('line model', () => {
expect(line.divides[0].width).toBe(20);
});
+ it('maps a drawing that crosses columns into each column coordinate system', () => {
+ const page = {
+ skeDrawings: new Map([
+ ['cross-column', {
+ aTop: 0,
+ aLeft: 80,
+ width: 40,
+ height: 20,
+ angle: 0,
+ drawingOrigin: {
+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,
+ distL: 0,
+ distR: 0,
+ distT: 0,
+ distB: 0,
+ wrapText: WrapTextType.BOTH_SIDES,
+ },
+ }],
+ ]),
+ skeTables: new Map(),
+ } as any;
+ const createLineForColumn = (columnLeft: number) => createSkeletonLine(
+ 1,
+ LineType.PARAGRAPH,
+ { lineHeight: 20, lineTop: 0, contentHeight: 14 },
+ 100,
+ 0,
+ true,
+ {} as any,
+ page,
+ null,
+ null,
+ columnLeft
+ );
+
+ const firstColumnLine = createLineForColumn(0);
+ const secondColumnLine = createLineForColumn(100);
+
+ expect(firstColumnLine.divides).toHaveLength(1);
+ expect(firstColumnLine.divides[0]).toMatchObject({ left: 0, width: 80 });
+ expect(secondColumnLine.divides).toHaveLength(1);
+ expect(secondColumnLine.divides[0]).toMatchObject({ left: 20, width: 80 });
+ });
+
+ it('matches page-relative drawings against section-relative line tops', () => {
+ const page = {
+ skeDrawings: new Map([
+ ['section-drawing', {
+ aTop: 80,
+ aLeft: 20,
+ width: 40,
+ height: 20,
+ angle: 0,
+ drawingOrigin: {
+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,
+ distL: 0,
+ distR: 0,
+ distT: 0,
+ distB: 0,
+ wrapText: WrapTextType.BOTH_SIDES,
+ },
+ }],
+ ]),
+ skeTables: new Map(),
+ } as any;
+
+ const line = createSkeletonLine(
+ 1,
+ LineType.PARAGRAPH,
+ { lineHeight: 10, lineTop: 10, contentHeight: 10 },
+ 100,
+ 0,
+ true,
+ {} as any,
+ page,
+ null,
+ null,
+ 0,
+ 70
+ );
+
+ expect(line.top).toBe(10);
+ expect(line.divides).toMatchObject([
+ { left: 0, width: 20 },
+ { left: 60, width: 40 },
+ ]);
+ });
+
it('does not split line divides for behind-doc wrap-none drawings', () => {
const page = {
skeDrawings: new Map([
@@ -414,6 +502,34 @@ describe('line model', () => {
expect(noOverlapTop).toBe(0);
});
+ it('only applies top-bottom drawings to intersecting columns', () => {
+ const page = {
+ skeDrawings: new Map([['left-column', createTopBottomDrawing(10, 40)]]),
+ skeTables: new Map(),
+ } as any;
+
+ expect(calculateLineTopByDrawings(15, 10, page, null, null, 0, 100)).toBe(52);
+ expect(calculateLineTopByDrawings(15, 10, page, null, null, 110, 100)).toBe(10);
+ });
+
+ it('only applies no-wrap tables to intersecting columns', () => {
+ const page = {
+ skeDrawings: new Map(),
+ skeTables: new Map([
+ ['left-column', {
+ top: 10,
+ left: 0,
+ width: 100,
+ height: 42,
+ tableSource: { textWrap: TableTextWrapType.NONE },
+ }],
+ ]),
+ } as any;
+
+ expect(calculateLineTopByDrawings(15, 10, page, null, null, 0, 100)).toBe(52);
+ expect(calculateLineTopByDrawings(15, 10, page, null, null, 110, 100)).toBe(10);
+ });
+
it('pushes line top below wrap drawings that block the whole column', () => {
const page = {
skeDrawings: new Map([
diff --git a/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts b/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts
index 429364e052..a2c9a742bf 100644
--- a/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts
@@ -335,6 +335,62 @@ describe('page model', () => {
expect(updateInlineDrawingCoordsAndBorderMock).toHaveBeenCalled();
});
+ it('finishes dirty floating-object relayout inside the table cell segment', () => {
+ dealWithSectionMock.mockClear();
+ resetContextMock.mockClear();
+ const ctx = {
+ layoutStartPointer: {},
+ skeletonResourceReference: createSkeletonResourceReference(),
+ isDirty: false,
+ } as any;
+ resetContextMock.mockImplementationOnce(() => {
+ ctx.isDirty = false;
+ });
+ dealWithSectionMock
+ .mockImplementationOnce((_ctx: any, _vm: any, _node: any, areaPage: any) => {
+ ctx.isDirty = true;
+ ctx.layoutStartPointer['table-1'] = 7;
+ return {
+ pages: [
+ { ...createDealPage(areaPage), pageNumber: 1 },
+ { ...createDealPage(areaPage), pageNumber: 2 },
+ ],
+ };
+ })
+ .mockImplementationOnce((_ctx: any, _vm: any, _node: any, areaPage: any, _config: any, layoutAnchor: any) => {
+ expect(layoutAnchor).toBe(7);
+ expect(areaPage.pageNumber).toBe(2);
+ return { pages: [createDealPage(areaPage)] };
+ });
+
+ const pages = createSkeletonCellPages(
+ ctx,
+ {} as any,
+ { startIndex: 10, endIndex: 20, children: [{}] } as any,
+ {
+ lists: [],
+ localeService: {} as any,
+ drawings: {},
+ pageSize: { width: 300, height: 200 },
+ headerTreeMap: new Map(),
+ footerTreeMap: new Map(),
+ } as any,
+ {
+ tableId: 'table-1',
+ tableRows: [{ tableCells: [{}] }],
+ tableColumns: [{ size: { width: { v: 80 } } }],
+ } as any,
+ 0,
+ 0
+ );
+
+ expect(pages.map((page) => page.pageNumber)).toEqual([1, 2]);
+ expect(ctx.isDirty).toBe(false);
+ expect(ctx.layoutStartPointer['table-1']).toBeNull();
+ expect(dealWithSectionMock).toHaveBeenCalledTimes(2);
+ expect(resetContextMock).toHaveBeenCalledTimes(1);
+ });
+
it('shrinks default cell margins for extremely narrow table columns', () => {
const ctx = {
layoutStartPointer: {},
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 5e6bccbba4..933d45c52d 100644
--- a/packages/engine-render/src/components/docs/layout/model/glyph.ts
+++ b/packages/engine-render/src/components/docs/layout/model/glyph.ts
@@ -94,10 +94,22 @@ export function createSkeletonWordGlyph(
export function createSkeletonLetterGlyph(
content: string,
config: IFontCreateConfig,
- glyphWidth?: number,
+ glyphMetrics?: number | { ascent?: number; descent?: number; width?: number },
glyphInfo?: IOpenTypeGlyphInfo
): IDocumentSkeletonGlyph {
- return _createSkeletonWordOrLetter(GlyphType.LETTER, content, config, glyphWidth, glyphInfo);
+ const glyphWidth = typeof glyphMetrics === 'number' ? glyphMetrics : glyphMetrics?.width;
+ const glyph = _createSkeletonWordOrLetter(GlyphType.LETTER, content, config, glyphWidth, glyphInfo);
+
+ if (typeof glyphMetrics === 'object') {
+ if (glyphMetrics.ascent != null) {
+ glyph.bBox.ba = glyph.bBox.aba = glyphMetrics.ascent;
+ }
+ if (glyphMetrics.descent != null) {
+ glyph.bBox.bd = glyph.bBox.abd = glyphMetrics.descent;
+ }
+ }
+
+ return glyph;
}
export function createSkeletonTabGlyph(config: IFontCreateConfig, glyphWidth?: number): IDocumentSkeletonGlyph {
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 cf598f6ab2..e3faa8583a 100644
--- a/packages/engine-render/src/components/docs/layout/model/line.ts
+++ b/packages/engine-render/src/components/docs/layout/model/line.ts
@@ -70,7 +70,9 @@ export function createSkeletonLine(
paragraphConfig: IParagraphConfig,
page: IDocumentSkeletonPage,
headerPage: Nullable<IDocumentSkeletonPage>,
- footerPage: Nullable<IDocumentSkeletonPage>
+ footerPage: Nullable<IDocumentSkeletonPage>,
+ columnLeft: number = 0,
+ sectionTop: number = 0
): IDocumentSkeletonLine {
const {
lineHeight = 15.6,
@@ -118,7 +120,8 @@ export function createSkeletonLine(
? [__getDivideSKe(0, columnWidth)]
: _calculateDividesByDrawings(
lineHeight,
- lineTop,
+ sectionTop + lineTop,
+ columnLeft,
columnWidth,
paddingLeft,
paddingRight,
@@ -145,9 +148,11 @@ export function calculateLineTopByDrawings(
headerPage: Nullable<IDocumentSkeletonPage>,
footerPage: Nullable<IDocumentSkeletonPage>,
columnLeft: number = 0,
- columnWidth: number = 0
+ columnWidth: number = 0,
+ sectionTop: number = 0
) {
- let maxTop = lineTop;
+ const absoluteLineTop = sectionTop + lineTop;
+ let maxTop = absoluteLineTop;
const pageSkeDrawings = page.skeDrawings;
const skeNonWrapTables = new Map(Array.from(page.skeTables).filter(([_, table]) => table.tableSource.textWrap === TableTextWrapType.NONE));
const headersDrawings = headerPage?.skeDrawings;
@@ -156,7 +161,13 @@ export function calculateLineTopByDrawings(
if (headerPage && headersDrawings) {
headersDrawings.forEach((drawing) => {
const transformedDrawing = translateHeaderFooterDrawingPosition(drawing, headerPage, page, true);
- const top = _getLineTopWidthWrapTopBottom(transformedDrawing, lineHeight, lineTop);
+ const top = _getLineTopWidthWrapTopBottom(
+ transformedDrawing,
+ lineHeight,
+ absoluteLineTop,
+ columnLeft,
+ columnWidth
+ );
if (top) {
maxTop = Math.max(maxTop, top);
}
@@ -166,7 +177,13 @@ export function calculateLineTopByDrawings(
if (footerPage && footersDrawings) {
footersDrawings.forEach((drawing) => {
const transformedDrawing = translateHeaderFooterDrawingPosition(drawing, footerPage, page, false);
- const top = _getLineTopWidthWrapTopBottom(transformedDrawing, lineHeight, lineTop);
+ const top = _getLineTopWidthWrapTopBottom(
+ transformedDrawing,
+ lineHeight,
+ absoluteLineTop,
+ columnLeft,
+ columnWidth
+ );
if (top) {
maxTop = Math.max(maxTop, top);
}
@@ -174,24 +191,24 @@ export function calculateLineTopByDrawings(
}
pageSkeDrawings?.forEach((drawing) => {
- const top = _getLineTopWidthWrapTopBottom(drawing, lineHeight, lineTop);
+ const top = _getLineTopWidthWrapTopBottom(drawing, lineHeight, absoluteLineTop, columnLeft, columnWidth);
if (top) {
maxTop = Math.max(maxTop, top);
}
- const blockingWrapTop = _getLineTopWithFullColumnWrap(drawing, lineHeight, lineTop, columnLeft, columnWidth);
+ const blockingWrapTop = _getLineTopWithFullColumnWrap(drawing, lineHeight, absoluteLineTop, columnLeft, columnWidth);
if (blockingWrapTop) {
maxTop = Math.max(maxTop, blockingWrapTop);
}
});
skeNonWrapTables?.forEach((table) => {
- const top = _getLineTopWidthWrapNone(table, lineHeight, lineTop);
+ const top = _getLineTopWidthWrapNone(table, lineHeight, absoluteLineTop, columnLeft, columnWidth);
if (top) {
maxTop = Math.max(maxTop, top);
}
});
- return maxTop;
+ return maxTop - sectionTop;
}
function _getLineTopWithFullColumnWrap(
@@ -261,8 +278,18 @@ function _getLineTopWithFullColumnWrap(
return bottom;
}
-function _getLineTopWidthWrapNone(table: IDocumentSkeletonTable, lineHeight: number, lineTop: number) {
- const { top, height } = table;
+function _getLineTopWidthWrapNone(
+ table: IDocumentSkeletonTable,
+ lineHeight: number,
+ lineTop: number,
+ columnLeft: number,
+ columnWidth: number
+) {
+ const { top, height, left, width } = table;
+
+ if (columnWidth > 0 && (left + width <= columnLeft || left >= columnLeft + columnWidth)) {
+ return;
+ }
// No need to consider the dist.
if (top + height < lineTop || top > lineHeight + lineTop) {
@@ -272,7 +299,13 @@ function _getLineTopWidthWrapNone(table: IDocumentSkeletonTable, lineHeight: num
return top + height;
}
-function _getLineTopWidthWrapTopBottom(drawing: IDocumentSkeletonDrawing, lineHeight: number, lineTop: number) {
+function _getLineTopWidthWrapTopBottom(
+ drawing: IDocumentSkeletonDrawing,
+ lineHeight: number,
+ lineTop: number,
+ columnLeft: number,
+ columnWidth: number
+) {
const { aTop, height, aLeft, width, angle = 0, drawingOrigin } = drawing;
const { layoutType, distT = 0, distB = 0 } = drawingOrigin;
@@ -280,6 +313,15 @@ function _getLineTopWidthWrapTopBottom(drawing: IDocumentSkeletonDrawing, lineHe
return;
}
+ if (columnWidth > 0) {
+ const bounds = angle === 0 ? { left: aLeft, width } : getBoundingBox(angle, aLeft, width, aTop, height);
+ const drawingLeft = bounds.left ?? aLeft;
+ const drawingRight = drawingLeft + (bounds.width ?? width);
+ if (drawingRight <= columnLeft || drawingLeft >= columnLeft + columnWidth) {
+ return;
+ }
+ }
+
// if (elementIndex && showElementIndex < elementIndex) {
// // Drawing appears after a specific element, usually in the same paragraph cross-page scenario
// // When operating on drawing, set showElementIndex if cross-page
@@ -311,6 +353,7 @@ function _getLineTopWidthWrapTopBottom(drawing: IDocumentSkeletonDrawing, lineHe
function _calculateDividesByDrawings(
lineHeight: number,
lineTop: number,
+ columnLeft: number,
columnWidth: number,
paddingLeft: number,
paddingRight: number,
@@ -338,7 +381,7 @@ function _calculateDividesByDrawings(
if (headerPage && headersDrawings) {
headersDrawings.forEach((drawing) => {
const transformedDrawing = translateHeaderFooterDrawingPosition(drawing, headerPage, page, true);
- const split = _calculateSplit(transformedDrawing, lineHeight, lineTop, columnWidth);
+ const split = _calculateSplit(transformedDrawing, lineHeight, lineTop, columnLeft, columnWidth);
if (split) {
drawingsMix.push(split);
@@ -349,7 +392,7 @@ function _calculateDividesByDrawings(
if (footerPage && footersDrawings) {
footersDrawings.forEach((drawing) => {
const transformedDrawing = translateHeaderFooterDrawingPosition(drawing, footerPage, page, false);
- const split = _calculateSplit(transformedDrawing, lineHeight, lineTop, columnWidth);
+ const split = _calculateSplit(transformedDrawing, lineHeight, lineTop, columnLeft, columnWidth);
if (split) {
drawingsMix.push(split);
@@ -358,7 +401,7 @@ function _calculateDividesByDrawings(
}
paragraphNonInlineSkeDrawings?.forEach((drawing) => {
- const split = _calculateSplit(drawing, lineHeight, lineTop, columnWidth);
+ const split = _calculateSplit(drawing, lineHeight, lineTop, columnLeft, columnWidth);
if (split) {
drawingsMix.push(split);
@@ -369,7 +412,7 @@ function _calculateDividesByDrawings(
wrapTypeTables.forEach((table) => {
const { left, top, width, height, tableSource } = table;
const { dist } = tableSource;
- const split = __getSplitWidthNoAngle(top, height, left, width, lineTop, lineHeight, columnWidth, dist);
+ const split = __getSplitWidthNoAngle(top, height, left - columnLeft, width, lineTop, lineHeight, columnWidth, dist);
if (split) {
drawingsMix.push(split);
@@ -414,6 +457,7 @@ function _calculateSplit(
drawing: IDocumentSkeletonDrawing,
lineHeight: number,
lineTop: number,
+ columnLeft: number,
columnWidth: number
): Nullable<IDrawingsSplit> {
const { aTop, height, aLeft, width, angle = 0, drawingOrigin } = drawing;
@@ -439,6 +483,10 @@ function _calculateSplit(
points.push(new Vector2(point[0], point[1]));
}
+ points.forEach((point) => {
+ point.x -= columnLeft;
+ });
+
if (angle !== 0) {
const transform = new Transform().rotate(angle); // Create a rotated transform class
for (let i = 0; i < points.length; i++) {
@@ -455,11 +503,11 @@ function _calculateSplit(
if (angle === 0) {
// No rotation case, wrapSquare | wrapThrough | wrapTight
- return __getSplitWidthNoAngle(aTop, height, aLeft, width, lineTop, lineHeight, columnWidth, dist, layoutType, wrapText);
+ return __getSplitWidthNoAngle(aTop, height, aLeft - columnLeft, width, lineTop, lineHeight, columnWidth, dist, layoutType, wrapText);
}
// In rotation case, consider the maximum area obtained by the first/last position of the line and the rotated drawing
- const boundingBox = getBoundingBox(angle, aLeft, width, aTop, height);
+ const boundingBox = getBoundingBox(angle, aLeft - columnLeft, width, aTop, height);
if (layoutType === PositionedObjectLayoutType.WRAP_SQUARE) {
// In WRAP_SQUARE case, the rotated shape will have a new rect, use this new rect to determine split
diff --git a/packages/engine-render/src/components/docs/layout/model/page.ts b/packages/engine-render/src/components/docs/layout/model/page.ts
index 74633eb7dc..0e166cbc55 100644
--- a/packages/engine-render/src/components/docs/layout/model/page.ts
+++ b/packages/engine-render/src/components/docs/layout/model/page.ts
@@ -386,17 +386,42 @@ export function createSkeletonCellPages(
maxCellPageHeight
);
- const { pages } = dealWithSection(
- ctx,
- viewModel,
- sectionNode,
- areaPage,
- cellSectionBreakConfig
- );
+ const segmentId = tableConfig.tableId;
+ const retainedPages: IDocumentSkeletonPage[] = [];
+ let currentPage = areaPage;
+ let pages: IDocumentSkeletonPage[] = [];
+
+ for (let count = 0; count <= 10; count++) {
+ const layoutAnchor = ctx.layoutStartPointer[segmentId];
+ ctx.layoutStartPointer[segmentId] = null;
+
+ const result = dealWithSection(
+ ctx,
+ viewModel,
+ sectionNode,
+ currentPage,
+ cellSectionBreakConfig,
+ layoutAnchor
+ );
+ pages = [...retainedPages, ...result.pages];
+
+ if (!ctx.isDirty || ctx.layoutStartPointer[segmentId] == null || count === 10) {
+ break;
+ }
+
+ const retryPage = pages.at(-1);
+ if (retryPage == null) {
+ break;
+ }
+
+ retainedPages.splice(0, retainedPages.length, ...pages.slice(0, -1));
+ currentPage = retryPage;
+ resetContext(ctx);
+ }
for (const p of pages) {
p.type = DocumentSkeletonPageType.CELL;
- p.segmentId = tableConfig.tableId;
+ p.segmentId = segmentId;
}
updateBlockIndex(
diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.ts
index ead3692f6a..fad2235e75 100644
--- a/packages/engine-render/src/components/docs/layout/tools.ts
+++ b/packages/engine-render/src/components/docs/layout/tools.ts
@@ -75,7 +75,7 @@ import {
} from '@univerjs/core';
import { DEFAULT_DOCUMENT_FONTSIZE } from '../../../basics/const';
import { GlyphType, LineType } from '../../../basics/i-document-skeleton-cached';
-import { getFontStyleString, isFunction } from '../../../basics/tools';
+import { getFontStyleString, isFunction, ptToPixel } from '../../../basics/tools';
import { getDocumentCompatibilityPolicy } from '../document-compatibility';
import { getDocsTableRenderViewport, hasDocsTableHorizontalViewport } from '../table-render-viewport';
import { updateInlineDrawingPosition } from './block/paragraph/layout-ruler';
@@ -1522,13 +1522,30 @@ export function getCustomRangeGlyphWidth(
paragraphNode: DataStreamTreeNode,
config: IFontCreateConfig
): number | undefined {
+ return getCustomRangeGlyphMetrics(index, viewModel, paragraphNode, config)?.width;
+}
+
+export function getCustomRangeGlyphMetrics(
+ index: number,
+ viewModel: DocumentViewModel,
+ paragraphNode: DataStreamTreeNode,
+ config: IFontCreateConfig
+): { ascent?: number; descent?: number; width?: number } | undefined {
const customRange = viewModel.getCustomRange(index + paragraphNode.startIndex);
- const glyphWidthEm = customRange?.glyphWidthEm;
- if (typeof glyphWidthEm !== 'number' || !Number.isFinite(glyphWidthEm) || glyphWidthEm < 0) {
+ if (!customRange) {
return undefined;
}
- return glyphWidthEm * config.fontStyle.originFontSize;
+ const fontSize = ptToPixel(config.fontStyle.originFontSize);
+ const toPixels = (value: unknown) =>
+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value * fontSize : undefined;
+ const metrics = {
+ ascent: toPixels(customRange.glyphAscentEm),
+ descent: toPixels(customRange.glyphDescentEm),
+ width: toPixels(customRange.glyphWidthEm),
+ };
+
+ return metrics.ascent == null && metrics.descent == null && metrics.width == null ? undefined : metrics;
}
// Generate an empty doc skeleton with the initial states.
diff --git a/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts b/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts
index 8d646c14f6..791281533b 100644
--- a/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts
+++ b/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts
@@ -46,7 +46,7 @@ function createService() {
describe('BrowserClipboardService', () => {
beforeEach(() => {
vi.mocked(supportClipboardAPI).mockReturnValue(true);
- (globalThis as any).ClipboardItem = MockClipboardItem;
+ vi.stubGlobal('ClipboardItem', MockClipboardItem);
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: {
@@ -61,6 +61,7 @@ describe('BrowserClipboardService', () => {
afterEach(() => {
vi.restoreAllMocks();
+ vi.unstubAllGlobals();
});
it('should expose clipboard support from utility', () => {
@@ -98,6 +99,16 @@ describe('BrowserClipboardService', () => {
expect(document.execCommand).toHaveBeenCalledWith('copy');
});
+ it('should fallback to legacy copy when ClipboardItem is unavailable', async () => {
+ vi.stubGlobal('ClipboardItem', undefined);
+ const { service } = createService();
+
+ await service.write('legacy', '<i>legacy</i>');
+
+ expect(document.execCommand).toHaveBeenCalledWith('copy');
+ expect(navigator.clipboard.write).not.toHaveBeenCalled();
+ });
+
it('should write raw sanitized html during legacy copy event', async () => {
vi.mocked(supportClipboardAPI).mockReturnValue(false);
const { service } = createService();
diff --git a/packages/ui/src/services/clipboard/clipboard-interface.service.ts b/packages/ui/src/services/clipboard/clipboard-interface.service.ts
index 49942ba745..069051f758 100644
--- a/packages/ui/src/services/clipboard/clipboard-interface.service.ts
+++ b/packages/ui/src/services/clipboard/clipboard-interface.service.ts
@@ -186,7 +186,7 @@ export class BrowserClipboardService extends Disposable implements IClipboardInt
}
async write(text: string, html: string, customData?: Record<string, string>): Promise<void> {
- if (!this.supportClipboard) {
+ if (!this.supportClipboard || typeof ClipboardItem === 'undefined' || typeof navigator.clipboard.write !== 'function') {
return this._legacyCopyHtml(text, html);
}