Skip to content

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

fix(docs): preserve block spacing, list styles and link hover (#7952)

Univer5ef0f54d6e4a
diff --git a/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts b/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
index a9482b25fd..992b49c701 100644
--- a/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
+++ b/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
@@ -18,7 +18,7 @@
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
import type { RenderUnit } from '@univerjs/engine-render';
-import { IPermissionService, LocaleService, LocaleType, Univer, UniverInstanceType } from '@univerjs/core';
+import { DocumentFlavor, IPermissionService, LocaleService, LocaleType, Univer, UniverInstanceType } from '@univerjs/core';
import {
DocLayoutExecutorService,
DocSelectionManagerService,
@@ -50,7 +50,7 @@ afterEach(() => {
vi.useRealTimers();
});
-function createService() {
+function createService(documentFlavor = DocumentFlavor.TRADITIONAL) {
// Canvas is the unavailable platform boundary; document and popup services stay real.
const context = new Proxy({ webkitBackingStorePixelRatio: 1, measureText: (text: string) => ({ width: text.length * 8, actualBoundingBoxAscent: 10, actualBoundingBoxDescent: 2, fontBoundingBoxAscent: 10, fontBoundingBoxDescent: 2 }) }, {
get: (target, key) => key in target ? Reflect.get(target, key) : () => {},
@@ -76,7 +76,7 @@ function createService() {
const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
id: 'doc-1',
body: { dataStream: 'first link and second link\r\n', paragraphs: [{ startIndex: 26, paragraphId: 'paragraph' }], sectionBreaks: [{ startIndex: 27, sectionId: 'section' }] },
- documentStyle: { pageSize: { width: 400, height: 300 } },
+ documentStyle: { documentFlavor, pageSize: { width: 400, height: 300 } },
});
univer.createUnit(UniverInstanceType.UNIVER_DOC, { id: 'doc-2' });
const manager = injector.get(IRenderManagerService);
@@ -97,6 +97,7 @@ function createService() {
const remove = vi.spyOn(canvasPopup, 'removePopup');
return {
injector,
+ model,
registerCustomHyperLinkUI: () => registerEditorRuntimeConfig(model, { customHyperLinkUI: true }),
dispose: () => univer.dispose(),
selectionManager,
@@ -318,26 +319,217 @@ describe('DocHyperLinkPopupService', () => {
}
});
- it('keeps the current popup while the pointer crosses adjacent links', () => {
- const { injector, attached, disposed } = createService();
- const service = injector.get(DocHyperLinkPopupService);
+ describe.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('hover in document flavor %s', (documentFlavor) => {
const firstLink = { unitId: 'doc-1', linkId: 'link-1', startIndex: 4, endIndex: 8 };
const secondLink = { unitId: 'doc-1', linkId: 'link-2', startIndex: 9, endIndex: 13 };
- service.showInfoPopup(firstLink);
- service.showInfoPopupFromHover(secondLink);
+ it('waits for hover intent on another link without extending the deadline for repeated hover events', () => {
+ vi.useFakeTimers();
+ const { injector, attached } = createService(documentFlavor);
+ const service = injector.get(DocHyperLinkPopupService);
+
+ service.showInfoPopupFromHover(secondLink);
+ service.showInfoPopupFromHover(firstLink);
+ vi.advanceTimersByTime(100);
+ service.showInfoPopupFromHover({ ...firstLink, segmentId: '' });
+ vi.advanceTimersByTime(99);
+ expect(service.showing).toEqual(secondLink);
+ expect(attached()).toHaveLength(1);
- expect(service.showing).toEqual(firstLink);
- expect(attached()).toHaveLength(1);
- expect(disposed()).toEqual([]);
+ vi.advanceTimersByTime(1);
+ expect(service.showing).toEqual(firstLink);
+ expect(attached()).toHaveLength(2);
+ });
- service.hideInfoPopup();
- service.showInfoPopupFromHover(secondLink);
- expect(service.showing).toEqual(secondLink);
- expect(attached()).toHaveLength(2);
- expect(disposed()).toEqual([1]);
+ it('replaces a hovered link in both directions without remounting the same link or changing the document', () => {
+ vi.useFakeTimers();
+ const { injector, attached, disposed, model } = createService(documentFlavor);
+ const service = injector.get(DocHyperLinkPopupService);
+ const snapshot = structuredClone(model.getSnapshot());
+
+ service.showInfoPopupFromHover(firstLink);
+ service.showInfoPopupFromHover(secondLink);
+ vi.advanceTimersByTime(200);
+ expect(service.showing).toEqual(secondLink);
+ expect(attached().at(-1)?.range).toMatchObject({ startOffset: 9, endOffset: 14 });
+ expect(disposed()).toEqual([1]);
- service.dispose();
+ service.showInfoPopupFromHover({ ...secondLink, segmentId: '' });
+ expect(attached()).toHaveLength(2);
+ expect(disposed()).toEqual([1]);
+
+ service.showInfoPopupFromHover(firstLink);
+ vi.advanceTimersByTime(200);
+ expect(service.showing).toEqual(firstLink);
+ expect(attached()).toHaveLength(3);
+ expect(disposed()).toEqual([1, 2]);
+ expect(service.infoPopupPinned).toBe(false);
+ expect(model.getSnapshot()).toEqual(snapshot);
+ });
+
+ it('cancels the previous link close timer and keeps the new popup open during pointer handoff', () => {
+ vi.useFakeTimers();
+ const { injector, disposed } = createService(documentFlavor);
+ const service = injector.get(DocHyperLinkPopupService);
+
+ service.showInfoPopupFromHover(firstLink);
+ service.scheduleHideInfoPopup();
+ vi.advanceTimersByTime(149);
+ service.showInfoPopupFromHover(secondLink);
+ vi.advanceTimersByTime(1);
+ expect(service.showing).toEqual(firstLink);
+ expect(disposed()).toEqual([]);
+ vi.advanceTimersByTime(199);
+ expect(service.showing).toEqual(secondLink);
+ expect(disposed()).toEqual([1]);
+
+ service.scheduleHideInfoPopup();
+ vi.advanceTimersByTime(149);
+ service.cancelScheduledHideInfoPopup();
+ vi.advanceTimersByTime(150);
+ expect(service.showing).toEqual(secondLink);
+
+ service.scheduleHideInfoPopup();
+ vi.advanceTimersByTime(150);
+ expect(service.showing).toBeNull();
+ expect(disposed()).toEqual([1, 2]);
+ });
+
+ it('cancels replacement when returning to the original link or leaving the candidate', () => {
+ vi.useFakeTimers();
+ const { injector, attached } = createService(documentFlavor);
+ const service = injector.get(DocHyperLinkPopupService);
+
+ service.showInfoPopupFromHover(firstLink);
+ service.showInfoPopupFromHover(secondLink);
+ vi.advanceTimersByTime(100);
+ service.showInfoPopupFromHover(firstLink);
+ vi.advanceTimersByTime(200);
+ expect(service.showing).toEqual(firstLink);
+ expect(attached()).toHaveLength(1);
+
+ service.showInfoPopupFromHover(secondLink);
+ vi.advanceTimersByTime(100);
+ service.scheduleHideInfoPopup();
+ vi.advanceTimersByTime(200);
+ expect(service.showing).toBeNull();
+ expect(attached()).toHaveLength(1);
+ });
+
+ it('ignores late canvas hover and leave events inside the popup and releases ownership on pointer leave', () => {
+ vi.useFakeTimers();
+ const { injector, attached } = createService(documentFlavor);
+ const service = injector.get(DocHyperLinkPopupService);
+
+ service.showInfoPopupFromHover(secondLink);
+ service.showInfoPopupFromHover(firstLink);
+ vi.advanceTimersByTime(100);
+ service.setInfoPopupHovered(true);
+ vi.advanceTimersByTime(30);
+ service.showInfoPopupFromHover(firstLink);
+ service.scheduleHideInfoPopup();
+ vi.advanceTimersByTime(200);
+ expect(service.showing).toEqual(secondLink);
+ expect(attached()).toHaveLength(1);
+
+ service.setInfoPopupHovered(false);
+ service.scheduleHideInfoPopup();
+ vi.advanceTimersByTime(149);
+ expect(service.showing).toEqual(secondLink);
+ vi.advanceTimersByTime(1);
+ expect(service.showing).toBeNull();
+ service.showInfoPopupFromHover(firstLink);
+ service.showInfoPopupFromHover(secondLink);
+ vi.advanceTimersByTime(200);
+ expect(service.showing).toEqual(secondLink);
+ });
+
+ it.each(['pin', 'edit', 'hide', 'dispose', 'dispose-render'] as const)('cancels pending replacement on %s', (action) => {
+ vi.useFakeTimers();
+ const { injector, attached, disposeRender } = createService(documentFlavor);
+ const service = injector.get(DocHyperLinkPopupService);
+
+ service.showInfoPopupFromHover(firstLink);
+ service.showInfoPopupFromHover(secondLink);
+ vi.advanceTimersByTime(100);
+ switch (action) {
+ case 'pin':
+ service.showInfoPopup(firstLink, { pinned: true });
+ break;
+ case 'edit':
+ service.showEditPopup('doc-1', firstLink);
+ break;
+ case 'hide':
+ service.hideInfoPopup();
+ break;
+ case 'dispose':
+ service.dispose();
+ break;
+ case 'dispose-render':
+ disposeRender('doc-1');
+ break;
+ }
+ const attachedCount = attached().length;
+ vi.advanceTimersByTime(200);
+ expect(attached()).toHaveLength(attachedCount);
+ expect(service.showing).toEqual(action === 'pin' || action === 'edit' ? firstLink : null);
+ if (action === 'pin') {
+ expect(service.infoPopupPinned).toBe(true);
+ }
+ if (action === 'edit') {
+ expect(service.editing).toEqual(firstLink);
+ }
+ });
+
+ it('preserves click pinning until the pinned popup closes', () => {
+ const { injector, attached, disposed } = createService(documentFlavor);
+ const service = injector.get(DocHyperLinkPopupService);
+
+ service.showInfoPopup(firstLink, { pinned: true });
+ service.showInfoPopupFromHover(secondLink);
+ expect(service.showing).toEqual(firstLink);
+ expect(service.infoPopupPinned).toBe(true);
+ expect(attached()).toHaveLength(1);
+ expect(disposed()).toEqual([]);
+
+ service.hideInfoPopup();
+ service.showInfoPopupFromHover(secondLink);
+ expect(service.showing).toEqual(secondLink);
+ expect(service.infoPopupPinned).toBe(false);
+ expect(attached()).toHaveLength(2);
+ });
+
+ it('does not reopen a hover popup during pointer-down suppression', () => {
+ vi.useFakeTimers();
+ const { injector, attached } = createService(documentFlavor);
+ const service = injector.get(DocHyperLinkPopupService);
+
+ service.showInfoPopupFromHover(firstLink);
+ service.hideInfoPopupOnPointerDown();
+ service.showInfoPopupFromHover(secondLink);
+ expect(service.showing).toBeNull();
+ expect(attached()).toHaveLength(1);
+
+ vi.advanceTimersByTime(0);
+ service.showInfoPopupFromHover(secondLink);
+ expect(service.showing).toEqual(secondLink);
+ expect(attached()).toHaveLength(2);
+ });
+ });
+
+ it('cancels replacement when its candidate render is disposed without closing the current popup', () => {
+ vi.useFakeTimers();
+ const { injector, attached, disposeRender } = createService();
+ const service = injector.get(DocHyperLinkPopupService);
+ const firstLink = { unitId: 'doc-1', linkId: 'link-1', startIndex: 4, endIndex: 8 };
+
+ service.showInfoPopupFromHover(firstLink);
+ service.showInfoPopupFromHover({ unitId: 'doc-2', linkId: 'link-2', startIndex: 0, endIndex: 3 });
+ disposeRender('doc-2');
+ vi.advanceTimersByTime(200);
+
+ expect(service.showing).toEqual(firstLink);
+ expect(attached()).toHaveLength(1);
});
it('does not show link information when the target document is not loaded', () => {
diff --git a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
index 98b4ac38cb..4f6c9e574a 100644
--- a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
+++ b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
@@ -49,6 +49,7 @@ export interface ILinkInfo {
}
const INFO_POPUP_HIDE_DELAY = 150;
+const INFO_POPUP_REPLACEMENT_DELAY = 200;
function isSameLinkInfo(current: ILinkInfo | null, next: ILinkInfo): boolean {
return current?.linkId === next.linkId &&
@@ -69,7 +70,9 @@ export class DocHyperLinkPopupService extends Disposable {
private _editPopupUnitId: string | null = null;
private _infoPopup: IDisposable | null = null;
private _infoPopupPinned = false;
+ private _infoPopupHovered = false;
private _infoPopupHideTimer: ReturnType<typeof setTimeout> | null = null;
+ private _infoPopupReplacement: { info: ILinkInfo; timer: ReturnType<typeof setTimeout> } | null = null;
private _infoPopupSuppressed = false;
private _infoPopupSuppressionTimer: ReturnType<typeof setTimeout> | null = null;
@@ -105,6 +108,9 @@ export class DocHyperLinkPopupService extends Disposable {
}
}));
this.disposeWithMe(this._renderManagerService.disposed$.subscribe((unitId) => {
+ if (this._infoPopupReplacement?.info.unitId === unitId) {
+ this._cancelScheduledInfoPopupReplacement();
+ }
if (this._editPopupUnitId === unitId) {
this.hideEditPopup();
}
@@ -133,6 +139,7 @@ export class DocHyperLinkPopupService extends Disposable {
}
showEditPopup(unitId: string, linkInfo: ILinkInfo | null): IDisposable | null {
+ this._cancelScheduledInfoPopupReplacement();
const doc = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
if (doc && getEditorRuntimeConfig(doc)?.customHyperLinkUI) {
return null;
@@ -187,6 +194,7 @@ export class DocHyperLinkPopupService extends Disposable {
if (!(doc instanceof DocumentDataModel) || getEditorRuntimeConfig(doc)?.customHyperLinkUI) {
return;
}
+ this._cancelScheduledInfoPopupReplacement();
this.cancelScheduledHideInfoPopup();
if (this._infoPopupSuppressed) {
return;
@@ -206,6 +214,7 @@ export class DocHyperLinkPopupService extends Disposable {
this._infoPopup = null;
}
this._infoPopupPinned = options?.pinned ?? false;
+ this._infoPopupHovered = false;
this._showingLink$.next({ unitId, linkId, segmentId, segmentPage, startIndex, endIndex });
this._infoPopup = this._openInfoSurface(info);
@@ -256,17 +265,47 @@ export class DocHyperLinkPopupService extends Disposable {
showInfoPopupFromHover(info: ILinkInfo): void {
this.cancelScheduledHideInfoPopup();
- if (this._infoPopupPinned || this._infoPopupSuppressed) {
+ if (this._infoPopupPinned || this._infoPopupHovered || this._infoPopupSuppressed) {
return;
}
- if (!this.showing) {
+ if (!this.showing || isSameLinkInfo(this.showing, info)) {
this.showInfoPopup(info);
+ return;
+ }
+ if (isSameLinkInfo(this._infoPopupReplacement?.info ?? null, info)) {
+ return;
+ }
+ this._cancelScheduledInfoPopupReplacement();
+ const pendingInfo = { ...info };
+ this._infoPopupReplacement = {
+ info: pendingInfo,
+ timer: setTimeout(() => {
+ this._infoPopupReplacement = null;
+ this.showInfoPopup(pendingInfo);
+ }, INFO_POPUP_REPLACEMENT_DELAY),
+ };
+ }
+
+ setInfoPopupHovered(hovered: boolean): void {
+ this._infoPopupHovered = hovered && this.showing !== null;
+ if (this._infoPopupHovered) {
+ this._cancelScheduledInfoPopupReplacement();
+ this.cancelScheduledHideInfoPopup();
+ }
+ }
+
+ private _cancelScheduledInfoPopupReplacement(): void {
+ if (this._infoPopupReplacement) {
+ clearTimeout(this._infoPopupReplacement.timer);
+ this._infoPopupReplacement = null;
}
}
hideInfoPopup() {
+ this._cancelScheduledInfoPopupReplacement();
this.cancelScheduledHideInfoPopup();
this._infoPopupPinned = false;
+ this._infoPopupHovered = false;
this._showingLink$.next(null);
const popup = this._infoPopup;
this._infoPopup = null;
@@ -274,7 +313,8 @@ export class DocHyperLinkPopupService extends Disposable {
}
scheduleHideInfoPopup() {
- if (this._infoPopupPinned || !this.showing) {
+ this._cancelScheduledInfoPopupReplacement();
+ if (this._infoPopupPinned || this._infoPopupHovered || !this.showing) {
return;
}
diff --git a/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx b/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
index 0bed3d062b..98216aed0b 100644
--- a/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
+++ b/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-import type { LocaleKey } from '../locale/types';
import {
CustomRangeType,
DocumentDataModel,
@@ -29,6 +28,7 @@ import { getDocumentPermissionValue } from '@univerjs/docs';
import { CopyIcon, LinkIcon, UnlinkIcon, WriteIcon } from '@univerjs/icons';
import { UnitAction } from '@univerjs/protocol';
import { IMessageService, useDependency, useObservable } from '@univerjs/ui';
+import type { LocaleKey } from '../locale/types';
import { DeleteDocHyperLinkCommand } from '../commands/commands/delete-link.command';
import { ClickDocHyperLinkOperation, ShowDocHyperLinkEditPopupOperation } from '../commands/operations/popup.operation';
import { DocHyperLinkPopupService } from '../services/hyper-link-popup.service';
@@ -67,9 +67,10 @@ export const DocLinkPopup = () => {
dark:!univer-bg-gray-900
`, borderClassName)}
onPointerEnter={() => {
- hyperLinkService.cancelScheduledHideInfoPopup();
+ hyperLinkService.setInfoPopupHovered(true);
}}
onPointerLeave={() => {
+ hyperLinkService.setInfoPopupHovered(false);
hyperLinkService.scheduleHideInfoPopup();
}}
onClick={() => {
diff --git a/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx b/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx
index 604a80d817..d74436e6f6 100644
--- a/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx
+++ b/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx
@@ -16,10 +16,9 @@
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
import type { Root } from 'react-dom/client';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
import {
CustomRangeType,
+ DocumentFlavor,
ICommandService,
IPermissionService,
IUniverInstanceService,
@@ -34,14 +33,16 @@ import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { UnitAction } from '@univerjs/protocol';
import { IDialogService, IMessageService, RediContext } from '@univerjs/ui';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { of } from 'rxjs';
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { AddDocHyperLinkCommand } from '../../commands/commands/add-link.command';
import { DeleteDocHyperLinkCommand } from '../../commands/commands/delete-link.command';
import { UpdateDocHyperLinkCommand } from '../../commands/commands/update-link.command';
-import { ShowDocHyperLinkEditPopupOperation } from '../../commands/operations/popup.operation';
+import { ClickDocHyperLinkOperation, ShowDocHyperLinkEditPopupOperation } from '../../commands/operations/popup.operation';
import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
import { DocHyperLinkEdit } from '../DocHyperLinkEdit';
import { DocLinkPopup } from '../DocLinkPopup';
@@ -103,7 +104,7 @@ function createDocData(): IDocumentData {
};
}
-function createPopupTestBed() {
+function createPopupTestBed(documentData = createDocData()) {
const univer = new Univer();
const injector = univer.__getInjector();
@@ -122,7 +123,7 @@ function createPopupTestBed() {
}]);
injector.add([DocHyperLinkPopupService]);
- const doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData());
+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, documentData);
injector.get(IUniverInstanceService).focusUnit(UNIT_ID);
injector.get(LocaleService).load({
[LocaleType.EN_US]: {
@@ -151,6 +152,7 @@ function createPopupTestBed() {
commandService.registerCommand(UpdateDocHyperLinkCommand);
commandService.registerCommand(DeleteDocHyperLinkCommand);
commandService.registerCommand(ShowDocHyperLinkEditPopupOperation);
+ commandService.registerCommand(ClickDocHyperLinkOperation);
commandService.registerCommand(RichTextEditingMutation);
return {
@@ -212,6 +214,8 @@ describe('DocLinkPopup', () => {
root = undefined;
container = undefined;
currentTestBed = undefined;
+ vi.restoreAllMocks();
+ vi.useRealTimers();
});
it('keeps desktop and mobile hyperlink edit components independent', () => {
@@ -254,6 +258,102 @@ describe('DocLinkPopup', () => {
});
});
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('displays and edits the newly hovered link (document flavor %s)', async (documentFlavor) => {
+ vi.useFakeTimers();
+ const documentData = createDocData();
+ documentData.documentStyle = { ...documentData.documentStyle, documentFlavor };
+ documentData.body?.customRanges?.unshift({
+ startIndex: 0,
+ endIndex: 4,
+ rangeId: 'first-link',
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: { url: 'https://example.com/first' },
+ });
+ currentTestBed = createPopupTestBed(documentData);
+ currentTestBed.popupService.showInfoPopupFromHover({
+ unitId: UNIT_ID,
+ linkId: 'first-link',
+ startIndex: 0,
+ endIndex: 4,
+ });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const actions = renderPopup(root, container, currentTestBed);
+ expect(container.textContent).toContain('https://example.com/first');
+ expect(container.textContent).not.toContain('https://univer.ai');
+ const secondLink = { unitId: UNIT_ID, linkId: 'existing-link', startIndex: 6, endIndex: 10 };
+ const executedCommands: Array<{ id: string; params: unknown }> = [];
+ currentTestBed.commandService.onCommandExecuted((command) => {
+ executedCommands.push({ id: command.id, params: command.params });
+ });
+
+ await act(async () => {
+ currentTestBed?.popupService.showInfoPopupFromHover(secondLink);
+ vi.advanceTimersByTime(200);
+ });
+ expect(container.textContent).toContain('https://univer.ai');
+ expect(container.textContent).not.toContain('https://example.com/first');
+ expect(container.contains(actions.edit)).toBe(true);
+
+ await act(async () => {
+ actions.edit.click();
+ });
+
+ expect(executedCommands).toContainEqual({
+ id: ShowDocHyperLinkEditPopupOperation.id,
+ params: { link: { ...secondLink, segmentId: undefined, segmentPage: undefined } },
+ });
+ expect(currentTestBed.popupService.editing).toEqual(secondLink);
+ expect(currentTestBed.popupService.showing).toBeNull();
+ });
+
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('keeps the current URL clickable while crossing an adjacent link into its popup (document flavor %s)', async (documentFlavor) => {
+ vi.useFakeTimers();
+ const documentData = createDocData();
+ documentData.documentStyle = { ...documentData.documentStyle, documentFlavor };
+ documentData.body?.customRanges?.unshift({
+ startIndex: 0,
+ endIndex: 4,
+ rangeId: 'first-link',
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: { url: 'https://example.com/first' },
+ });
+ currentTestBed = createPopupTestBed(documentData);
+ const popupService = currentTestBed.popupService;
+ const secondLink = { unitId: UNIT_ID, linkId: 'existing-link', startIndex: 6, endIndex: 10 };
+ popupService.showInfoPopupFromHover(secondLink);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ renderPopup(root, container, currentTestBed);
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+ const popup = container.firstElementChild;
+ expect(popup).toBeInstanceOf(HTMLElement);
+
+ await act(async () => {
+ popupService.showInfoPopupFromHover({ unitId: UNIT_ID, linkId: 'first-link', startIndex: 0, endIndex: 4 });
+ vi.advanceTimersByTime(100);
+ popup?.dispatchEvent(new MouseEvent('pointerover', { bubbles: true }));
+ vi.advanceTimersByTime(30);
+ popupService.showInfoPopupFromHover({ unitId: UNIT_ID, linkId: 'first-link', startIndex: 0, endIndex: 4 });
+ popupService.scheduleHideInfoPopup();
+ vi.advanceTimersByTime(200);
+ });
+ expect(popupService.showing).toEqual(secondLink);
+ expect(container.firstElementChild).toBe(popup);
+ expect(container.textContent).toContain('https://univer.ai');
+ expect(container.textContent).not.toContain('https://example.com/first');
+
+ const url = Array.from(container.querySelectorAll('span')).find((span) => span.textContent === 'https://univer.ai');
+ expect(url).toBeDefined();
+ await act(async () => {
+ url?.click();
+ });
+ expect(open).toHaveBeenCalledExactlyOnceWith('https://univer.ai', '_blank', 'noopener noreferrer');
+ expect(popupService.showing).toBeNull();
+ });
+
it('disables the copy action when document copy permission is denied', () => {
currentTestBed = createPopupTestBed();
setDocumentPermissionValue(
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts
index e9854b1c19..e269241bb7 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts
@@ -751,6 +751,25 @@ describe('docs layout tools extra', () => {
expect(JSON.stringify(dataModel.getSnapshot())).toBe(before);
});
+ it.each([true, false])('keeps marker and hyperlink font caches separate with marker first %s', (markerFirst) => {
+ clearFontCreateConfigCache();
+ const paragraph = { startIndex: 4, paragraphId: 'linked-paragraph' };
+ const { viewModel, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('Link', {
+ body: {
+ paragraphs: [paragraph],
+ textRuns: [{ st: 0, ed: 4, ts: { fs: 18, cl: { rgb: '#123456' } } }],
+ customRanges: [{ startIndex: 0, endIndex: 3, rangeId: 'link', rangeType: CustomRangeType.HYPERLINK, properties: { url: 'https://example.test' } }],
+ },
+ });
+ for (const marker of [markerFirst, !markerFirst, markerFirst]) {
+ const config = getFontCreateConfig(0, viewModel, paragraphNode, sectionBreakConfig, paragraph, !marker);
+ expect(config.textStyle.fs).toBe(18);
+ expect(config.textStyle.cl).toEqual({ rgb: marker ? '#123456' : 'blue.600' });
+ expect(config.textStyle.ul?.s).toBe(marker ? undefined : BooleanNumber.TRUE);
+ }
+ clearFontCreateConfigCache();
+ });
+
it('creates default skeleton, prepares section config, and resolves page paths', () => {
const skeleton = getNullSkeleton();
const pages = [{ segmentId: 'seg-1' }, { segmentId: 'seg-2' }] as any[];
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/list-marker-style.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/list-marker-style.spec.ts
new file mode 100644
index 0000000000..a83080c2af
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/list-marker-style.spec.ts
@@ -0,0 +1,194 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IBullet, IHyperlink, ITextStyle } from '@univerjs/core';
+import { BooleanNumber, CustomRangeType, DataStreamTreeTokenType, DocumentFlavor, PositionedObjectLayoutType, PRESET_LIST_TYPE, PresetListType } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { GlyphType } from '../../../../../../basics/i-document-skeleton-cached';
+import { FontCache } from '../../../shaping-engine/font-cache';
+import { dealWidthParagraph } from '../paragraph-layout';
+import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';
+
+const CONTENT = 'Workspace architecture';
+
+function layoutList(
+ documentFlavor: DocumentFlavor,
+ listType: PresetListType,
+ options: {
+ linkStart?: number;
+ properties?: Partial<IHyperlink> & { textColorMode?: 'text' };
+ runStyle?: ITextStyle;
+ bulletStyle?: ITextStyle;
+ listStyle?: ITextStyle;
+ markStyle?: ITextStyle;
+ floatingAnchor?: boolean;
+ } = {}
+) {
+ const bullet: IBullet = { listId: 'marker-style', listType, nestingLevel: 0, textStyle: options.bulletStyle };
+ const offset = options.floatingAnchor ? 1 : 0;
+ const content = options.floatingAnchor ? `${DataStreamTreeTokenType.CUSTOM_BLOCK}${CONTENT}` : CONTENT;
+ const bed = createParagraphLayoutTestBed(content, {
+ body: {
+ paragraphs: [{ startIndex: content.length, paragraphId: 'list-paragraph', bullet, paragraphStyle: { paragraphMarkTextStyle: options.markStyle } }],
+ textRuns: [
+ ...offset ? [{ st: 0, ed: offset, ts: {} }] : [],
+ { st: offset, ed: content.length, ts: options.runStyle ?? {} },
+ ],
+ customBlocks: options.floatingAnchor ? [{ startIndex: 0, blockId: 'behind-picture' }] : [],
+ customRanges: options.linkStart == null
+ ? []
+ : [{
+ startIndex: options.linkStart + offset,
+ endIndex: content.length - 1,
+ rangeId: 'workspace-link',
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: { url: 'https://example.test/workspace', ...options.properties },
+ }],
+ },
+ drawings: options.floatingAnchor
+ ? {
+ 'behind-picture': {
+ drawingId: 'behind-picture',
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ behindDoc: BooleanNumber.TRUE,
+ docTransform: {
+ size: { width: 120, height: 90 },
+ positionH: { posOffset: 0 },
+ positionV: { posOffset: 0 },
+ angle: 0,
+ },
+ },
+ }
+ : {},
+ documentStyle: { documentFlavor },
+ lists: options.listStyle == null
+ ? undefined
+ : {
+ [listType]: {
+ ...PRESET_LIST_TYPE[listType],
+ nestingLevel: PRESET_LIST_TYPE[listType].nestingLevel.map((level) => ({ ...level, textStyle: options.listStyle })),
+ },
+ },
+ });
+ const snapshot = structuredClone(bed.dataModel.getSnapshot());
+ const pages = dealWidthParagraph(bed.ctx, bed.viewModel, bed.paragraphNode, bed.curPage, bed.sectionBreakConfig);
+ const lines = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));
+ const glyphs = lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup));
+ const marker = glyphs.find((glyph) => glyph.glyphType === GlyphType.LIST)!;
+ const text = glyphs.filter((glyph) => glyph.glyphType !== GlyphType.LIST);
+ expect(marker).toBeDefined();
+ expect(bed.dataModel.getSnapshot()).toEqual(snapshot);
+ return { marker, text, lines };
+}
+
+describe.each([DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL])('list marker hyperlink styles in flavor %s', (flavor) => {
+ it.each([PresetListType.BULLET_LIST, PresetListType.ORDER_LIST])('keeps a leading hyperlink off the %s marker without changing layout', (listType) => {
+ const reference = layoutList(flavor, listType);
+ const linked = layoutList(flavor, listType, { linkStart: 0 });
+
+ expect(linked.marker.ts).toEqual(reference.marker.ts);
+ expect(linked.marker.ts?.cl?.rgb).not.toBe('blue.600');
+ expect(linked.marker.ts?.ul?.s).not.toBe(BooleanNumber.TRUE);
+ expect(linked.text[0].ts).toMatchObject({ cl: { rgb: 'blue.600' }, ul: { s: BooleanNumber.TRUE } });
+ expect(linked.marker.width).toBe(reference.marker.width);
+ expect(linked.marker.bBox).toEqual(reference.marker.bBox);
+ expect(linked.text.map(({ width, left, bBox }) => ({ width, left, bBox })))
+ .toEqual(reference.text.map(({ width, left, bBox }) => ({ width, left, bBox })));
+ expect(linked.lines.map(({ top, lineHeight }) => ({ top, lineHeight })))
+ .toEqual(reference.lines.map(({ top, lineHeight }) => ({ top, lineHeight })));
+ });
+
+ it('does not change a marker when the hyperlink starts later in the item', () => {
+ const reference = layoutList(flavor, PresetListType.BULLET_LIST);
+ const linked = layoutList(flavor, PresetListType.BULLET_LIST, { linkStart: 10 });
+ expect(linked.marker.ts).toEqual(reference.marker.ts);
+ expect(linked.text.find((glyph) => glyph.ts?.cl?.rgb === 'blue.600')?.ts?.ul?.s).toBe(BooleanNumber.TRUE);
+ });
+
+ it.each([
+ { textColorMode: 'text' },
+ { textStyleMode: 'text' },
+ ] satisfies Array<Partial<IHyperlink> & { textColorMode?: 'text' }>)('preserves hyperlink text appearance mode %j', (properties) => {
+ const runStyle: ITextStyle = { cl: { rgb: '#8E24AA' }, ul: { s: BooleanNumber.TRUE }, fs: 18, bl: BooleanNumber.TRUE };
+ const reference = layoutList(flavor, PresetListType.ORDER_LIST, { runStyle });
+ const linked = layoutList(flavor, PresetListType.ORDER_LIST, { linkStart: 0, properties, runStyle });
+ expect(linked.marker.ts).toEqual(reference.marker.ts);
+ expect(linked.text[0].ts).toMatchObject(runStyle);
+ });
+
+ it('preserves explicitly styled markers ahead of hyperlink styling', () => {
+ const bulletStyle: ITextStyle = { cl: { rgb: '#8E24AA' }, ul: { s: BooleanNumber.TRUE }, fs: 18 };
+ const linked = layoutList(flavor, PresetListType.ORDER_LIST, { linkStart: 0, bulletStyle });
+ expect(linked.marker.ts).toMatchObject(bulletStyle);
+ expect(linked.text[0].ts).toMatchObject({ cl: { rgb: 'blue.600' }, ul: { s: BooleanNumber.TRUE } });
+ const listStyle: ITextStyle = { cl: { rgb: '#4CAF50' }, ul: { s: BooleanNumber.FALSE } };
+ const listStyled = layoutList(flavor, PresetListType.ORDER_LIST, { linkStart: 0, bulletStyle, listStyle });
+ expect(listStyled.marker.ts).toMatchObject({ ...bulletStyle, ...listStyle });
+ });
+
+ it('preserves authored leading-run color when paragraph-mark color is unspecified', () => {
+ const runStyle: ITextStyle = { cl: { rgb: '#8E24AA' }, fs: 18, bl: BooleanNumber.TRUE };
+ const reference = layoutList(flavor, PresetListType.ORDER_LIST, { runStyle });
+ const linked = layoutList(flavor, PresetListType.ORDER_LIST, { linkStart: 0, runStyle });
+ expect(linked.marker.ts).toEqual(reference.marker.ts);
+ expect(linked.marker.ts).toMatchObject(runStyle);
+ expect(linked.text[0].ts).toMatchObject({ cl: { rgb: 'blue.600' }, fs: 18, bl: BooleanNumber.TRUE });
+ });
+
+ it.each([false, true])('keeps first visible run style after a floating anchor with link %s', (link) => {
+ const measure = vi.spyOn(FontCache, 'getTextSize').mockReturnValue({
+ width: 8,
+ ba: 10,
+ bd: 4,
+ aba: 10,
+ abd: 4,
+ sp: 0,
+ sbr: 0,
+ sbo: 0,
+ spr: 0,
+ spo: 0,
+ });
+ try {
+ const runStyle: ITextStyle = { cl: { rgb: '#8E24AA' }, ul: { s: BooleanNumber.TRUE }, fs: 18 };
+ const result = layoutList(flavor, PresetListType.ORDER_LIST, { floatingAnchor: true, runStyle, linkStart: link ? 0 : undefined });
+ expect(result.marker.ts).toMatchObject({
+ ...runStyle,
+ ul: { s: flavor === DocumentFlavor.TRADITIONAL ? BooleanNumber.FALSE : BooleanNumber.TRUE },
+ });
+ } finally {
+ measure.mockRestore();
+ }
+ });
+});
+
+it('preserves traditional paragraph-mark color ahead of a linked leading run', () => {
+ const linked = layoutList(DocumentFlavor.TRADITIONAL, PresetListType.ORDER_LIST, {
+ linkStart: 0,
+ runStyle: { cl: { rgb: '#8E24AA' } },
+ markStyle: { cl: { rgb: '#4CAF50' }, ul: { s: BooleanNumber.TRUE } },
+ });
+ expect(linked.marker.ts).toMatchObject({ cl: { rgb: '#4CAF50' }, ul: { s: BooleanNumber.FALSE } });
+ expect(linked.text[0].ts).toMatchObject({ cl: { rgb: 'blue.600' }, ul: { s: BooleanNumber.TRUE } });
+});
+
+it('keeps authored first-run color, underline and typography on modern markers', () => {
+ const runStyle: ITextStyle = { cl: { rgb: '#8E24AA' }, ul: { s: BooleanNumber.TRUE }, fs: 18, bl: BooleanNumber.TRUE };
+ const reference = layoutList(DocumentFlavor.MODERN, PresetListType.BULLET_LIST, { runStyle });
+ const linked = layoutList(DocumentFlavor.MODERN, PresetListType.BULLET_LIST, { linkStart: 0, runStyle });
+ expect(linked.marker.ts).toEqual(reference.marker.ts);
+ expect(linked.marker.ts).toMatchObject(runStyle);
+ expect(linked.text[0].ts).toMatchObject({ cl: { rgb: 'blue.600' }, ul: { s: BooleanNumber.TRUE }, fs: 18, bl: BooleanNumber.TRUE });
+});
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/quote-block-layout.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/quote-block-layout.spec.ts
new file mode 100644
index 0000000000..f610da80cc
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/quote-block-layout.spec.ts
@@ -0,0 +1,245 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentData } from '@univerjs/core';
+import {
+ BooleanNumber,
+ DataStreamTreeTokenType,
+ DocumentBlockRangeType,
+ DocumentDataModel,
+ DocumentFlavor,
+ JSONX,
+ LocaleService,
+ SectionType,
+ TextX,
+ validateDocumentStructure,
+} from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DocumentViewModel } from '../../../../view-model/document-view-model';
+import { DocumentSkeleton } from '../../../doc-skeleton';
+import { FontCache } from '../../../shaping-engine/font-cache';
+import { clearFontCreateConfigCache } from '../../../tools';
+
+const { BLOCK_START, BLOCK_END, PARAGRAPH, SECTION_BREAK } = DataStreamTreeTokenType;
+
+function quoteSnapshot(contents: string[], flavor: DocumentFlavor, blockType: DocumentBlockRangeType, prefix = '', width = 900, terminal = false): IDocumentData {
+ const leading = prefix ? `${prefix}${PARAGRAPH}` : '';
+ const quoteText = `${contents.join(PARAGRAPH)}${PARAGRAPH}`;
+ const rangeStart = leading.length;
+ const rangeEnd = rangeStart + quoteText.length + 1;
+ const dataStream = `${leading}${BLOCK_START}${quoteText}${BLOCK_END}${terminal ? '' : `After${PARAGRAPH}`}${SECTION_BREAK}`;
+ const paragraphs = [...dataStream.matchAll(/\r/g)].map((match, index) => ({
+ startIndex: match.index!,
+ paragraphId: `quote-paragraph-${index}`,
+ paragraphStyle: match.index! > rangeStart && match.index! < rangeEnd
+ ? { indentStart: { v: 22 }, keepLines: BooleanNumber.TRUE, widowControl: BooleanNumber.TRUE }
+ : {},
+ }));
+ return {
+ id: 'quote-block-layout',
+ body: {
+ dataStream,
+ paragraphs,
+ textRuns: [],
+ sectionBreaks: [{ sectionId: 'quote-section', startIndex: dataStream.length - 1 }],
+ blockRanges: [{
+ blockId: 'quote',
+ blockType,
+ startIndex: rangeStart,
+ endIndex: rangeEnd,
+ }],
+ },
+ documentStyle: {
+ documentFlavor: flavor,
+ textStyle: { ff: 'Quote marker regression', fs: 14 },
+ pageSize: { width, height: 1000 },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ autoHyphenation: BooleanNumber.FALSE,
+ ...(flavor === DocumentFlavor.MODERN
+ ? { defaultParagraphStyle: { lineSpacing: 1.5, spaceAbove: { v: 0 }, spaceBelow: { v: 12 } } }
+ : {}),
+ },
+ };
+}
+
+function layout(snapshot: IDocumentData) {
+ expect(validateDocumentStructure(snapshot)).toEqual([]);
+ const model = new DocumentDataModel(snapshot);
+ const viewModel = new DocumentViewModel(model);
+ const skeleton = DocumentSkeleton.create(viewModel, new LocaleService());
+ const initial = structuredClone(model.getSnapshot());
+ skeleton.calculate();
+ return { model, viewModel, skeleton, initial };
+}
+
+function lines(skeleton: DocumentSkeleton) {
+ return skeleton.getSkeletonData()!.pages.flatMap((page) =>
+ page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines))
+ );
+}
+
+function quoteLines(model: DocumentDataModel, skeleton: DocumentSkeleton) {
+ const range = model.getBody()!.blockRanges![0];
+ return lines(skeleton).filter((line) => line.paragraphIndex > range.startIndex && line.paragraphIndex < range.endIndex);
+}
+
+function expectLogicalOffsets(model: DocumentDataModel, skeleton: DocumentSkeleton) {
+ const body = model.getBody()!;
+ const glyphs = lines(skeleton).flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup));
+ expect(glyphs.map((glyph) => glyph.raw).join('')).toBe(body.dataStream);
+ expect(glyphs.reduce((count, glyph) => count + glyph.count, 0)).toBe(body.dataStream.length);
+ for (const offset of [body.dataStream.indexOf('First'), body.dataStream.indexOf('After')].filter((offset) => offset >= 0)) {
+ const position = skeleton.findNodePositionByCharIndex(offset)!;
+ expect(position).toBeDefined();
+ expect(skeleton.findCharIndexByPosition(position)).toBe(offset);
+ }
+}
+
+describe.each([DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL].flatMap((flavor) =>
+ [DocumentBlockRangeType.QUOTE, DocumentBlockRangeType.CALLOUT, DocumentBlockRangeType.CODE].map((blockType) => ({ flavor, blockType }))))('native $blockType closing-marker layout in flavor $flavor', ({ flavor, blockType }) => {
+ const disposables: Array<{ dispose(): void }> = [];
+ beforeEach(() => {
+ clearFontCreateConfigCache();
+ vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text, font) => {
+ const match = font.match(/([\d.]+)(px|pt)/)!;
+ const pixels = Number(match[1]) * (match[2] === 'pt' ? 4 / 3 : 1);
+ return {
+ width: text.length * pixels / 2,
+ fontBoundingBoxAscent: pixels * 0.75,
+ fontBoundingBoxDescent: pixels * 0.25,
+ actualBoundingBoxAscent: pixels * 0.75,
+ actualBoundingBoxDescent: pixels * 0.25,
+ };
+ });
+ vi.spyOn(FontCache, 'getNormalLineHeight').mockReturnValue(14);
+ });
+ afterEach(() => {
+ for (const disposable of disposables.splice(0).reverse()) disposable.dispose();
+ vi.restoreAllMocks();
+ clearFontCreateConfigCache();
+ });
+
+ it.each([
+ { label: 'single paragraph', contents: ['First sentence.'] },
+ { label: 'multiple paragraphs', contents: ['First sentence.', 'Second sentence.'] },
+ { label: 'authored blank paragraph', contents: ['First sentence.', '', 'Second sentence.'] },
+ { label: 'empty editable quote', contents: [''] },
+ ])('does not add a rendered line for the closing marker of $label', ({ contents }) => {
+ const snapshot = quoteSnapshot(contents, flavor, blockType);
+ const { model, skeleton, initial } = layout(snapshot);
+ disposables.push(model, skeleton);
+ expect(quoteLines(model, skeleton)).toHaveLength(contents.length);
+ expect(lines(skeleton)).toHaveLength(contents.length + 1);
+ expect(model.getSnapshot()).toEqual(initial);
+ expectLogicalOffsets(model, skeleton);
+ });
+
+ it('keeps a block after an existing paragraph to its authored line', () => {
+ const { model, skeleton } = layout(quoteSnapshot(['First sentence.'], flavor, blockType, 'Before'));
+ disposables.push(model, skeleton);
+ expect(quoteLines(model, skeleton)).toHaveLength(1);
+ expect(lines(skeleton)).toHaveLength(3);
+ expectLogicalOffsets(model, skeleton);
+ });
+
+ it('keeps wrapped text and attaches the closing marker to its authored paragraph mark', () => {
+ const { model, skeleton } = layout(quoteSnapshot(['First sentence repeats and wraps to multiple lines. '.repeat(4).trimEnd()], flavor, blockType, '', 500));
+ disposables.push(model, skeleton);
+ const rendered = quoteLines(model, skeleton);
+ expect(rendered.length).toBeGreaterThan(1);
+ for (const line of rendered) {
+ const glyphs = line.divides.flatMap((divide) => divide.glyphGroup);
+ expect(glyphs.every((glyph) => glyph.raw === BLOCK_END)).toBe(false);
+ }
+ const lastGlyphs = rendered[rendered.length - 1].divides.flatMap((divide) => divide.glyphGroup);
+ expect(lastGlyphs.map((glyph) => glyph.raw).join('')).toContain(`${PARAGRAPH}${BLOCK_END}`);
+ expectLogicalOffsets(model, skeleton);
+ });
+
+ it.each([1, 2])('preserves %s authored line breaks before the closing marker', (count) => {
+ const { model, skeleton, initial } = layout(quoteSnapshot([
+ `First sentence.${DataStreamTreeTokenType.COLUMN_BREAK.repeat(count)}Second sentence.`,
+ ], flavor, blockType));
+ disposables.push(model, skeleton);
+ expect(quoteLines(model, skeleton)).toHaveLength(count + 1);
+ expect(lines(skeleton)).toHaveLength(count + 2);
+ expect(model.getSnapshot()).toEqual(initial);
+ expectLogicalOffsets(model, skeleton);
+ });
+
+ it('keeps a terminal block editable without adding a closing-marker line', () => {
+ const { model, skeleton, initial } = layout(quoteSnapshot(['First sentence.', ''], flavor, blockType, '', 900, true));
+ disposables.push(model, skeleton);
+ expect(quoteLines(model, skeleton)).toHaveLength(2);
+ expect(lines(skeleton)).toHaveLength(2);
+ expect(model.getSnapshot()).toEqual(initial);
+ expectLogicalOffsets(model, skeleton);
+ });
+
+ it('preserves ordinary body paragraph marks and authored blank paragraphs', () => {
+ const snapshot = quoteSnapshot(['First sentence.'], flavor, blockType);
+ const dataStream = `First sentence.${PARAGRAPH}${PARAGRAPH}After${PARAGRAPH}${SECTION_BREAK}`;
+ snapshot.body = {
+ dataStream,
+ paragraphs: [...dataStream.matchAll(/\r/g)].map((match, index) => ({ startIndex: match.index!, paragraphId: `plain-${index}` })),
+ sectionBreaks: [{ sectionId: 'plain-section', startIndex: dataStream.length - 1 }],
+ };
+ const { model, skeleton, initial } = layout(snapshot);
+ disposables.push(model, skeleton);
+ expect(lines(skeleton)).toHaveLength(3);
+ expect(model.getSnapshot()).toEqual(initial);
+ expectLogicalOffsets(model, skeleton);
+ });
+
+ it('preserves native pagination of a following NEXT_PAGE section after a terminal block marker', () => {
+ const snapshot = quoteSnapshot(['First sentence.'], flavor, blockType);
+ const body = snapshot.body!;
+ const sectionOffset = body.blockRanges![0].endIndex + 1;
+ body.dataStream = `${body.dataStream.slice(0, sectionOffset)}${SECTION_BREAK}${body.dataStream.slice(sectionOffset)}`;
+ body.paragraphs = body.paragraphs!.map((paragraph) => paragraph.startIndex >= sectionOffset
+ ? { ...paragraph, startIndex: paragraph.startIndex + 1 }
+ : paragraph);
+ body.sectionBreaks = [
+ { sectionId: 'block-section', startIndex: sectionOffset },
+ { sectionId: 'following-section', startIndex: body.dataStream.length - 1, sectionType: SectionType.NEXT_PAGE },
+ ];
+ const { model, skeleton, initial } = layout(snapshot);
+ disposables.push(model, skeleton);
+ expect(quoteLines(model, skeleton)).toHaveLength(1);
+ expect(lines(skeleton)).toHaveLength(2);
+ expect(skeleton.getSkeletonData()!.pages).toHaveLength(flavor === DocumentFlavor.TRADITIONAL ? 2 : 1);
+ expect(model.getSnapshot()).toEqual(initial);
+ expectLogicalOffsets(model, skeleton);
+ });
+
+ it('preserves editable model offsets and the closing marker after inserting text', () => {
+ const { model, viewModel, skeleton } = layout(quoteSnapshot(['First sentence.'], flavor, blockType));
+ disposables.push(model, skeleton);
+ const paragraphId = model.getBody()!.paragraphs![0].paragraphId;
+ const textX = new TextX().retain(1).insert(7, { dataStream: 'Edited ' });
+ model.apply(JSONX.getInstance().editOp(textX.serialize(), ['body']));
+ viewModel.reset(model);
+ skeleton.makeDirty(true);
+ skeleton.calculate();
+ expect(model.getBody()!.paragraphs![0].paragraphId).toBe(paragraphId);
+ expect(model.getBody()!.dataStream).toContain(`${BLOCK_START}Edited First sentence.${PARAGRAPH}${BLOCK_END}`);
+ expect(quoteLines(model, skeleton)).toHaveLength(1);
+ expectLogicalOffsets(model, skeleton);
+ });
+});
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/table-paragraph-spacing.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/table-paragraph-spacing.spec.ts
new file mode 100644
index 0000000000..1119682b8e
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/table-paragraph-spacing.spec.ts
@@ -0,0 +1,248 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IParagraphStyle } from '@univerjs/core';
+import {
+ DataStreamTreeTokenType,
+ DocumentFlavor,
+ NamedStyleType,
+ ObjectRelativeFromH,
+ ObjectRelativeFromV,
+ SpacingRule,
+ TableAlignmentType,
+ TableRowHeightRule,
+ TableSizeType,
+ TableTextWrapType,
+} from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { IDocumentSkeletonLine } from '../../../../../../basics/i-document-skeleton-cached';
+import { DocumentSkeleton } from '../../../doc-skeleton';
+import { clearFontCreateConfigCache } from '../../../tools';
+import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';
+
+interface ISpacingOptions {
+ before?: number;
+ after?: number;
+ pageHeight?: number;
+ rowCount?: number;
+ incremental?: boolean;
+ beforeStyle?: NamedStyleType | null;
+ afterStyle?: NamedStyleType | null;
+ defaultParagraphStyle?: IParagraphStyle;
+ tableWrap?: TableTextWrapType | null;
+}
+
+function layoutTable(documentFlavor: DocumentFlavor, options: ISpacingOptions = {}) {
+ const T = DataStreamTreeTokenType;
+ const prefix = `Before${T.PARAGRAPH}`;
+ const row = `${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}`;
+ const tableStream = options.tableWrap === null ? '' : `${T.TABLE_START}${row.repeat(options.rowCount ?? 1)}${T.TABLE_END}`;
+ const content = `${prefix}${tableStream}After`;
+ const dataStream = `${content}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const beforeIndex = prefix.length - 1;
+ const afterIndex = content.length;
+ const beforeStyle = options.beforeStyle === undefined ? NamedStyleType.HEADING_1 : options.beforeStyle;
+ const afterStyle = options.afterStyle === undefined ? NamedStyleType.HEADING_2 : options.afterStyle;
+ const paragraphs = [...dataStream.matchAll(/\r/g)].map((match) => ({
+ startIndex: match.index,
+ paragraphId: `p-${match.index}`,
+ paragraphStyle: match.index === beforeIndex
+ ? { ...(beforeStyle == null ? {} : { namedStyleType: beforeStyle }), ...(options.before == null ? {} : { spaceBelow: { v: options.before } }) }
+ : match.index === afterIndex
+ ? { ...(afterStyle == null ? {} : { namedStyleType: afterStyle }), ...(options.after == null ? {} : { spaceAbove: { v: options.after } }) }
+ : { spacingRule: SpacingRule.EXACT, lineSpacing: 20 },
+ }));
+ const bed = createParagraphLayoutTestBed(content, {
+ body: {
+ paragraphs,
+ sectionBreaks: [...dataStream.matchAll(/\n/g)].map((match) => ({ startIndex: match.index })),
+ tables: tableStream ? [{ tableId: 'between-headings', startIndex: prefix.length, endIndex: prefix.length + tableStream.length }] : [],
+ },
+ tableSource: tableStream
+ ? {
+ 'between-headings': {
+ tableId: 'between-headings',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: options.tableWrap ?? TableTextWrapType.NONE,
+ ...(options.tableWrap === TableTextWrapType.WRAP
+ ? {
+ position: {
+ positionH: { relativeFrom: ObjectRelativeFromH.COLUMN, posOffset: 20 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 200 },
+ },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ }
+ : {}),
+ size: { type: TableSizeType.SPECIFIED, width: { v: 200 } },
+ cellMargin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 200 } } }],
+ tableRows: Array.from({ length: options.rowCount ?? 1 }, () => ({
+ tableCells: [{}],
+ trHeight: { val: { v: 20 }, hRule: TableRowHeightRule.EXACT },
+ })),
+ },
+ }
+ : undefined,
+ documentStyle: {
+ documentFlavor,
+ ...(options.defaultParagraphStyle ? { defaultParagraphStyle: options.defaultParagraphStyle } : {}),
+ pageSize: { width: 400, height: options.pageHeight ?? 600 },
+ marginTop: 20,
+ marginBottom: 20,
+ paragraphLineGapDefault: 0,
+ },
+ });
+ const source = JSON.stringify(bed.dataModel.getSnapshot());
+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);
+ try {
+ if (options.incremental) {
+ const generation = skeleton.startIncrementalLayout();
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let step = 0; step < 100 && !progress.complete; step++) {
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+ expect(progress.complete).toBe(true);
+ } else {
+ skeleton.calculate();
+ }
+ expect(JSON.stringify(bed.dataModel.getSnapshot())).toBe(source);
+ const pages = skeleton.getSkeletonData()!.pages;
+ const lines = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));
+ const before = lines.find((line) => line.paragraphIndex === beforeIndex)!;
+ const after = lines.find((line) => line.paragraphIndex === afterIndex)!;
+ const tables = pages.flatMap((page) => [...page.skeTables.values()]);
+ return { before, after, tables, pages };
+ } finally {
+ skeleton.dispose();
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+}
+
+function contentBottom(line: IDocumentSkeletonLine): number {
+ return (line.parent?.parent?.top ?? 0) + line.top + line.lineHeight - (line.marginBottom ?? 0);
+}
+
+describe('paragraph spacing around native inline tables', () => {
+ beforeEach(() => {
+ clearFontCreateConfigCache();
+ vi.stubGlobal('document', {
+ createElement: () => ({
+ getContext: () => ({
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText(value: string) {
+ return {
+ width: value.length * 8,
+ fontBoundingBoxAscent: 10,
+ fontBoundingBoxDescent: 4,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 4,
+ };
+ },
+ }),
+ }),
+ });
+ });
+ afterEach(() => vi.unstubAllGlobals());
+
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('keeps SDK heading defaults on their own side of a table (flavor: %s)', (flavor) => {
+ const { before, after, tables } = layoutTable(flavor);
+ expect(tables).toHaveLength(1);
+ const table = tables[0];
+ expect(table.top - contentBottom(before)).toBeCloseTo(10);
+ expect(after.top + after.marginTop - table.top - table.height).toBeCloseTo(18);
+ });
+
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN].flatMap((flavor) => [
+ { flavor, beforeStyle: NamedStyleType.NORMAL_TEXT, afterStyle: NamedStyleType.NORMAL_TEXT, beforeGap: 12, afterGap: 0 },
+ { flavor, beforeStyle: NamedStyleType.HEADING_1, afterStyle: NamedStyleType.NORMAL_TEXT, beforeGap: 10, afterGap: 0 },
+ { flavor, beforeStyle: NamedStyleType.NORMAL_TEXT, afterStyle: NamedStyleType.HEADING_2, beforeGap: 12, afterGap: 18 },
+ ]))('keeps native body and heading spacing on their own side (flavor: $flavor, before: $beforeStyle, after: $afterStyle)', ({ flavor, beforeStyle, afterStyle, beforeGap, afterGap }) => {
+ const { before, after, tables: [table] } = layoutTable(flavor, { beforeStyle, afterStyle });
+ expect(table.top - contentBottom(before)).toBeCloseTo(beforeGap);
+ expect(after.top + after.marginTop - table.top - table.height).toBeCloseTo(afterGap);
+ });
+
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('respects unstyled body defaults without requiring a named style (flavor: %s)', (flavor) => {
+ const { before, after, tables: [table] } = layoutTable(flavor, { beforeStyle: null, afterStyle: null });
+ expect(table.top - contentBottom(before)).toBeCloseTo(flavor === DocumentFlavor.MODERN ? 12 : 0);
+ expect(after.top + after.marginTop - table.top - table.height).toBeCloseTo(0);
+ });
+
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('keeps explicit imported document defaults around a table (flavor: %s)', (flavor) => {
+ const { before, after, tables: [table] } = layoutTable(flavor, {
+ beforeStyle: null,
+ afterStyle: null,
+ defaultParagraphStyle: { spaceAbove: { v: 7 }, spaceBelow: { v: 14 } },
+ });
+ expect(table.top - contentBottom(before)).toBeCloseTo(14);
+ expect(after.top + after.marginTop - table.top - table.height).toBeCloseTo(7);
+ });
+
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN].flatMap((flavor) => [
+ { flavor, before: 40, after: 10 },
+ { flavor, before: 10, after: 40 },
+ ]))('still collapses adjacent paragraphs without a table (flavor: $flavor, before: $before, after: $after)', ({ flavor, before: beforeGap, after: afterGap }) => {
+ const { before, after, tables } = layoutTable(flavor, { before: beforeGap, after: afterGap, tableWrap: null });
+ expect(tables).toHaveLength(0);
+ expect(after.top + after.marginTop - contentBottom(before)).toBeCloseTo(Math.max(beforeGap, afterGap));
+ });
+
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('keeps ordinary paragraph geometry with a page-positioned floating table (flavor: %s)', (flavor) => {
+ const options = { before: 40, after: 10 };
+ const plain = layoutTable(flavor, { ...options, tableWrap: null });
+ const floating = layoutTable(flavor, { ...options, tableWrap: TableTextWrapType.WRAP });
+ expect(floating.tables).toHaveLength(1);
+ expect(floating.tables[0].top).toBeGreaterThan(contentBottom(floating.after));
+ expect(contentBottom(floating.before)).toBeCloseTo(contentBottom(plain.before));
+ expect(floating.after.top + floating.after.marginTop).toBeCloseTo(plain.after.top + plain.after.marginTop);
+ });
+
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN].flatMap((flavor) =>
+ [0, 10, 40].flatMap((before) => [0, 10, 40].map((after) => ({ flavor, before, after })))))('keeps independent spacing before=$before and after=$after (flavor: $flavor)', ({ flavor, before: beforeGap, after: afterGap }) => {
+ const { before, after, tables } = layoutTable(flavor, { before: beforeGap, after: afterGap });
+ const table = tables[0];
+ expect(table.top - contentBottom(before)).toBeCloseTo(beforeGap);
+ expect(after.top + after.marginTop - table.top - table.height).toBeCloseTo(afterGap);
+ });
+
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('matches incremental and complete table geometry (flavor: %s)', (flavor) => {
+ const geometry = (incremental: boolean) => {
+ const { before, after, tables } = layoutTable(flavor, { before: 40, after: 10, incremental });
+ return { before: contentBottom(before), table: tables.map(({ top, height }) => ({ top, height })), after: after.top + after.marginTop };
+ };
+ expect(geometry(true)).toEqual(geometry(false));
+ });
+
+ it.each([false, true])('keeps before-spacing on the first table slice and after-spacing after the last slice (incremental: %s)', (incremental) => {
+ const { before, after, tables, pages } = layoutTable(DocumentFlavor.TRADITIONAL, {
+ before: 40,
+ after: 10,
+ pageHeight: 180,
+ rowCount: 6,
+ incremental,
+ });
+ expect(pages).toHaveLength(2);
+ expect(tables).toHaveLength(2);
+ expect(tables.reduce((total, table) => total + table.rows.length, 0)).toBe(6);
+ expect(tables[0].top - contentBottom(before)).toBeCloseTo(40);
+ expect(tables[1].top).toBe(0);
+ expect(after.parent?.parent?.parent).toBe(tables[1].parent);
+ expect(after.top + after.marginTop - tables[1].top - tables[1].height).toBeCloseTo(10);
+ });
+});
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 eae9ed9eaf..03729a7691 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { INumberUnit, IParagraphProperties, ITabStop, Nullable } from '@univerjs/core';
+import type { INumberUnit, IParagraphProperties, ITabStop, ITextStyle, Nullable } from '@univerjs/core';
import {
BooleanNumber,
characterSpacingControlType,
@@ -254,7 +254,8 @@ export function layoutParagraph(
isParagraphFirstShapedText: boolean,
breakPointType = BreakPointType.Normal,
renderBullet = isParagraphFirstShapedText,
- startNewLine = false
+ startNewLine = false,
+ markerTextStyle?: Pick<ITextStyle, 'cl' | 'ul'>
) {
paragraphConfig.documentCompatibilityPolicy ??= sectionBreakConfig.documentCompatibilityPolicy;
if (isParagraphFirstShapedText || startNewLine) {
@@ -268,7 +269,10 @@ export function layoutParagraph(
const { snapToGrid = BooleanNumber.TRUE } = paragraphStyle;
const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);
- const bulletGlyph = createSkeletonBulletGlyph(glyphGroup[0], bulletSkeleton, charSpaceApply, paragraphConfig.documentCompatibilityPolicy ?? sectionBreakConfig.documentCompatibilityPolicy);
+ const resolvedBulletSkeleton = markerTextStyle
+ ? { ...bulletSkeleton, ts: { ...markerTextStyle, ...bulletSkeleton.ts } }
+ : bulletSkeleton;
+ const bulletGlyph = createSkeletonBulletGlyph(glyphGroup[0], resolvedBulletSkeleton, charSpaceApply, paragraphConfig.documentCompatibilityPolicy ?? sectionBreakConfig.documentCompatibilityPolicy);
const paragraphProperties = bulletSkeleton.paragraphProperties || {};
const bulletParagraphStyle = {
...paragraphProperties,
@@ -1482,6 +1486,11 @@ function _getParagraphLineMetrics(
const startingSection = lastPage.type === DocumentSkeletonPageType.BODY && preLine == null
? ctx.viewModel.getChildren().find((section, index) => index > 0 && section.children[0]?.endIndex === paragraphIndex)
: undefined;
+ const hasInlineTableBoundary = isParagraphFirstShapedText &&
+ paragraphConfig.skeTablesInParagraph?.find((item) => !item.hasPositioned)?.table.tableSource.textWrap === TableTextWrapType.NONE;
+ // Inline tables are attached to the following paragraph in the view model.
+ // Spacing on opposite sides of that table must not collapse together.
+ const spaceBeforeTable = hasInlineTableBoundary ? Math.max(0, preLine?.spaceBelowApply ?? 0) : 0;
let { marginTop, spaceBelowApply } = isHiddenParagraph
? { marginTop: 0, spaceBelowApply: preLine?.spaceBelowApply ?? 0 }
: __getParagraphSpace(
@@ -1490,8 +1499,8 @@ function _getParagraphLineMetrics(
suppressCellAutoSpaceAbove ? undefined : spaceAbove,
spaceBelow,
isParagraphFirstShapedText,
- preLine,
- _shouldSuppressPageTopSpacing(lastPage, column, paragraphConfig, preLine, firstPageNumber, startingSection != null),
+ hasInlineTableBoundary ? undefined : preLine,
+ !hasInlineTableBoundary && _shouldSuppressPageTopSpacing(lastPage, column, paragraphConfig, preLine, firstPageNumber, startingSection != null),
drawingMLLineHeight
);
@@ -1553,6 +1562,7 @@ function _getParagraphLineMetrics(
paddingBottom,
contentHeight,
marginTop,
+ spaceBeforeTable,
spaceBelowApply,
borderTopSpace,
borderBottomSpace,
@@ -1730,6 +1740,7 @@ function _lineOperator(
paddingBottom,
contentHeight,
marginTop,
+ spaceBeforeTable,
spaceBelowApply,
borderTopSpace,
borderBottomSpace,
@@ -1774,7 +1785,7 @@ function _lineOperator(
);
if (skeTablesInParagraph != null && skeTablesInParagraph.length > 0) {
- needOpenNewPageByTableLayout = _updateAndPositionTable(ctx, lineTop, lineHeight, lastPage, pages, column, section, skeTablesInParagraph, paragraphConfig.paragraphIndex, sectionBreakConfig, pDrawingAnchor?.get(paragraphIndex)?.top);
+ needOpenNewPageByTableLayout = _updateAndPositionTable(ctx, lineTop + spaceBeforeTable, lineHeight, lastPage, pages, column, section, skeTablesInParagraph, paragraphConfig.paragraphIndex, sectionBreakConfig, pDrawingAnchor?.get(paragraphIndex)?.top);
}
const hasSameParagraphTopBottomDrawingWithInline = hasInlineCustomBlock &&
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 3d0776dadb..57a9d0e12d 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
@@ -26,6 +26,17 @@ import type {
IParagraphStyle,
Nullable,
} from '@univerjs/core';
+import {
+ BooleanNumber,
+ DataStreamTreeNodeType,
+ DataStreamTreeTokenType,
+ DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING,
+ DocumentBlockRangeType,
+ DocxBreakType,
+ PositionedObjectLayoutType,
+ resolveDocumentParagraphStyle,
+ TableTextWrapType,
+} from '@univerjs/core';
import type {
IDocumentSkeletonBullet,
IDocumentSkeletonColumn,
@@ -41,17 +52,6 @@ import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-no
import type { DocumentViewModel } from '../../../view-model/document-view-model';
import type { ILayoutContext } from '../../tools';
import type { IShapedText } from './shaping';
-import {
- BooleanNumber,
- DataStreamTreeNodeType,
- DataStreamTreeTokenType,
- DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING,
- DocumentBlockRangeType,
- DocxBreakType,
- PositionedObjectLayoutType,
- resolveDocumentParagraphStyle,
- TableTextWrapType,
-} from '@univerjs/core';
import { BreakType, DocumentSkeletonPageType, GlyphType } from '../../../../../basics/i-document-skeleton-cached';
import { getDocumentCompatibilityPolicy, isTraditionalDocumentCompatibility } from '../../../document-compatibility';
import { BreakPointType } from '../../line-breaker/break';
@@ -115,6 +115,34 @@ function _hasOnlyCustomBlockGlyphs(glyphs: IDocumentSkeletonGlyph[]): boolean {
return glyphs.length > 0 && glyphs.every((glyph) => glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK);
}
+function _mergeTrailingBlockEndShapedTexts(shapedTextList: IShapedText[]): IShapedText[] {
+ const result: IShapedText[] = [];
+ for (const shapedText of shapedTextList) {
+ const previous = result[result.length - 1];
+ if (
+ previous?.breakPointType === BreakPointType.Mandatory &&
+ _endsWithToken(previous.text, previous.glyphs, DataStreamTreeTokenType.PARAGRAPH) &&
+ shapedText.glyphs.length > 0 &&
+ shapedText.glyphs.some((glyph) => glyph.streamType === DataStreamTreeTokenType.BLOCK_END) &&
+ shapedText.glyphs.every((glyph, index) => glyph.width === 0 && (
+ glyph.streamType === DataStreamTreeTokenType.BLOCK_END ||
+ (index === shapedText.glyphs.length - 1 && glyph.streamType === DataStreamTreeTokenType.SECTION_BREAK)
+ ))
+ ) {
+ // A block delimiter and optional section end follow the authored paragraph mark.
+ // Keep its logical offset on that line instead of opening an empty line.
+ result[result.length - 1] = {
+ ...previous,
+ text: previous.text + shapedText.text,
+ glyphs: [...previous.glyphs, ...shapedText.glyphs],
+ };
+ } else {
+ result.push(shapedText);
+ }
+ }
+ return result;
+}
+
function _mergeAdjacentCustomBlockShapedTexts(
shapedTextList: IShapedText[],
customBlockDrawings: Map<string, IDocumentSkeletonDrawing>
@@ -1045,7 +1073,7 @@ function _prepareLineBreaking(
...getFontCreateConfig(endIndex - paragraphNode.contentStartIndex, viewModel, paragraphNode, sectionBreakConfig, {
...paragraph,
paragraphStyle: resolvedParagraphStyle,
- }).textStyle,
+ }, false).textStyle,
// Explicit list formatting below may underline the marker; paragraph-mark formatting may not.
ul: { s: BooleanNumber.FALSE },
}
@@ -1156,9 +1184,11 @@ function _layoutShapedTexts({
const referencePageBreaks = retainedBreaks
? new Set(retainedBreaks.map((offset) => offset - paragraphNode.contentStartIndex))
: undefined;
- const mergedShapedTextList = _mergeAdjacentCustomBlockShapedTexts(
- _splitAtReferencePageBreaks(shapedTextList, referencePageBreaks),
- paragraphNonInlineSkeDrawingsByBlockId
+ const mergedShapedTextList = _mergeTrailingBlockEndShapedTexts(
+ _mergeAdjacentCustomBlockShapedTexts(
+ _splitAtReferencePageBreaks(shapedTextList, referencePageBreaks),
+ paragraphNonInlineSkeDrawingsByBlockId
+ )
);
for (let shapedIndex = 0; shapedIndex < mergedShapedTextList.length; shapedIndex++) {
@@ -1175,6 +1205,7 @@ function _layoutShapedTexts({
return;
}
+ const markerSourceIndex = textStartIndex - paragraphNode.contentStartIndex - _glyphCount(deferredRenderedMarkers);
if (deferredRenderedMarkers.length > 0) {
pendingGlyphs = [...deferredRenderedMarkers, ...pendingGlyphs];
deferredRenderedMarkers = [];
@@ -1193,6 +1224,17 @@ function _layoutShapedTexts({
glyph.streamType !== DataStreamTreeTokenType.PARAGRAPH &&
glyph.streamType !== DataStreamTreeTokenType.SECTION_BREAK &&
glyph.streamType !== DataStreamTreeTokenType.DOCS_END));
+ const renderBullet = renderParagraphBullet && !preserveParagraphStart;
+ const paragraph = renderBullet && paragraphConfig.bulletSkeleton
+ ? viewModel.getParagraph(paragraphNode.endIndex)
+ : undefined;
+ // Resolve the actual marker provider after zero-height anchors, without copying hyperlink appearance.
+ const markerTextStyle = paragraph
+ ? getFontCreateConfig(markerSourceIndex, viewModel, paragraphNode, sectionBreakConfig, {
+ ...paragraph,
+ paragraphStyle: paragraphConfig.paragraphStyle,
+ }, false).textStyle
+ : undefined;
allPages = layoutParagraph(
ctx,
pendingGlyphs,
@@ -1201,8 +1243,9 @@ function _layoutShapedTexts({
paragraphConfig,
isParagraphFirstShapedText || (!nonFlowAnchor && hasOnlyFloatingCustomBlockGlyphs(pendingGlyphs, paragraphNonInlineSkeDrawingsByBlockId)),
layoutBreakPointType,
- renderParagraphBullet && !preserveParagraphStart,
- startNewLine
+ renderBullet,
+ startNewLine,
+ markerTextStyle ? { cl: markerTextStyle.cl, ul: markerTextStyle.ul } : undefined
);
// Zero-height drawing anchors do not consume the visible first line.
diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.ts
index ed987fc298..1c657bc3e0 100644
--- a/packages/engine-render/src/components/docs/layout/tools.ts
+++ b/packages/engine-render/src/components/docs/layout/tools.ts
@@ -1744,7 +1744,8 @@ export function getFontCreateConfig(
viewModel: DocumentViewModel,
paragraphNode: DataStreamTreeNode,
sectionBreakConfig: ISectionBreakConfig,
- paragraph: IDocumentLayoutParagraph
+ paragraph: IDocumentLayoutParagraph,
+ includeCustomRangeStyle = true
) {
const {
gridType = GridType.LINES,
@@ -1770,7 +1771,7 @@ export function getFontCreateConfig(
const customDecoration = viewModel.getCustomDecoration(index + startIndex);
const showCustomDecoration = customDecoration && (customDecoration.show !== false);
const customDecorationStyle = showCustomDecoration ? getCustomDecorationStyle(customDecoration) : null;
- const customRange = viewModel.getCustomRange(index + startIndex);
+ const customRange = includeCustomRangeStyle ? viewModel.getCustomRange(index + startIndex) : null;
const showCustomRange = customRange && (customRange.show !== false);
const customRangeStyle = showCustomRange ? getCustomRangeStyle(customRange) : null;
const hasAddonStyle = showCustomRange || showCustomDecoration || !!bullet || paragraphStyle?.namedStyleType || paragraphStyle?.textStyle != null || paragraphStyle?.paragraphMarkTextStyle != null;