Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(docs): support instance-scoped layout presentations (#7697)
Univer1d090608fa27
diff --git a/packages/docs-ui/src/basics/__tests__/paragraph.spec.ts b/packages/docs-ui/src/basics/__tests__/paragraph.spec.tsindex 474c1a700e..da0988733a 100644--- a/packages/docs-ui/src/basics/__tests__/paragraph.spec.ts+++ b/packages/docs-ui/src/basics/__tests__/paragraph.spec.ts@@ -14,10 +14,45 @@* limitations under the License.*/+import { DataStreamTreeTokenType } from '@univerjs/core';import { describe, expect, it } from 'vitest';-import { getTextRunAtPosition } from '../paragraph';+import { getTextRunAtInputPosition, getTextRunAtPosition } from '../paragraph';describe('getTextRunAtPosition', () => {+ it.each(['i', ''])('inherits the first column paragraph style when inserting before %j', (text) => {+ const token = DataStreamTreeTokenType;+ const prefix = `${token.COLUMN_GROUP_START}${token.COLUMN_START}Heading\r${token.COLUMN_END}${token.COLUMN_START}`;+ const position = prefix.length;+ const body = {+ dataStream: `${prefix}${text}\r${token.COLUMN_END}${token.COLUMN_GROUP_END}\n`,+ textRuns: [+ { st: 2, ed: 10, ts: { ff: 'Heading', fs: 14 } },+ {+ st: position,+ ed: position + text.length + 1,+ ts: { ff: 'Monospace', fs: 10 },+ },+ ],+ };++ expect(getTextRunAtInputPosition(body, position, { ff: 'Heading', fs: 14 }, null, false, true).ts)+ .toEqual({ ff: 'Monospace', fs: 10 });+ expect(getTextRunAtInputPosition(body, position, {}, { fs: 12 }, false, true).ts)+ .toEqual({ ff: 'Monospace', fs: 12 });+ });++ it('retains left-run inheritance inside a column at an ordinary style boundary', () => {+ const body = {+ dataStream: `${DataStreamTreeTokenType.COLUMN_START}AB\r`,+ textRuns: [+ { st: 1, ed: 2, ts: { ff: 'Left', fs: 10 } },+ { st: 2, ed: 3, ts: { ff: 'Right', fs: 14 } },+ ],+ };++ expect(getTextRunAtInputPosition(body, 2, {}, null).ts).toEqual({ ff: 'Left', fs: 10 });+ });+it('uses the concrete default text color without overriding inherited or cached colors', () => {const defaultStyle = { cl: { rgb: '#F7F9FC' }, ff: 'Arial', fs: 11 };@@ -43,4 +78,38 @@ describe('getTextRunAtPosition', () => {cl: { rgb: '#000000' },});});++ it('inherits the following run at a non-empty paragraph start', () => {+ const body = {+ dataStream: 'A\rB\r\n',+ textRuns: [+ {+ st: 0,+ ed: 2,+ ts: { ff: 'Previous', fs: 20 },+ },+ {+ st: 2,+ ed: 3,+ ts: {+ ff: 'Following',+ fs: 8,+ },+ },+ ],+ };++ expect(getTextRunAtPosition(body, 2, {}, null).ts).toEqual({+ ff: 'Previous',+ fs: 20,+ });+ expect(getTextRunAtInputPosition(body, 2, {}, null).ts).toEqual({+ ff: 'Previous',+ fs: 20,+ });+ expect(getTextRunAtInputPosition(body, 2, {}, null, false, true).ts).toEqual({+ ff: 'Following',+ fs: 8,+ });+ });});diff --git a/packages/docs-ui/src/basics/paragraph.ts b/packages/docs-ui/src/basics/paragraph.tsindex 3d56a128a8..46c30e78ff 100644--- a/packages/docs-ui/src/basics/paragraph.ts+++ b/packages/docs-ui/src/basics/paragraph.ts@@ -14,7 +14,16 @@* limitations under the License.*/-import type { ICustomDecoration, ICustomRange, ICustomTable, IDocumentBody, IParagraph, ITextRun, ITextStyle, Nullable } from '@univerjs/core';+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 {@@ -87,6 +96,38 @@ export function getTextRunAtPosition(return retTextRun;}+export function getTextRunAtInputPosition(+ body: IDocumentBody,+ position: number,+ defaultStyle: ITextStyle,+ cacheStyle: Nullable<ITextStyle>,+ isCellEditor?: boolean,+ inheritParagraphStartStyle = false+): ITextRun {+ if (!inheritParagraphStartStyle) {+ return getTextRunAtPosition(body, position, defaultStyle, cacheStyle, isCellEditor);+ }+ const inheritedTextRun = getTextRunAtPosition(body, position, defaultStyle, cacheStyle, isCellEditor);+ const previousToken = body.dataStream[position - 1];+ const startsParagraph = previousToken === DataStreamTreeTokenType.PARAGRAPH ||+ previousToken === DataStreamTreeTokenType.COLUMN_START;+ const nextTextRun = startsParagraph+ ? body.textRuns?.find((textRun) => textRun.st === position && textRun.ed > position)+ : undefined;+ const textStyle = nextTextRun+ ? {+ ...(!defaultStyle.cl ? {} : { cl: { ...defaultStyle.cl } }),+ ...nextTextRun.ts,+ ...cacheStyle,+ }+ : { ...inheritedTextRun.ts };++ return {+ ...(nextTextRun ?? inheritedTextRun),+ ts: textStyle,+ };+}+export function getCustomRangeAtPosition(customRanges: ICustomRange[], position: number, extendRange?: boolean) {if (extendRange) {const range = customRanges.find((customRange) => position >= customRange.startIndex && position <= customRange.endIndex + 1);diff --git a/packages/docs-ui/src/commands/commands/ime-input.command.ts b/packages/docs-ui/src/commands/commands/ime-input.command.tsindex f54333a98b..ac297c1a6a 100644--- a/packages/docs-ui/src/commands/commands/ime-input.command.ts+++ b/packages/docs-ui/src/commands/commands/ime-input.command.ts@@ -17,12 +17,28 @@import type { DocumentDataModel, ICommand, ICommandInfo, ICustomRange } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';-import { BuildTextUtils, CommandType, getRichTextEditPath, ICommandService, IUniverInstanceService, JSONX, SHEET_EDITOR_UNITS, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';+import {+ BuildTextUtils,+ CommandType,+ getRichTextEditPath,+ ICommandService,+ IUniverInstanceService,+ JSONX,+ SHEET_EDITOR_UNITS,+ TextX,+ TextXActionType,+ UniverInstanceType,+} from '@univerjs/core';import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';import { IRenderManagerService } from '@univerjs/engine-render';-import { getCustomDecorationAtPosition, getCustomRangeAtPosition, getTextRunAtPosition } from '../../basics/paragraph';+import {+ getCustomDecorationAtPosition,+ getCustomRangeAtPosition,+ getTextRunAtInputPosition,+} from '../../basics/paragraph';import { DocIMEInputManagerService } from '../../services/doc-ime-input-manager.service';import { DocMenuStyleService } from '../../services/doc-menu-style.service';+import { getEditorRuntimeConfig } from '../../services/editor/editor-runtime-config';import { getDocRangeInsertOffset, getReplaceDocRangesActions } from './clipboard.inner.command';export interface IIMEInputCommandParams {@@ -144,12 +160,13 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {const range = getCustomRangeAtPosition(body.customRanges ?? [], styleOffset, SHEET_EDITOR_UNITS.includes(unitId));inheritedRanges = range ? [range] : [];}- const curTextRun = getTextRunAtPosition(+ const curTextRun = getTextRunAtInputPosition(body,replacesComplexSelection ? replacementOffset : isCompositionStart ? endOffset : startOffset + oldTextLen,defaultTextStyle,styleCache,- SHEET_EDITOR_UNITS.includes(unitId)+ SHEET_EDITOR_UNITS.includes(unitId),+ getEditorRuntimeConfig(docDataModel)?.inheritParagraphStartStyle === true);const customDecorations = getCustomDecorationAtPosition(body.customDecorations ?? [], styleOffset);diff --git a/packages/docs-ui/src/commands/commands/insert-special-character.command.ts b/packages/docs-ui/src/commands/commands/insert-special-character.command.tsindex 76e7630136..1b84becaa4 100644--- a/packages/docs-ui/src/commands/commands/insert-special-character.command.ts+++ b/packages/docs-ui/src/commands/commands/insert-special-character.command.ts@@ -18,8 +18,13 @@ import type { DocumentDataModel, ICommand } from '@univerjs/core';import type { IInsertTextCommandParams } from '@univerjs/docs';import { CommandType, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService, InsertTextCommand } from '@univerjs/docs';-import { getCustomDecorationAtPosition, getCustomRangeAtPosition, getTextRunAtPosition } from '../../basics/paragraph';+import {+ getCustomDecorationAtPosition,+ getCustomRangeAtPosition,+ getTextRunAtInputPosition,+} from '../../basics/paragraph';import { DocMenuStyleService } from '../../services/doc-menu-style.service';+import { getEditorRuntimeConfig } from '../../services/editor/editor-runtime-config';export const InsertSpecialCharacterCommand: ICommand<{value: string;@@ -49,11 +54,13 @@ export const InsertSpecialCharacterCommand: ICommand<{}const { value } = params;- const curTextRun = getTextRunAtPosition(+ const curTextRun = getTextRunAtInputPosition(originBody,activeRange.endOffset,docMenuStyleService.getDefaultStyle(),- docMenuStyleService.getStyleCache()+ docMenuStyleService.getStyleCache(),+ false,+ getEditorRuntimeConfig(docDataModel)?.inheritParagraphStartStyle === true);const curCustomRange = getCustomRangeAtPosition(originBody.customRanges ?? [], activeRange.endOffset);const curCustomDecorations = getCustomDecorationAtPosition(originBody.customDecorations ?? [], activeRange.endOffset);diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-input.controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-input.controller.spec.tsindex 842a096214..dd8d9b3249 100644--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-input.controller.spec.ts+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-input.controller.spec.ts@@ -18,10 +18,14 @@* @vitest-environment jsdom*/-import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '@univerjs/core';+import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DocumentDataModel } from '@univerjs/core';import { Subject } from 'rxjs';import { describe, expect, it, vi } from 'vitest';-import { EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, EmbedInteractionBoundaryService, EmbedRuntimeFocusCoordinator } from '../../../services/doc-embed-integration.service';+import {+ EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE,+ EmbedInteractionBoundaryService,+ EmbedRuntimeFocusCoordinator,+} from '../../../services/doc-embed-integration.service';import { DocInputController } from '../doc-input.controller';describe('DocInputController', () => {@@ -38,11 +42,7 @@ describe('DocInputController', () => {new DocInputController({unitId: 'host-doc',- unit: {- getSelfOrHeaderFooterModel: vi.fn(() => ({- getBody: vi.fn(() => ({ dataStream: '\r\n' })),- })),- },+ unit: new DocumentDataModel({ body: ({ dataStream: '\r\n' }) }),} as never,{ onInput$, getAllRectRanges: vi.fn(() => []) } as never,{ getSkeleton: vi.fn(() => ({})) } as never,@@ -83,11 +83,7 @@ describe('DocInputController', () => {new DocInputController({unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,- unit: {- getSelfOrHeaderFooterModel: vi.fn(() => ({- getBody: vi.fn(() => ({ dataStream: '\r\n' })),- })),- },+ unit: new DocumentDataModel({ body: ({ dataStream: '\r\n' }) }),} as never,{ onInput$, getAllRectRanges: vi.fn(() => []) } as never,{ getSkeleton: vi.fn(() => ({})) } as never,@@ -132,11 +128,7 @@ describe('DocInputController', () => {new DocInputController({unitId: 'other-host-doc',- unit: {- getSelfOrHeaderFooterModel: vi.fn(() => ({- getBody: vi.fn(() => ({ dataStream: '\r\n' })),- })),- },+ unit: new DocumentDataModel({ body: ({ dataStream: '\r\n' }) }),} as never,{ onInput$, getAllRectRanges: vi.fn(() => []) } as never,{ getSkeleton: vi.fn(() => ({})) } as never,@@ -187,11 +179,7 @@ describe('DocInputController', () => {new DocInputController({unitId: 'child-doc',- unit: {- getSelfOrHeaderFooterModel: vi.fn(() => ({- getBody: vi.fn(() => ({ dataStream: '\r\n' })),- })),- },+ unit: new DocumentDataModel({ body: ({ dataStream: '\r\n' }) }),} as never,{ onInput$, getAllRectRanges: vi.fn(() => []) } as never,{ getSkeleton: vi.fn(() => ({})) } as never,@@ -241,11 +229,7 @@ describe('DocInputController', () => {new DocInputController({unitId: 'child-doc',- unit: {- getSelfOrHeaderFooterModel: vi.fn(() => ({- getBody: vi.fn(() => ({ dataStream: '\r\n' })),- })),- },+ unit: new DocumentDataModel({ body: ({ dataStream: '\r\n' }) }),} as never,{ onInput$, getAllRectRanges: vi.fn(() => []) } as never,{ getSkeleton: vi.fn(() => ({})) } as never,@@ -278,7 +262,10 @@ describe('DocInputController', () => {it('routes input over mixed text and table ranges through structural replacement', async () => {const onInput$ = new Subject<unknown>();- const executeCommand = vi.fn(() => Promise.resolve(true));+ const executeCommand = vi.fn((+ _id: string,+ _params?: { body?: { textRuns?: Array<{ ts?: unknown }> } }+ ) => Promise.resolve(true));const activeRange = {segmentId: '',startOffset: 0,@@ -290,11 +277,7 @@ describe('DocInputController', () => {new DocInputController({unitId: 'test-doc',- unit: {- getSelfOrHeaderFooterModel: vi.fn(() => ({- getBody: vi.fn(() => ({ dataStream: 'text\r\n' })),- })),- },+ unit: new DocumentDataModel({ body: ({ dataStream: 'text\r\n' }) }),} as never,{onInput$,diff --git a/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.tsindex a3b605a30e..c20e0f5d83 100644--- a/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts@@ -354,6 +354,9 @@ export class DocBackScrollRenderController extends RxDisposable implements Enginlet offsetX = 0;const editorRenderConfig = this._editorService.getEditorRenderConfig(unitId);+ if (editorRenderConfig?.disableBackScroll) {+ return;+ }const delta = editorRenderConfig ? editorRenderConfig.backScrollOffset ?? 0 : 100;offsetY = this._getVerticalScrollDelta(top, height, boundTop, boundBottom, delta);diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.tsindex 64b0218320..a49f929292 100644--- a/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts@@ -20,11 +20,19 @@ import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import type { Subscription } from 'rxjs';import { Disposable, ICommandService, Inject, Optional, SHEET_EDITOR_UNITS } from '@univerjs/core';import { DocSkeletonManagerService, InsertTextCommand } from '@univerjs/docs';-import { getCustomDecorationAtPosition, getCustomRangeAtPosition, getTextRunAtPosition } from '../../basics/paragraph';+import {+ getCustomDecorationAtPosition,+ getCustomRangeAtPosition,+ getTextRunAtInputPosition,+} from '../../basics/paragraph';import { AfterSpaceCommand } from '../../commands/commands/auto-format.command';import { ReplaceSelectionCommand } from '../../commands/commands/replace-content.command';-import { IDocEmbedInteractionBoundaryService, IDocEmbedRuntimeFocusCoordinator } from '../../services/doc-embed-integration.service';+import {+ IDocEmbedInteractionBoundaryService,+ IDocEmbedRuntimeFocusCoordinator,+} from '../../services/doc-embed-integration.service';import { DocMenuStyleService } from '../../services/doc-menu-style.service';+import { getEditorRuntimeConfig } from '../../services/editor/editor-runtime-config';import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';export class DocInputController extends Disposable implements IRenderModule {@@ -91,19 +99,13 @@ export class DocInputController extends Disposable implements IRenderModule {const defaultTextStyle = this._docMenuStyleService.getDefaultStyle();const cacheStyle = this._docMenuStyleService.getStyleCache();const curCustomRange = getCustomRangeAtPosition(originBody?.customRanges ?? [], activeRange.endOffset, SHEET_EDITOR_UNITS.includes(unitId));- const curTextRun = getTextRunAtPosition(originBody, activeRange.endOffset, defaultTextStyle, cacheStyle, SHEET_EDITOR_UNITS.includes(unitId));+ const curTextRun = getTextRunAtInputPosition(originBody, activeRange.endOffset, defaultTextStyle, cacheStyle, SHEET_EDITOR_UNITS.includes(unitId), getEditorRuntimeConfig(docDataModel)?.inheritParagraphStartStyle === true);const curCustomDecorations = getCustomDecorationAtPosition(originBody?.customDecorations ?? [], activeRange.endOffset);const insertBody = {dataStream: content,textRuns: curTextRun- ? [- {- ...curTextRun,- st: 0,- ed: content.length,- },- ]+ ? [{ ...curTextRun, st: 0, ed: content.length }]: [],customRanges: curCustomRange? [{diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.tsindex 492082f834..fb54554ea7 100644--- a/packages/docs-ui/src/index.ts+++ b/packages/docs-ui/src/index.ts@@ -264,6 +264,7 @@ export type { IDocPrintComponentContext, IDocPrintContext } from './services/docexport { DocsRenderService } from './services/docs-render.service';export { Editor } from './services/editor/editor';export { EditorService, IEditorService } from './services/editor/editor-manager.service';+export type { IEditorRuntimeConfig } from './services/editor/editor-runtime-config';export { DocFloatMenuService } from './services/float-menu.service';export {isInSameTableCell,@@ -303,4 +304,5 @@ export type {IKeyboardEventConfig,} from './views/rich-text-editor/hooks';export { RichTextEditor } from './views/RichTextEditor';+export type { IRichTextEditorProps } from './views/RichTextEditor';diff --git a/packages/docs-ui/src/services/__tests__/doc-ime-input-manager.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-ime-input-manager.service.spec.tsindex 23b1f42b38..3c03142dd5 100644--- a/packages/docs-ui/src/services/__tests__/doc-ime-input-manager.service.spec.ts+++ b/packages/docs-ui/src/services/__tests__/doc-ime-input-manager.service.spec.ts@@ -53,6 +53,21 @@ describe('DocIMEInputManagerService', () => {});});+ it('keeps the pre-composition and final host layout state across multiple IME updates', () => {+ const service = createService();+ service.setActiveRange({ startOffset: 0, endOffset: 0, collapsed: true });+ for (const [before, after] of [[0, 1], [1, 2], [2, 3]]) {+ service.pushUndoRedoMutationParams(+ { unitId: 'doc-1', actions: JSONX.getInstance().replaceOp(['revision'], after, before), textRanges: [], layoutState: before },+ { unitId: 'doc-1', actions: JSONX.getInstance().replaceOp(['revision'], before, after), textRanges: [], layoutState: after }+ );+ }+ expect(service.fetchComposedUndoRedoMutationParams()).toMatchObject({+ undoMutationParams: { layoutState: 0 },+ redoMutationParams: { layoutState: 3 },+ });+ });+it('clears cached IME mutation params', () => {const service = createService();service.setUndoRedoMutationParamsCache({diff --git a/packages/docs-ui/src/services/doc-ime-input-manager.service.ts b/packages/docs-ui/src/services/doc-ime-input-manager.service.tsindex 15f2ecbf7a..a5aa75dc3f 100644--- a/packages/docs-ui/src/services/doc-ime-input-manager.service.ts+++ b/packages/docs-ui/src/services/doc-ime-input-manager.service.ts@@ -107,7 +107,7 @@ export class DocIMEInputManagerService extends RxDisposable implements IRenderMoconst { unitId } = this._undoMutationParamsCache[0];const firstUndoParams = this._undoMutationParamsCache[0];- const lastRedoParams = this._redoMutationParamsCache.at(-1);+ const lastRedoParams = this._redoMutationParamsCache[this._redoMutationParamsCache.length - 1];const undoMutationParams: IRichTextEditingMutationParams = {unitId,@@ -116,6 +116,7 @@ export class DocIMEInputManagerService extends RxDisposable implements IRenderMo}, null as JSONXActions),textRanges: [], // Add empty array, will never use, just fix type errorsegmentId: firstUndoParams.segmentId,+ ...(firstUndoParams.layoutState === undefined ? {} : { layoutState: firstUndoParams.layoutState }),};const redoMutationParams: IRichTextEditingMutationParams = {@@ -125,6 +126,7 @@ export class DocIMEInputManagerService extends RxDisposable implements IRenderMo}, null as JSONXActions),textRanges: lastRedoParams?.textRanges ?? [],segmentId: lastRedoParams?.segmentId,+ ...(lastRedoParams?.layoutState === undefined ? {} : { layoutState: lastRedoParams.layoutState }),options: lastRedoParams?.options,isEditing: lastRedoParams?.isEditing,};diff --git a/packages/docs-ui/src/services/doc-ime-state-change-interceptor.service.ts b/packages/docs-ui/src/services/doc-ime-state-change-interceptor.service.tsindex 687d13c29c..5bfe5793fb 100644--- a/packages/docs-ui/src/services/doc-ime-state-change-interceptor.service.ts+++ b/packages/docs-ui/src/services/doc-ime-state-change-interceptor.service.ts@@ -49,6 +49,7 @@ export class DocIMEStateChangeInterceptorService implements IDocStateChangeInter...changeStateInfo,redoState: {...changeStateInfo.redoState,+ ...(redoMutationParams.layoutState === undefined ? {} : { layoutState: redoMutationParams.layoutState }),actions: redoMutationParams.actions,textRanges: redoMutationParams.textRanges,options: redoMutationParams.options,@@ -56,6 +57,7 @@ export class DocIMEStateChangeInterceptorService implements IDocStateChangeInter},undoState: {...changeStateInfo.undoState,+ ...(undoMutationParams.layoutState === undefined ? {} : { layoutState: undoMutationParams.layoutState }),actions: undoMutationParams.actions,textRanges: previousDocRanges.length ? previousDocRanges : [previousActiveRange],options: previousSelectionOptions ?? undefined,diff --git a/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts b/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.tsindex 617f5b287d..62f51f9fa2 100644--- a/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts+++ b/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts@@ -14,6 +14,25 @@* limitations under the License.*/+import type { IDocSelectionInnerParam } from '@univerjs/engine-render';+/**+ * 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.+ */++// @vitest-environment jsdom+import {CommandService,ConfigService,@@ -44,13 +63,18 @@ import {RichTextEditingMutation,SetTextSelectionsOperation,} from '@univerjs/docs';-import { IRenderManagerService, NORMAL_TEXT_SELECTION_PLUGIN_STYLE, RenderManagerService } from '@univerjs/engine-render';+import {+ IRenderManagerService,+ NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ RenderManagerService,+} from '@univerjs/engine-render';import { Subject } from 'rxjs';import { afterEach, describe, expect, it, vi } from 'vitest';import { ReplaceSnapshotCommand } from '../../../commands/commands/replace-content.command';import { DocSelectionRenderService } from '../../selection/doc-selection-render.service';import { Editor } from '../editor';import { EditorService, IEditorService } from '../editor-manager.service';+import { getEditorRuntimeConfig } from '../editor-runtime-config';const EDITOR_ID = 'editor-1';@@ -62,6 +86,7 @@ class TestDocSelectionRenderService {readonly onKeydown$ = new Subject<{ event: KeyboardEvent; content?: string }>();readonly onCompositionupdate$ = new Subject<{ event: CompositionEvent; content?: string }>();readonly onCompositionend$ = new Subject<{ event: CompositionEvent; content?: string }>();+ readonly movingSelection$ = new Subject<IDocSelectionInnerParam>();isFocusing = true;focusCount = 0;blurCount = 0;@@ -89,7 +114,12 @@ class TestDocSelectionRenderService {class TestRender {constructor(private readonly _selectionRenderService: TestDocSelectionRenderService) {}+ with(service: typeof DocSelectionRenderService): TestDocSelectionRenderService;+ with(service: typeof DocSkeletonManagerService): { getViewModel: () => undefined };with(service: unknown) {+ if (service === DocSkeletonManagerService) {+ return { getViewModel: () => undefined };+ }if (service === DocSelectionRenderService) {return this._selectionRenderService;}@@ -119,10 +149,12 @@ class TestRegisterRender extends TestRender {readonly canvas = document.createElement('canvas');readonly viewport = new TestRegisterViewport();container: HTMLDivElement | null = null;+ resizeOnMount: boolean | undefined;readonly engine = {canvasColorService: {},- mount: (container: HTMLDivElement) => {+ mount: (container: HTMLDivElement, resize?: boolean) => {this.container = container;+ this.resizeOnMount = resize;},getCanvas: () => ({getCanvasEle: () => this.canvas,@@ -246,6 +278,23 @@ function createEditor(}describe('EditorService', () => {+ it('lets an external editor layout host own the engine resize listener', () => {+ const { service } = createService(TestRegisterRenderManagerService);+ service.register({+ cancelDefaultResizeListener: true,+ initialSnapshot: {+ id: EDITOR_ID,+ body: {+ dataStream: 'abc\r\n',+ paragraphs: [{ startIndex: 0, paragraphId: createParagraphId(new Set()) }],+ },+ documentStyle: {},+ },+ }, document.createElement('div'));++ expect(TestRegisterRenderManagerService.renders.get(EDITOR_ID)?.resizeOnMount).toBe(false);+ });+afterEach(() => {vi.unstubAllGlobals();TestRegisterRenderManagerService.renders.clear();@@ -289,7 +338,7 @@ describe('EditorService', () => {expect(editorFocused).toBe(1);});- it('turns render-layer editing activity into editor events and document updates', async () => {+ it.each([false, true])('publishes drag selection only when configured (%s)', async (emitSelectionWhileDragging) => {const { injector, univerInstanceService } = createService();const commandService = injector.get(ICommandService);commandService.registerCommand(ReplaceSnapshotCommand);@@ -298,6 +347,7 @@ describe('EditorService', () => {const selectionRenderService = new TestDocSelectionRenderService();const editor = injector.createInstance(Editor, {initialSnapshot: { id: EDITOR_ID },+ emitSelectionWhileDragging,render: new TestRender(selectionRenderService),editorDom: document.createElement('div'),} as never, univerInstanceService, injector.get(DocSelectionManagerService), commandService, injector.get(IUndoRedoService), injector);@@ -356,6 +406,20 @@ describe('EditorService', () => {style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,isEditing: true,}, { unitId: EDITOR_ID, subUnitId: EDITOR_ID });+ selectionRenderService.movingSelection$.next({+ textRanges: [{+ startOffset: 2,+ endOffset: 4,+ collapsed: false,+ isActive: true,+ }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ isEditing: false,+ });+ expect(editor.getSelectionRanges().map((range) => [range.startOffset, range.endOffset])).toEqual(emitSelectionWhileDragging ? [[2, 4]] : [[1, 2]]);editor.replaceText('quarterly');await Promise.resolve();@@ -364,7 +428,7 @@ describe('EditorService', () => {expect(changeEvents).toEqual(['abc\r\n']);expect(inputs).toEqual(['d:false', 'cut:false', ':false', '拼:true', 'paste-text:false']);expect(pastes).toEqual(['paste-text']);- expect(selections).toEqual(['1:2:false']);+ expect(selections).toEqual(emitSelectionWhileDragging ? ['1:2:false', '2:4:false'] : ['1:2:false']);expect(editor.getDocumentData().body?.dataStream).toBe('quarterly\r\n');expect(refreshSelections.at(-1)).toBe('9:9');expect(univerInstanceService.getUnit<DocumentDataModel>(EDITOR_ID)?.getBody()?.dataStream).toBe('quarterly\r\n');@@ -523,6 +587,7 @@ describe('EditorService', () => {preserveHostFocus: true,});expect(render.container).toBe(container);+ expect(render.resizeOnMount).toBe(true);expect(render.viewport.disposed).toBe(true);expect(render.viewport.scrollVal).toEqual({scrollX: 0,@@ -545,13 +610,13 @@ describe('EditorService', () => {it.each([false, true])('keeps replacement resources and releases old listeners (old container disposed first: %s)', (previousFirst) => {const { service, univerInstanceService } = createService(TestRegisterRenderManagerService);const snapshot = univerInstanceService.getUnit<DocumentDataModel>(EDITOR_ID)!.getSnapshot();- const previousLease = service.register({ initialSnapshot: snapshot }, document.createElement('div'));+ const previousLease = service.register({ initialSnapshot: snapshot, renderConfig: { disableSelectionAutoScroll: true } }, document.createElement('div'));const previousEditor = service.getEditor(EDITOR_ID)!;const oldInputs: string[] = [];previousEditor.input$.subscribe(({ content }) => oldInputs.push(content));service.focus(EDITOR_ID);const currentContainer = document.createElement('div');- const currentLease = service.register({ initialSnapshot: snapshot }, currentContainer);+ const currentLease = service.register({ initialSnapshot: snapshot, renderConfig: { inheritParagraphStartStyle: true } }, currentContainer);const currentEditor = service.getEditor(EDITOR_ID)!;expect(currentEditor).not.toBe(previousEditor);const model = univerInstanceService.getUnit<DocumentDataModel>(EDITOR_ID)!;@@ -564,6 +629,7 @@ describe('EditorService', () => {if (previousFirst) {previousLease.dispose();}+ expect(getEditorRuntimeConfig(model)).toEqual({ inheritParagraphStartStyle: true });expect(service.getEditor(EDITOR_ID)).toBe(currentEditor);expect(univerInstanceService.getUnit(EDITOR_ID)).toBe(model);expect(model.getSnapshot()).toEqual(snapshot);@@ -574,6 +640,7 @@ describe('EditorService', () => {currentLease.dispose();previousLease.dispose();currentLease.dispose();+ expect(getEditorRuntimeConfig(model)).toBeUndefined();expect(service.getEditor(EDITOR_ID)).toBeUndefined();expect(univerInstanceService.getUnit(EDITOR_ID)).toBeUndefined();expect(TestRegisterRenderManagerService.removedRenderIds).toEqual([EDITOR_ID]);diff --git a/packages/docs-ui/src/services/editor/__tests__/editor-runtime-config.spec.ts b/packages/docs-ui/src/services/editor/__tests__/editor-runtime-config.spec.tsnew file mode 100644index 0000000000..7936e53196--- /dev/null+++ b/packages/docs-ui/src/services/editor/__tests__/editor-runtime-config.spec.ts@@ -0,0 +1,50 @@+/**+ * 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 { IEditorRuntimeConfig } from '../editor-runtime-config';+import { DocumentDataModel } from '@univerjs/core';+import { getDocumentLayoutPresentation } from '@univerjs/engine-render';+import { describe, expect, it } from 'vitest';+import { getEditorRuntimeConfig, registerEditorRuntimeConfig } from '../editor-runtime-config';++describe('editor runtime configuration', () => {+ it('isolates instances and protects a replacement registration even when its config is reused', () => {+ const first = new DocumentDataModel({ id: 'runtime-first' });+ const second = new DocumentDataModel({ id: 'runtime-second' });+ const config: IEditorRuntimeConfig = {+ disableSelectionAutoScroll: true,+ layout: {+ getSnapshot: (snapshot) => snapshot,+ captureState: () => undefined,+ applyActions: () => {},+ restoreState: () => {},+ },+ };+ const initial = registerEditorRuntimeConfig(first, config);+ const replacement = registerEditorRuntimeConfig(first, config);+ initial.dispose();+ expect(getEditorRuntimeConfig(first)).toBe(config);+ expect(getDocumentLayoutPresentation(first)).toBe(config.layout);+ expect(getEditorRuntimeConfig(second)).toBeUndefined();+ expect(first.getSnapshot()).not.toHaveProperty('renderConfig');+ replacement.dispose();+ replacement.dispose();+ expect(getEditorRuntimeConfig(first)).toBeUndefined();+ expect(getDocumentLayoutPresentation(first)).toBeUndefined();+ first.dispose();+ second.dispose();+ });+});diff --git a/packages/docs-ui/src/services/editor/editor-manager.service.ts b/packages/docs-ui/src/services/editor/editor-manager.service.tsindex 51ab5b85fa..59217f06a4 100644--- a/packages/docs-ui/src/services/editor/editor-manager.service.ts+++ b/packages/docs-ui/src/services/editor/editor-manager.service.ts@@ -18,19 +18,41 @@ import type { DocumentDataModel, IDisposable, IDocumentBody, IDocumentData, Nullimport type { DocBackground, ISuccinctDocRangeParam, Scene } from '@univerjs/engine-render';import type { Observable } from 'rxjs';import type { IEditorCanvasStyle, IEditorConfigParams } from './editor';-import { createIdentifier, createParagraphId, DEFAULT_EMPTY_DOCUMENT_VALUE, Disposable, EDITOR_ACTIVATED, FOCUSING_COMMENT_EDITOR, FOCUSING_EDITOR_STANDALONE, HorizontalAlign, ICommandService, IContextService, Inject, Injector, isCommentEditorID, isInternalEditorID, IUndoRedoService, IUniverInstanceService, toDisposable, UniverInstanceType, VerticalAlign } from '@univerjs/core';-import { DocSelectionManagerService } from '@univerjs/docs';+import {+ createIdentifier,+ createParagraphId,+ DEFAULT_EMPTY_DOCUMENT_VALUE,+ Disposable,+ EDITOR_ACTIVATED,+ FOCUSING_COMMENT_EDITOR,+ FOCUSING_EDITOR_STANDALONE,+ HorizontalAlign,+ ICommandService,+ IContextService,+ Inject,+ Injector,+ isCommentEditorID,+ isInternalEditorID,+ IUndoRedoService,+ IUniverInstanceService,+ toDisposable,+ UniverInstanceType,+ VerticalAlign,+} from '@univerjs/core';+import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';import { IRenderManagerService } from '@univerjs/engine-render';import { fromEvent, Subject } from 'rxjs';import { DOCS_VIEW_KEY } from '../../basics/docs-view-key';import { resolveDocRenderBackground } from '../doc-render-background';import { Editor } from './editor';+import { getEditorRuntimeConfig, registerEditorRuntimeConfig } from './editor-runtime-config';export interface IEditorRenderConfig {canvasStyle: IEditorCanvasStyle;preserveHostFocus?: boolean;scrollBar?: boolean;backScrollOffset?: number;+ disableBackScroll?: boolean;}/**@@ -250,18 +272,19 @@ export class EditorService extends Disposable implements IEditorService, IDisposthis.ensureNotDisposed();const { initialSnapshot, canvasStyle = {} } = config;const editorUnitId = initialSnapshot.id;+ const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(editorUnitId, UniverInstanceType.UNIVER_DOC);+ const previousLayout = documentDataModel && getEditorRuntimeConfig(documentDataModel)?.layout;this._editors.get(editorUnitId)?.dispose(false);this._editors.delete(editorUnitId);const renderConfig: IEditorRenderConfig = {canvasStyle,scrollBar: config.scrollBar,...(config.backScrollOffset === undefined ? {} : { backScrollOffset: config.backScrollOffset }),+ ...(config.disableBackScroll === undefined ? {} : { disableBackScroll: config.disableBackScroll }),...(config.preserveHostFocus === undefined ? {} : { preserveHostFocus: config.preserveHostFocus }),};this._editorRenderConfigs.set(editorUnitId, renderConfig);- const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(editorUnitId, UniverInstanceType.UNIVER_DOC);-if (documentDataModel == null) {this._univerInstanceService.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC,@@ -270,52 +293,70 @@ export class EditorService extends Disposable implements IEditorService, IDispos);}- let render = this._renderManagerService.getRenderUnitById(editorUnitId);- if (render == null) {- render = this._renderManagerService.createRender(editorUnitId);- }-- if (render) {- render.engine.mount(container);+ const model = this._univerInstanceService.getUnit<DocumentDataModel>(editorUnitId, UniverInstanceType.UNIVER_DOC)!;+ const runtime = config.renderConfig && registerEditorRuntimeConfig(model, config.renderConfig);- const editor = new Editor(- { ...config, render, editorDom: container, canvasStyle },- this._univerInstanceService,- this._docSelectionManagerService,- this._commandService,- this._undoRedoService,- this._injector- );-- this._editors.set(editorUnitId, editor);-- const resolvedEditorBackground = resolveDocRenderBackground({- canvasColorService: render.engine.canvasColorService,- editorBackgroundColor: canvasStyle.backgroundColor,- isEditor: true,- });- render.engine.getCanvas().getCanvasEle().style.backgroundColor = resolvedEditorBackground.canvasElementBackgroundColor;- const docBackground = render.components.get(DOCS_VIEW_KEY.BACKGROUND) as DocBackground | undefined;- docBackground?.setFillColors(- resolvedEditorBackground.docBackgroundFillColor,- resolvedEditorBackground.docBackgroundFillColor,- resolvedEditorBackground.docBackgroundFillColor,- resolvedEditorBackground.docBackgroundFillColor- );+ let render = this._renderManagerService.getRenderUnitById(editorUnitId);+ try {+ if (render != null && (previousLayout || config.renderConfig?.layout)) {+ render.with(DocSkeletonManagerService).getViewModel()?.reset(model);+ }+ if (render == null) {+ render = this._renderManagerService.createRender(editorUnitId);+ }- // Delete scroll bar- if (!config.scrollBar) {- const viewport = (render.mainComponent?.getScene() as Scene)?.getViewports()?.[0];- viewport?.getScrollBar()?.dispose();- viewport?.updateScrollVal({- scrollX: 0,- scrollY: 0,- viewportScrollX: 0,- viewportScrollY: 0,+ if (render) {+ render.engine.mount(container, !config.cancelDefaultResizeListener);++ const editor = new Editor(+ { ...config, render, editorDom: container, canvasStyle },+ this._univerInstanceService,+ this._docSelectionManagerService,+ this._commandService,+ this._undoRedoService,+ this._injector+ );++ if (runtime) {+ editor.disposeWithMe(runtime);+ }+ this._editors.set(editorUnitId, editor);++ const resolvedEditorBackground = resolveDocRenderBackground({+ canvasColorService: render.engine.canvasColorService,+ editorBackgroundColor: canvasStyle.backgroundColor,+ isEditor: true,});+ render.engine.getCanvas().getCanvasEle().style.backgroundColor = resolvedEditorBackground.canvasElementBackgroundColor;+ const docBackground = render.components.get(DOCS_VIEW_KEY.BACKGROUND) as DocBackground | undefined;+ docBackground?.setFillColors(+ resolvedEditorBackground.docBackgroundFillColor,+ resolvedEditorBackground.docBackgroundFillColor,+ resolvedEditorBackground.docBackgroundFillColor,+ resolvedEditorBackground.docBackgroundFillColor+ );++ // Delete scroll bar+ if (!config.scrollBar) {+ const viewport = (render.mainComponent?.getScene() as Scene)?.getViewports()?.[0];+ viewport?.getScrollBar()?.dispose();+ viewport?.updateScrollVal({+ scrollX: 0,+ scrollY: 0,+ viewportScrollX: 0,+ viewportScrollY: 0,+ });+ }}+ } catch (error) {+ runtime?.dispose();+ this._editors.get(editorUnitId)?.dispose(false);+ this._editors.delete(editorUnitId);+ this._editorRenderConfigs.delete(editorUnitId);+ throw error;}return toDisposable(() => {+ runtime?.dispose();// An older container may unmount after a replacement has registered the same ID.if (this._editorRenderConfigs.get(editorUnitId) === renderConfig) {this._unRegister(editorUnitId);diff --git a/packages/docs-ui/src/services/editor/editor-runtime-config.ts b/packages/docs-ui/src/services/editor/editor-runtime-config.tsnew file mode 100644index 0000000000..2f46f5feb4--- /dev/null+++ b/packages/docs-ui/src/services/editor/editor-runtime-config.ts@@ -0,0 +1,44 @@+/**+ * 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 { DocumentDataModel, IDisposable } from '@univerjs/core';+import type { IDocumentLayoutPresentation } from '@univerjs/engine-render';+import { toDisposable } from '@univerjs/core';+import { registerDocumentLayoutPresentation } from '@univerjs/engine-render';++export interface IEditorRuntimeConfig {+ layout?: IDocumentLayoutPresentation;+ inheritParagraphStartStyle?: boolean;+ disableSelectionAutoScroll?: boolean;+}++const configs = new WeakMap<DocumentDataModel, { config: IEditorRuntimeConfig }>();++export function registerEditorRuntimeConfig(model: DocumentDataModel, config: IEditorRuntimeConfig): IDisposable {+ const registration = { config };+ configs.set(model, registration);+ const layout = config.layout && registerDocumentLayoutPresentation(model, config.layout);+ return toDisposable(() => {+ layout?.dispose();+ if (configs.get(model) === registration) {+ configs.delete(model);+ }+ });+}++export function getEditorRuntimeConfig(model: DocumentDataModel): IEditorRuntimeConfig | undefined {+ return configs.get(model)?.config;+}diff --git a/packages/docs-ui/src/services/editor/editor.ts b/packages/docs-ui/src/services/editor/editor.tsindex f3d20fe8cd..1d0c282457 100644--- a/packages/docs-ui/src/services/editor/editor.ts+++ b/packages/docs-ui/src/services/editor/editor.ts@@ -33,6 +33,7 @@ import type {} from '@univerjs/engine-render';import type { Observable } from 'rxjs';import type { IEditorInputConfig } from '../selection/doc-selection-render.service';+import type { IEditorRuntimeConfig } from './editor-runtime-config';import { createParagraphId, createSectionId, Disposable, isInternalEditorID, UniverInstanceType } from '@univerjs/core';import { DocSkeletonManagerService } from '@univerjs/docs';import { IRenderManagerService } from '@univerjs/engine-render';@@ -102,10 +103,16 @@ export interface IEditorCanvasStyle {}export interface IEditorConfigParams {+ /** Instance-only layout and interaction settings, never persisted in the document. */+ renderConfig?: IEditorRuntimeConfig;initialSnapshot: IDocumentData;/** Keep the globally focused unit on the editor's host while this editor receives input focus. */preserveHostFocus?: boolean;cancelDefaultResizeListener?: boolean;+ /** Use a fixed canvas backing-store ratio for an editor managed by an external layout host. */+ pixelRatio?: number;+ /** Publish transient drag ranges to an external editor host. Defaults to false. */+ emitSelectionWhileDragging?: boolean;canvasStyle?: IEditorCanvasStyle;// A Boolean attribute which, if present, indicates that the editor should automatically have focus.// No more than one editor in the document may have the autofocus attribute.@@ -115,6 +122,7 @@ export interface IEditorConfigParams {readonly?: boolean;backScrollOffset?: number;+ disableBackScroll?: boolean;// The unique id of editor.editorUnitId?: string;@@ -151,6 +159,7 @@ export class Editor extends Disposable implements IEditor {// Emit when doc selection changed.private readonly _selectionChange$ = new Subject<IDocSelectionInnerParam>();selectionChange$: Observable<IDocSelectionInnerParam> = this._selectionChange$.asObservable();+ private _movingSelectionRanges?: ITextRangeWithStyle[];constructor(private _param: IEditorOptions,@@ -174,6 +183,7 @@ export class Editor extends Disposable implements IEditor {this.disposeWithMe(docSelectionRenderService.onBlur$.subscribe((e) => {+ this._movingSelectionRanges = undefined;this._blur$.next(e);const data = this.getDocumentData();@@ -238,10 +248,20 @@ export class Editor extends Disposable implements IEditor {const editorId = this.getEditorId();if (unitId === editorId) {+ this._movingSelectionRanges = undefined;this._selectionChange$.next(params);}}));++ if (this._param.emitSelectionWhileDragging) {+ this.disposeWithMe(+ docSelectionRenderService.movingSelection$.subscribe((selection) => {+ this._movingSelectionRanges = selection.textRanges;+ this._selectionChange$.next(selection);+ })+ );+ }}isFocus() {@@ -293,6 +313,7 @@ export class Editor extends Disposable implements IEditor {// Selects the specified range of characters within editor.setSelectionRanges(ranges: ISuccinctDocRangeParam[], shouldFocus = true): void {+ this._movingSelectionRanges = undefined;const editorUnitId = this.getEditorId();const params = {unitId: editorUnitId,@@ -304,6 +325,9 @@ export class Editor extends Disposable implements IEditor {// Get current doc ranges. include text range and rect range.getSelectionRanges(): ITextRangeWithStyle[] {+ if (this._movingSelectionRanges) {+ return this._movingSelectionRanges;+ }const editorUnitId = this.getEditorId();const params = {unitId: editorUnitId,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.tsindex f519a739a9..6cc2f291c0 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@@ -759,23 +759,31 @@ describe('selection convert text range helpers', () => {expect(getSelectionBounds(end, start)).toEqual(expectedBounds);});- it('excludes layout-only paragraph spacing from text selection height', () => {+ it.each([+ { name: 'normal font metrics', bBox: { ba: 10, bd: 3 }, ascent: 13, contentHeight: 16 },+ {+ name: 'fixed line metrics',+ bBox: { ba: 56, bd: 0, fontAscent: 10, fontDescent: 3 },+ ascent: 59,+ contentHeight: 62,+ },+ ])('excludes layout-only spacing from the caret with $name', ({ bBox, ascent, contentHeight }) => {const glyph = {- bBox: { ba: 10, bd: 3 },+ bBox: { ...bBox },count: 1,glyphType: 'LETTER',left: 0,width: 20,};const line = {- asc: 13,- contentHeight: 16,+ asc: ascent,+ contentHeight,divides: [{glyphGroup: [glyph],left: 0,paddingLeft: 0,}],- lineHeight: 92,+ lineHeight: contentHeight + 76,marginBottom: 34,marginTop: 0,paddingBottom: 4,@@ -825,11 +833,19 @@ describe('selection convert text range helpers', () => {const result = convertor.getRangePointData(position, position);expect(getLineBounding(result.borderBoxPointGroup)[0]).toEqual({- bottom: 24,+ bottom: contentHeight + 8,left: 0,right: 20,top: 0,});+ expect(getAnchorBounding(result.contentBoxPointGroup)).toEqual({+ left: 0,+ top: 4 + ascent - 10,+ width: 20,+ height: 13,+ });+ expect(line.asc).toBe(ascent);+ expect(glyph.bBox).toEqual(bBox);});it('uses normal caret height for non-inline embed custom blocks', () => {diff --git a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.tsindex bae9bfe62e..25008f34a7 100644--- a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts+++ b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts@@ -32,6 +32,7 @@ import {import { DocLayoutExecutorService, DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';import { DeviceType, GlyphType, NORMAL_TEXT_SELECTION_PLUGIN_STYLE, PointerInput, RenderUnit } from '@univerjs/engine-render';import { ILayoutService } from '@univerjs/ui';+import { Subject } from 'rxjs';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE,@@ -241,6 +242,7 @@ function createService() {_logService: {error: vi.fn(),},+ _movingSelection$: new Subject(),_textSelectionInner$: {next: vi.fn(),value: { isEditing: false },diff --git a/packages/docs-ui/src/services/selection/convert-text-range.ts b/packages/docs-ui/src/services/selection/convert-text-range.tsindex c281906a96..b2061a9f06 100644--- a/packages/docs-ui/src/services/selection/convert-text-range.ts+++ b/packages/docs-ui/src/services/selection/convert-text-range.ts@@ -365,6 +365,8 @@ export class NodePositionConvertToCursor {const collapsed = start === end;const rawAnchorGlyph = isStartBack ? (preGlyph ?? firstGlyph) : firstGlyph;const anchorGlyph = this._getCaretGlyph(rawAnchorGlyph, glyphGroup, start_sp);+ const caretAscent = anchorGlyph.bBox.fontAscent ?? anchorGlyph.bBox.ba;+ const caretDescent = anchorGlyph.bBox.fontDescent ?? anchorGlyph.bBox.bd;const selectedGlyphs = glyphGroup.slice(start_sp, end_sp + 1);const isSelectionOnlyNonInlineDrawing = !collapsed &&selectedGlyphs.length > 0 &&@@ -384,9 +386,9 @@ export class NodePositionConvertToCursor {contentBoxPosition = {startX: startX + firstGlyphLeft + (isCurrentList ? firstGlyphWidth : 0),- startY: startY + paddingTop + asc - anchorGlyph.bBox.ba,+ startY: startY + paddingTop + asc - caretAscent,endX: startX + lastGlyphLeft + (isEndBack ? 0 : lastGlyphWidth),- endY: startY + paddingTop + asc + anchorGlyph.bBox.bd,+ endY: startY + paddingTop + asc + caretDescent,};} else {const isStartBackFin = isStartBack && !isCurrentList;@@ -400,9 +402,9 @@ export class NodePositionConvertToCursor {contentBoxPosition = {startX: startX + firstGlyphLeft + (isStartBackFin ? 0 : firstGlyphWidth),- startY: startY + paddingTop + asc - anchorGlyph.bBox.ba,+ startY: startY + paddingTop + asc - caretAscent,endX: startX + lastGlyphLeft + (isEndBack ? 0 : lastGlyphWidth),- endY: startY + paddingTop + asc + anchorGlyph.bBox.bd,+ endY: startY + paddingTop + asc + caretDescent,};}diff --git a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts b/packages/docs-ui/src/services/selection/doc-selection-render.service.tsindex afa14bd68e..f956d9dbcb 100644--- a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts+++ b/packages/docs-ui/src/services/selection/doc-selection-render.service.ts@@ -58,7 +58,12 @@ import {} from '@univerjs/engine-render';import { ILayoutService, KeyCode } from '@univerjs/ui';import { BehaviorSubject, filter, fromEvent, merge, Subject, takeUntil } from 'rxjs';-import { DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, IDocEmbedInteractionBoundaryService, IDocEmbedRuntimeFocusCoordinator } from '../doc-embed-integration.service';+import {+ DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE,+ IDocEmbedInteractionBoundaryService,+ IDocEmbedRuntimeFocusCoordinator,+} from '../doc-embed-integration.service';+import { getEditorRuntimeConfig } from '../editor/editor-runtime-config';import { compareNodePositionLogic } from './convert-text-range';import {getCanvasOffsetByEngine,@@ -114,6 +119,9 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMoprivate readonly _textSelectionInner$ = new BehaviorSubject<Nullable<IDocSelectionInnerParam>>(null);readonly textSelectionInner$ = this._textSelectionInner$.asObservable();+ private readonly _movingSelection$ = new Subject<IDocSelectionInnerParam>();+ readonly movingSelection$ = this._movingSelection$.asObservable();+private readonly _onFocus$ = new Subject<IEditorInputConfig>();readonly onFocus$ = this._onFocus$.asObservable();@@ -753,9 +761,12 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMoscene.disableObjectsEvent();- const scrollTimer = ScrollTimer.create(scene);- this._scrollTimers.push(scrollTimer);- scrollTimer.startScroll(evtOffsetX, evtOffsetY);+ const disableAutoScroll = getEditorRuntimeConfig(this._context.unit)?.disableSelectionAutoScroll === true;+ const scrollTimer = disableAutoScroll ? undefined : ScrollTimer.create(scene);+ if (scrollTimer) {+ this._scrollTimers.push(scrollTimer);+ scrollTimer.startScroll(evtOffsetX, evtOffsetY);+ }this._onSelectionStart$.next(this._getActiveRangeInstance()?.startNodePosition);@@ -775,7 +786,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMothis._tryMoving(moveOffsetX, moveOffsetY);- scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {+ scrollTimer?.scrolling(moveOffsetX, moveOffsetY, () => {this._tryMoving(moveOffsetX, moveOffsetY);});@@ -1245,6 +1256,16 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMothis._addTextRangesToCache(textRanges);this._addRectRangesToCache(rectRanges);+ if (this._movingSelection$.observed) {+ this._movingSelection$.next({+ textRanges: this._rangeListCache.map(serializeTextRange),+ rectRanges: this._rectRangeListCache.map(serializeRectRange),+ segmentId: this._currentSegmentId,+ segmentPage: this._currentSegmentPage,+ style: this._selectionStyle,+ isEditing: false,+ });+ }this.deactivate();}@@ -1371,6 +1392,16 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMothis._addTextRangesToCache(textRanges);this._addRectRangesToCache(rectRanges);+ if (this._movingSelection$.observed) {+ this._movingSelection$.next({+ textRanges: this._rangeListCache.map(serializeTextRange),+ rectRanges: this._rectRangeListCache.map(serializeRectRange),+ segmentId: this._currentSegmentId,+ segmentPage: this._currentSegmentPage,+ style: this._selectionStyle,+ isEditing: false,+ });+ }this.deactivate();this._context.scene?.getEngine()?.setCapture();@@ -1854,6 +1885,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMothis._onCompositionend$.complete();this._onSelectionStart$.complete();this._textSelectionInner$.complete();+ this._movingSelection$.complete();this._onPaste$.complete();this._onFocus$.complete();this._onBlur$.complete();diff --git a/packages/docs-ui/src/views/RichTextEditor.tsx b/packages/docs-ui/src/views/RichTextEditor.tsxindex c55612c34a..148e4a08b6 100644--- a/packages/docs-ui/src/views/RichTextEditor.tsx+++ b/packages/docs-ui/src/views/RichTextEditor.tsx@@ -17,7 +17,8 @@import type { IDocumentData } from '@univerjs/core';import type { CSSProperties, ReactNode, RefObject } from 'react';import type { Editor, IEditorCanvasStyle } from '../services/editor/editor';-import type { IKeyboardEventConfig } from './rich-text-editor/hooks';+import type { IEditorRuntimeConfig } from '../services/editor/editor-runtime-config';+import type { IKeyboardEventConfig } from './rich-text-editor/hooks/use-keyboard-event';import {BuildTextUtils,createInternalEditorID,@@ -37,12 +38,18 @@ import { useDependency, useEvent, useObservable } from '@univerjs/ui';import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { map, merge, startWith } from 'rxjs';import { DocSelectionRenderService } from '../services/selection/doc-selection-render.service';-import { createEditorUndoRedoKeyboardConfig, useEditorClickOutside, useIsFocusing, useKeyboardEvent, useResize } from './rich-text-editor/hooks';+import { createEditorUndoRedoKeyboardConfig } from './rich-text-editor/hooks/editor-undo-redo-keyboard';import { useEditor } from './rich-text-editor/hooks/use-editor';+import { useEditorClickOutside } from './rich-text-editor/hooks/use-editor-click-outside';+import { useIsFocusing } from './rich-text-editor/hooks/use-is-focusing';+import { useKeyboardEvent } from './rich-text-editor/hooks/use-keyboard-event';import { useLeftAndRightArrow } from './rich-text-editor/hooks/use-left-and-right-arrow';import { useOnChange } from './rich-text-editor/hooks/use-on-change';+import { useResize } from './rich-text-editor/hooks/use-resize';export interface IRichTextEditorProps {+ /** Instance-only layout and interaction settings, never persisted in the document. */+ renderConfig?: IEditorRuntimeConfig;className?: string;autoFocus?: boolean;onFocusChange?: (isFocus: boolean, newValue?: string) => void;@@ -50,6 +57,22 @@ export interface IRichTextEditorProps {onClickOutside?: () => void;/** Keep the globally focused unit on the editor's host while this editor receives input focus. */preserveHostFocus?: boolean;+ /** Let the host own engine sizing, including a fixed backing-store ratio. */+ cancelDefaultResizeListener?: boolean;+ /** Fixed canvas backing-store ratio used with a host-managed layout. */+ pixelRatio?: number;+ /** Use an untransformed layout size when the editor DOM is displayed through a CSS transform. */+ layoutSize?: Readonly<Pick<DOMRectReadOnly, 'width' | 'height'>>;+ /** Keep document reflow independent from an oversized host-managed canvas. */+ documentLayoutSize?: Readonly<Pick<DOMRectReadOnly, 'width' | 'height'>>;+ /** Keep the editor viewport anchored while a host expands it to fit content. */+ autoScroll?: boolean;+ /** Let the editor create scrollbars when its content exceeds the current layout size. */+ autoScrollbar?: boolean;+ /** Publish transient drag ranges to the host. Defaults to false. */+ emitSelectionWhileDragging?: boolean;+ /** Keep host keyboard handlers active for non-collapsed selections. Defaults to false. */+ keyboardEventsOnSelection?: boolean;keyboardEventConfig?: IKeyboardEventConfig;moveCursor?: boolean;style?: CSSProperties;@@ -74,7 +97,15 @@ export const RichTextEditor = (props: IRichTextEditorProps) => {initialValue,onClickOutside: _onClickOutside,preserveHostFocus,+ cancelDefaultResizeListener,+ documentLayoutSize,+ autoScroll = true,+ autoScrollbar = true,+ emitSelectionWhileDragging,+ keyboardEventsOnSelection = false,keyboardEventConfig,+ layoutSize,+ pixelRatio,moveCursor = true,style,isSingle,@@ -88,6 +119,7 @@ export const RichTextEditor = (props: IRichTextEditorProps) => {placeholder,noStyle,canvasStyle,+ renderConfig,} = props;const commandService = useDependency(ICommandService);@@ -101,10 +133,16 @@ export const RichTextEditor = (props: IRichTextEditorProps) => {const editor = useEditor({editorId,initialValue,+ renderConfig,container: formulaEditorContainerRef,preserveHostFocus,+ cancelDefaultResizeListener,+ disableBackScroll: !autoScroll,+ emitSelectionWhileDragging,+ documentLayoutSize,autoFocus,isSingle,+ pixelRatio,canvasStyle,});const direction = useObservable(localeService.direction$, localeService.getDirection());@@ -137,7 +175,15 @@ export const RichTextEditor = (props: IRichTextEditorProps) => {false,[editor]);- const { checkScrollBar } = useResize(editor, isSingle, true, true);+ const { checkScrollBar } = useResize(+ editor,+ isSingle,+ autoScrollbar,+ autoScroll,+ layoutSize,+ pixelRatio,+ documentLayoutSize+ );useLayoutEffect(() => {if (!editorRef || !editor) return;@@ -187,7 +233,8 @@ export const RichTextEditor = (props: IRichTextEditorProps) => {}), [commandService, editorId, keyboardEventConfig, univerInstanceService]);useLeftAndRightArrow(isFocusing && moveCursor, false, editor);- useKeyboardEvent(isFocusing, resolvedKeyboardEventConfig, editor);+ // Undo can restore a non-collapsed selection without blurring the editor.+ useKeyboardEvent(keyboardEventsOnSelection ? editorFocused : isFocusing, resolvedKeyboardEventConfig, editor);useOnChange(editor, onChange);return (diff --git a/packages/docs-ui/src/views/__tests__/RichTextEditor.spec.tsx b/packages/docs-ui/src/views/__tests__/RichTextEditor.spec.tsxindex 03aa4137ec..1cccb323ad 100644--- a/packages/docs-ui/src/views/__tests__/RichTextEditor.spec.tsx+++ b/packages/docs-ui/src/views/__tests__/RichTextEditor.spec.tsx@@ -45,7 +45,7 @@ import {RichTextEditingMutation,SetTextSelectionsOperation,} from '@univerjs/docs';-import { IRenderManagerService } from '@univerjs/engine-render';+import { DocumentViewModel, IRenderManagerService } from '@univerjs/engine-render';import {IPlatformService,IShortcutService,@@ -77,6 +77,7 @@ class TestEditorRender extends Disposable {onCompositionupdate$: new Subject(),onCompositionend$: new Subject(),textSelectionInner$: new Subject(),+ movingSelection$: new Subject(),isFocusing: false,};@@ -86,15 +87,32 @@ class TestEditorRender extends Disposable {canvasColorService: {},mount: (container: HTMLDivElement) => container.appendChild(this.canvas),getCanvas: () => ({ getCanvasEle: () => this.canvas }),+ resizeBySize: (width: number, height: number) => {+ this.canvas.width = width;+ this.canvas.height = height;+ },};+ readonly scene = { transformByState: () => undefined, getViewport: () => undefined };+ private readonly _viewModel: DocumentViewModel;++ constructor(model: DocumentDataModel) {+ super();+ this._viewModel = new DocumentViewModel(model);+ this.disposeWithMe(this._viewModel);+ }++ isDisposed() {+ return this._disposed;+ }+with(token: unknown) {if (token === DocSelectionRenderService) {return this.selection;}if (token === DocSkeletonManagerService) {return {- getViewModel: () => undefined,+ getViewModel: () => this._viewModel,getSkeleton: () => ({ getActualSize: () => ({ actualWidth: 100, actualHeight: 20 }) }),};}@@ -115,8 +133,12 @@ class TestEditorRender extends Disposable {class TestRenderManagerService extends Disposable {private readonly _renders = new Map<string, TestEditorRender>();+ constructor(@IUniverInstanceService private readonly _instanceService: IUniverInstanceService) {+ super();+ }+createRender(id: string) {- const render = new TestEditorRender();+ const render = new TestEditorRender(this._instanceService.getUnit<DocumentDataModel>(id)!);this._renders.set(id, render);this.disposeWithMe(render);return render;diff --git a/packages/docs-ui/src/views/rich-text-editor/hooks/__tests__/use-resize.spec.tsx b/packages/docs-ui/src/views/rich-text-editor/hooks/__tests__/use-resize.spec.tsxnew file mode 100644index 0000000000..24525036c2--- /dev/null+++ b/packages/docs-ui/src/views/rich-text-editor/hooks/__tests__/use-resize.spec.tsx@@ -0,0 +1,147 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/**+ * @vitest-environment jsdom+ */++import type { Editor } from '../../../../services/editor/editor';+import { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { resizeEditor } from '../use-resize';++describe('useResize', () => {+ it('does not access canvas resources after the editor render is disposed', () => {+ const getBoundingClientRect = vi.fn(() => {+ throw new Error('Disposed editor DOM');+ });+ const editor = { render: { isDisposed: () => true }, getBoundingClientRect } as unknown as Editor;+ expect(() => resizeEditor(editor, false, { width: 100, height: 20 })).not.toThrow();+ expect(getBoundingClientRect).not.toHaveBeenCalled();+ });++ it('preserves engine-owned sizing when no host dimensions are configured', () => {+ const updateDocumentDataPageSize = vi.fn();+ const sceneTransform = vi.fn();+ const documentResize = vi.fn();+ const documentTranslate = vi.fn();+ const backgroundTranslate = vi.fn();+ const engineResize = vi.fn();+ const editor = {+ getBoundingClientRect: () => ({ width: 320, height: 96 }),+ getSelectionRanges: () => [],+ input$: new Subject(),+ render: {+ isDisposed: () => false,+ components: { get: () => ({ translate: backgroundTranslate }) },+ engine: {+ getCanvas: () => ({ setPixelRatio: vi.fn() }),+ resizeBySize: engineResize,+ },+ mainComponent: { resize: documentResize, translate: documentTranslate },+ scene: { transformByState: sceneTransform },+ with: () => ({+ getViewModel: () => ({+ getDataModel: () => ({ updateDocumentDataPageSize }),+ }),+ }),+ },+ } as unknown as Editor;++ resizeEditor(editor, false);++ expect(updateDocumentDataPageSize).toHaveBeenCalledWith(320, Infinity);+ expect(engineResize).not.toHaveBeenCalled();+ expect(sceneTransform).toHaveBeenCalledWith({ width: 320, height: 96 });+ expect(documentResize).toHaveBeenCalledWith(320, 96);+ expect(documentTranslate).toHaveBeenCalledWith(0, 0);+ expect(backgroundTranslate).toHaveBeenCalledWith(0, 0);+ });++ it('uses the explicit layout size when the editor DOM is CSS transformed', () => {+ const updateDocumentDataPageSize = vi.fn();+ const sceneTransform = vi.fn();+ const documentResize = vi.fn();+ const engineResize = vi.fn();+ const setPixelRatio = vi.fn();+ const editor = {+ getBoundingClientRect: () => ({ width: 24, height: 480 }),+ getSelectionRanges: () => [],+ input$: new Subject(),+ render: {+ isDisposed: () => false,+ components: { get: () => ({ translate: vi.fn() }) },+ engine: {+ getCanvas: () => ({ setPixelRatio }),+ resizeBySize: engineResize,+ },+ mainComponent: { resize: documentResize, translate: vi.fn() },+ scene: { transformByState: sceneTransform },+ with: () => ({+ getViewModel: () => ({+ getDataModel: () => ({ updateDocumentDataPageSize }),+ }),+ }),+ },+ } as unknown as Editor;++ resizeEditor(editor, false, { width: 480, height: 24 }, 2);++ expect(updateDocumentDataPageSize).toHaveBeenCalledWith(480, Infinity);+ expect(engineResize).toHaveBeenCalledWith(480, 24);+ expect(setPixelRatio).toHaveBeenCalledWith(2);+ expect(sceneTransform).toHaveBeenCalledWith({ width: 480, height: 24 });+ expect(documentResize).toHaveBeenCalledWith(480, 24);+ });++ it('can oversize the canvas without changing the document reflow width', () => {+ const updateDocumentDataPageSize = vi.fn();+ const documentResize = vi.fn();+ const engineResize = vi.fn();+ const editor = {+ getBoundingClientRect: () => ({ width: 204, height: 30 }),+ getSelectionRanges: () => [],+ input$: new Subject(),+ render: {+ isDisposed: () => false,+ components: { get: () => ({ translate: vi.fn() }) },+ engine: {+ getCanvas: () => ({ setPixelRatio: vi.fn() }),+ resizeBySize: engineResize,+ },+ mainComponent: { resize: documentResize, translate: vi.fn() },+ scene: { transformByState: vi.fn() },+ with: () => ({+ getViewModel: () => ({+ getDataModel: () => ({ updateDocumentDataPageSize }),+ }),+ }),+ },+ } as unknown as Editor;++ resizeEditor(+ editor,+ false,+ { width: 240, height: 30 },+ 1,+ { width: 204, height: 30 }+ );++ expect(engineResize).toHaveBeenCalledWith(240, 30);+ expect(updateDocumentDataPageSize).toHaveBeenCalledWith(204, Infinity);+ expect(documentResize).toHaveBeenCalledWith(204, 30);+ });+});diff --git a/packages/docs-ui/src/views/rich-text-editor/hooks/use-editor.ts b/packages/docs-ui/src/views/rich-text-editor/hooks/use-editor.tsindex 5923fe1dc3..523929b128 100644--- a/packages/docs-ui/src/views/rich-text-editor/hooks/use-editor.ts+++ b/packages/docs-ui/src/views/rich-text-editor/hooks/use-editor.ts@@ -17,12 +17,15 @@import type { IDocumentData, Nullable } from '@univerjs/core';import type { RefObject } from 'react';import type { Editor, IEditorCanvasStyle } from '../../../services/editor/editor';+import type { IEditorRuntimeConfig } from '../../../services/editor/editor-runtime-config';import { createParagraphId, RichTextBuilder, Tools } from '@univerjs/core';import { useDependency } from '@univerjs/ui';import { useLayoutEffect, useMemo, useState } from 'react';import { IEditorService } from '../../../services/editor/editor-manager.service';export interface IUseEditorProps {+ /** Instance-only layout and interaction settings, never persisted in the document. */+ renderConfig?: IEditorRuntimeConfig;editorId: string;initialValue: Nullable<IDocumentData | string>;container: RefObject<HTMLDivElement>;@@ -30,10 +33,29 @@ export interface IUseEditorProps {autoFocus?: boolean;isSingle?: boolean;canvasStyle?: IEditorCanvasStyle;+ cancelDefaultResizeListener?: boolean;+ disableBackScroll?: boolean;+ documentLayoutSize?: Readonly<Pick<DOMRectReadOnly, 'width' | 'height'>>;+ pixelRatio?: number;+ emitSelectionWhileDragging?: boolean;}export function useEditor(opts: IUseEditorProps) {- const { editorId, initialValue, container, preserveHostFocus, autoFocus: _autoFocus, isSingle, canvasStyle } = opts;+ const {+ autoFocus: _autoFocus,+ cancelDefaultResizeListener,+ canvasStyle,+ container,+ disableBackScroll,+ documentLayoutSize,+ emitSelectionWhileDragging,+ editorId,+ initialValue,+ isSingle,+ pixelRatio,+ preserveHostFocus,+ renderConfig,+ } = opts;const autoFocus = useMemo(() => _autoFocus ?? false, []);const [editor, setEditor] = useState<Editor>();const editorService = useDependency(IEditorService);@@ -60,7 +82,8 @@ export function useEditor(opts: IUseEditorProps) {documentStyle: {...initialDoc?.documentStyle,pageSize: {- width: !isSingle ? container.current.clientWidth : Infinity,+ // Match the first skeleton to the explicit reflow width, before resize runs.+ width: isSingle ? Infinity : (documentLayoutSize?.width ?? container.current.clientWidth),height: Infinity,},},@@ -69,9 +92,14 @@ export function useEditor(opts: IUseEditorProps) {const dispose = editorService.register({autofocus: true,+ cancelDefaultResizeListener,canvasStyle,+ disableBackScroll,editorUnitId: editorId,+ emitSelectionWhileDragging,initialSnapshot: snapshot,+ renderConfig,+ pixelRatio,preserveHostFocus,},container.currentdiff --git a/packages/docs-ui/src/views/rich-text-editor/hooks/use-resize.ts b/packages/docs-ui/src/views/rich-text-editor/hooks/use-resize.tsindex 7041f8025b..b214d9f60c 100644--- a/packages/docs-ui/src/views/rich-text-editor/hooks/use-resize.ts+++ b/packages/docs-ui/src/views/rich-text-editor/hooks/use-resize.ts@@ -19,7 +19,7 @@ import type { Editor } from '../../../services/editor/editor';import { debounce } from '@univerjs/core';import { DocSkeletonManagerService } from '@univerjs/docs';import { ScrollBar } from '@univerjs/engine-render';-import { useCallback, useEffect, useMemo } from 'react';+import { useCallback, useEffect, useLayoutEffect, useMemo } from 'react';import { DOCS_VIEW_KEY, VIEWPORT_KEY } from '../../../basics/docs-view-key';interface IUseResizeReturn {@@ -27,45 +27,82 @@ interface IUseResizeReturn {checkScrollBar: () => void;}-// eslint-disable-next-line max-lines-per-function-export const useResize = (editor?: Editor, isSingle = true, autoScrollbar?: boolean, autoScroll?: boolean): IUseResizeReturn => {- const resize = useCallback(() => {- if (editor) {- const { scene, mainComponent } = editor.render;- const docSkeletonManagerService = editor.render.with(DocSkeletonManagerService);- const { width, height } = editor.getBoundingClientRect();+export function resizeEditor(+ editor: Editor,+ isSingle: boolean,+ layoutSize?: Readonly<Pick<DOMRectReadOnly, 'width' | 'height'>>,+ pixelRatio?: number,+ documentLayoutSize?: Readonly<Pick<DOMRectReadOnly, 'width' | 'height'>>+): void {+ if (editor.render.isDisposed()) {+ return;+ }+ const { scene, mainComponent } = editor.render;+ const docSkeletonManagerService = editor.render.with(DocSkeletonManagerService);+ const { width, height } = layoutSize ?? editor.getBoundingClientRect();- docSkeletonManagerService.getViewModel().getDataModel().updateDocumentDataPageSize(isSingle ? Infinity : width, Infinity);- scene.transformByState({- width,- height,- });+ if (layoutSize || documentLayoutSize || pixelRatio !== undefined) {+ editor.render.engine.resizeBySize(width, height);+ }+ if (pixelRatio !== undefined) {+ editor.render.engine.getCanvas().setPixelRatio(pixelRatio);+ }- mainComponent?.resize(width, height);- mainComponent?.translate(0, 0);- editor.render.components.get(DOCS_VIEW_KEY.BACKGROUND)?.translate(0, 0);+ const documentWidth = documentLayoutSize?.width ?? width;+ docSkeletonManagerService.getViewModel().getDataModel().updateDocumentDataPageSize(+ isSingle ? Infinity : documentWidth,+ Infinity+ );+ scene.transformByState({+ width,+ height,+ });- const selectionRanges = editor.getSelectionRanges();- if (selectionRanges.length > 0) {- editor.setSelectionRanges(selectionRanges, false);- }+ mainComponent?.resize(documentWidth, height);+ mainComponent?.translate(0, 0);+ editor.render.components.get(DOCS_VIEW_KEY.BACKGROUND)?.translate(0, 0);++ const selectionRanges = editor.getSelectionRanges();+ if (selectionRanges.length > 0) {+ editor.setSelectionRanges(selectionRanges, false);+ }+}++export const useResize = (+ editor?: Editor,+ isSingle = true,+ autoScrollbar?: boolean,+ autoScroll?: boolean,+ layoutSize?: Readonly<Pick<DOMRectReadOnly, 'width' | 'height'>>,+ pixelRatio?: number,+ documentLayoutSize?: Readonly<Pick<DOMRectReadOnly, 'width' | 'height'>>+): IUseResizeReturn => {+ const resize = useCallback(() => {+ if (editor) {+ resizeEditor(editor, isSingle, layoutSize, pixelRatio, documentLayoutSize);}- }, [editor, isSingle]);+ }, [documentLayoutSize, editor, isSingle, layoutSize, pixelRatio]);const checkScrollBar = useMemo(() => {// eslint-disable-next-line complexityreturn debounce(() => {- if (!autoScrollbar) return;- if (!editor || !autoScrollbar || editor.render.isDisposed()) {+ if (!editor || editor.render.isDisposed()) {return;}const docSkeletonManagerService = editor.render.with(DocSkeletonManagerService);- const skeleton = docSkeletonManagerService.getSkeleton();const { scene, mainComponent } = editor.render;const viewportMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);+ if (!autoScrollbar) {+ if (layoutSize && autoScroll === false) {+ viewportMain?.scrollToBarPos({ x: 0, y: 0 });+ viewportMain?.getScrollBar()?.dispose();+ }+ return;+ }+ const skeleton = docSkeletonManagerService.getSkeleton();const { actualWidth, actualHeight } = skeleton.getActualSize();- const { width, height } = editor.getBoundingClientRect();+ const { width, height } = layoutSize ?? editor.getBoundingClientRect();let scrollBar = viewportMain?.getScrollBar() as Nullable<ScrollBar>;const contentWidth = Math.max(actualWidth, width);const contentHeight = Math.max(actualHeight, height);@@ -116,7 +153,13 @@ export const useResize = (editor?: Editor, isSingle = true, autoScrollbar?: bool}}}, 30);- }, [editor, autoScrollbar, isSingle, autoScroll]);+ }, [editor, autoScrollbar, isSingle, autoScroll, layoutSize]);++ useLayoutEffect(() => {+ if (editor && (layoutSize || documentLayoutSize || pixelRatio !== undefined)) {+ resize();+ }+ }, [documentLayoutSize, editor, layoutSize, pixelRatio, resize]);useEffect(() => {if (!autoScrollbar) return;@@ -132,7 +175,9 @@ export const useResize = (editor?: Editor, isSingle = true, autoScrollbar?: bool}, [editor, autoScrollbar, resize, checkScrollBar]);useEffect(() => {- if (!autoScrollbar) return;+ if (!autoScrollbar && !(layoutSize && autoScroll === false)) {+ return;+ }if (editor) {const d = editor.input$.subscribe(() => {checkScrollBar();@@ -141,7 +186,7 @@ export const useResize = (editor?: Editor, isSingle = true, autoScrollbar?: boold.unsubscribe();};}- }, [editor, autoScrollbar, checkScrollBar]);+ }, [autoScroll, editor, autoScrollbar, checkScrollBar, layoutSize]);return { resize, checkScrollBar };};diff --git a/packages/docs/src/commands/mutations/__tests__/core-editing.mutation.spec.ts b/packages/docs/src/commands/mutations/__tests__/core-editing.mutation.spec.tsindex fa355e47c1..ffbd7b09a9 100644--- a/packages/docs/src/commands/mutations/__tests__/core-editing.mutation.spec.ts+++ b/packages/docs/src/commands/mutations/__tests__/core-editing.mutation.spec.ts@@ -16,7 +16,7 @@import type { IRichTextEditingMutationParams } from '../core-editing.mutation';import { CustomRangeType, DocumentFlavor, ICommandService, JSONX, TextX } from '@univerjs/core';-import { NORMAL_TEXT_SELECTION_PLUGIN_STYLE } from '@univerjs/engine-render';+import { NORMAL_TEXT_SELECTION_PLUGIN_STYLE, registerDocumentLayoutPresentation } from '@univerjs/engine-render';import { describe, expect, it, vi } from 'vitest';import { createDocumentData, createTestBed } from '../../../facade/__tests__/create-test-bed';import { DocSelectionManagerService } from '../../../services/doc-selection-manager.service';@@ -257,3 +257,63 @@ describe('RichTextEditingMutation selection scheduling', () => {testBed.univer.dispose();});});++describe('host layout state at the mutation boundary', () => {+ it('restores local layout state with undo and redo without changing the document snapshot schema', () => {+ const bed = createTestBed(createDocumentData('runtime-history', { dataStream: 'AB\r\n' }));+ let layoutState = { offset: 1 };+ const runtime = registerDocumentLayoutPresentation(bed.doc, {+ getSnapshot: (document) => document,+ captureState: () => ({ ...layoutState }),+ applyActions: () => { layoutState = { offset: 2 }; },+ restoreState: (state) => { layoutState = state as typeof layoutState; },+ });+ try {+ const command = bed.get(ICommandService);+ const params: IRichTextEditingMutationParams = {+ unitId: bed.doc.getUnitId(),+ textRanges: null,+ actions: JSONX.getInstance().editOp(new TextX().retain(1).insert(1, { dataStream: 'X' }).serialize()),+ };+ const undo = command.syncExecuteCommand<IRichTextEditingMutationParams, IRichTextEditingMutationParams>(RichTextEditingMutation.id, params);+ expect(layoutState).toEqual({ offset: 2 });+ expect(bed.doc.getBody()?.dataStream).toBe('AXB\r\n');+ expect(bed.doc.getSnapshot()).not.toHaveProperty('layoutState');+ const redo = command.syncExecuteCommand<IRichTextEditingMutationParams, IRichTextEditingMutationParams>(RichTextEditingMutation.id, undo);+ expect(layoutState).toEqual({ offset: 1 });+ expect(bed.doc.getBody()?.dataStream).toBe('AB\r\n');+ command.syncExecuteCommand(RichTextEditingMutation.id, redo);+ expect(layoutState).toEqual({ offset: 2 });+ expect(bed.doc.getBody()?.dataStream).toBe('AXB\r\n');+ } finally {+ runtime.dispose();+ bed.univer.dispose();+ }+ });++ it('rolls back document content and host state together when layout adaptation fails', () => {+ const bed = createTestBed(createDocumentData('runtime-failure', { dataStream: 'AB\r\n' }));+ let layoutState = 1;+ const runtime = registerDocumentLayoutPresentation(bed.doc, {+ getSnapshot: (document) => document,+ captureState: () => layoutState,+ applyActions: () => {+ layoutState = 2;+ throw new Error('layout failed');+ },+ restoreState: (state) => { layoutState = state as number; },+ });+ try {+ expect(() => bed.get(ICommandService).syncExecuteCommand(RichTextEditingMutation.id, {+ unitId: bed.doc.getUnitId(),+ textRanges: null,+ actions: JSONX.getInstance().editOp(new TextX().retain(1).insert(1, { dataStream: 'X' }).serialize()),+ })).toThrow('layout failed');+ expect(bed.doc.getBody()?.dataStream).toBe('AB\r\n');+ expect(layoutState).toBe(1);+ } finally {+ runtime.dispose();+ bed.univer.dispose();+ }+ });+});diff --git a/packages/docs/src/commands/mutations/core-editing.mutation.ts b/packages/docs/src/commands/mutations/core-editing.mutation.tsindex 1511147bb5..163dbee031 100644--- a/packages/docs/src/commands/mutations/core-editing.mutation.ts+++ b/packages/docs/src/commands/mutations/core-editing.mutation.ts@@ -41,7 +41,7 @@ import {UndoCommandId,UniverInstanceType,} from '@univerjs/core';-import { IRenderManagerService } from '@univerjs/engine-render';+import { getDocumentLayoutPresentation, IRenderManagerService } from '@univerjs/engine-render';import { DocSelectionManagerService } from '../../services/doc-selection-manager.service';import { DocSkeletonManagerService } from '../../services/doc-skeleton-manager.service';import { DocStateEmitService } from '../../services/doc-state-emit.service';@@ -62,6 +62,8 @@ export enum DocHistoryAction {export interface IRichTextEditingMutationParams extends IMutationCommonParams {unitId: string;+ /** Host-owned transient layout state, used only by local editor history. */+ layoutState?: unknown;historyAction?: string;historyActions?: string[];actions: JSONXActions;@@ -333,6 +335,9 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,return { unitId, actions: [], textRanges: docRanges };}+ const presentation = getDocumentLayoutPresentation(documentDataModel);+ const previousLayoutState = presentation?.captureState();+const { actions: appliedActions, undoActions, preservesStructure } = applyValidatedDocumentActions(documentDataModel,segmentId,@@ -340,6 +345,21 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,isHistoryReplay);+ if (presentation) {+ try {+ if (params.layoutState !== undefined) {+ presentation.restoreState(params.layoutState);+ } else {+ presentation.applyActions(appliedActions, documentDataModel.getSnapshot());+ }+ params.layoutState = presentation.captureState();+ } catch (error) {+ documentDataModel.apply(undoActions);+ presentation.restoreState(previousLayoutState);+ throw error;+ }+ }+// Publish reference deletion and note cleanup in the same deterministic mutation.params.actions = appliedActions;resetDocumentViewModel(documentViewModel, documentDataModel, segmentId, appliedActions, preservesStructure);@@ -354,12 +374,14 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,noHistory,debounce,redoState: {+ ...(presentation ? { layoutState: params.layoutState } : {}),actions: appliedActions,textRanges,options: params.options,isEditing,},undoState: {+ ...(presentation ? { layoutState: previousLayoutState } : {}),actions: undoActions,textRanges: prevTextRanges ?? docRanges,options: selectionInfo?.options,@@ -374,6 +396,7 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,return {unitId,actions: undoActions,+ ...(presentation ? { layoutState: previousLayoutState } : {}),textRanges: docRanges,};},diff --git a/packages/docs/src/services/__tests__/doc-skeleton-manager.service.spec.ts b/packages/docs/src/services/__tests__/doc-skeleton-manager.service.spec.tsindex 850f802375..499f23b151 100644--- a/packages/docs/src/services/__tests__/doc-skeleton-manager.service.spec.ts+++ b/packages/docs/src/services/__tests__/doc-skeleton-manager.service.spec.ts@@ -33,8 +33,13 @@ import {UniverInstanceService,UniverInstanceType,} from '@univerjs/core';+import { registerDocumentLayoutPresentation } from '@univerjs/engine-render';import { afterEach, describe, expect, it, vi } from 'vitest';-import { DocLayoutExecutorService, DocLayoutExecutorType, DocLayoutSessionStatus } from '../doc-layout-executor.service';+import {+ DocLayoutExecutorService,+ DocLayoutExecutorType,+ DocLayoutSessionStatus,+} from '../doc-layout-executor.service';import { DocSkeletonManagerService } from '../doc-skeleton-manager.service';function createDocument(options?: { documentFlavor?: DocumentFlavor; id?: string }) {@@ -181,6 +186,22 @@ describe('DocSkeletonManagerService', () => {expect(service.getSkeleton().getSkeletonData()).toBeUndefined();});+ it('keeps a host layout projection synchronous while ordinary Docs can use the registered executor', () => {+ const document = createDocument({ documentFlavor: DocumentFlavor.TRADITIONAL });+ const registration = registerDocumentLayoutPresentation(document, {+ getSnapshot: (snapshot) => snapshot,+ captureState: () => undefined,+ applyActions: () => {},+ restoreState: () => {},+ });+ const service = createService(document, true);+ expect(service.supportsIncrementalLayout()).toBe(false);+ expect(service.getSkeleton().getSkeletonData()).not.toBeNull();+ registration.dispose();+ expect(service.supportsIncrementalLayout()).toBe(true);+ service.dispose();+ });+it('keeps an internal editor synchronous even if its flavor is paginated', () => {const service = createService(createDocument({id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,diff --git a/packages/docs/src/services/__tests__/doc-state-change-manager.service.spec.ts b/packages/docs/src/services/__tests__/doc-state-change-manager.service.spec.tsindex 0e92e55e48..d26e2c42d7 100644--- a/packages/docs/src/services/__tests__/doc-state-change-manager.service.spec.ts+++ b/packages/docs/src/services/__tests__/doc-state-change-manager.service.spec.ts@@ -120,6 +120,29 @@ describe('DocStateChangeManagerService', () => {sub.unsubscribe();});+ it('keeps host layout history local and excludes it from collaborative change events', () => {+ const { service, emitter, undoRedoService, univerInstanceService } = createService();+ univerInstanceService.__addUnit(new DocumentDataModel({ id: 'doc-1' }));+ univerInstanceService.focusUnit('doc-1');+ const changes: unknown[] = [];+ const subscription = service.docStateChange$.subscribe((value) => changes.push(value));+ const base = createChange();+ const change = {+ ...base,+ undoState: { ...base.undoState, layoutState: { glyph: 'before' } },+ redoState: { ...base.redoState, layoutState: { glyph: 'after' } },+ };+ emitter.emitStateChangeInfo(change);+ expect(undoRedoService.pitchTopUndoElement()).toMatchObject({+ undoMutations: [{ params: { layoutState: { glyph: 'before' } } }],+ redoMutations: [{ params: { layoutState: { glyph: 'after' } } }],+ });+ expect(changes).toHaveLength(2);+ expect(changes[1]).not.toHaveProperty('undoState.layoutState');+ expect(changes[1]).not.toHaveProperty('redoState.layoutState');+ subscription.unsubscribe();+ });+it('filters sync or intercepted state changes without changing caches', () => {const synced = createService();synced.emitter.emitStateChangeInfo(createChange({ isSync: true }));diff --git a/packages/docs/src/services/doc-skeleton-manager.service.ts b/packages/docs/src/services/doc-skeleton-manager.service.tsindex a0947f55ca..d91b785865 100644--- a/packages/docs/src/services/doc-skeleton-manager.service.ts+++ b/packages/docs/src/services/doc-skeleton-manager.service.ts@@ -16,8 +16,16 @@import type { DocumentDataModel, Nullable } from '@univerjs/core';import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';-import { DocumentFlavor, Inject, isInternalEditorID, IUniverInstanceService, LocaleService, RxDisposable, UniverInstanceType } from '@univerjs/core';-import { DocumentSkeleton, DocumentViewModel } from '@univerjs/engine-render';+import {+ DocumentFlavor,+ Inject,+ isInternalEditorID,+ IUniverInstanceService,+ LocaleService,+ RxDisposable,+ UniverInstanceType,+} from '@univerjs/core';+import { DocumentSkeleton, DocumentViewModel, getDocumentLayoutPresentation } from '@univerjs/engine-render';import { BehaviorSubject, takeUntil } from 'rxjs';import { DocLayoutExecutorService } from './doc-layout-executor.service';@@ -88,6 +96,7 @@ export class DocSkeletonManagerService extends RxDisposable implements IRenderMoreturn this._docLayoutExecutorService.getExecutor() != null &&!isInternalEditorID(this._context.unitId) &&+ !getDocumentLayoutPresentation(this._context.unit) &&(documentFlavor === DocumentFlavor.TRADITIONAL || documentFlavor === DocumentFlavor.MODERN);}diff --git a/packages/docs/src/services/doc-state-change-manager.service.ts b/packages/docs/src/services/doc-state-change-manager.service.tsindex 13958e202f..d09b52ec2d 100644--- a/packages/docs/src/services/doc-state-change-manager.service.ts+++ b/packages/docs/src/services/doc-state-change-manager.service.ts@@ -17,7 +17,19 @@import type { DocumentDataModel, JSONXActions, Nullable } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';import type { IDocStateChangeInfo, IDocStateChangeParams } from './doc-state-emit.service';-import { createIdentifier, ICommandService, Inject, IUndoRedoService, IUniverInstanceService, JSONX, Optional, RedoCommandId, RxDisposable, UndoCommandId, UniverInstanceType } from '@univerjs/core';+import {+ createIdentifier,+ ICommandService,+ Inject,+ IUndoRedoService,+ IUniverInstanceService,+ JSONX,+ Optional,+ RedoCommandId,+ RxDisposable,+ UndoCommandId,+ UniverInstanceType,+} from '@univerjs/core';import { BehaviorSubject, takeUntil } from 'rxjs';import { DocStateEmitService } from './doc-state-emit.service';@@ -215,6 +227,7 @@ export class DocStateChangeManagerService extends RxDisposable {const redoParams: IRichTextEditingMutationParams = {unitId,trigger: RedoCommandId,+ ...(lastState.redoState.layoutState === undefined ? {} : { layoutState: lastState.redoState.layoutState }),actions: cacheStates.reduce((acc, cur) => JSONX.compose(acc, cur.redoState.actions), null as JSONXActions),textRanges: lastState.redoState.textRanges,segmentId: lastState.segmentId,@@ -225,6 +238,7 @@ export class DocStateChangeManagerService extends RxDisposable {const undoParams: IRichTextEditingMutationParams = {unitId,trigger: UndoCommandId,+ ...(firstState.undoState.layoutState === undefined ? {} : { layoutState: firstState.undoState.layoutState }),// Always need to put undoParams after redoParams, because `reverse` will change the `cacheStates` order.actions: cacheStates.reverse().reduce((acc, cur) => JSONX.compose(acc, cur.undoState.actions), null as JSONXActions),textRanges: firstState.undoState.textRanges,diff --git a/packages/docs/src/services/doc-state-emit.service.ts b/packages/docs/src/services/doc-state-emit.service.tsindex ecf2acf371..88882ea78a 100644--- a/packages/docs/src/services/doc-state-emit.service.ts+++ b/packages/docs/src/services/doc-state-emit.service.ts@@ -20,6 +20,7 @@ import { RxDisposable } from '@univerjs/core';import { BehaviorSubject } from 'rxjs';interface IDocChangeState {+ layoutState?: unknown;actions: JSONXActions;textRanges: Nullable<ITextRangeWithStyle[]>;options?: { [key: string]: boolean };diff --git a/packages/engine-render/src/basics/i-document-skeleton-cached.ts b/packages/engine-render/src/basics/i-document-skeleton-cached.tsindex e1c6300877..4bdd9a692a 100644--- a/packages/engine-render/src/basics/i-document-skeleton-cached.ts+++ b/packages/engine-render/src/basics/i-document-skeleton-cached.ts@@ -19,19 +19,21 @@ import type {ColumnSeparatorType,DataStreamTreeTokenType,IColorStyle,- IColumnGroup,IDocDrawingBase,- IDocumentRenderConfig,INestingLevel,- IParagraph,IParagraphBorder,IParagraphProperties,ITable,ITableRow,- ITextStyle,PageOrientType,TabStopLeader,} from '@univerjs/core';+import type {+ IDocumentLayoutColumnGroup,+ IDocumentLayoutParagraph,+ IDocumentLayoutRenderConfig,+ IDocumentLayoutTextStyle,+} from '../components/docs/document-layout-presentation';import type { BreakPointType } from '../components/docs/layout/line-breaker/break';export interface IDocumentSkeletonCached extends ISkeletonResourceReference {@@ -45,7 +47,7 @@ export interface IDocumentSkeletonCached extends ISkeletonResourceReference {export interface IParagraphList {bullet: IDocumentSkeletonBullet;- paragraph: IParagraph;+ paragraph: IDocumentLayoutParagraph;}export interface IDocumentSkeletonParagraphBorders {@@ -143,7 +145,7 @@ export interface IDocumentSkeletonPage {skeColumnGroups: Map<string, IDocumentSkeletonColumnGroup>; // column group skeletons in the pagesegmentId: string; // header/footer id if header/footer, empty string if body pagetype: DocumentSkeletonPageType; // page type: header, footer, body, or cell- renderConfig?: IDocumentRenderConfig;+ renderConfig?: IDocumentLayoutRenderConfig;parent?: IDocumentSkeletonCached | IDocumentSkeletonRow | IDocumentSkeletonColumnGroupColumn | IDocumentSkeletonNote;}@@ -214,7 +216,7 @@ export interface IDocumentSkeletonColumnGroup {st: number;ed: number;columnGroupId: string;- columnGroupSource: IColumnGroup;+ columnGroupSource: IDocumentLayoutColumnGroup;parent?: IDocumentSkeletonPage;}@@ -327,8 +329,8 @@ export interface IDocumentSkeletonGlyph {raw: string;adjustability: IAdjustability; // The adjustability of the glyph.isJustifiable: boolean; // Whether this glyph is justifiable for CJK scripts.- ts?: ITextStyle; // text style- fontStyle?: IDocumentSkeletonFontStyle; // fontStyle : ITextStyle convert to canvas font+ ts?: IDocumentLayoutTextStyle; // text style+ fontStyle?: IDocumentSkeletonFontStyle; // fontStyle : IDocumentLayoutTextStyle convert to canvas fontparent?: IDocumentSkeletonDivide;url?: string; // image urlfeatureId?: string; // support interaction for feature ,eg. hyperLine person@@ -347,8 +349,8 @@ export interface IDocumentSkeletonGlyph {export interface IDocumentSkeletonBullet {listId: string; // listIdsymbol: string; // symbol list content- ts: ITextStyle; // text style- fontStyle?: IDocumentSkeletonFontStyle; // fontStyle converted from ITextStyle to canvas font+ ts: IDocumentLayoutTextStyle; // text style+ fontStyle?: IDocumentSkeletonFontStyle; // fontStyle converted from IDocumentLayoutTextStyle to canvas fontstartIndexItem: number; // startIndexItem, list start indexstartNumber?: number; // zero-based start number retained across a restarted sequence// bBox: IDocumentSkeletonBoundingBox; // bBox text position information@@ -403,6 +405,9 @@ export interface IDocumentSkeletonBoundingBox {width: number; // widthba: number; // boundingBoxAscentbd: number; // boundingBoxDescent+ /** Font metrics retained for the caret when ba/bd are overridden for fixed line layout. */+ fontAscent?: number;+ fontDescent?: number;normalLineHeight?: number; // Normal font spacing, including leading when available, for Word AUTO spacing.aba: number; // actualBoundingBoxAscentabd: number; // actualBoundingBoxDescentdiff --git a/packages/engine-render/src/basics/interfaces.ts b/packages/engine-render/src/basics/interfaces.tsindex 2a0e66acae..686c7c8f4e 100644--- a/packages/engine-render/src/basics/interfaces.ts+++ b/packages/engine-render/src/basics/interfaces.ts@@ -20,16 +20,19 @@ import type {IDocStyleBase,IDocumentLayout,IOffset,- IParagraphStyle,IReferenceSource,IScale,ISectionBreakBase,ISize,- ITextStyle,ITransformState,LocaleService,} from '@univerjs/core';import type { IDocumentCompatibilityPolicy } from '../components/docs/document-compatibility';+import type {+ IDocumentLayoutParagraphStyle,+ IDocumentLayoutRenderConfig,+ IDocumentLayoutTextStyle,+} from '../components/docs/document-layout-presentation';import type { DataStreamTreeNode } from '../components/docs/view-model/data-stream-tree-node';import type { DocumentViewModel } from '../components/docs/view-model/document-view-model';import type {@@ -93,7 +96,7 @@ export interface IFontLocale {export interface IDocsConfig extends IReferenceSource, IDocumentLayout {localeService: LocaleService;- documentTextStyle?: ITextStyle;+ documentTextStyle?: IDocumentLayoutTextStyle;documentCompatibilityPolicy?: IDocumentCompatibilityPolicy;headerTreeMap: Map<string, DocumentViewModel>;footerTreeMap: Map<string, DocumentViewModel>;@@ -112,6 +115,7 @@ export interface IFooterIds {}export interface ISectionBreakConfig extends IDocStyleBase, ISectionBreakBase, IDocsConfig {+ renderConfig?: IDocumentLayoutRenderConfig;sectionId: string;/** Cell continuation pages retain their segment and physical row-slice budgets. */cellTableId?: string;@@ -147,7 +151,7 @@ export interface IParagraphConfig {pptxEmptyParagraphFontSize?: number;pptxHasExplicitEndParaFontSize?: boolean;sumPptxParagraphSpacing?: boolean;- docxFallbackAnchorLeft?: IParagraphStyle['indentStart'];+ docxFallbackAnchorLeft?: IDocumentLayoutParagraphStyle['indentStart'];paragraphNonInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>;paragraphInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>;topBottomCustomBlockFlowBottom?: number;@@ -156,7 +160,7 @@ export interface IParagraphConfig {bulletSkeleton?: IDocumentSkeletonBullet;// pageContentWidth: number;// pageContentHeight: number;- paragraphStyle?: IParagraphStyle;+ paragraphStyle?: IDocumentLayoutParagraphStyle;borderTopSpace?: number;borderBottomSpace?: number;skeHeaders: Map<string, Map<number, IDocumentSkeletonHeaderFooter>>;@@ -167,7 +171,7 @@ export interface IParagraphConfig {export interface IFontCreateConfig {fontStyle: IDocumentSkeletonFontStyle;- textStyle: ITextStyle;+ textStyle: IDocumentLayoutTextStyle;charSpace: number;snapToGrid: BooleanNumber;documentCompatibilityPolicy?: IDocumentCompatibilityPolicy;diff --git a/packages/engine-render/src/components/docs/__tests__/document-compatibility.spec.ts b/packages/engine-render/src/components/docs/__tests__/document-compatibility.spec.tsindex 710a5659b9..ac66d95696 100644--- a/packages/engine-render/src/components/docs/__tests__/document-compatibility.spec.ts+++ b/packages/engine-render/src/components/docs/__tests__/document-compatibility.spec.ts@@ -157,4 +157,20 @@ describe('document compatibility policy', () => {expect(applyFontMetricCompatibility('中', simSunFallback, { ...bBox, width: 10 }, traditional).width).toBeCloseTo(9.7);});++ it('keeps traditional layout behavior while allowing font metric scaling to be disabled', () => {+ const policy = getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL, false);+ const simSunFallback = {+ ...fontStyle,+ fontString: 'normal normal 12pt "Times New Roman", 宋体',+ fontSize: 12,+ originFontSize: 12,+ fontFamily: '"Times New Roman", 宋体',+ fontCache: 'normal normal 12pt "Times New Roman", 宋体',+ } as IDocumentSkeletonFontStyle;++ expect(policy.mode).toBe('traditional');+ expect(policy.useWordStyleLineHeight).toBe(true);+ expect(applyFontMetricCompatibility('中', simSunFallback, { ...bBox, width: 10 }, policy).width).toBe(10);+ });});diff --git a/packages/engine-render/src/components/docs/__tests__/document.spec.ts b/packages/engine-render/src/components/docs/__tests__/document.spec.tsindex a804cbadd1..3120072f71 100644--- a/packages/engine-render/src/components/docs/__tests__/document.spec.ts+++ b/packages/engine-render/src/components/docs/__tests__/document.spec.ts@@ -18,6 +18,7 @@ import type { IDocumentBody, IParagraphStyle, IScale, ITable } from '@univerjs/cimport type { IDocumentSkeletonGlyph } from '../../../basics/i-document-skeleton-cached';import type { IExtensionConfig } from '../../extension';import {+ BooleanNumber,ColumnSeparatorType,CustomRangeType,DashStyleType,@@ -394,6 +395,63 @@ describe('documents render', () => {setDocsTableRenderViewportProvider(null);});+ it('routes glyphs with source groups and replays them without accumulating baseline offsets', () => {+ const bed = createParagraphLayoutTestBed('AB', {+ body: { textRuns: [+ { st: 0, ed: 1, ts: { fs: 12, pos: 3, customGlyphGroup: 'first' } },+ { st: 1, ed: 2, ts: { fs: 18, customGlyphGroup: 'second' } },+ ] },+ });+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);+ const documents = new Documents('ordered-glyphs', skeleton);+ try {+ skeleton.calculate();+ scene.addObject(documents, 1);+ const context = canvas.getContext();+ const draw = vi.spyOn(context, 'fillText');+ documents.draw(context);+ const original = draw.mock.calls.map((args) => [...args]);+ expect(original.map(([text]) => text).join('').trim()).toBe('AB');+ draw.mockClear();+ const sink = vi.fn();+ const subscription = documents.setGlyphPaintSink(sink);+ documents.draw(context);+ expect(draw).not.toHaveBeenCalled();+ const paints = documents.getGlyphPaints();+ expect(sink).toHaveBeenCalledWith(paints);+ expect(paints.slice(0, 2).map((paint) => paint.group)).toEqual(['first', 'second']);+ for (let repeat = 0; repeat < 2; repeat++) {+ draw.mockClear();+ for (const paint of paints) {+ context.save();+ context.setTransform(...paint.transform);+ paint.draw(context);+ context.restore();+ }+ expect(draw.mock.calls).toEqual(original);+ }+ const replacement = vi.fn();+ const nextSubscription = documents.setGlyphPaintSink(replacement);+ subscription.dispose();+ documents.draw(context);+ expect(replacement).toHaveBeenCalledOnce();+ nextSubscription.dispose();+ expect(documents.getGlyphPaints()).toEqual([]);+ draw.mockClear();+ documents.draw(context);+ expect(draw.mock.calls).toEqual(original);+ documents.setGlyphPaintSink(sink);+ documents.draw(context);+ documents.dispose();+ expect(documents.getGlyphPaints()).toEqual([]);+ } finally {+ documents.dispose();+ skeleton.dispose();+ bed.viewModel.dispose();+ bed.dataModel.dispose();+ }+ });+it.each(['separator', 'continuationSeparator', 'continuationNotice'] as const)('renders each note kind with its own %s fields', (kind) => {const fieldBody = (fieldType: string) => ({dataStream: '\uFFFC\r\n',@@ -2075,6 +2133,53 @@ describe('documents render', () => {documents.dispose();});+ it('allows a column group to render overflowing content without clipping', () => {+ const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');+ attachColumnGroup(bodyPage);+ const columnGroup = bodyPage.skeColumnGroups.get('column-group-1')!;+ columnGroup.columnGroupSource.clipContent = BooleanNumber.FALSE;+ const nestedPage = columnGroup.columns[0].page;+ nestedPage.sections[0].columns[0].lines = [];++ const documents = new Documents('docs-column-group-overflow');+ (documents as any)._drawLiquid = {+ x: 12,+ y: 20,+ translateSave: vi.fn(),+ translateRestore: vi.fn(),+ translateSection: vi.fn(),+ translateColumn: vi.fn(),+ };+ const ctx = {+ beginPath: vi.fn(),+ clip: vi.fn(),+ closePath: vi.fn(),+ rectByPrecision: vi.fn(),+ restore: vi.fn(),+ save: vi.fn(),+ } as any;++ (documents as any)._drawNestedPageContent(+ ctx,+ bodyPage,+ nestedPage,+ [],+ null,+ [],+ [],+ { x: 0, y: 0 },+ 0,+ 0,+ {},+ { scaleX: 1, scaleY: 1 }+ );++ expect(ctx.rectByPrecision).not.toHaveBeenCalled();+ expect(ctx.clip).not.toHaveBeenCalled();++ documents.dispose();+ });+it('draws tables inside column group nested pages', () => {const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');attachColumnGroup(bodyPage);diff --git a/packages/engine-render/src/components/docs/custom-glyph-renderer.ts b/packages/engine-render/src/components/docs/custom-glyph-renderer.tsnew file mode 100644index 0000000000..c67f73c4b6--- /dev/null+++ b/packages/engine-render/src/components/docs/custom-glyph-renderer.ts@@ -0,0 +1,74 @@+/**+ * 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 { IDisposable } from '@univerjs/core';+import type { UniverRenderingContext } from '../../context';+import { toDisposable } from '@univerjs/core';++export interface IDocCustomGlyphRenderInput {+ bold?: boolean;+ italic?: boolean;+ content: string;+ context: UniverRenderingContext;+ fontSizePx: number;+ glyphKey?: string;+ x: number;+ y: number;+}++export type DocCustomGlyphRenderer = (input: IDocCustomGlyphRenderInput) => boolean;++export interface IDocCustomGlyphRendererRegistration {+ fontFamily: string;+ renderer: DocCustomGlyphRenderer;+ strokeRenderer?: DocCustomGlyphRenderer;+}++const CUSTOM_GLYPH_RENDERERS = new Map<string, IDocCustomGlyphRendererRegistration>();++export function registerDocCustomGlyphRenderer(registration: IDocCustomGlyphRendererRegistration): IDisposable {+ CUSTOM_GLYPH_RENDERERS.set(registration.fontFamily, registration);+ return toDisposable(() => {+ if (CUSTOM_GLYPH_RENDERERS.get(registration.fontFamily) === registration) {+ CUSTOM_GLYPH_RENDERERS.delete(registration.fontFamily);+ }+ });+}++export function getDocCustomGlyphRenderer(fontFamily: string | undefined): DocCustomGlyphRenderer | undefined {+ return getDocCustomGlyphRegistration(fontFamily)?.renderer;+}++export function getDocCustomGlyphStrokeRenderer(fontFamily: string | undefined): DocCustomGlyphRenderer | undefined {+ return getDocCustomGlyphRegistration(fontFamily)?.strokeRenderer;+}++function getDocCustomGlyphRegistration(fontFamily: string | undefined): IDocCustomGlyphRendererRegistration | undefined {+ if (!fontFamily) {+ return undefined;+ }+ const firstFamily = fontFamily.split(',')[0]?.trim();+ if (!firstFamily) {+ return undefined;+ }+ const unquotedFamily = (+ (firstFamily.startsWith('"') && firstFamily.endsWith('"'))+ || (firstFamily.startsWith("'") && firstFamily.endsWith("'"))+ )+ ? firstFamily.slice(1, -1)+ : firstFamily;+ return CUSTOM_GLYPH_RENDERERS.get(unquotedFamily);+}diff --git a/packages/engine-render/src/components/docs/document-compatibility.ts b/packages/engine-render/src/components/docs/document-compatibility.tsindex 6027785f64..7e192baa93 100644--- a/packages/engine-render/src/components/docs/document-compatibility.ts+++ b/packages/engine-render/src/components/docs/document-compatibility.ts@@ -86,6 +86,13 @@ const TRADITIONAL_DOCUMENT_COMPATIBILITY_POLICY: IDocumentCompatibilityPolicy =},};+const TRADITIONAL_DOCUMENT_COMPATIBILITY_WITHOUT_FONT_METRIC_SCALE_POLICY: IDocumentCompatibilityPolicy = {+ ...TRADITIONAL_DOCUMENT_COMPATIBILITY_POLICY,+ font: {+ metricScaleRules: [],+ },+};+const UNSPECIFIED_DOCUMENT_COMPATIBILITY_POLICY: IDocumentCompatibilityPolicy = {mode: 'unspecified',applyDocumentDefaultParagraphStyle: false,@@ -105,7 +112,10 @@ const DRAWINGML_COMPATIBILITY_POLICY: IDocumentCompatibilityPolicy = {mode: 'drawingml',};-export function getDocumentCompatibilityPolicy(documentFlavor?: DocumentFlavor): IDocumentCompatibilityPolicy {+export function getDocumentCompatibilityPolicy(+ documentFlavor?: DocumentFlavor,+ fontMetricScaleEnabled = true+): IDocumentCompatibilityPolicy {if (documentFlavor === DocumentFlavor.DRAWINGML) {return DRAWINGML_COMPATIBILITY_POLICY;}@@ -114,7 +124,9 @@ export function getDocumentCompatibilityPolicy(documentFlavor?: DocumentFlavor):}if (documentFlavor === DocumentFlavor.TRADITIONAL) {- return TRADITIONAL_DOCUMENT_COMPATIBILITY_POLICY;+ return fontMetricScaleEnabled+ ? TRADITIONAL_DOCUMENT_COMPATIBILITY_POLICY+ : TRADITIONAL_DOCUMENT_COMPATIBILITY_WITHOUT_FONT_METRIC_SCALE_POLICY;}return UNSPECIFIED_DOCUMENT_COMPATIBILITY_POLICY;diff --git a/packages/engine-render/src/components/docs/document-layout-presentation.ts b/packages/engine-render/src/components/docs/document-layout-presentation.tsnew file mode 100644index 0000000000..fd42792e21--- /dev/null+++ b/packages/engine-render/src/components/docs/document-layout-presentation.ts@@ -0,0 +1,153 @@+/**+ * 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 {+ BooleanNumber,+ DocumentDataModel,+ IColumn,+ IColumnGroup,+ ICustomColumnGroup,+ IDisposable,+ IDocTextOutline,+ IDocumentBody,+ IDocumentData,+ IDocumentRenderConfig,+ IDocumentStyle,+ IParagraph,+ IParagraphStyle,+ ISectionBreak,+ ITextDecoration,+ ITextRun,+ ITextStyle,+ JSONXActions,+} from '@univerjs/core';+import { toDisposable } from '@univerjs/core';++/** Transient layout data. These fields are never part of a document model or snapshot. */+export interface IDocumentLayoutTextDecoration extends ITextDecoration {+ offset?: number;+ offsetReference?: 'line-bottom' | 'baseline';+}++export interface IDocumentLayoutTextStyle extends ITextStyle {+ fontRenderScale?: number;+ textSkewX?: number;+ textAdvance?: number;+ customGlyphKey?: string;+ customGlyphGroup?: string;+ lineAscent?: number;+ lineDescent?: number;+ textPaintOffsets?: Array<{ x: number; y: number }>;+ textOutline?: IDocTextOutline & {+ lineCap?: 'butt' | 'round' | 'square';+ lineJoin?: 'bevel' | 'miter' | 'round';+ miterLimit?: number;+ };+ ul?: IDocumentLayoutTextDecoration;+ st?: IDocumentLayoutTextDecoration;+ ol?: IDocumentLayoutTextDecoration;+}++export interface IDocumentLayoutRenderConfig extends IDocumentRenderConfig {+ topAlignExactLineSpacing?: BooleanNumber;+ useTextInkForHitTesting?: BooleanNumber;+ preservePunctuationSpacing?: BooleanNumber;+ applyTextPosition?: BooleanNumber;+ paintTextOutline?: BooleanNumber;+ useCustomGlyphRenderer?: BooleanNumber;+}++export interface IDocumentLayoutParagraphStyle extends IParagraphStyle {+ fixedTabStops?: BooleanNumber;+ textStyle?: IDocumentLayoutTextStyle;+ paragraphMarkTextStyle?: IDocumentLayoutTextStyle;+}++export interface IDocumentLayoutParagraph extends IParagraph {+ paragraphStyle?: IDocumentLayoutParagraphStyle;+}++export interface IDocumentLayoutTextRun extends ITextRun {+ ts?: IDocumentLayoutTextStyle;+}++export interface IDocumentLayoutColumn extends IColumn {+ topOffset?: IColumn['minWidth'];+}++export interface IDocumentLayoutColumnGroup extends IColumnGroup {+ horizontalPadding?: IColumnGroup['gap'];+ minHeight?: IColumnGroup['gap'];+ clipContent?: BooleanNumber;+ columns: IDocumentLayoutColumn[];+}++export interface IDocumentLayoutCustomColumnGroup extends ICustomColumnGroup {+ horizontalPadding?: IColumnGroup['gap'];+ minHeight?: IColumnGroup['gap'];+ clipContent?: BooleanNumber;+ columns?: IDocumentLayoutColumn[];+}++export interface IDocumentLayoutSectionBreak extends ISectionBreak {+ renderConfig?: IDocumentLayoutRenderConfig;+}++export interface IDocumentLayoutStyle extends IDocumentStyle {+ fontMetricScaleEnabled?: BooleanNumber;+ textStyle?: IDocumentLayoutTextStyle;+ renderConfig?: IDocumentLayoutRenderConfig;+}++export interface IDocumentLayoutBody extends IDocumentBody {+ textRuns?: IDocumentLayoutTextRun[];+ paragraphs?: IDocumentLayoutParagraph[];+ sectionBreaks?: IDocumentLayoutSectionBreak[];+ columnGroups?: IDocumentLayoutCustomColumnGroup[];+}++/** A read-only layout projection owned by an external host, not a persisted Doc snapshot. */+export interface IDocumentLayoutSnapshot extends IDocumentData {+ documentStyle: IDocumentLayoutStyle;+ body?: IDocumentLayoutBody;+}++/** Synchronous, model-only hooks for host layout metadata and its local undo history. */+export interface IDocumentLayoutPresentation {+ getSnapshot(document: IDocumentData): IDocumentLayoutSnapshot;+ captureState(): unknown;+ applyActions(actions: JSONXActions, document: IDocumentData): void;+ restoreState(state: unknown): void;+}++const presentations = new WeakMap<DocumentDataModel, { presentation: IDocumentLayoutPresentation }>();++export function registerDocumentLayoutPresentation(+ model: DocumentDataModel,+ presentation: IDocumentLayoutPresentation+): IDisposable {+ const registration = { presentation };+ presentations.set(model, registration);+ return toDisposable(() => {+ if (presentations.get(model) === registration) {+ presentations.delete(model);+ }+ });+}++export function getDocumentLayoutPresentation(model: DocumentDataModel): IDocumentLayoutPresentation | undefined {+ return presentations.get(model)?.presentation;+}diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.tsindex 58d222e61c..9d771221d2 100644--- a/packages/engine-render/src/components/docs/document.ts+++ b/packages/engine-render/src/components/docs/document.ts@@ -16,7 +16,7 @@import type {ICustomRange,- IDocumentRenderConfig,+ IDisposable,IParagraphBorder,IScale,ITableCell,@@ -41,10 +41,12 @@ import type { UniverRenderingContext } from '../../context';import type { Scene } from '../../scene';import type { ComponentExtension, IDrawInfo, IExtensionConfig } from '../extension';import type { IDocumentsConfig, IPageMarginLayout } from './doc-component';+import type { IDocumentLayoutRenderConfig } from './document-layout-presentation';import type { DocumentSkeleton } from './layout/doc-skeleton';import type { IDocsTableRenderViewport } from './table-render-viewport';import type { DocumentViewModel } from './view-model/document-view-model';import {+ BooleanNumber,CellValueType,ColumnSeparatorType,DashStyleType,@@ -53,6 +55,7 @@ import {HorizontalAlign,TableTextWrapType,TabStopAlignment,+ toDisposable,VerticalAlign,WrapStrategy,} from '@univerjs/core';@@ -297,7 +300,34 @@ export function drawSectionColumnSeparators(ctx.restore();}+export interface IDocumentGlyphPaint {+ group?: string;+ transform: readonly [number, number, number, number, number, number];+ draw(context: UniverRenderingContext): void;+}+export class Documents extends DocComponent {+ private _glyphPaintSink?: (paints: readonly IDocumentGlyphPaint[]) => void;+ private _glyphPaints: IDocumentGlyphPaint[] = [];++ /** Route actual Docs glyph painters into a host's ordered compositor. */+ setGlyphPaintSink(sink: (paints: readonly IDocumentGlyphPaint[]) => void): IDisposable {+ this._glyphPaintSink = sink;+ this.makeDirty(true);+ return toDisposable(() => {+ if (this._glyphPaintSink === sink) {+ this._glyphPaintSink = undefined;+ this._glyphPaints = [];+ this.makeDirty(true);+ }+ });+ }++ /** Most recent glyph frame routed to the host, also used for isolated ink measurement. */+ getGlyphPaints(): readonly IDocumentGlyphPaint[] {+ return this._glyphPaints;+ }+private readonly _pageRender$ = new Subject<IPageRenderConfig>();readonly pageRender$ = this._pageRender$.asObservable();@@ -319,6 +349,8 @@ export class Documents extends DocComponent {}override dispose() {+ this._glyphPaintSink = undefined;+ this._glyphPaints = [];super.dispose();this._pageRender$.complete();@@ -416,6 +448,7 @@ export class Documents extends DocComponent {return;}+ this._glyphPaints = [];this._drawLiquid.reset();const { pages, skeHeaders, skeFooters } = skeletonData;@@ -681,6 +714,7 @@ export class Documents extends DocComponent {pageLeft += x;pageTop += y;}+ this._glyphPaintSink?.(this._glyphPaints);}private _drawBodySections(@@ -693,7 +727,7 @@ export class Documents extends DocComponent {alignOffsetNoAngle: Vector2,centerAngle: number,vertexAngle: number,- renderConfig: IDocumentRenderConfig,+ renderConfig: IDocumentLayoutRenderConfig,parentScale: IScale,isContinuousLayout: boolean,pageTop: number,@@ -919,7 +953,7 @@ export class Documents extends DocComponent {alignOffset: Vector2,centerAngle: number,vertexAngle: number,- renderConfig: IDocumentRenderConfig,+ renderConfig: IDocumentLayoutRenderConfig,extensions: ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>[],drawInfo?: IDrawInfo): void {@@ -961,15 +995,54 @@ export class Documents extends DocComponent {renderConfig,};+ this._paintGlyph(ctx, parentScale, glyph, extensionOffset, extensions, drawInfo);+ }+ }++ private _paintGlyph(+ context: UniverRenderingContext,+ parentScale: IScale,+ glyph: IDocumentSkeletonGlyph,+ offset: IExtensionConfig,+ extensions: ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>[],+ drawInfo?: IDrawInfo+ ): void {+ if (!this._glyphPaintSink) {for (const extension of extensions) {- extension.extensionOffset = extensionOffset;+ extension.extensionOffset = offset;if (drawInfo) {- extension.draw(ctx, parentScale, glyph, [], { ...drawInfo });+ extension.draw(context, parentScale, glyph, [], { ...drawInfo });} else {- extension.draw(ctx, parentScale, glyph);+ extension.draw(context, parentScale, glyph);}}+ return;}+ const draw = (target: UniverRenderingContext) => {+ const replayOffset = {+ ...offset,+ originTranslate: offset.originTranslate?.clone(),+ spanStartPoint: offset.spanStartPoint?.clone(),+ spanPointWithFont: offset.spanPointWithFont?.clone(),+ centerPoint: offset.centerPoint?.clone(),+ alignOffset: offset.alignOffset?.clone(),+ };+ for (const extension of extensions) {+ const previous = extension.extensionOffset;+ extension.extensionOffset = replayOffset;+ try {+ extension.draw(target, parentScale, glyph, [], drawInfo ? { ...drawInfo } : undefined);+ } finally {+ extension.extensionOffset = previous;+ }+ }+ };+ const matrix = context.getTransform();+ this._glyphPaints.push({+ group: glyph.ts?.customGlyphGroup,+ transform: [matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f],+ draw,+ });}private _drawTable(@@ -983,7 +1056,7 @@ export class Documents extends DocComponent {alignOffsetNoAngle: Vector2,centerAngle: number,vertexAngle: number,- renderConfig: IDocumentRenderConfig,+ renderConfig: IDocumentLayoutRenderConfig,parentScale: IScale,fieldContext?: IHeaderFooterFieldContext) {@@ -1074,7 +1147,7 @@ export class Documents extends DocComponent {alignOffsetNoAngle: Vector2,centerAngle: number,vertexAngle: number,- renderConfig: IDocumentRenderConfig,+ renderConfig: IDocumentLayoutRenderConfig,parentScale: IScale) {const drawLiquid = this._drawLiquid;@@ -1354,15 +1427,12 @@ export class Documents extends DocComponent {alignOffset);- for (const extension of preTextBackgroundExtensions) {- extension.extensionOffset = {- originTranslate,- spanStartPoint,- centerPoint,- alignOffset,- };- extension.draw(ctx, parentScale, glyph);- }+ this._paintGlyph(ctx, parentScale, glyph, {+ originTranslate,+ spanStartPoint,+ centerPoint,+ alignOffset,+ }, preTextBackgroundExtensions);}if (!backgroundExtension) {@@ -1384,10 +1454,7 @@ export class Documents extends DocComponent {alignOffset);- backgroundExtension.extensionOffset = {- spanStartPoint,- };- backgroundExtension.draw(ctx, parentScale, glyph);+ this._paintGlyph(ctx, parentScale, glyph, { spanStartPoint }, [backgroundExtension]);}}@@ -1403,7 +1470,7 @@ export class Documents extends DocComponent {alignOffsetNoAngle: Vector2,centerAngle: number,vertexAngle: number,- renderConfig: IDocumentRenderConfig,+ renderConfig: IDocumentLayoutRenderConfig,parentScale: IScale,fieldContext?: IHeaderFooterFieldContext) {@@ -1440,7 +1507,7 @@ export class Documents extends DocComponent {alignOffsetNoAngle: Vector2,centerAngle: number,vertexAngle: number,- renderConfig: IDocumentRenderConfig,+ renderConfig: IDocumentLayoutRenderConfig,parentScale: IScale,fieldContext?: IHeaderFooterFieldContext) {@@ -1505,10 +1572,12 @@ export class Documents extends DocComponent {drawNestedTables(floatingTables);}- ctx.beginPath();- ctx.rectByPrecision(clipOrigin.x, clipOrigin.y, pageWidth, pageHeight);- ctx.closePath();- ctx.clip();+ if (shouldClipNestedPageContent(nestedPage)) {+ ctx.beginPath();+ ctx.rectByPrecision(clipOrigin.x, clipOrigin.y, pageWidth, pageHeight);+ ctx.closePath();+ ctx.clip();+ }const clippedTables = floatingTables.size > 0? new Map([...skeTables].filter(([id]) => !floatingTables.has(id)))@@ -1811,7 +1880,7 @@ export class Documents extends DocComponent {alignOffsetNoAngle: Vector2,centerAngle: number,vertexAngle: number,- renderConfig: IDocumentRenderConfig,+ renderConfig: IDocumentLayoutRenderConfig,parentScale: IScale,parentPage: IDocumentSkeletonPage,isHeader = true,@@ -2060,6 +2129,12 @@ function isColumnGroupNestedPage(page: IDocumentSkeletonPage): boolean {return parent?.columnId != null && parent.parent?.columnGroupId != null;}+function shouldClipNestedPageContent(page: IDocumentSkeletonPage): boolean {+ const parent = page.parent as IDocumentSkeletonColumnGroupColumn | undefined;+ return !isColumnGroupNestedPage(page)+ || parent?.parent?.columnGroupSource.clipContent !== BooleanNumber.FALSE;+}+function fillRectByPrecisionBounds(ctx: UniverRenderingContext,x: number,diff --git a/packages/engine-render/src/components/docs/extensions/__tests__/background-runs.spec.ts b/packages/engine-render/src/components/docs/extensions/__tests__/background-runs.spec.tsnew file mode 100644index 0000000000..82dba71cf0--- /dev/null+++ b/packages/engine-render/src/components/docs/extensions/__tests__/background-runs.spec.ts@@ -0,0 +1,33 @@+/**+ * 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 { IDocumentSkeletonGlyph } from '../../../../basics/i-document-skeleton-cached';+import { describe, expect, it } from 'vitest';+import { collectBackgroundGlyphRuns } from '../background-runs';++describe('background glyph runs', () => {+ it.each([false, true])('keeps host paint boundaries without splitting ordinary backgrounds: %s', (routed) => {+ const glyphs = ['A', 'B', 'C'].map((content, index) => ({+ content,+ left: index * 10,+ width: 10,+ ts: { bg: { rgb: '#ff0000' }, customGlyphGroup: routed ? ['first', 'first', 'second'][index] : undefined },+ } as IDocumentSkeletonGlyph));+ const runs = collectBackgroundGlyphRuns(glyphs);+ expect(runs.map(({ left, width }) => [left, width])).toEqual(routed ? [[0, 20], [20, 10]] : [[0, 30]]);+ expect(glyphs.map(({ width }) => width)).toEqual([10, 10, 10]);+ });+});diff --git a/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts b/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.tsindex 137b3f2775..88f9ebdfe5 100644--- a/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts+++ b/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts@@ -16,24 +16,29 @@import type { IScale } from '@univerjs/core';import type { IDocumentSkeletonGlyph } from '../../../../basics/i-document-skeleton-cached';-import type { UniverRenderingContext } from '../../../../context';import type { IExtensionConfig } from '../../../extension';-import { BaselineOffset } from '@univerjs/core';+import { BaselineOffset, BooleanNumber } from '@univerjs/core';import { describe, expect, it, vi } from 'vitest';import { COLOR_BLACK_RGB } from '../../../../basics/const';import { GlyphType } from '../../../../basics/i-document-skeleton-cached';import { getFontStyleString } from '../../../../basics/tools';import { Vector2 } from '../../../../basics/vector2';+import { UniverRenderingContext } from '../../../../context';import { CheckboxShape } from '../../../../shape/checkbox';+import { registerDocCustomGlyphRenderer } from '../../custom-glyph-renderer';import { FontAndBaseLine } from '../font-and-base-line';type MockRenderContext = UniverRenderingContext & {save: ReturnType<typeof vi.fn>;restore: ReturnType<typeof vi.fn>;fillText: ReturnType<typeof vi.fn>;+ strokeText: ReturnType<typeof vi.fn>;translate: ReturnType<typeof vi.fn>;+ transform: ReturnType<typeof vi.fn>;rotate: ReturnType<typeof vi.fn>;scale: ReturnType<typeof vi.fn>;+ measureText: ReturnType<typeof vi.fn>;+ getScale: ReturnType<typeof vi.fn>;createLinearGradient: ReturnType<typeof vi.fn>;createRadialGradient: ReturnType<typeof vi.fn>;createPattern: ReturnType<typeof vi.fn>;@@ -73,12 +78,19 @@ function createContext(): MockRenderContext {shadowBlur: 0,shadowOffsetX: 0,shadowOffsetY: 0,+ strokeStyle: '',+ lineWidth: 1,save: vi.fn(),restore: vi.fn(),fillText: vi.fn(),+ strokeText: vi.fn(),translate: vi.fn(),+ transform: vi.fn(),rotate: vi.fn(),scale: vi.fn(),+ measureText: vi.fn((text: string) => ({ width: text.length * 8 })),+ getScale: vi.fn(() => ({ scaleX: 1, scaleY: 1 })),+ canvas: { clientWidth: 100, width: 100 },createLinearGradient: vi.fn(() => gradient),createRadialGradient: vi.fn(() => gradient),createPattern: vi.fn(() => ({ setTransform: vi.fn() })),@@ -252,6 +264,378 @@ describe('docs font and baseline extension', () => {expect(SeparatorContext.restore).toHaveBeenCalledOnce();});+ it('does not paint positioned tabs when no leader is configured', () => {+ const extension = new FontAndBaseLine();+ const TestContext = createContext();+ extension.extensionOffset = {+ spanPointWithFont: Vector2.create(12, 20),+ spanStartPoint: Vector2.create(10, 10),+ centerPoint: Vector2.create(8, 8),+ renderConfig: {+ vertexAngle: 0,+ centerAngle: 0,+ },+ };++ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('\t', {+ glyphType: GlyphType.TAB,+ ts: { textAdvance: 20 },+ }));++ expect(TestContext.fillText).not.toHaveBeenCalled();+ });++ it('renders a text outline after the glyph fill', () => {+ const extension = new FontAndBaseLine();+ const TestContext = createContext();+ const paintOrder: string[] = [];+ TestContext.strokeText.mockImplementation(() => paintOrder.push('stroke'));+ TestContext.fillText.mockImplementation(() => paintOrder.push('fill'));+ extension.extensionOffset = {+ spanPointWithFont: Vector2.create(12, 20),+ spanStartPoint: Vector2.create(10, 10),+ centerPoint: Vector2.create(8, 8),+ renderConfig: { paintTextOutline: BooleanNumber.TRUE, vertexAngle: 0, centerAngle: 0 },+ };++ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('A', {+ ts: {+ fs: 12,+ cl: { rgb: '#ff0000' },+ textOutline: {+ color: '#ff0000',+ width: 1.25,+ lineCap: 'square',+ lineJoin: 'bevel',+ miterLimit: 2,+ },+ },+ }));++ expect(TestContext.strokeText).toHaveBeenCalledWith('A', 12, 20);+ expect(TestContext.strokeStyle).toBe('#ff0000');+ expect(TestContext.lineWidth).toBe(1.25);+ expect(TestContext.lineCap).toBe('square');+ expect(TestContext.lineJoin).toBe('bevel');+ expect(TestContext.miterLimit).toBe(2);+ expect(paintOrder).toEqual(['fill', 'stroke']);+ });++ it('renders characters at their fixed layout advances', () => {+ const extension = new FontAndBaseLine();+ const TestContext = createContext();+ extension.extensionOffset = {+ spanPointWithFont: Vector2.create(12, 20),+ spanStartPoint: Vector2.create(10, 10),+ centerPoint: Vector2.create(8, 8),+ renderConfig: {+ vertexAngle: 0,+ centerAngle: 0,+ },+ };++ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('AB', {+ ts: { fs: 12, sa: 50, textAdvance: 20 },+ }));++ expect(TestContext.translate).toHaveBeenCalledWith(12, 20);+ expect(TestContext.transform).toHaveBeenCalledWith(0.5, 0, 0, 1, 0, 0);+ expect(TestContext.fillText).toHaveBeenNthCalledWith(1, 'A', 0, 0);+ expect(TestContext.fillText).toHaveBeenNthCalledWith(2, 'B', 40, 0);+ });++ it('paints source glyphs with a horizontal shear without changing their advances', () => {+ const extension = new FontAndBaseLine();+ const TestContext = createContext();+ extension.extensionOffset = {+ spanPointWithFont: Vector2.create(12, 20),+ spanStartPoint: Vector2.create(10, 10),+ centerPoint: Vector2.create(8, 8),+ renderConfig: {+ vertexAngle: 0,+ centerAngle: 0,+ },+ };++ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('AB', {+ ts: { fs: 12, textAdvance: 20, textSkewX: -0.25 },+ }));++ expect(TestContext.translate).toHaveBeenCalledWith(12, 20);+ expect(TestContext.transform).toHaveBeenCalledWith(1, 0, -0.25, 1, 0, 0);+ expect(TestContext.fillText).toHaveBeenNthCalledWith(1, 'A', 0, 0);+ expect(TestContext.fillText).toHaveBeenNthCalledWith(2, 'B', 20, 0);+ });++ it('repeats glyph paint at source-relative offsets', () => {+ const extension = new FontAndBaseLine();+ const TestContext = createContext();+ extension.extensionOffset = {+ spanPointWithFont: Vector2.create(12, 20),+ spanStartPoint: Vector2.create(10, 10),+ centerPoint: Vector2.create(8, 8),+ renderConfig: {+ vertexAngle: 0,+ centerAngle: 0,+ },+ };++ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('A', {+ ts: { fs: 12, textPaintOffsets: [{ x: 0.4, y: 0.1 }] },+ }));++ expect(TestContext.fillText).toHaveBeenNthCalledWith(1, 'A', 12, 20);+ expect(TestContext.fillText).toHaveBeenNthCalledWith(2, 'A', 12.4, 20.1);+ });++ it('reconstructs the source glyph raster scale relative to the current document transform', () => {+ const extension = new FontAndBaseLine();+ const nativeContext = createContext();+ const getTransform = vi.fn(() => ({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }));+ const TestContext = new UniverRenderingContext(Object.assign(nativeContext, { getTransform }));+ let font = nativeContext.font;+ const fontStack: string[] = [];+ const readFont = vi.fn(() => font);+ const writeFont = vi.fn((value: string) => {+ font = value;+ });+ Object.defineProperty(nativeContext, 'font', { get: readFont, set: writeFont });+ nativeContext.save.mockImplementation(() => {+ fontStack.push(font);+ });+ nativeContext.restore.mockImplementation(() => {+ font = fontStack.pop() ?? font;+ });+ const paintedFonts: string[] = [];+ nativeContext.fillText.mockImplementation(() => paintedFonts.push(font));+ extension.extensionOffset = {+ spanPointWithFont: Vector2.create(12, 20),+ spanStartPoint: Vector2.create(10, 10),+ centerPoint: Vector2.create(8, 8),+ renderConfig: {+ vertexAngle: 0,+ centerAngle: 0,+ },+ };++ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('A', {+ ts: { fs: 12, fontRenderScale: 0.5 },+ }));++ expect(nativeContext.translate).toHaveBeenCalledWith(12, 20);+ expect(nativeContext.scale).toHaveBeenCalledWith(0.5, 0.5);+ expect(nativeContext.fillText).toHaveBeenCalledWith('A', 0, 0);+ expect(paintedFonts).toEqual(['24px Arial']);+ expect(TestContext.font).toBe('12px Arial');+ // Native restore already restores the font; assigning it again invalidates the normalized cache.+ expect(writeFont.mock.calls.map(([value]) => value)).toEqual(['12px Arial', '24px Arial']);+ expect(readFont.mock.calls.length).toBe(3);++ getTransform.mockReturnValue({ a: 0.5, b: 0, c: 0, d: 0.5, e: 0, f: 0 });+ nativeContext.translate.mockClear();+ nativeContext.scale.mockClear();+ nativeContext.fillText.mockClear();+ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('A', {+ ts: { fs: 12, fontRenderScale: 0.5 },+ }));++ expect(nativeContext.translate).not.toHaveBeenCalled();+ expect(nativeContext.scale).not.toHaveBeenCalled();+ expect(nativeContext.fillText).toHaveBeenCalledWith('A', 12, 20);+ });++ it.each([1.000296950340271, 1.25, 2])('preserves the source font size at fractional canvas density %s', (pixelRatio) => {+ const extension = new FontAndBaseLine();+ const TestContext = createContext();+ const canvasWidth = 721;+ const logicalWidth = canvasWidth / pixelRatio;+ Object.assign(TestContext.canvas, {+ width: canvasWidth,+ clientWidth: Math.round(logicalWidth),+ style: { width: `${logicalWidth}px` },+ });+ TestContext.getScale.mockReturnValue({ scaleX: pixelRatio, scaleY: pixelRatio });+ const paintedFonts: string[] = [];+ TestContext.fillText.mockImplementation(() => paintedFonts.push(TestContext.font));+ extension.extensionOffset = {+ spanPointWithFont: Vector2.create(12, 20),+ spanStartPoint: Vector2.create(10, 10),+ centerPoint: Vector2.create(8, 8),+ renderConfig: { vertexAngle: 0, centerAngle: 0 },+ };++ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('A', {+ ts: { fs: 12, fontRenderScale: 1 },+ }));++ expect(paintedFonts).toEqual(['12px Arial']);+ expect(TestContext.scale).not.toHaveBeenCalled();+ });++ it.each([undefined, BooleanNumber.TRUE])('isolates registered glyph painters from ordinary text (outline: %s)', (paintTextOutline) => {+ const extension = new FontAndBaseLine();+ const TestContext = createContext();+ const renderer = vi.fn(() => true);+ const strokeRenderer = vi.fn(() => true);+ const registration = registerDocCustomGlyphRenderer({ fontFamily: 'SharedFont', renderer, strokeRenderer });+ const glyph = createGlyph('A', {+ ts: { fs: 12, ff: 'SharedFont', textOutline: { color: '#123456', width: 1 } },+ });+ const offset = {+ spanPointWithFont: Vector2.create(12, 20),+ spanStartPoint: Vector2.create(10, 10),+ centerPoint: Vector2.create(8, 8),+ };+ try {+ extension.extensionOffset = { ...offset, renderConfig: { paintTextOutline } };+ extension.draw(TestContext, DEFAULT_SCALE, glyph);+ expect(renderer).not.toHaveBeenCalled();+ expect(strokeRenderer).not.toHaveBeenCalled();+ expect(TestContext.fillText).toHaveBeenCalledWith('A', 12, 20);++ extension.extensionOffset = {+ ...offset,+ renderConfig: { paintTextOutline, useCustomGlyphRenderer: BooleanNumber.TRUE },+ };+ TestContext.fillText.mockClear();+ extension.draw(TestContext, DEFAULT_SCALE, glyph);+ expect(renderer).toHaveBeenCalledTimes(1);+ expect(TestContext.fillText).not.toHaveBeenCalled();+ expect(strokeRenderer).toHaveBeenCalledTimes(paintTextOutline === BooleanNumber.TRUE ? 1 : 0);++ extension.extensionOffset = { ...offset, renderConfig: { paintTextOutline } };+ extension.draw(TestContext, DEFAULT_SCALE, glyph);+ expect(renderer).toHaveBeenCalledTimes(1);+ expect(strokeRenderer).toHaveBeenCalledTimes(paintTextOutline === BooleanNumber.TRUE ? 1 : 0);+ expect(TestContext.fillText).toHaveBeenCalledWith('A', 12, 20);+ } finally {+ registration.dispose();+ }+ });++ it('uses a registered runtime glyph painter for the primary font family', () => {+ const extension = new FontAndBaseLine();+ const TestContext = createContext();+ const renderer = vi.fn(() => true);+ const registration = registerDocCustomGlyphRenderer({ fontFamily: 'PdfOutline', renderer });+ extension.extensionOffset = {+ spanPointWithFont: Vector2.create(12, 20),+ spanStartPoint: Vector2.create(10, 10),+ centerPoint: Vector2.create(8, 8),+ renderConfig: {+ useCustomGlyphRenderer: BooleanNumber.TRUE,+ vertexAngle: 0,+ centerAngle: 0,+ },+ };++ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('A', {+ ts: { customGlyphKey: 'pdf-glyph-1', fs: 12, ff: '"PdfOutline", serif', bl: 1, it: 1 },+ }));++ expect(renderer).toHaveBeenCalledWith({+ bold: true,+ italic: true,+ content: 'A',+ context: TestContext,+ fontSizePx: 12,+ glyphKey: 'pdf-glyph-1',+ x: 12,+ y: 20,+ });+ expect(TestContext.fillText).not.toHaveBeenCalled();++ registration.dispose();+ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('A', {+ ts: { fs: 12, ff: '"PdfOutline", serif' },+ }));+ expect(TestContext.fillText).toHaveBeenCalledWith('A', 12, 20);+ });++ it('strokes the registered glyph outline and releases both painters on disposal', () => {+ const extension = new FontAndBaseLine();+ const TestContext = createContext();+ const renderer = vi.fn(() => true);+ const strokeRenderer = vi.fn(() => {+ expect(TestContext.strokeStyle).toBe('#123456');+ expect(TestContext.lineWidth).toBe(0.16);+ return true;+ });+ const registration = registerDocCustomGlyphRenderer({ fontFamily: 'PdfOutline', renderer, strokeRenderer });+ extension.extensionOffset = {+ spanPointWithFont: Vector2.create(12, 20),+ spanStartPoint: Vector2.create(10, 10),+ centerPoint: Vector2.create(8, 8),+ renderConfig: {+ useCustomGlyphRenderer: BooleanNumber.TRUE,+ paintTextOutline: BooleanNumber.TRUE,+ vertexAngle: 0,+ centerAngle: 0,+ },+ };+ const glyph = createGlyph('A', {+ ts: { fs: 12, ff: '"PdfOutline", serif', textOutline: { color: '#123456', width: 0.16 } },+ });++ extension.draw(TestContext, DEFAULT_SCALE, glyph);++ expect(strokeRenderer).toHaveBeenCalledWith({+ bold: false,+ italic: false,+ content: 'A',+ context: TestContext,+ fontSizePx: 12,+ x: 12,+ y: 20,+ });+ expect(renderer.mock.invocationCallOrder[0]).toBeLessThan(strokeRenderer.mock.invocationCallOrder[0]);+ expect(TestContext.fillText).not.toHaveBeenCalled();+ expect(TestContext.strokeText).not.toHaveBeenCalled();++ strokeRenderer.mockReturnValue(false);+ extension.draw(TestContext, DEFAULT_SCALE, glyph);+ expect(TestContext.strokeText).toHaveBeenCalledWith('A', 12, 20);++ registration.dispose();+ extension.draw(TestContext, DEFAULT_SCALE, glyph);+ expect(renderer).toHaveBeenCalledTimes(2);+ expect(strokeRenderer).toHaveBeenCalledTimes(2);+ expect(TestContext.fillText).toHaveBeenCalledWith('A', 12, 20);+ expect(TestContext.strokeText).toHaveBeenCalledTimes(2);+ });++ it('uses the resolved glyph font family when the source text style omits it', () => {+ const extension = new FontAndBaseLine();+ const TestContext = createContext();+ const renderer = vi.fn(() => true);+ const registration = registerDocCustomGlyphRenderer({ fontFamily: 'PdfOutline', renderer });+ extension.extensionOffset = {+ spanPointWithFont: Vector2.create(12, 20),+ spanStartPoint: Vector2.create(10, 10),+ centerPoint: Vector2.create(8, 8),+ renderConfig: {+ useCustomGlyphRenderer: BooleanNumber.TRUE,+ vertexAngle: 0,+ centerAngle: 0,+ },+ };++ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('A', {+ ts: { fs: 12 },+ fontStyle: {+ fontFamily: '"PdfOutline", serif',+ fontSize: 12,+ fontString: '12px "PdfOutline", serif',+ fontCache: '12px "PdfOutline", serif',+ originFontSize: 12,+ },+ }));++ expect(renderer).toHaveBeenCalled();+ expect(TestContext.fillText).not.toHaveBeenCalled();+ registration.dispose();+ });+it('renders public glow and outer shadow behind the source text without canvas filters', () => {const extension = new FontAndBaseLine();const TestContext = createContext();@@ -339,6 +723,28 @@ describe('docs font and baseline extension', () => {extension.draw(TestContext, DEFAULT_SCALE, superscript);expect(TestContext.fillText).toHaveBeenCalledWith('S', 12, 17);+ extension.extensionOffset = {+ spanPointWithFont: Vector2.create(12, 20),+ spanStartPoint: Vector2.create(10, 10),+ centerPoint: Vector2.create(8, 8),+ renderConfig: {+ vertexAngle: 0,+ centerAngle: 0,+ },+ } as IExtensionConfig;+ const positioned = createGlyph('P', {+ ts: {+ fs: 12,+ cl: { rgb: '#111111' },+ pos: 3,+ },+ });+ extension.draw(TestContext, DEFAULT_SCALE, positioned);+ expect(TestContext.fillText).toHaveBeenCalledWith('P', 12, 20);+ extension.extensionOffset.renderConfig!.applyTextPosition = BooleanNumber.TRUE;+ extension.draw(TestContext, DEFAULT_SCALE, positioned);+ expect(TestContext.fillText).toHaveBeenCalledWith('P', 12, 16);+extension.extensionOffset = {spanPointWithFont: Vector2.create(12, 20),spanStartPoint: Vector2.create(10, 10),diff --git a/packages/engine-render/src/components/docs/extensions/__tests__/line.spec.ts b/packages/engine-render/src/components/docs/extensions/__tests__/line.spec.tsindex 5af0c6f749..b8716504cc 100644--- a/packages/engine-render/src/components/docs/extensions/__tests__/line.spec.ts+++ b/packages/engine-render/src/components/docs/extensions/__tests__/line.spec.ts@@ -94,6 +94,46 @@ describe('docs line extension', () => {expect(ctx.lineTo).toHaveBeenCalled();});+ it('applies a custom underline offset without moving other decorations', () => {+ const line = new Line();+ (line as any).extensionOffset = {};+ const ctx = createCtx();+ const glyph = createGlyph();+ glyph.ts.ul.offset = 2.5;+ glyph.ts.st = undefined;+ glyph.ts.ol = undefined;+ glyph.ts.bbl = undefined;++ line.draw(ctx, { scaleX: 1, scaleY: 1 } as any, glyph);++ expect(ctx.moveTo.mock.calls[0][0]).toBeCloseTo(10);+ expect(ctx.moveTo.mock.calls[0][1]).toBeCloseTo(10.5);+ expect(ctx.lineTo.mock.calls[0][0]).toBeCloseTo(22);+ expect(ctx.lineTo.mock.calls[0][1]).toBeCloseTo(10.5);+ });++ it('keeps a baseline-relative underline in place when the line descent changes', () => {+ const line = new Line();+ line.extensionOffset = {};+ const ctx = createCtx();+ const glyph = createGlyph();+ glyph.ts.ul = { s: BooleanNumber.TRUE, offset: 2.5, offsetReference: 'baseline' };+ glyph.ts.st = undefined;+ glyph.ts.ol = undefined;+ glyph.ts.bbl = undefined;++ for (const descent of [0, 2, 5]) {+ glyph.parent.parent.dsc = descent;+ line.draw(ctx, { scaleX: 1, scaleY: 1 }, glyph);+ }++ expect(ctx.moveTo).toHaveBeenCalledTimes(3);+ expect(ctx.lineTo).toHaveBeenCalledTimes(3);+ for (const call of [...ctx.moveTo.mock.calls, ...ctx.lineTo.mock.calls]) {+ expect(call[1]).toBeCloseTo(8.5);+ }+ });+it('handles early return and baseline offset variants', () => {const line = new Line();(line as any).extensionOffset = {};diff --git a/packages/engine-render/src/components/docs/extensions/background-runs.ts b/packages/engine-render/src/components/docs/extensions/background-runs.tsindex b6338e5ccb..bb4ce4eae6 100644--- a/packages/engine-render/src/components/docs/extensions/background-runs.ts+++ b/packages/engine-render/src/components/docs/extensions/background-runs.ts@@ -66,7 +66,8 @@ export function collectBackgroundGlyphRuns(glyphGroup: IDocumentSkeletonGlyph[])const glyphLeft = glyph.left;const glyphRight = glyph.left + glyph.width;- if (activeGlyph && activeColor === backgroundColor) {+ if (activeGlyph && activeColor === backgroundColor+ && activeGlyph.ts?.customGlyphGroup === glyph.ts?.customGlyphGroup) {activeRight = Math.max(activeRight, glyphRight);continue;}diff --git a/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts b/packages/engine-render/src/components/docs/extensions/font-and-base-line.tsindex c0a17fc822..eeaeb85a81 100644--- a/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts+++ b/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts@@ -19,7 +19,7 @@ import type { IDocumentSkeletonGlyph } from '../../../basics/i-document-skeletonimport type { IBoundRectNoAngle } from '../../../basics/vector2';import type { UniverRenderingContext } from '../../../context';import type { IDrawInfo } from '../../extension';-import { BaselineOffset } from '@univerjs/core';+import { BaselineOffset, BooleanNumber } from '@univerjs/core';import { cjk } from '../../../basics/cjk-regexp';import { COLOR_BLACK_RGB } from '../../../basics/const';import { resolveGlowEffect, resolveOuterShadowEffect } from '../../../basics/drawing-effect';@@ -28,6 +28,7 @@ import { getFontStyleString } from '../../../basics/tools';import { Vector2 } from '../../../basics/vector2';import { CheckboxShape, isCheckboxGlyph } from '../../../shape/checkbox';import { DocumentsSpanAndLineExtensionRegistry } from '../../extension';+import { getDocCustomGlyphRenderer, getDocCustomGlyphStrokeRenderer } from '../custom-glyph-renderer';import { docExtension } from '../doc-extension';import { getTextHorizontalScale } from '../layout/model/glyph';import { getColorStyleForCanvas } from '../layout/style/color';@@ -105,9 +106,13 @@ export class FontAndBaseLine extends docExtension {}}- const { cl: colorStyle, va: baselineOffset, textFill, glow, outerShadow } = textStyle;+ const { cl: colorStyle, pos: position, va: baselineOffset, textFill, glow, outerShadow } = textStyle;const fontColor = getColorStyleForCanvas(colorStyle) || COLOR_BLACK_RGB;+ if (this.extensionOffset.renderConfig?.applyTextPosition === BooleanNumber.TRUE+ && typeof position === 'number' && Number.isFinite(position)) {+ spanPointWithFont.y -= position * 4 / 3;+ }if (baselineOffset === BaselineOffset.SUPERSCRIPT) {spanPointWithFont.y += -bBox.spo;} else if (baselineOffset === BaselineOffset.SUBSCRIPT) {@@ -421,13 +426,15 @@ export class FontAndBaseLine extends docExtension {return;}- if (glyph.glyphType === GlyphType.TAB && glyph.tabLeader != null) {- const leader = this._getTabLeaderCharacter(glyph.tabLeader);- if (leader) {- const leaderWidth = ctx.measureText(leader).width;- const count = leaderWidth > 0 ? Math.floor(width / leaderWidth) : 0;- if (count > 0) {- ctx.fillText(leader.repeat(count), spanPointWithFont.x, spanPointWithFont.y);+ if (glyph.glyphType === GlyphType.TAB && (glyph.tabLeader != null || glyph.ts?.textAdvance !== undefined)) {+ if (glyph.tabLeader != null) {+ const leader = this._getTabLeaderCharacter(glyph.tabLeader);+ if (leader) {+ const leaderWidth = ctx.measureText(leader).width;+ const count = leaderWidth > 0 ? Math.floor(width / leaderWidth) : 0;+ if (count > 0) {+ this._paintText(ctx, glyph, leader.repeat(count), spanPointWithFont.x, spanPointWithFont.y);+ }}}return;@@ -473,10 +480,36 @@ export class FontAndBaseLine extends docExtension {x_offset = (glyph.width - glyph.bBox.width) / 2;y_offset = -(glyph.width - fontHeight) / 2;}- if (horizontalScale !== 1) {+ const requestedTextSkewX = glyph.ts?.textSkewX;+ const textSkewX = typeof requestedTextSkewX === 'number' && Number.isFinite(requestedTextSkewX)+ ? requestedTextSkewX+ : 0;+ const requestedTextAdvance = glyph.ts?.textAdvance;+ const textAdvance = typeof requestedTextAdvance === 'number'+ && Number.isFinite(requestedTextAdvance)+ && requestedTextAdvance >= 0+ ? requestedTextAdvance+ : undefined;+ if (!isVertical && textAdvance !== undefined) {+ const characters = Array.from(content);+ const localTextAdvance = textAdvance / horizontalScale;+ let cursor = 0;+ ctx.save();+ ctx.translate(spanPointWithFont.x + x_offset, spanPointWithFont.y + y_offset);+ ctx.transform(horizontalScale, 0, textSkewX, 1, 0, 0);+ characters.forEach((character) => {+ this._paintText(ctx, glyph, character, cursor, 0);+ cursor += localTextAdvance;+ });+ ctx.restore();+ } else if (horizontalScale !== 1 || (!isVertical && textSkewX !== 0)) {ctx.save();ctx.translate(spanPointWithFont.x + x_offset, spanPointWithFont.y + y_offset);- ctx.scale(horizontalScale, 1);+ if (!isVertical && textSkewX !== 0) {+ ctx.transform(horizontalScale, 0, textSkewX, 1, 0, 0);+ } else {+ ctx.scale(horizontalScale, 1);+ }this._paintGlyphText(ctx, glyph, 0, 0);ctx.restore();} else {@@ -486,15 +519,125 @@ export class FontAndBaseLine extends docExtension {}}+ private _paintText(+ ctx: UniverRenderingContext,+ glyph: IDocumentSkeletonGlyph,+ content: string,+ x: number,+ y: number+ ) {+ const requestedRenderScale = glyph.ts?.fontRenderScale;+ const renderConfig = this.extensionOffset.renderConfig;+ if (requestedRenderScale === undefined && !glyph.ts?.textPaintOffsets?.length+ && renderConfig?.useCustomGlyphRenderer !== BooleanNumber.TRUE+ && renderConfig?.paintTextOutline !== BooleanNumber.TRUE) {+ ctx.fillText(content, x, y);+ return;+ }+ if (requestedRenderScale === undefined) {+ this._paintTextAtPoint(ctx, glyph, content, x, y);+ return;+ }+ const contextScaleY = ctx.getScale().scaleY;+ // Canvas.setSize retains its fractional logical width here. clientWidth rounds it,+ // which would turn backing-store density into an unintended font-size adjustment.+ const inlineWidth = ctx.canvas.style?.width;+ const logicalWidth = inlineWidth?.endsWith('px') ? Number.parseFloat(inlineWidth) : ctx.canvas.clientWidth;+ const pixelRatio = Number.isFinite(logicalWidth) && logicalWidth > 0+ ? ctx.canvas.width / logicalWidth+ : 1;+ const logicalScaleY = contextScaleY / (Number.isFinite(pixelRatio) && pixelRatio > 0 ? pixelRatio : 1);+ const renderScale = typeof requestedRenderScale === 'number'+ && Number.isFinite(requestedRenderScale)+ && requestedRenderScale > 0+ && Number.isFinite(logicalScaleY)+ && logicalScaleY > 0+ ? requestedRenderScale / logicalScaleY+ : 1;+ if (Math.abs(renderScale - 1) > 1e-6) {+ const originalFont = ctx.font;+ const sourceFont = scaleCanvasFontPixelSize(originalFont, 1 / renderScale);+ ctx.save();+ ctx.translate(x, y);+ ctx.scale(renderScale, renderScale);+ ctx.font = sourceFont;+ this._paintTextAtPoint(ctx, glyph, content, 0, 0);+ ctx.restore();+ return;+ }+ this._paintTextAtPoint(ctx, glyph, content, x, y);+ }++ private _paintTextAtPoint(+ ctx: UniverRenderingContext,+ glyph: IDocumentSkeletonGlyph,+ content: string,+ x: number,+ y: number+ ) {+ this._paintTextAtSinglePoint(ctx, glyph, content, x, y);+ glyph.ts?.textPaintOffsets?.forEach((offset) => {+ if (!Number.isFinite(offset.x) || !Number.isFinite(offset.y) || (offset.x === 0 && offset.y === 0)) {+ return;+ }+ this._paintTextAtSinglePoint(ctx, glyph, content, x + offset.x, y + offset.y);+ });+ }++ private _paintTextAtSinglePoint(+ ctx: UniverRenderingContext,+ glyph: IDocumentSkeletonGlyph,+ content: string,+ x: number,+ y: number+ ) {+ const fontFamily = glyph.ts?.ff ?? glyph.fontStyle?.fontFamily ?? undefined;+ const useCustomGlyphRenderer = this.extensionOffset.renderConfig?.useCustomGlyphRenderer === BooleanNumber.TRUE;+ const customRenderer = useCustomGlyphRenderer ? getDocCustomGlyphRenderer(fontFamily) : undefined;+ const fontSizePx = customRenderer ? canvasFontPixelSize(ctx.font) : undefined;+ const bold = glyph.ts?.bl === BooleanNumber.TRUE;+ const italic = glyph.ts?.it === BooleanNumber.TRUE;+ const customRendered = customRenderer && fontSizePx !== undefined+ ? customRenderer({ bold, italic, content, context: ctx, fontSizePx, glyphKey: glyph.ts?.customGlyphKey, x, y })+ : false;+ if (!customRendered) {+ ctx.fillText(content, x, y);+ }+ const outline = glyph.ts?.textOutline;+ if (this.extensionOffset.renderConfig?.paintTextOutline === BooleanNumber.TRUE+ && outline?.color && outline.width && outline.width > 0) {+ ctx.save();+ ctx.strokeStyle = outline.color;+ ctx.lineWidth = outline.width;+ if (outline.lineCap) {+ ctx.lineCap = outline.lineCap;+ }+ if (outline.lineJoin) {+ ctx.lineJoin = outline.lineJoin;+ }+ if (outline.miterLimit !== undefined) {+ ctx.miterLimit = outline.miterLimit;+ }+ const strokeRenderer = useCustomGlyphRenderer ? getDocCustomGlyphStrokeRenderer(fontFamily) : undefined;+ const customStroked = strokeRenderer && fontSizePx !== undefined+ ? strokeRenderer({ bold, italic, content, context: ctx, fontSizePx, glyphKey: glyph.ts?.customGlyphKey, x, y })+ : false;+ if (!customStroked) {+ ctx.strokeText(content, x, y);+ }+ ctx.restore();+ }+ }+private _paintGlyphText(ctx: UniverRenderingContext, glyph: IDocumentSkeletonGlyph, x: number, y: number): void {const { content, textSpacing } = glyph;// Field resolution can replace content after shaping; never paint offsets belonging to the old text.if (textSpacing?.content === content) {for (const segment of textSpacing.segments) {- ctx.fillText(segment.content, x + segment.left / getTextHorizontalScale(glyph.ts?.sa), y);+ this._paintText(ctx, glyph, segment.content, x + segment.left / getTextHorizontalScale(glyph.ts?.sa), y);}} else {- ctx.fillText(content, x, y);+ this._paintText(ctx, glyph, content, x, y);}}@@ -520,4 +663,16 @@ export class FontAndBaseLine extends docExtension {}}+function scaleCanvasFontPixelSize(font: string, scale: number): string {+ return font.replace(/(^|\s)(\d+(?:\.\d+)?)px(?=\s)/, (_match, prefix: string, size: string) => (+ `${prefix}${Number(size) * scale}px`+ ));+}++function canvasFontPixelSize(font: string): number | undefined {+ const match = /(^|\s)(\d+(?:\.\d+)?)px(?=\s)/.exec(font);+ const size = match ? Number(match[2]) : Number.NaN;+ return Number.isFinite(size) && size > 0 ? size : undefined;+}+DocumentsSpanAndLineExtensionRegistry.add(new FontAndBaseLine());diff --git a/packages/engine-render/src/components/docs/extensions/line.ts b/packages/engine-render/src/components/docs/extensions/line.tsindex ab7b73be3a..dc590c6a5d 100644--- a/packages/engine-render/src/components/docs/extensions/line.ts+++ b/packages/engine-render/src/components/docs/extensions/line.ts@@ -14,11 +14,12 @@* limitations under the License.*/-import type { IScale, ITextDecoration } from '@univerjs/core';+import type { IScale } from '@univerjs/core';import type { IDocumentSkeletonGlyph } from '../../../basics/i-document-skeleton-cached';import type { IBoundRectNoAngle } from '../../../basics/vector2';import type { UniverRenderingContext } from '../../../context';import type { IDrawInfo } from '../../extension';+import type { IDocumentLayoutTextDecoration } from '../document-layout-presentation';import { BaselineOffset, BooleanNumber, TextDecoration } from '@univerjs/core';import { COLOR_BLACK_RGB, DEFAULT_OFFSET_SPACING } from '../../../basics/const';import { calculateRectRotate } from '../../../basics/draw';@@ -60,7 +61,8 @@ export class Line extends docExtension {const { ul: underline, st: strikethrough, ol: overline, va: baselineOffset, bbl: bottomBorderLine } = textStyle;if (underline) {- const startY = asc + dsc;+ const originY = underline.offsetReference === 'baseline' ? asc : asc + dsc;+ const startY = originY + (underline.offset ?? 0);this._drawLine(ctx, glyph, underline, startY, scale, 1, more?.viewBound);}@@ -103,7 +105,7 @@ export class Line extends docExtension {private _drawLine(ctx: UniverRenderingContext,glyph: IDocumentSkeletonGlyph,- line: ITextDecoration,+ line: IDocumentLayoutTextDecoration,startY: number,_scale: number,lineWidth = 1,diff --git a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.tsindex b234838d2a..bc0a7da324 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@@ -15,9 +15,12 @@*/import type { IDocumentData, IParagraph } from '@univerjs/core';+import type { IDocumentLayoutSnapshot } from '../../document-layout-presentation';import type { IDocumentLayoutPageGeometryPublication } from '../document-layout-publication';import {BooleanNumber,+ ColumnLayoutType,+ ColumnResponsiveType,ColumnSeparatorType,createDocumentModelWithStyle,CustomRangeType,@@ -29,6 +32,7 @@ import {GridType,HorizontalAlign,LocaleService,+ LocaleType,ObjectRelativeFromH,ObjectRelativeFromV,PageOrientType,@@ -44,16 +48,14 @@ import {TabStopLeader,Univer,VerticalAlignmentType,+ WrapStrategy,WrapTextType,} from '@univerjs/core';import { afterEach, describe, expect, it, vi } from 'vitest';-import {- DocumentSkeletonPageType,- GlyphType,- PageLayoutType,-} from '../../../../basics/i-document-skeleton-cached';+import { DocumentSkeletonPageType, GlyphType, PageLayoutType } from '../../../../basics/i-document-skeleton-cached';import { Vector2 } from '../../../../basics/vector2';import { setDocsCustomBlockRenderViewportProvider } from '../../custom-block-render-viewport';+import { registerDocumentLayoutPresentation } from '../../document-layout-presentation';import { setDocsTableRenderViewportProvider } from '../../table-render-viewport';import { DocumentViewModel } from '../../view-model/document-view-model';import { DocumentSkeleton } from '../doc-skeleton';@@ -241,7 +243,838 @@ function createPage(type: DocumentSkeletonPageType, st: number, tableId = '') {};}+function createPresentationModel(layout: IDocumentLayoutSnapshot): DocumentDataModel {+ const privateKeys = new Set([+ 'fontRenderScale',+ 'textSkewX',+ 'textAdvance',+ 'customGlyphKey',+ 'customGlyphGroup',+ 'lineAscent',+ 'lineDescent',+ 'textPaintOffsets',+ 'fontMetricScaleEnabled',+ 'topAlignExactLineSpacing',+ 'useTextInkForHitTesting',+ 'preservePunctuationSpacing',+ 'applyTextPosition',+ 'paintTextOutline',+ 'fixedTabStops',+ 'horizontalPadding',+ 'minHeight',+ 'clipContent',+ 'topOffset',+ ]);+ const model = new DocumentDataModel(JSON.parse(JSON.stringify(layout, (key, value) => (+ privateKeys.has(key) ? undefined : value+ ))));+ registerDocumentLayoutPresentation(model, {+ getSnapshot: () => layout,+ captureState: () => undefined,+ applyActions: () => {},+ restoreState: () => {},+ });+ return model;+}+describe('doc skeleton', () => {+ it('invalidates only requested font measurements before laying out loaded fonts again', () => {+ const univer = new Univer();+ const model = createPresentationModel({+ id: 'font-loading-layout',+ body: {+ dataStream: 'A\r\n',+ paragraphs: [{ startIndex: 1, paragraphId: 'font-loading-paragraph' }],+ sectionBreaks: [{ startIndex: 2, sectionId: 'font-loading-section' }],+ },+ documentStyle: { pageSize: { width: 200, height: 200 }, textStyle: { ff: 'FontLoadingRegression', fs: 12 } },+ });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));+ const getGlyph = () => skeleton.getSkeletonData()!.pages[0].sections[0].columns[0].lines[0].divides[0].glyphGroup[0];+ try {+ skeleton.calculate();+ const glyph = getGlyph();+ const fontStyle = glyph.fontStyle!.fontString;+ const originalWidth = glyph.width;+ const fresh = FontCache.getMeasureText('A', fontStyle);+ const stale = { ...fresh, width: 99, fontBoundingBoxAscent: 77, fontBoundingBoxDescent: 33 };+ FontCache.setFontMeasureCache(fontStyle, 'A', stale);+ FontCache.setFontMeasureCache('unrelated-font', 'A', stale);+ skeleton.makeDirty(false);++ skeleton.invalidateFontMetrics([fontStyle]);++ expect(skeleton.dirty).toBe(true);+ expect(FontCache.getFontMeasureCache(fontStyle, 'A')).toBeUndefined();+ expect(FontCache.getFontMeasureCache('unrelated-font', 'A')).toEqual(stale);+ skeleton.calculate();+ expect(getGlyph().width).toBe(originalWidth);+ expect(model.getBody()?.dataStream).toBe('A\r\n');+ } finally {+ FontCache.clearFontMeasureCache('unrelated-font');+ skeleton.dispose();+ univer.dispose();+ }+ });+ it('keeps the surviving line baseline when a deleted paragraph contributes its final mark', () => {+ const univer = new Univer();+ const localeService = univer.__getInjector().get(LocaleService);+ const content = 'that require complex patterns of tool us';+ const baselines: number[] = [];++ try {+ for (const markAscent of [12, 17]) {+ const model = createPresentationModel({+ id: `merged-positioned-paragraph-${markAscent}`,+ body: {+ dataStream: `${content}\r\n`,+ paragraphs: [{ startIndex: content.length, paragraphId: 'surviving-paragraph' }],+ textRuns: [+ { st: 0, ed: content.length, ts: { lineAscent: 12, lineDescent: 4 } },+ { st: content.length, ed: content.length + 1, ts: { lineAscent: markAscent, lineDescent: 0 } },+ ],+ sectionBreaks: [{ startIndex: content.length + 1, sectionId: 'positioned-section' }],+ },+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ fontMetricScaleEnabled: BooleanNumber.FALSE,+ pageSize: { width: 500, height: 200 },+ marginTop: 0,+ marginBottom: 0,+ marginLeft: 0,+ marginRight: 0,+ textStyle: { fs: 9, textAdvance: 10 },+ defaultParagraphStyle: {+ spacingRule: SpacingRule.EXACT,+ lineSpacing: markAscent,+ snapToGrid: BooleanNumber.FALSE,+ spaceAbove: { v: 0 },+ spaceBelow: { v: 0 },+ },+ renderConfig: {+ topAlignExactLineSpacing: BooleanNumber.TRUE,+ useTextInkForHitTesting: BooleanNumber.TRUE,+ applyTextPosition: BooleanNumber.TRUE,+ zeroWidthParagraphBreak: BooleanNumber.TRUE,+ },+ },+ });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), localeService);+ try {+ skeleton.calculate();+ const lines = skeleton.getSkeletonData()!.pages[0].sections[0].columns[0].lines;+ expect(lines).toHaveLength(1);+ baselines.push(lines[0].top + lines[0].asc);+ expect(new DocumentViewModel(model).getBody()?.textRuns?.slice(-1)[0].ts?.lineAscent).toBe(markAscent);+ } finally {+ skeleton.dispose();+ }+ }+ expect(baselines).toEqual([12, 12]);+ } finally {+ univer.dispose();+ }+ });++ it.each([BooleanNumber.TRUE, BooleanNumber.FALSE])('hit-tests positioned glyphs with top-aligned exact spacing %s', (topAlignExactLineSpacing) => {+ const topAligned = topAlignExactLineSpacing === BooleanNumber.TRUE;+ const univer = new Univer();+ const injector = univer.__getInjector();+ const documentModel = createPresentationModel({+ id: 'positioned-exact-line-hit-test',+ body: {+ dataStream: '公司航路\r公司航路名称。(可选择性输入)\r航班号\r\n',+ paragraphs: [+ { startIndex: 4, paragraphId: 'positioned-label', paragraphStyle: { lineSpacing: 15 } },+ {+ startIndex: 20,+ paragraphId: 'positioned-description',+ paragraphStyle: { lineSpacing: topAligned ? 5 : 15, spaceAbove: { v: 5 } },+ },+ { startIndex: 24, paragraphId: 'positioned-field', paragraphStyle: { indentStart: { v: 468 } } },+ ],+ textRuns: [+ { st: 0, ed: 5, ts: { lineAscent: 15, lineDescent: 0 } },+ { st: 5, ed: 25, ts: { lineAscent: 10.8, lineDescent: 3.6 } },+ ],+ sectionBreaks: [{ startIndex: 25, sectionId: 'positioned-section' }],+ },+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ fontMetricScaleEnabled: BooleanNumber.FALSE,+ pageSize: { width: 600, height: 200 },+ marginTop: 7,+ marginBottom: 0,+ marginLeft: 0,+ marginRight: 0,+ textStyle: { fs: 9, textAdvance: 12 },+ defaultParagraphStyle: {+ spacingRule: SpacingRule.EXACT,+ lineSpacing: 14.4,+ snapToGrid: BooleanNumber.FALSE,+ spaceAbove: { v: 0 },+ spaceBelow: { v: 0 },+ },+ renderConfig: {+ topAlignExactLineSpacing,+ useTextInkForHitTesting: topAlignExactLineSpacing,+ zeroWidthParagraphBreak: BooleanNumber.TRUE,+ wrapStrategy: WrapStrategy.OVERFLOW,+ },+ },+ });+ const skeleton = DocumentSkeleton.create(+ new DocumentViewModel(documentModel),+ injector.get(LocaleService)+ );++ try {+ skeleton.calculate();+ // Short advances can overlap the labels vertically without overlapping their painted horizontal bounds.+ expect(skeleton.findNodeByCoord(Vector2.FromArray([37, 33]), PageLayoutType.VERTICAL, 0, 0)?.node.content)+ .toBe('路');+ expect(skeleton.findNodeByCoord(Vector2.FromArray([133, 38]), PageLayoutType.VERTICAL, 0, 0)?.node.content)+ .toBe('性');+ expect(skeleton.findNodeByCoord(Vector2.FromArray([481, topAligned ? 38 : 48]), PageLayoutType.VERTICAL, 0, 0)?.node.content)+ .toBe('班');+ } finally {+ skeleton.dispose();+ univer.dispose();+ }+ });++ it.each([[1, 0.75], [1.5, 0.75], [1, 0.95]])('hits overlapping text at scale %s and advance ratio %s', (scale, ratio) => {+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text, font) => {+ const small = text === '1';+ const metricScale = font.includes('1024px') ? 1024 / ((small ? 7 : 10) * 4 / 3) : 1;+ return {+ width: text.length * (small ? 4.645 : 6.64) * metricScale,+ actualBoundingBoxAscent: small ? 6.278 : 9.221,+ actualBoundingBoxDescent: small ? 0 : 0.182,+ fontBoundingBoxAscent: (small ? 8 : 12) * metricScale,+ fontBoundingBoxDescent: (small ? 2 : 3) * metricScale,+ };+ });+ const univer = new Univer({ locale: LocaleType.EN_US });+ const model = createPresentationModel({+ id: 'overlapping-advance-gap-hit-test',+ body: {+ dataStream: 'd\r1\r\n',+ paragraphs: [+ { startIndex: 1, paragraphId: 'upper' },+ { startIndex: 3, paragraphId: 'lower', paragraphStyle: { indentStart: { v: 50 } } },+ ],+ textRuns: [+ { st: 0, ed: 2, ts: { fs: 10, sa: scale * 100, textAdvance: 100, lineAscent: 14, lineDescent: 4 } },+ { st: 2, ed: 4, ts: { fs: 7, textAdvance: 5, lineAscent: 8.4, lineDescent: 2.8 } },+ ],+ sectionBreaks: [{ startIndex: 4, sectionId: 'scripts' }],+ },+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ fontMetricScaleEnabled: BooleanNumber.FALSE,+ pageSize: { width: 200, height: 100 },+ marginTop: 7,+ marginBottom: 0,+ marginLeft: 3,+ marginRight: 0,+ defaultParagraphStyle: {+ spacingRule: SpacingRule.EXACT,+ lineSpacing: 5.6,+ snapToGrid: BooleanNumber.FALSE,+ },+ renderConfig: {+ topAlignExactLineSpacing: BooleanNumber.TRUE,+ useTextInkForHitTesting: BooleanNumber.TRUE,+ applyTextPosition: BooleanNumber.TRUE,+ zeroWidthParagraphBreak: BooleanNumber.TRUE,+ wrapStrategy: WrapStrategy.OVERFLOW,+ },+ },+ });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));+ try {+ skeleton.calculate();+ const page = skeleton.getSkeletonData()!.pages[0];+ const column = page.sections[0].columns[0];+ const [upper, lower] = column.lines;+ const glyph = lower.divides[0].glyphGroup[0];+ const x = page.marginLeft + lower.divides[0].left + lower.divides[0].paddingLeft + glyph.left + glyph.width * ratio;+ const y = page.marginTop + lower.top + lower.marginTop + lower.paddingTop + lower.asc+ - (glyph.bBox.aba - glyph.bBox.abd) / 2;+ expect(lower.top).toBeLessThan(upper.top + upper.contentHeight);+ expect(x - page.marginLeft).toBeLessThan(upper.divides[0].glyphGroup[0].width);+ expect(skeleton.findNodeByCoord(Vector2.FromArray([x, y]), PageLayoutType.VERTICAL, 0, 0)?.node)+ .toBe(glyph);+ const upperGlyph = upper.divides[0].glyphGroup[0];+ const upperY = page.marginTop + upper.top + upper.marginTop + upper.paddingTop + upper.asc+ - (upperGlyph.bBox.aba - upperGlyph.bBox.abd) / 2;+ expect(skeleton.findNodeByCoord(+ Vector2.FromArray([page.marginLeft + upperGlyph.bBox.width * scale / 2, upperY]),+ PageLayoutType.VERTICAL,+ 0,+ 0+ )?.node).toBe(upperGlyph);+ // The same advance remains selectable when no other line paints under the pointer.+ expect(skeleton.findNodeByCoord(Vector2.FromArray([page.marginLeft + 90, upperY]), PageLayoutType.VERTICAL, 0, 0)?.node)+ .toBe(upperGlyph);+ } finally {+ skeleton.dispose();+ model.dispose();+ univer.dispose();+ measureSpy.mockRestore();+ }+ });++ it('hits visible text through a positioned tab while keeping blank space selectable', () => {+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text, font) => {+ const metricScale = font.includes('1024px') ? 1024 / (8 * 4 / 3) : 1;+ return {+ width: 6.5 * metricScale,+ actualBoundingBoxAscent: text.trim() ? 7 : 0,+ actualBoundingBoxDescent: 0,+ fontBoundingBoxAscent: 10 * metricScale,+ fontBoundingBoxDescent: 2 * metricScale,+ };+ });+ const univer = new Univer({ locale: LocaleType.EN_US });+ const model = createPresentationModel({+ id: 'overlapping-tab-hit-test',+ body: {+ dataStream: '\t\rT\r\n',+ paragraphs: [+ { startIndex: 1, paragraphId: 'tab', paragraphStyle: {+ tabStops: [{ offset: 521, alignment: TabStopAlignment.START }],+ fixedTabStops: BooleanNumber.TRUE,+ } },+ { startIndex: 3, paragraphId: 'text', paragraphStyle: { indentStart: { v: 350 } } },+ ],+ textRuns: [+ { st: 0, ed: 2, ts: { fs: 8, textAdvance: 521, lineAscent: 13.283, lineDescent: 4, pos: -2.649 } },+ { st: 2, ed: 4, ts: { fs: 8, textAdvance: 8, lineAscent: 13.283, lineDescent: 0 } },+ ],+ sectionBreaks: [{ startIndex: 4, sectionId: 'positioned' }],+ },+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ fontMetricScaleEnabled: BooleanNumber.FALSE,+ pageSize: { width: 600, height: 100 },+ marginTop: 0,+ marginBottom: 0,+ marginLeft: 0,+ marginRight: 0,+ defaultParagraphStyle: {+ spacingRule: SpacingRule.EXACT,+ lineSpacing: 6.8,+ snapToGrid: BooleanNumber.FALSE,+ },+ renderConfig: {+ topAlignExactLineSpacing: BooleanNumber.TRUE,+ useTextInkForHitTesting: BooleanNumber.TRUE,+ applyTextPosition: BooleanNumber.TRUE,+ zeroWidthParagraphBreak: BooleanNumber.TRUE,+ wrapStrategy: WrapStrategy.OVERFLOW,+ },+ },+ });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));+ try {+ skeleton.calculate();+ const [upper, lower] = skeleton.getSkeletonData()!.pages[0].sections[0].columns[0].lines;+ const tab = upper.divides[0].glyphGroup[0];+ const glyph = lower.divides[0].glyphGroup[0];+ const y = lower.top + lower.marginTop + lower.paddingTop + lower.asc - glyph.bBox.aba / 2;+ const x = lower.divides[0].left + glyph.left + glyph.width - 0.25;+ expect(x).toBeLessThan(tab.width);+ expect(x).toBeGreaterThan(lower.divides[0].left + glyph.left + glyph.bBox.width);+ expect(skeleton.findNodeByCoord(Vector2.FromArray([x, y]), PageLayoutType.VERTICAL, 0, 0)?.node)+ .toBe(glyph);+ expect(skeleton.findNodeByCoord(Vector2.FromArray([100, y]), PageLayoutType.VERTICAL, 0, 0)?.node)+ .toBe(tab);+ } finally {+ skeleton.dispose();+ model.dispose();+ univer.dispose();+ measureSpy.mockRestore();+ }+ });++ it('keeps a leader-gap hit beside the nearer same-line dot instead of a lower positioned line', () => {+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text, font) => {+ const metricScale = font.includes('1024px') ? 1024 / (8.9664 * 4 / 3) : 1;+ return {+ width: (text.length * (text === '.' ? 3.308 : 11.95)) * metricScale,+ actualBoundingBoxAscent: text === '.' ? 1.64 : 10.089,+ actualBoundingBoxDescent: text === '.' ? 0.193 : 0.321,+ fontBoundingBoxAscent: (12) * metricScale,+ fontBoundingBoxDescent: (3) * metricScale,+ };+ });+ const univer = new Univer({ locale: LocaleType.EN_US });+ const model = createPresentationModel({+ id: 'positioned-leader-gap-hit-test',+ body: {+ dataStream: '..\r电\r\n',+ paragraphs: [+ { startIndex: 2, paragraphId: 'leaders', paragraphStyle: { lineSpacing: 9.233 } },+ { startIndex: 4, paragraphId: 'lower', paragraphStyle: { indentStart: { v: 6.785 }, lineSpacing: 16.604 } },+ ],+ textRuns: [+ { st: 0, ed: 3, ts: { fs: 8.9664, textAdvance: 13.283, lineAscent: 14.944, lineDescent: 0 } },+ { st: 3, ed: 5, ts: { fs: 8.9664, textAdvance: 12.408, lineAscent: 16.604, lineDescent: 0, pos: -4.682 } },+ ],+ sectionBreaks: [{ startIndex: 5, sectionId: 'positioned' }],+ },+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ fontMetricScaleEnabled: BooleanNumber.FALSE,+ pageSize: { width: 200, height: 100 },+ marginTop: 7,+ marginBottom: 0,+ marginLeft: 3,+ marginRight: 0,+ defaultParagraphStyle: { spacingRule: SpacingRule.EXACT, snapToGrid: BooleanNumber.FALSE },+ renderConfig: {+ topAlignExactLineSpacing: BooleanNumber.TRUE,+ useTextInkForHitTesting: BooleanNumber.TRUE,+ applyTextPosition: BooleanNumber.TRUE,+ zeroWidthParagraphBreak: BooleanNumber.TRUE,+ wrapStrategy: WrapStrategy.OVERFLOW,+ },+ },+ });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));+ try {+ skeleton.calculate();+ const page = skeleton.getSkeletonData()!.pages[0];+ const [upper, lower] = page.sections[0].columns[0].lines;+ const [firstDot, nextDot] = upper.divides[0].glyphGroup;+ const dotY = page.marginTop + upper.top + upper.marginTop + upper.paddingTop + upper.asc+ - (firstDot.bBox.aba - firstDot.bBox.abd) / 2;+ const x = page.marginLeft + nextDot.left - 0.25;+ const nearest = skeleton.findNodeByCoord(Vector2.FromArray([x, dotY]), PageLayoutType.VERTICAL, 0, 0);+ expect(nearest?.node).toBe(nextDot);+ expect(nearest?.ratioX).toBeLessThan(0.5);+ const lowerGlyph = lower.divides[0].glyphGroup[0];+ const lowerX = page.marginLeft + lower.divides[0].left + lowerGlyph.left + lowerGlyph.width / 2;+ const lowerY = page.marginTop + lower.top + lower.marginTop + lower.paddingTop + lower.asc+ + 4.682 * 4 / 3 - (lowerGlyph.bBox.aba - lowerGlyph.bBox.abd) / 2;+ expect(skeleton.findNodeByCoord(Vector2.FromArray([lowerX, lowerY]), PageLayoutType.VERTICAL, 0, 0)?.node)+ .toBe(lowerGlyph);+ } finally {+ skeleton.dispose();+ model.dispose();+ univer.dispose();+ measureSpy.mockRestore();+ }+ });++ it('keeps an in-glyph subscript drag on the script beside an overlapping upper-line space', () => {+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text, font) => {+ const small = text === 'k';+ const metricScale = font.includes('1024px') ? 1024 / ((small ? 7 : 10) * 4 / 3) : 1;+ const space = text === ' ';+ const ascent = small ? 6.45 : 9.22;+ const width = small ? 4.645 : 6.64;+ return {+ width: (space ? 3.32 : text.length * width) * metricScale,+ actualBoundingBoxAscent: space ? 0 : ascent,+ actualBoundingBoxDescent: space || small ? 0 : 2.84,+ fontBoundingBoxAscent: (small ? 8 : 12) * metricScale,+ fontBoundingBoxDescent: (small ? 2 : 3) * metricScale,+ };+ });+ const univer = new Univer({ locale: LocaleType.EN_US });+ const model = createPresentationModel({+ id: 'narrow-subscript-drag-hit-test',+ body: {+ dataStream: 'g (\rk\r\n',+ paragraphs: [+ { startIndex: 3, paragraphId: 'upper', paragraphStyle: { spaceAbove: { v: 1.9874 } } },+ { startIndex: 5, paragraphId: 'script', paragraphStyle: { indentStart: { v: 6.332 }, lineSpacing: 4.3163 } },+ ],+ textRuns: [+ { st: 0, ed: 1, ts: { fs: 10, textAdvance: 6.3362, lineAscent: 13.1887, lineDescent: 3.9851 } },+ { st: 1, ed: 2, ts: { fs: 10, textAdvance: 6.5319, lineAscent: 13.1887, lineDescent: 3.9851 } },+ { st: 2, ed: 4, ts: { fs: 10, textAdvance: 5.1653, lineAscent: 13.1887, lineDescent: 3.9851 } },+ { st: 4, ed: 6, ts: { fs: 7, textAdvance: 5.6469, lineAscent: 8.3686, lineDescent: 2.7895 } },+ ],+ sectionBreaks: [{ startIndex: 6, sectionId: 'scripts' }],+ },+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ fontMetricScaleEnabled: BooleanNumber.FALSE,+ pageSize: { width: 200, height: 100 },+ marginTop: 7,+ marginBottom: 0,+ marginLeft: 3,+ marginRight: 0,+ defaultParagraphStyle: {+ spacingRule: SpacingRule.EXACT,+ lineSpacing: 8.8007,+ snapToGrid: BooleanNumber.FALSE,+ },+ renderConfig: {+ topAlignExactLineSpacing: BooleanNumber.TRUE,+ useTextInkForHitTesting: BooleanNumber.TRUE,+ applyTextPosition: BooleanNumber.TRUE,+ zeroWidthParagraphBreak: BooleanNumber.TRUE,+ wrapStrategy: WrapStrategy.OVERFLOW,+ },+ },+ });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));+ try {+ skeleton.calculate();+ const page = skeleton.getSkeletonData()!.pages[0];+ const [upper, lower] = page.sections[0].columns[0].lines;+ const divide = lower.divides[0];+ const glyph = divide.glyphGroup[0];+ const left = page.marginLeft + divide.left + divide.paddingLeft + glyph.left;+ const y = page.marginTop + lower.top + lower.marginTop + lower.paddingTop + lower.asc+ - (glyph.bBox.aba - glyph.bBox.abd) / 2;+ expect(lower.top).toBeLessThan(upper.top + upper.contentHeight);+ expect(glyph.width - 0.5).toBeGreaterThan(3);+ for (const x of [left + 0.25, left + glyph.width - 0.25]) {+ expect(skeleton.findNodeByCoord(Vector2.FromArray([x, y]), PageLayoutType.VERTICAL, 0, 0)?.node)+ .toBe(glyph);+ }+ } finally {+ skeleton.dispose();+ model.dispose();+ univer.dispose();+ measureSpy.mockRestore();+ }+ });++ it.each([false, true])('hits a positioned root sign beside an overlapping radicand, nested: %s', (nested) => {+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text, font) => {+ const metricScale = font.includes('1024px') ? 1024 / (11.04 * 4 / 3) : 1;+ return {+ width: (text === '√' ? 9.66717529296875 : 7.4174957275390625) * metricScale,+ actualBoundingBoxAscent: text === '√' ? 13.555624961853027 : 6.871250152587891,+ actualBoundingBoxDescent: text === '√' ? 0.6109380722045898 : 0.07187557220458984,+ fontBoundingBoxAscent: (11) * metricScale,+ fontBoundingBoxDescent: (3) * metricScale,+ };+ });+ const univer = new Univer({ locale: LocaleType.EN_US });+ const token = DataStreamTreeTokenType;+ const dataStream = nested+ ? `${token.COLUMN_GROUP_START}${token.COLUMN_START}mod\r${token.COLUMN_END}${token.COLUMN_START}v\r√\r${token.COLUMN_END}${token.COLUMN_GROUP_END}\n`+ : 'v\r√\r\n';+ const radicandOffset = dataStream.indexOf('v');+ const model = createPresentationModel({+ id: 'positioned-root-sign-hit-test',+ body: {+ dataStream,+ paragraphs: [+ ...(nested ? [{ startIndex: dataStream.indexOf('\r'), paragraphId: 'label' }] : []),+ { startIndex: radicandOffset + 1, paragraphId: 'radicand', paragraphStyle: { indentStart: { v: 9.6 }, lineSpacing: 1.04 } },+ { startIndex: radicandOffset + 3, paragraphId: 'root' },+ ],+ textRuns: [+ { st: radicandOffset, ed: radicandOffset + 2, ts: { fs: 11.04, textAdvance: 8, lineAscent: 14.127979002624672, lineDescent: 4.415958005249342 } },+ { st: radicandOffset + 2, ed: radicandOffset + 4, ts: { fs: 11.04, textAdvance: 9.67104, lineAscent: 13.247979002624671, lineDescent: 4.415958005249344 } },+ ],+ sectionBreaks: [{ startIndex: dataStream.length - 1, sectionId: 'root-sign' }],+ columnGroups: nested+ ? [{+ startIndex: 0,+ endIndex: dataStream.indexOf(token.COLUMN_GROUP_END),+ columnGroupId: 'root-sign-columns',+ columns: [+ { columnId: 'label', widthRatio: 36.74404199475065, minWidth: { v: 0 } },+ { columnId: 'formula', widthRatio: 420.99202099737533, minWidth: { v: 0 } },+ ],+ gap: { v: 39.93595800524935 },+ horizontalPadding: { v: 0 },+ clipContent: BooleanNumber.FALSE,+ layout: ColumnLayoutType.FIXED,+ minHeight: { v: 0 },+ responsive: ColumnResponsiveType.SHRINK,+ }]+ : undefined,+ },+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ fontMetricScaleEnabled: BooleanNumber.FALSE,+ pageSize: { width: 497.67202099737534, height: 100 },+ marginTop: 8,+ marginBottom: 0,+ marginLeft: 0,+ marginRight: 0,+ defaultParagraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: 12, snapToGrid: BooleanNumber.FALSE },+ renderConfig: {+ topAlignExactLineSpacing: BooleanNumber.TRUE,+ useTextInkForHitTesting: BooleanNumber.TRUE,+ applyTextPosition: BooleanNumber.TRUE,+ zeroWidthParagraphBreak: BooleanNumber.TRUE,+ wrapStrategy: WrapStrategy.OVERFLOW,+ },+ },+ });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));+ try {+ skeleton.calculate();+ const page = skeleton.getSkeletonData()!.pages[0];+ const group = Array.from(page.skeColumnGroups.values())[0];+ const nestedColumn = group?.columns[1];+ const contentPage = nestedColumn?.page ?? page;+ const offsetX = nestedColumn ? page.marginLeft + group.left + nestedColumn.left : 0;+ const offsetY = nestedColumn ? page.marginTop + group.top + nestedColumn.top : 0;+ const [radicand, root] = contentPage.sections[0].columns[0].lines;+ const glyph = root.divides[0].glyphGroup[0];+ expect(Boolean(nestedColumn)).toBe(nested);+ expect(radicand.divides[0].left + radicand.divides[0].paddingLeft).toBeCloseTo(9.6);+ expect(root.top - radicand.top).toBeCloseTo(1.04);+ const left = offsetX + contentPage.marginLeft + root.divides[0].left + root.divides[0].paddingLeft + glyph.left;+ const y = offsetY + contentPage.marginTop + root.top + root.marginTop + root.paddingTop + root.asc+ - (glyph.bBox.aba - glyph.bBox.abd) / 2;+ expect(root.top).toBeLessThan(radicand.top + radicand.contentHeight);+ for (const x of [left + 0.25, left + glyph.width / 2, left + glyph.width - 0.25]) {+ expect(skeleton.findNodeByCoord(Vector2.FromArray([x, y]), PageLayoutType.VERTICAL, 0, 0)?.node)+ .toBe(glyph);+ }+ } finally {+ skeleton.dispose();+ model.dispose();+ univer.dispose();+ measureSpy.mockRestore();+ }+ });++ it('hits the painted script rather than an overlapping positioned line', () => {+ const univer = new Univer({ locale: LocaleType.EN_US });+ const model = createPresentationModel({+ id: 'overlapping-script-hit-test',+ body: {+ dataStream: 'd23x\rmodel\r\n',+ paragraphs: [+ { startIndex: 4, paragraphId: 'upper' },+ { startIndex: 10, paragraphId: 'lower', paragraphStyle: { indentStart: { v: 7 } } },+ ],+ textRuns: [+ { st: 0, ed: 1, ts: { fs: 10, textAdvance: 7, lineAscent: 14, lineDescent: 4 } },+ { st: 1, ed: 3, ts: { fs: 7, textAdvance: 5, pos: 4.25, lineAscent: 8.4, lineDescent: 2.8 } },+ { st: 3, ed: 5, ts: { fs: 10, textAdvance: 7, lineAscent: 14, lineDescent: 4 } },+ { st: 5, ed: 11, ts: { fs: 7, textAdvance: 5, lineAscent: 8.4, lineDescent: 2.8 } },+ ],+ sectionBreaks: [{ startIndex: 11, sectionId: 'scripts' }],+ },+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ fontMetricScaleEnabled: BooleanNumber.FALSE,+ pageSize: { width: 200, height: 100 },+ marginTop: 7,+ marginBottom: 0,+ marginLeft: 3,+ marginRight: 0,+ defaultParagraphStyle: {+ spacingRule: SpacingRule.EXACT,+ lineSpacing: 9.5,+ snapToGrid: BooleanNumber.FALSE,+ },+ renderConfig: {+ topAlignExactLineSpacing: BooleanNumber.TRUE,+ useTextInkForHitTesting: BooleanNumber.TRUE,+ applyTextPosition: BooleanNumber.TRUE,+ zeroWidthParagraphBreak: BooleanNumber.TRUE,+ wrapStrategy: WrapStrategy.OVERFLOW,+ },+ },+ });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));+ try {+ skeleton.calculate();+ const page = skeleton.getSkeletonData()!.pages[0];+ const column = page.sections[0].columns[0];+ const [upper, lower] = column.lines;+ expect(lower.top).toBeLessThan(upper.top + upper.contentHeight);+ for (const line of [upper, lower]) {+ const divide = line.divides[0];+ for (const glyph of divide.glyphGroup.filter((glyph) => glyph.content.trim())) {+ const baseline = page.marginTop + line.top + line.marginTop + line.paddingTop + line.asc+ - (glyph.ts?.pos ?? 0) * 4 / 3;+ const point = Vector2.FromArray([+ page.marginLeft + column.left + divide.left + divide.paddingLeft + glyph.left + glyph.width / 2,+ baseline - (glyph.bBox.aba - glyph.bBox.abd) / 2,+ ]);+ expect(skeleton.findNodeByCoord(point, PageLayoutType.VERTICAL, 0, 0)?.node).toBe(glyph);+ }+ }+ } finally {+ skeleton.dispose();+ model.dispose();+ univer.dispose();+ }+ });++ it('hits punctuation below a positioned line with zero nominal descent', () => {+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text, font) => {+ const metricScale = font.includes('1024px') ? 1024 / (10 * 4 / 3) : 1;+ return {+ width: (text.length * (text === ',' ? 3.2536 : 8)) * metricScale,+ actualBoundingBoxAscent: text === ',' ? 1.296875 : 9,+ actualBoundingBoxDescent: text === ',' ? 2.211172 : 0,+ fontBoundingBoxAscent: (12) * metricScale,+ fontBoundingBoxDescent: (3) * metricScale,+ };+ });+ const univer = new Univer({ locale: LocaleType.EN_US });+ const model = createPresentationModel({+ id: 'positioned-punctuation-descender',+ body: {+ dataStream: 'A,\rBB\r\n',+ paragraphs: [{ startIndex: 2, paragraphId: 'upper' }, { startIndex: 5, paragraphId: 'lower' }],+ textRuns: [+ { st: 0, ed: 1, ts: { fs: 10, textAdvance: 8, lineAscent: 16.6043, lineDescent: 0 } },+ { st: 1, ed: 2, ts: { fs: 10, textAdvance: 3.2544, lineAscent: 16.6043, lineDescent: 0 } },+ { st: 3, ed: 5, ts: { fs: 10, textAdvance: 8, lineAscent: 16.6043, lineDescent: 0 } },+ ],+ sectionBreaks: [{ startIndex: 6, sectionId: 'references' }],+ },+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ fontMetricScaleEnabled: BooleanNumber.FALSE,+ pageSize: { width: 200, height: 100 },+ marginTop: 7.6237,+ marginBottom: 0,+ marginLeft: 0,+ marginRight: 0,+ defaultParagraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: 14.7113, snapToGrid: BooleanNumber.FALSE },+ renderConfig: {+ topAlignExactLineSpacing: BooleanNumber.TRUE,+ useTextInkForHitTesting: BooleanNumber.TRUE,+ applyTextPosition: BooleanNumber.TRUE,+ zeroWidthParagraphBreak: BooleanNumber.TRUE,+ wrapStrategy: WrapStrategy.OVERFLOW,+ },+ },+ });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));+ try {+ skeleton.calculate();+ const page = skeleton.getSkeletonData()!.pages[0];+ const [upper, lower] = page.sections[0].columns[0].lines;+ const punctuation = upper.divides[0].glyphGroup[1];+ const baseline = page.marginTop + upper.top + upper.marginTop + upper.paddingTop + upper.asc;+ const y = baseline - (punctuation.bBox.aba - punctuation.bBox.abd) / 2;+ expect(y).toBeGreaterThan(page.marginTop + upper.top + upper.contentHeight);+ for (const ratio of [0.1, 0.5, 0.9]) {+ const point = new Vector2(punctuation.left + punctuation.width * ratio, y);+ for (const restrictions of [undefined, { strict: true, segmentId: '', segmentPage: -1 }]) {+ expect(skeleton.findNodeByCoord(point, PageLayoutType.VERTICAL, 0, 0, restrictions)?.node)+ .toBe(punctuation);+ }+ }+ const lowerGlyph = lower.divides[0].glyphGroup[1];+ const lowerY = page.marginTop + lower.top + lower.asc - lowerGlyph.bBox.aba / 2;+ expect(skeleton.findNodeByCoord(new Vector2(lowerGlyph.left + lowerGlyph.width / 2, lowerY), PageLayoutType.VERTICAL, 0, 0)?.node)+ .toBe(lowerGlyph);+ } finally {+ skeleton.dispose();+ model.dispose();+ univer.dispose();+ measureSpy.mockRestore();+ }+ });++ it.each([+ { clipContent: undefined, glyphLeft: 0, lineTop: 0, pointerOffset: 0, hit: true },+ { clipContent: undefined, glyphLeft: 110, lineTop: 0, pointerOffset: 0, hit: false },+ { clipContent: BooleanNumber.TRUE, glyphLeft: 110, lineTop: 0, pointerOffset: 0, hit: false },+ { clipContent: BooleanNumber.FALSE, glyphLeft: 110, lineTop: 0, pointerOffset: 0, hit: true },+ { clipContent: BooleanNumber.FALSE, glyphLeft: 150, lineTop: 0, pointerOffset: 0, hit: true },+ { clipContent: BooleanNumber.FALSE, glyphLeft: -20, lineTop: 0, pointerOffset: 0, hit: true },+ { clipContent: BooleanNumber.FALSE, glyphLeft: 0, lineTop: 110, pointerOffset: 0, hit: true },+ { clipContent: BooleanNumber.FALSE, glyphLeft: 150, lineTop: 0, pointerOffset: 20, hit: false },+ ])('hits painted column text within its clipping policy: %o', ({ clipContent, glyphLeft, lineTop, pointerOffset, hit }) => {+ const body = createPage(DocumentSkeletonPageType.BODY, 0);+ const columnPage = createPage(DocumentSkeletonPageType.CELL, 100);+ body.column.lines = [];+ body.page.ed = 110;+ body.section.ed = 110;+ body.column.ed = 110;+ columnPage.page.pageWidth = 100;+ columnPage.page.pageHeight = 80;+ columnPage.page.marginLeft = 0;+ columnPage.page.marginTop = 0;+ columnPage.page.marginRight = 0;+ columnPage.page.marginBottom = 0;+ columnPage.glyphs.glyphA.left = glyphLeft;+ columnPage.glyphs.glyphA.width = 10;+ columnPage.line.top = lineTop;+ columnPage.divide.glyphGroup = [columnPage.glyphs.glyphA];++ const columnGroup = {+ columns: [+ {+ columnId: 'col-1',+ left: 60,+ top: 0,+ width: 100,+ height: 80,+ st: 100,+ ed: 110,+ page: columnPage.page,+ },+ ],+ width: 180,+ height: 80,+ top: 30,+ left: 20,+ st: 90,+ ed: 110,+ columnGroupId: 'cg-1',+ columnGroupSource: { clipContent },+ parent: body.page,+ } as any;+ columnGroup.columns[0].parent = columnGroup;+ columnPage.page.parent = columnGroup.columns[0];+ body.page.skeColumnGroups.set('cg-1', columnGroup);++ const docViewModel = {+ getDataModel: () => ({+ documentStyle: {+ pageSize: { width: 210, height: 297 },+ },+ }),+ getHeaderFooterTreeMap: () => ({+ headerTreeMap: new Map(),+ footerTreeMap: new Map(),+ }),+ dispose: vi.fn(),+ } as any;+ const skeleton = new DocumentSkeleton(docViewModel, {} as any);+ const skeletonData = {+ pages: [body.page],+ skeHeaders: new Map(),+ skeFooters: new Map(),+ };+ body.page.parent = skeletonData as any;+ (skeleton as any)._skeletonData = skeletonData;++ const node = skeleton.findNodeByCoord(+ Vector2.FromArray([90 + glyphLeft + pointerOffset, 45 + lineTop]),+ PageLayoutType.VERTICAL,+ 0,+ 0+ );++ expect(node?.node).toBe(hit ? columnPage.glyphs.glyphA : undefined);+ expect(skeleton.findNodeByCharIndex(100)).toBe(columnPage.glyphs.glyphA);+ expect(skeleton.findNodePositionByCharIndex(110)?.path).toEqual([+ 'pages',+ 0,+ 'skeColumnGroups',+ 'cg-1',+ 'columns',+ 0,+ 'page',+ ]);+ });+it('uses the largest DrawingML text size across runs, without changing snapshots or document defaults', () => {const measure = vi.spyOn(FontCache, 'getMeasureText').mockReturnValue({width: 6.1572265625,diff --git a/packages/engine-render/src/components/docs/layout/block/__tests__/column.spec.ts b/packages/engine-render/src/components/docs/layout/block/__tests__/column.spec.tsindex b91b5c9581..e7439ce79d 100644--- a/packages/engine-render/src/components/docs/layout/block/__tests__/column.spec.ts+++ b/packages/engine-render/src/components/docs/layout/block/__tests__/column.spec.ts@@ -36,4 +36,23 @@ describe('column group layout', () => {expect(layout.columns[1].width).toBeCloseTo(25);expect(layout.columns[2].width).toBeCloseTo(25);});++ it('preserves independent column top offsets in a fixed horizontal layout', () => {+ const layout = calculateColumnGroupLayout({+ columnGroupId: 'column-group-1',+ columns: [+ { columnId: 'column-1', widthRatio: 1 },+ { columnId: 'column-2', widthRatio: 1, topOffset: { v: -8 } },+ ],+ gap: { v: 20 },+ layout: ColumnLayoutType.FIXED,+ responsive: ColumnResponsiveType.SHRINK,+ }, 220, [60, 60]);++ expect(layout.columns).toEqual([+ { columnId: 'column-1', left: 0, top: 0, width: 100 },+ { columnId: 'column-2', left: 120, top: -8, width: 100 },+ ]);+ expect(layout.height).toBe(60);+ });});diff --git a/packages/engine-render/src/components/docs/layout/block/column.ts b/packages/engine-render/src/components/docs/layout/block/column.tsindex ef5527c928..9028816020 100644--- a/packages/engine-render/src/components/docs/layout/block/column.ts+++ b/packages/engine-render/src/components/docs/layout/block/column.ts@@ -14,9 +14,15 @@* limitations under the License.*/-import type { IColumn, IColumnGroup, Nullable } from '@univerjs/core';-import type { IDocumentSkeletonColumnGroup, IDocumentSkeletonColumnGroupColumn, IDocumentSkeletonLine, IDocumentSkeletonPage } from '../../../../basics/i-document-skeleton-cached';+import type { Nullable } from '@univerjs/core';+import type {+ IDocumentSkeletonColumnGroup,+ IDocumentSkeletonColumnGroupColumn,+ IDocumentSkeletonLine,+ IDocumentSkeletonPage,+} from '../../../../basics/i-document-skeleton-cached';import type { ISectionBreakConfig } from '../../../../basics/interfaces';+import type { IDocumentLayoutColumn, IDocumentLayoutColumnGroup } from '../../document-layout-presentation';import type { DataStreamTreeNode } from '../../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../../view-model/document-view-model';import type { ILayoutContext } from '../tools';@@ -41,8 +47,8 @@ interface IColumnGroupLayout {columns: IColumnGroupLayoutColumn[];}-const EMPTY_COLUMN_GROUP_MIN_HEIGHT = 72;-const COLUMN_GROUP_HORIZONTAL_PADDING = 8;+const DEFAULT_COLUMN_GROUP_MIN_HEIGHT = 72;+const DEFAULT_COLUMN_GROUP_HORIZONTAL_PADDING = 8;export function createColumnGroupSkeleton(ctx: ILayoutContext,@@ -62,13 +68,18 @@ export function createColumnGroupSkeleton(return null;}+ const horizontalPadding = Math.max(+ 0,+ columnGroupSource.horizontalPadding?.v ?? DEFAULT_COLUMN_GROUP_HORIZONTAL_PADDING+ );+ const minHeight = Math.max(0, columnGroupSource.minHeight?.v ?? DEFAULT_COLUMN_GROUP_MIN_HEIGHT);const columnPages = columnGroupNode.children.map((columnNode, index) => {const sourceColumn = columnGroupSource.columns[index];const width = Math.max(0, getInitialColumnWidth(columnGroupSource, sourceColumn, hostColumn.width));- return createColumnContentPage(ctx, viewModel, columnNode, sectionBreakConfig, width);+ return createColumnContentPage(ctx, viewModel, columnNode, sectionBreakConfig, width, horizontalPadding);});- const columnHeights = columnPages.map((page) => Math.max(page.height, EMPTY_COLUMN_GROUP_MIN_HEIGHT));+ const columnHeights = columnPages.map((page) => Math.max(page.height, minHeight));const layout = calculateColumnGroupLayout(columnGroupSource, hostColumn.width, columnHeights);const columns = layout.columns.map((layoutColumn, index): IDocumentSkeletonColumnGroupColumn => {const page = columnPages[index];@@ -128,7 +139,8 @@ function createColumnContentPage(viewModel: DocumentViewModel,columnNode: DataStreamTreeNode,sectionBreakConfig: ISectionBreakConfig,- width: number+ width: number,+ horizontalPadding: number): IDocumentSkeletonPage {const columnSectionBreakConfig: ISectionBreakConfig = {...sectionBreakConfig,@@ -138,8 +150,8 @@ function createColumnContentPage(},marginTop: 0,marginBottom: 0,- marginLeft: COLUMN_GROUP_HORIZONTAL_PADDING,- marginRight: COLUMN_GROUP_HORIZONTAL_PADDING,+ marginLeft: horizontalPadding,+ marginRight: horizontalPadding,columnProperties: [],};const page = createSkeletonPage(ctx, columnSectionBreakConfig, ctx.skeletonResourceReference);@@ -210,7 +222,7 @@ function getNextBlockTop(lines: IDocumentSkeletonLine[]) {return lastLine.top + lastLine.lineHeight;}-export function calculateColumnGroupLayout(source: IColumnGroup, availableWidth: number, columnHeights: number[]): IColumnGroupLayout {+export function calculateColumnGroupLayout(source: IDocumentLayoutColumnGroup, availableWidth: number, columnHeights: number[]): IColumnGroupLayout {const width = Math.max(0, availableWidth);const gap = Math.max(0, source.gap?.v ?? 0);const columns = source.columns;@@ -226,21 +238,23 @@ export function calculateColumnGroupLayout(source: IColumnGroup, availableWidth:if (shouldStack(columns, width, gap, source.responsive)) {let top = 0;+ const layoutColumns = columns.map((column, index) => {+ const topOffset = getColumnTopOffset(column);+ const layoutColumn = {+ columnId: column.columnId,+ left: 0,+ top: top + topOffset,+ width,+ };+ top += Math.max(0, topOffset + (columnHeights[index] ?? 0));++ return layoutColumn;+ });return {mode: 'stack',width,- height: sumHeights(columnHeights),- columns: columns.map((column, index) => {- const layoutColumn = {- columnId: column.columnId,- left: 0,- top,- width,- };- top += Math.max(0, columnHeights[index] ?? 0);-- return layoutColumn;- }),+ height: top,+ columns: layoutColumns,};}@@ -248,25 +262,33 @@ export function calculateColumnGroupLayout(source: IColumnGroup, availableWidth:const widths = allocateHorizontalWidths(columns, contentWidth);let left = 0;+ const layoutColumns = columns.map((column, index) => {+ const layoutColumn = {+ columnId: column.columnId,+ left,+ top: getColumnTopOffset(column),+ width: widths[index],+ };+ left += widths[index] + gap;++ return layoutColumn;+ });return {mode: 'horizontal',width,- height: Math.max(0, ...columnHeights),- columns: columns.map((column, index) => {- const layoutColumn = {- columnId: column.columnId,- left,- top: 0,- width: widths[index],- };- left += widths[index] + gap;-- return layoutColumn;- }),+ height: Math.max(0, ...layoutColumns.map((column, index) => (+ column.top + Math.max(0, columnHeights[index] ?? 0)+ ))),+ columns: layoutColumns,};}-function shouldStack(columns: IColumn[], availableWidth: number, gap: number, responsive: ColumnResponsiveType): boolean {+function getColumnTopOffset(column: IDocumentLayoutColumn): number {+ const offset = column.topOffset?.v;+ return typeof offset === 'number' && Number.isFinite(offset) ? offset : 0;+}++function shouldStack(columns: IDocumentLayoutColumn[], availableWidth: number, gap: number, responsive: ColumnResponsiveType): boolean {if (responsive !== ColumnResponsiveType.STACK) {return false;}@@ -276,7 +298,7 @@ function shouldStack(columns: IColumn[], availableWidth: number, gap: number, rereturn totalMinWidth > availableWidth;}-function getInitialColumnWidth(source: IColumnGroup, column: IColumn | undefined, availableWidth: number): number {+function getInitialColumnWidth(source: IDocumentLayoutColumnGroup, column: IDocumentLayoutColumn | undefined, availableWidth: number): number {if (column == null) {return availableWidth;}@@ -287,7 +309,7 @@ function getInitialColumnWidth(source: IColumnGroup, column: IColumn | undefinedreturn Math.max(getMinWidth(column), contentWidth * (Math.max(0, column.widthRatio || 0) || 1) / ratioSum);}-function allocateHorizontalWidths(columns: IColumn[], contentWidth: number): number[] {+function allocateHorizontalWidths(columns: IDocumentLayoutColumn[], contentWidth: number): number[] {const ratioSum = columns.reduce((sum, column) => sum + Math.max(0, column.widthRatio || 0), 0) || columns.length;const idealWidths = columns.map((column) => contentWidth * (Math.max(0, column.widthRatio || 0) || 1) / ratioSum);const minWidths = columns.map(getMinWidth);@@ -318,10 +340,6 @@ function compressToFit(widths: number[], minWidths: number[], overflow: number):return nextWidths;}-function getMinWidth(column: IColumn): number {+function getMinWidth(column: IDocumentLayoutColumn): number {return Math.max(0, column.minWidth?.v ?? 0);}--function sumHeights(heights: number[]): number {- return heights.reduce((sum, height) => sum + Math.max(0, height), 0);-}diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.tsindex 0b0e0f085c..27df91ada0 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@@ -14,7 +14,10 @@* limitations under the License.*/-import type { IDocumentSkeletonDivide, IDocumentSkeletonGlyph } from '../../../../../../basics/i-document-skeleton-cached';+import type {+ IDocumentSkeletonDivide,+ IDocumentSkeletonGlyph,+} from '../../../../../../basics/i-document-skeleton-cached';import type { IParagraphConfig } from '../../../../../../basics/interfaces';import {AlignTypeH,@@ -41,11 +44,7 @@ import {WrapTextType,} from '@univerjs/core';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import {- DocumentSkeletonPageType,- GlyphType,- LineType,-} from '../../../../../../basics/i-document-skeleton-cached';+import { DocumentSkeletonPageType, GlyphType, LineType } from '../../../../../../basics/i-document-skeleton-cached';import { setDocsCustomBlockRenderViewportProvider } from '../../../../custom-block-render-viewport';import { getDocumentCompatibilityPolicy } from '../../../../document-compatibility';import { DocumentSkeleton } from '../../../doc-skeleton';@@ -63,6 +62,46 @@ import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bedimport issue1207Snapshot from './fixtures/issue-1207-bullet-style.snapshot.json';describe('layout-ruler', () => {+ it('does not skip a fixed tab stop after preceding text crosses it', () => {+ const tab = createGlyph(DataStreamTreeTokenType.TAB, 36);+ tab.glyphType = GlyphType.TAB;+ tab.left = 120;+ const divide = { glyphGroup: [tab], width: 580 } as IDocumentSkeletonDivide;+ const paragraphConfig = {+ paragraphStyle: {+ tabStops: [{ offset: 100, alignment: 1 }, { offset: 200, alignment: 1 }],+ fixedTabStops: BooleanNumber.TRUE,+ },+ } as IParagraphConfig;++ __testing.adjustExplicitTabStop(divide, [], paragraphConfig);++ expect(tab.width).toBe(0);+ expect(tab.bBox.width).toBe(0);+ });++ it('top-aligns glyphs in compact exact line boxes when requested by an embedded editor', () => {+ const metrics = getLineHeightMetrics(+ 18,+ 0,+ 15.6,+ GridType.LINES,+ 14,+ SpacingRule.EXACT,+ BooleanNumber.FALSE,+ true,+ true,+ undefined,+ false,+ undefined,+ true+ );++ expect(metrics.paddingTop).toBe(0);+ expect(metrics.paddingBottom).toBe(-4);+ expect(getLineBoxHeight(metrics)).toBe(14);+ });+beforeEach(() => {clearFontCreateConfigCache();vi.stubGlobal('document', {diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.tsindex 6960cf3ac3..6bdd1e180b 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts@@ -35,6 +35,46 @@ import { shaping } from '../shaping';import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';describe('line-adjustment', () => {+ it.each(['“内容”', '文。。文', '(二)内容'])('preserves punctuation widths when compression is disabled: %s', (text) => {+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(text, {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ characterSpacingControl: characterSpacingControlType.doNotCompress,+ renderConfig: { preservePunctuationSpacing: BooleanNumber.TRUE },+ },+ });+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);+ const pages = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);++ const punctuation = pages[0].sections[0].columns[0].lines[0].divides[0].glyphGroup+ .filter((glyph) => ['“', '”', '。', '(', ')'].includes(glyph.content));+ expect(punctuation.length).toBeGreaterThan(0);+ for (const glyph of punctuation) {+ expect(glyph.xOffset).toBe(0);+ expect(glyph.width).toBeCloseTo(glyph.bBox.width);+ }+ });++ it.each([undefined, characterSpacingControlType.compressPunctuation])(+ 'retains default punctuation compression (%s)',+ (characterSpacingControl) => {+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('“内容”', {+ documentStyle: { characterSpacingControl },+ });+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);+ const pages = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);++ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);++ const openingQuote = pages[0].sections[0].columns[0].lines[0].divides[0].glyphGroup[0];+ expect(openingQuote.content).toBe('“');+ expect(openingQuote.xOffset).toBeLessThan(0);+ expect(openingQuote.width).toBeLessThan(openingQuote.bBox.width);+ }+ );+it.each([12, 17, 22, 30].flatMap((points) => [DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN].map((documentFlavor) => ({ points, documentFlavor }))))('aligns exact-spaced text like Word without changing line boxes: %j', ({ points, documentFlavor }) => {const measure = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({width: text.length * 8,@@ -488,6 +528,36 @@ describe('line-adjustment', () => {expect(() => lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig)).not.toThrow();});+ it('preserves authoritative advances for punctuation at line boundaries', () => {+ const firstGlyph = createGlyph('(', 20, {+ ts: { textAdvance: 20 },+ adjustability: {+ stretchability: [0, 0],+ shrinkability: [10, 0],+ },+ });+ const lastGlyph = createGlyph(')', 20, {+ ts: { textAdvance: 20 },+ adjustability: {+ stretchability: [0, 0],+ shrinkability: [0, 10],+ },+ });+ const divide = {+ width: 40,+ isFull: false,+ paddingLeft: 0,+ glyphGroup: [firstGlyph, lastGlyph],+ } as any;+ const context = createPagesWithLine(divide, HorizontalAlign.LEFT);++ lineAdjustment(context.pages, context.viewModel, context.paragraphNode, context.sectionBreakConfig);++ expect(firstGlyph.xOffset).toBe(0);+ expect(firstGlyph.width).toBe(20);+ expect(lastGlyph.width).toBe(20);+ });+it('handles horizontal align CENTER', () => {const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Hello', {body: {diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.tsindex a1e104f511..7fc1b3da27 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts@@ -23,6 +23,7 @@ import {DocumentFlavor,NamedStyleType,PositionedObjectLayoutType,+ TabStopAlignment,} from '@univerjs/core';import { describe, expect, it, vi } from 'vitest';import { getFontStyleString } from '../../../../../../basics/tools';@@ -33,10 +34,88 @@ import { BreakPointType } from '../../../line-breaker/break';import { createSkeletonLetterGlyph } from '../../../model/glyph';import { FontCache } from '../../../shaping-engine/font-cache';import { clearFontCreateConfigCache } from '../../../tools';+import { lineBreaking } from '../linebreaking';import { shaping } from '../shaping';import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';describe('shaping', () => {+ it.each([+ { content: '/\t/\t/\t/', positions: [0, 100, 200, 300] },+ { content: '/\t/1\t/\t/', positions: [0, 100, 200, 300] },+ { content: '/1\t/1\t/1\t/', positions: [0, 100, 200, 300] },+ { content: '\t/\t/\t/', positions: [100, 200, 300] },+ { content: '/\t\t/\t/', positions: [0, 200, 300] },+ ])(+ 'keeps fixed tab anchors after preceding text changes: $content',+ ({ content, positions }) => {+ const testBed = createParagraphLayoutTestBed(content, {+ documentStyle: { pageSize: { width: 800, height: 600 } },+ body: {+ textRuns: Array.from(content, (character, index) => ({+ st: index,+ ed: index + 1,+ ts: { textAdvance: character === '\t' ? 92 : 8 },+ })),+ paragraphs: [{+ startIndex: content.length,+ paragraphStyle: {+ tabStops: [100, 200, 300].map((offset) => ({ offset, alignment: TabStopAlignment.START })),+ fixedTabStops: BooleanNumber.TRUE,+ },+ }],+ },+ });+ const { ctx, paragraphNode, viewModel, sectionBreakConfig, curPage } = testBed;+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);+ const glyphs = pages[0].sections[0].columns[0].lines[0].divides[0].glyphGroup;++ expect(glyphs.filter((glyph) => glyph.content === '/').map((glyph) => glyph.left))+ .toEqual(positions);+ }+ );++ it.each([+ { content: 'that require tool us', fixed: true, expectedAscent: 12, expectedDescent: 4 },+ { content: 'that require tool us ', fixed: true, expectedAscent: 12, expectedDescent: 4 },+ { content: '', fixed: true, expectedAscent: 17, expectedDescent: 0 },+ { content: 'that require tool us', fixed: false, expectedAscent: 17, expectedDescent: 0 },+ ])('preserves surviving positioned text metrics after paragraph merging: $content / $fixed', ({+ content,+ fixed,+ expectedAscent,+ expectedDescent,+ }) => {+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {+ body: {+ paragraphs: [{+ startIndex: content.length,+ paragraphId: 'merged-positioned-paragraph',+ paragraphStyle: { textStyle: { lineAscent: 17, lineDescent: 0 } },+ }],+ textRuns: [+ ...(content.length ? [{ st: 0, ed: content.length, ts: { lineAscent: 12, lineDescent: 4 } }] : []),+ { st: content.length, ed: content.length + 1, ts: { lineAscent: 17, lineDescent: 0 } },+ ],+ },+ documentStyle: {+ renderConfig: {+ zeroWidthParagraphBreak: BooleanNumber.TRUE,+ topAlignExactLineSpacing: fixed ? BooleanNumber.TRUE : BooleanNumber.FALSE,+ },+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ });+ const glyphs = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig)+ .flatMap((item) => item.glyphs);+ const paragraphMark = glyphs.find((glyph) => glyph.content === '\r');++ expect(paragraphMark?.bBox.ba).toBe(expectedAscent);+ expect(paragraphMark?.bBox.bd).toBe(expectedDescent);+ expect(viewModel.getDataModel().getBody()?.textRuns?.slice(-1)[0].ts)+ .toEqual({ lineAscent: 17, lineDescent: 0 });+ });+it.each(['…', '….', '....', ',...'])('keeps spaced trailing punctuation with its preceding Word token (%s)', (punctuation) => {const content = `Before word ${punctuation} after`;const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {@@ -756,6 +835,23 @@ describe('shaping', () => {}});+ it('preserves authoritative advances for consecutive CJK punctuation', () => {+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('):', {+ body: {+ textRuns: [{+ st: 0,+ ed: 2,+ ts: { textAdvance: 10 },+ }],+ },+ });+ const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);+ const glyphs = result.flatMap((item) => item.glyphs).filter((glyph) => glyph.content && glyph.content !== '\r');++ expect(glyphs.map((glyph) => glyph.width)).toEqual([10, 10]);+ expect(glyphs.map((glyph) => glyph.xOffset)).toEqual([0, 0]);+ });+it('adds CJK Latin spacing for mixed text', () => {const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('A好B');@@ -766,6 +862,31 @@ describe('shaping', () => {expect(allGlyphs.length).toBeGreaterThan(0);});+ it('does not add CJK Latin spacing when fixed advances define the source layout', () => {+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('好5号', {+ body: {+ textRuns: [{+ st: 0,+ ed: 3,+ ts: { textAdvance: 10 },+ }],+ },+ });++ const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);+ const allGlyphs = result.flatMap((item) => item.glyphs).filter((glyph) => glyph.content && glyph.content !== '\r');++ expect(allGlyphs.map((glyph) => ({+ content: glyph.content,+ width: glyph.width,+ xOffset: glyph.xOffset,+ }))).toEqual([+ { content: '好', width: 10, xOffset: 0 },+ { content: '5', width: 10, xOffset: 0 },+ { content: '号', width: 10, xOffset: 0 },+ ]);+ });+it('shapes paragraph break with zero width when configured', () => {const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('Hello');sectionBreakConfig.renderConfig = {diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.tsindex 264d5d0e0b..1c41fcaf1c 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@@ -929,7 +929,8 @@ function _getExpandedLineMetrics(? undefined: normalLineHeight || undefined,false,- drawingMLLineHeight+ drawingMLLineHeight,+ sectionBreakConfig.renderConfig?.topAlignExactLineSpacing === BooleanNumber.TRUE);// Extra font leading can change the line extent without changing its@@ -1084,13 +1085,15 @@ function _adjustExplicitTabStop(return;}- const origin = isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)+ const usesFixedTabStops = paragraphConfig.paragraphStyle?.fixedTabStops === BooleanNumber.TRUE;+ const origin = !usesFixedTabStops && isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)? divide.left + divide.paddingLeft: 0;const tabLeft = origin + tabGlyph.left;- const tabStop = [...tabStops]- .sort((left, right) => left.offset - right.offset)- .find(({ offset, clear }) => !clear && offset > tabLeft);+ const sortedTabStops = [...tabStops].filter(({ clear }) => !clear).sort((left, right) => left.offset - right.offset);+ const tabStop = usesFixedTabStops+ ? sortedTabStops[divide.glyphGroup.filter((glyph) => glyph.glyphType === GlyphType.TAB).length - 1]+ : sortedTabStops.find(({ offset }) => offset > tabLeft);if (!tabStop) {return;}@@ -1106,6 +1109,11 @@ function _adjustExplicitTabStop(const targetOffset = Math.min(tabStop.offset, origin + divide.width);const width = targetOffset - tabLeft - alignmentOffset;if (width <= 0) {+ if (usesFixedTabStops) {+ tabGlyph.width = 0;+ tabGlyph.bBox.width = 0;+ tabGlyph.tabLeader = tabStop.leader;+ }return;}@@ -1357,7 +1365,8 @@ function _getParagraphContentMetrics(snapMultilineParagraphToWholeGrid || (hasInlineCustomBlock && isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy!)),- drawingMLLineHeight+ drawingMLLineHeight,+ sectionBreakConfig.renderConfig?.topAlignExactLineSpacing === BooleanNumber.TRUE);const wordAutoLeading = isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)&& spacingRule === SpacingRule.AUTO && lineSpacing > 1 && !hasInlineCustomBlock@@ -2813,7 +2822,8 @@ export function getLineHeightMetrics(scaleAutoLineSpacingByGlyphHeight = true,normalLineHeight?: number,snapAutoLineSpacingToWholeGridLines = false,- drawingMLLineHeight?: number+ drawingMLLineHeight?: number,+ topAlignExactLineSpacing = false) {const usesLineGridType = gridType === GridType.LINES || gridType === GridType.LINES_AND_CHARS;const hasNoLineGrid = !usesLineGridType || snapToGrid === BooleanNumber.FALSE;@@ -2935,8 +2945,8 @@ export function getLineHeightMetrics(const exactPadding = (exactLineSpacingApply - glyphLineHeight) / 2;return {- paddingTop: exactPadding,- paddingBottom: exactPadding,+ paddingTop: topAlignExactLineSpacing ? 0 : exactPadding,+ paddingBottom: topAlignExactLineSpacing ? exactLineSpacingApply - glyphLineHeight : exactPadding,contentHeight: glyphLineHeight,lineSpacingApply: exactLineSpacingApply,};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.tsindex ab1b609a52..2185adfee3 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@@ -331,13 +331,20 @@ function shrinkStartAndEndCJKPunctuation(line: IDocumentSkeletonLine, preserveEnconst firstGlyph = divide.glyphGroup[0];const lastGlyph = divide.glyphGroup[glyphGroupLength - 1];- if (isCjkRightAlignedPunctuation(firstGlyph.content)) {+ if (+ firstGlyph.ts?.textAdvance === undefined+ && isCjkRightAlignedPunctuation(firstGlyph.content)+ ) {const shrinkAmount = firstGlyph.adjustability.shrinkability[0];glyphShrinkLeft(firstGlyph, shrinkAmount);}- if (!preserveEndSpace && isCjkLeftAlignedPunctuation(lastGlyph.content)) {+ if (+ !preserveEndSpace+ && lastGlyph.ts?.textAdvance === undefined+ && isCjkLeftAlignedPunctuation(lastGlyph.content)+ ) {const shrinkAmount = lastGlyph.adjustability.shrinkability[1];glyphShrinkRight(lastGlyph, shrinkAmount);@@ -421,6 +428,7 @@ export function lineAdjustment(for (let index = low; index < lines.length && lines[index].paragraphIndex === paragraph.startIndex; index++) {const line = lines[index];if (traditional && resolvedParagraphStyle.spacingRule === SpacingRule.EXACT && line.contentHeight > 0.01 &&+ sectionBreakConfig.renderConfig?.topAlignExactLineSpacing !== BooleanNumber.TRUE &&!line.divides.some((divide) => divide.glyphGroup.some((glyph) => glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width > 0))) {// Word places text at 80% of the exact line box, independent of font ascent.// Keep the line box unchanged so pagination and following objects do not move.diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.tsindex b970a18357..18dc46be4b 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@@ -39,6 +39,9 @@ import {hasArabic,hasThai,hasTibetan,+ isCjkCenterAlignedPunctuation,+ isCjkLeftAlignedPunctuation,+ isCjkRightAlignedPunctuation,startWithEmoji,} from '../../../../../basics/tools';import { getDocsCustomBlockRenderViewport } from '../../../custom-block-render-viewport';@@ -84,6 +87,8 @@ function punctuationSpaceAdjustment(shapedGlyphs: IDocumentSkeletonGlyph[], inclif ((cjk.hasCJKPunctuation(content) || (includeEastAsianQuotes && /^[“”‘’]$/.test(content))) &&(cjk.hasCJKPunctuation(nextGlyph.content) || (includeEastAsianQuotes && /^[“”‘’]$/.test(nextGlyph.content))) &&+ curGlyph.ts?.textAdvance === undefined &&+ nextGlyph.ts?.textAdvance === undefined &&curGlyph.adjustability.shrinkability[1] + nextGlyph.adjustability.shrinkability[0] >= delta) {const leftDelta = Math.min(curGlyph.adjustability.shrinkability[1], delta);@@ -110,7 +115,13 @@ function addCJKLatinSpacing(shapedTextList: IShapedText[]) {const width = curGlyph.ts?.sc && Number.isFinite(curGlyph.ts.sc) ? curGlyph.bBox.width : curGlyph.width;// Case 1: CJ followed by a Latin character.- if (cjk.hasCJKText(curGlyph.content) && nextGlyph && LATIN_REG.test(nextGlyph.content)) {+ if (+ cjk.hasCJKText(curGlyph.content)+ && nextGlyph+ && LATIN_REG.test(nextGlyph.content)+ && curGlyph.ts?.textAdvance === undefined+ && nextGlyph.ts?.textAdvance === undefined+ ) {curGlyph.autoSpacing = [0, width / 4];curGlyph.width += width / 4;curGlyph.adjustability.shrinkability[1] += width / 8;@@ -118,7 +129,13 @@ function addCJKLatinSpacing(shapedTextList: IShapedText[]) {}// Case 2: Latin followed by a CJ character.- if (cjk.hasCJKText(curGlyph.content) && prevGlyph && LATIN_REG.test(prevGlyph.content)) {+ if (+ cjk.hasCJKText(curGlyph.content)+ && prevGlyph+ && LATIN_REG.test(prevGlyph.content)+ && curGlyph.ts?.textAdvance === undefined+ && prevGlyph.ts?.textAdvance === undefined+ ) {curGlyph.autoSpacing = [width / 4, curGlyph.autoSpacing?.[1] ?? 0];curGlyph.width += width / 4;curGlyph.xOffset += width / 4;@@ -460,7 +477,8 @@ function createNoteLabelGlyph(function appendShapedText(shapedTextList: IShapedText[],shapedGlyphs: IDocumentSkeletonGlyph[],- breakPointType: BreakPointType+ breakPointType: BreakPointType,+ fixedTabStops = false): void {const shapedGlyphsList: IDocumentSkeletonGlyph[][] = [[]];@@ -477,6 +495,9 @@ function appendShapedText(} else {lastList.push(glyph);}+ if (fixedTabStops && glyph.glyphType === GlyphType.TAB && i < shapedGlyphs.length - 1) {+ shapedGlyphsList.push([]);+ }}const lastShapedGlyphs = shapedGlyphsList[shapedGlyphsList.length - 1];@@ -630,6 +651,20 @@ export function shaping(char = getFirstGrapheme(src) ?? char;}const newGlyph = createWhitespaceGlyph(char, config, i, viewModel, paragraphNode, sectionBreakConfig, snapToGrid, traditionalLayout);+ if (char === DataStreamTreeTokenType.PARAGRAPH+ && sectionBreakConfig.renderConfig?.zeroWidthParagraphBreak === BooleanNumber.TRUE+ && sectionBreakConfig.renderConfig?.topAlignExactLineSpacing === BooleanNumber.TRUE) {+ let previousGlyph = shapedGlyphs[shapedGlyphs.length - 1];+ for (let index = shapedTextList.length - 1; !previousGlyph && index >= 0; index--) {+ const glyphs = shapedTextList[index].glyphs;+ previousGlyph = glyphs[glyphs.length - 1];+ }+ if (previousGlyph?.bBox.fontAscent != null && previousGlyph.bBox.fontDescent != null) {+ // A merged paragraph mark must not move surviving positioned text.+ const { ba, bd, normalLineHeight } = previousGlyph.bBox;+ newGlyph.bBox = { ...newGlyph.bBox, ba, bd, normalLineHeight };+ }+ }shapedGlyphs.push(newGlyph);i += char.length;@@ -655,14 +690,28 @@ export function shaping(}}+ // Keep the opt-out in glyph metrics so both line fitting and edge adjustment respect it.+ if (sectionBreakConfig.renderConfig?.preservePunctuationSpacing === BooleanNumber.TRUE) {+ for (const glyph of shapedGlyphs) {+ if (+ isCjkLeftAlignedPunctuation(glyph.content)+ || isCjkRightAlignedPunctuation(glyph.content)+ || isCjkCenterAlignedPunctuation(glyph.content)+ ) {+ glyph.adjustability.shrinkability = [0, 0];+ }+ }+ }+// With line compression enabled, Word resolves spacing for the whole line.// doNotCompress still retains fixed adjacent-punctuation spacing, including// East Asian quote/bracket pairs, independently of line justification.- if (!traditionalLayout || fixedPunctuationPairs) {+ if (sectionBreakConfig.renderConfig?.preservePunctuationSpacing !== BooleanNumber.TRUE+ && (!traditionalLayout || fixedPunctuationPairs)) {punctuationSpaceAdjustment(shapedGlyphs, fixedPunctuationPairs);}- appendShapedText(shapedTextList, shapedGlyphs, bk.type);+ appendShapedText(shapedTextList, shapedGlyphs, bk.type, paragraphStyle.fixedTabStops === BooleanNumber.TRUE);last = bk.position;}diff --git a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-skeleton.tsindex 043fde2098..14eee3c115 100644--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts@@ -63,6 +63,7 @@ import type {} from './document-layout-types';import type { IDocumentPaginationMetrics, ILayoutContext } from './tools';import {+ BaselineOffset,BooleanNumber,DataStreamTreeNodeType,DataStreamTreeTokenType,@@ -111,6 +112,7 @@ import { LanguageDetector } from './hyphenation/language-detector';import { createSkeletonPage } from './model/page';import { createSkeletonSection } from './model/section';import { resolveNoteReferences } from './note-numbering';+import { FontCache } from './shaping-engine/font-cache';import {getLastNotFullColumnInfo,getLastPage,@@ -945,6 +947,34 @@ function isHitTestAddressableGlyph(glyph: IDocumentSkeletonGlyph): boolean {(glyph.streamType === DataStreamTreeTokenType.PARAGRAPH && glyph.count > 0);}+function resolveUnclippedColumnHitBounds(column: IDocumentSkeletonColumnGroupColumn) {+ const bounds = { left: 0, top: 0, right: column.width, bottom: column.height };+ const page = column.page;+ for (const section of page.sections) {+ for (const nestedColumn of section.columns) {+ for (const line of nestedColumn.lines) {+ if (line.type === LineType.BLOCK) {+ continue;+ }+ const top = page.marginTop + section.top + line.top;+ bounds.top = Math.min(bounds.top, top);+ bounds.bottom = Math.max(bounds.bottom, top + line.lineHeight);+ for (const divide of line.divides) {+ const left = page.marginLeft + nestedColumn.left + (divide.left ?? 0) + (divide.paddingLeft ?? 0);+ for (const glyph of divide.glyphGroup) {+ if (!isHitTestAddressableGlyph(glyph)) {+ continue;+ }+ bounds.left = Math.min(bounds.left, left + glyph.left);+ bounds.right = Math.max(bounds.right, left + glyph.left + glyph.width);+ }+ }+ }+ }+ }+ return bounds;+}+function getFirstBodyFlowCharIndex(page: IDocumentSkeletonPage): number {for (const section of page.sections) {for (const column of section.columns) {@@ -2504,6 +2534,14 @@ export class DocumentSkeleton extends Skeleton {return this._skeletonData;}+ /** Invalidate measurements captured before the requested fonts finished loading. */+ invalidateFontMetrics(fontStyles: readonly string[]): void {+ for (const fontStyle of new Set(fontStyles)) {+ FontCache.clearFontMeasureCache(fontStyle);+ }+ this.makeDirty(true);+ }+/*** Refreshes Custom Block viewport-only metrics without rebuilding document flow.* Pure presentation metrics are published as one batch. Flow metrics are only@@ -3547,16 +3585,17 @@ export class DocumentSkeleton extends Skeleton {x: number,y: number,pageLength: number,- nestLevel: number = 0+ nestLevel: number = 0,+ allowPageOverflow = false): Nullable<INodeInfo> {this._findLiquid.translateSave();const { bounds, paddingLeft, paddingTop } = this._getHitTestPageLayout(segmentPage, pageType, page);const { left: pageLeft, right: pageRight, top: pageTop, bottom: pageBottom } = bounds;- let pointInPage = x >= pageLeft+ let pointInPage = allowPageOverflow || (x >= pageLeft&& x <= pageRight&& y >= pageTop- && y <= pageBottom;+ && y <= pageBottom);// Handle the outmost page.if (nestLevel === 0 && pageType === DocumentSkeletonPageType.BODY) {@@ -3732,12 +3771,13 @@ export class DocumentSkeleton extends Skeleton {const { top: columnGroupTop, left: columnGroupLeft, width: columnGroupWidth, height: columnGroupHeight, columns } = columnGroup;const absoluteColumnGroupLeft = this._findLiquid.x + columnGroupLeft;const absoluteColumnGroupTop = this._findLiquid.y + columnGroupTop;+ const allowOverflow = columnGroup.columnGroupSource?.clipContent === BooleanNumber.FALSE;if (- x < absoluteColumnGroupLeft ||+ !allowOverflow && (x < absoluteColumnGroupLeft ||x > absoluteColumnGroupLeft + columnGroupWidth ||y < absoluteColumnGroupTop ||- y > absoluteColumnGroupTop + columnGroupHeight+ y > absoluteColumnGroupTop + columnGroupHeight)) {continue;}@@ -3748,12 +3788,15 @@ export class DocumentSkeleton extends Skeleton {for (const column of columns) {const absoluteColumnLeft = absoluteColumnGroupLeft + column.left;const absoluteColumnTop = absoluteColumnGroupTop + column.top;+ const bounds = allowOverflow+ ? resolveUnclippedColumnHitBounds(column)+ : { left: 0, top: 0, right: column.width, bottom: column.height };if (- x < absoluteColumnLeft ||- x > absoluteColumnLeft + column.width ||- y < absoluteColumnTop ||- y > absoluteColumnTop + column.height+ x < absoluteColumnLeft + bounds.left ||+ x > absoluteColumnLeft + bounds.right ||+ y < absoluteColumnTop + bounds.top ||+ y > absoluteColumnTop + bounds.bottom) {continue;}@@ -3776,7 +3819,8 @@ export class DocumentSkeleton extends Skeleton {x,y,pageLength,- nestLevel + 1+ nestLevel + 1,+ allowOverflow) ?? this._getNearestNode(nestedCache.nearestNodeList, nestedCache.nearestNodeDistanceList);this._findLiquid.translateRestore();@@ -3797,6 +3841,9 @@ export class DocumentSkeleton extends Skeleton {y: number,nestLevel: number): Nullable<INodeInfo> {+ if (page.renderConfig?.useTextInkForHitTesting === BooleanNumber.TRUE) {+ return this._collectNearestInkNode(page, segment, cache, x, y, nestLevel);+ }let nearestDistanceY = Number.POSITIVE_INFINITY;const { x: originX, y: originY } = this._findLiquid;for (const section of page.sections) {@@ -3840,6 +3887,102 @@ export class DocumentSkeleton extends Skeleton {}}+ private _collectNearestInkNode(+ page: IDocumentSkeletonPage,+ segment: Pick<INodeInfo, 'segmentId' | 'segmentPage'>,+ cache: INearestCache,+ x: number,+ y: number,+ nestLevel: number+ ): Nullable<INodeInfo> {+ let nearestDistanceY = Number.POSITIVE_INFINITY;+ let positionedMatch: Nullable<INodeInfo>;+ let positionedDistance = Number.POSITIVE_INFINITY;+ let positionedMatchHasText = false;+ const { x: originX, y: originY } = this._findLiquid;+ for (const section of page.sections) {+ for (const column of section.columns) {+ for (const line of column.lines) {+ if (line.type === LineType.BLOCK) {+ continue;+ }+ const startY = originY + (section.top ?? 0) + line.top+ + (line.marginTop ?? 0) + (line.paddingTop ?? 0);+ const endY = startY + line.contentHeight;+ const hitsLine = y >= startY && y <= endY;+ for (const divide of line.divides) {+ const divideLeft = originX + column.left + divide.left + divide.paddingLeft;+ for (let index = 0; index < divide.glyphGroup.length; index++) {+ const glyph = divide.glyphGroup[index];+ if (!isHitTestAddressableGlyph(glyph)) {+ continue;+ }+ const startX = divideLeft + glyph.left;+ const endX = startX + glyph.width;+ const { bBox, ts } = glyph;+ let baseline = startY + line.asc;+ if (page.renderConfig?.applyTextPosition === BooleanNumber.TRUE+ && typeof ts?.pos === 'number' && Number.isFinite(ts.pos)) {+ baseline -= ts.pos * 4 / 3;+ }+ if (ts?.va === BaselineOffset.SUPERSCRIPT) {+ baseline -= bBox.spo;+ } else if (ts?.va === BaselineOffset.SUBSCRIPT) {+ baseline += bBox.sbo;+ }+ const hitsPaintedVerticalBounds = bBox.aba + bBox.abd > 0+ && y >= baseline - bBox.aba && y <= baseline + bBox.abd;+ const sameLine = hitsLine || hitsPaintedVerticalBounds;+ const distanceY = sameLine ? Number.NEGATIVE_INFINITY : Math.abs(y - endY);+ const node = { node: glyph, ...segment, ratioX: x / (startX + endX), ratioY: y / (startY + endY) };+ const hitsGlyphAdvance = x >= startX && x <= endX;+ if (sameLine) {+ const usesPositionedAdvance = ts?.textAdvance !== undefined && glyph.content.length === 1 && !ts.textSkewX;+ const previousGlyph = divide.glyphGroup[index - 1];+ const nextGlyph = divide.glyphGroup[index + 1];+ // Leader gaps should follow the nearer adjacent ink without attracting distant inline gaps.+ const hitsNeighborAdvance = usesPositionedAdvance && glyph.content.trim().length > 0 && bBox.width > 0 && (+ (previousGlyph && x >= divideLeft + previousGlyph.left && x <= divideLeft + previousGlyph.left + previousGlyph.width)+ || (nextGlyph && x >= divideLeft + nextGlyph.left && x <= divideLeft + nextGlyph.left + nextGlyph.width)+ );+ if (hitsGlyphAdvance || hitsNeighborAdvance) {+ const glyphDistanceY = Math.max(baseline - bBox.aba - y, y - baseline - bBox.abd, 0);+ const paintedLeft = startX + (glyph.xOffset ?? 0);+ // bBox.width already includes the horizontal character scale.+ const glyphDistanceX = usesPositionedAdvance+ ? Math.max(paintedLeft - x, x - paintedLeft - bBox.width, 0)+ : 0;+ const distance = Math.hypot(glyphDistanceX, glyphDistanceY);+ const hasText = glyph.content.trim().length > 0;+ if (distance === 0 && hitsGlyphAdvance && hasText) {+ return node;+ }+ // Empty advances remain selectable, but must not steal overlapping visible text.+ if ((hasText && !positionedMatchHasText)+ || (hasText === positionedMatchHasText && distance < positionedDistance)) {+ positionedMatch = node;+ positionedDistance = distance;+ positionedMatchHasText = hasText;+ }+ }+ }+ if (distanceY < nearestDistanceY) {+ nearestDistanceY = distanceY;+ cache.nearestNodeList = [];+ cache.nearestNodeDistanceList = [];+ }+ if (distanceY === nearestDistanceY) {+ cache.nearestNodeList.push(node);+ cache.nearestNodeDistanceList.push({ coordInPage: true, distance: Math.abs(x - endX), nestLevel });+ }+ }+ }+ }+ }+ }+ return positionedMatch;+ }+private _getNearestNode(nearestNodeList: INodeInfo[], nearestNodeDistanceList: IDistance[]) {if (nearestNodeDistanceList.length === 0) {return;@@ -4924,7 +5067,7 @@ export class DocumentSkeleton extends Skeleton {const viewModel = this.getViewModel();const dataModel = viewModel.getDataModel();const { headerTreeMap, footerTreeMap } = viewModel.getHeaderFooterTreeMap();- const { documentStyle, drawings, lists: customLists = {} } = dataModel;+ const { documentStyle, drawings, lists: customLists = {} } = viewModel.getSnapshot();const lists = {...PRESET_LIST_TYPE,...customLists,@@ -4943,7 +5086,10 @@ export class DocumentSkeleton extends Skeleton {drawings,localeService: this._localeService,- documentCompatibilityPolicy: getDocumentCompatibilityPolicy(documentStyle.documentFlavor),+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(+ documentStyle.documentFlavor,+ documentStyle.fontMetricScaleEnabled !== BooleanNumber.FALSE+ ),paragraphLineGapDefault,defaultTabStop,documentTextStyle: textStyle,diff --git a/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts b/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.tsindex 19af06ac5c..012ec50a07 100644--- a/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts+++ b/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts@@ -18,7 +18,7 @@ import type { ITextStyle } from '@univerjs/core';import type { IDocumentSkeletonGlyph } from '../../../../../basics/i-document-skeleton-cached';import type { IFontCreateConfig } from '../../../../../basics/interfaces';import { BooleanNumber, DataStreamTreeTokenType, DocumentFlavor, GridType } from '@univerjs/core';-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it, onTestFinished, vi } from 'vitest';import { GlyphType } from '../../../../../basics/i-document-skeleton-cached';import { getFontStyleString } from '../../../../../basics/tools';import { getDocumentCompatibilityPolicy } from '../../../document-compatibility';@@ -454,6 +454,42 @@ describe('Glyph utils test cases', () => {});});+ describe('test explicit text advance', () => {+ it('keeps fixed punctuation advances out of line shrink calculations', () => {+ const measureSpy = vi.spyOn(FontCache, 'getTextSize').mockReturnValue({+ width: 9,+ ba: 10,+ bd: 2,+ aba: 10,+ abd: 2,+ sp: 0,+ sbr: 0,+ sbo: 0,+ spr: 0,+ spo: 0,+ });+ onTestFinished(() => measureSpy.mockRestore());+ const glyph = createSkeletonLetterGlyph(',', {+ fontStyle: {+ fontString: 'normal normal 12pt Arial',+ fontSize: 12,+ originFontSize: 12,+ fontFamily: 'Arial',+ fontCache: 'normal normal 12pt Arial',+ },+ textStyle: { textAdvance: 12 },+ charSpace: 0,+ snapToGrid: 0,+ } as IFontCreateConfig);++ expect(glyph.width).toBe(12);+ expect(glyph.adjustability).toEqual({+ stretchability: [0, 0],+ shrinkability: [0, 0],+ });+ });+ });+describe('test glyphShrinkRight', () => {it('should shrink right', () => {const glyph = {@@ -658,6 +694,51 @@ describe('Glyph utils test cases', () => {});describe('test font compatibility policy', () => {+ it.each([+ {+ name: 'font glyph',+ metrics: undefined,+ expected: { ba: 13, bd: 5, fontAscent: 30, fontDescent: 9, aba: 24, abd: 6 },+ },+ {+ name: 'measured custom range',+ metrics: { ascent: 7, descent: 2 },+ expected: { ba: 7, bd: 2, fontAscent: undefined, fontDescent: undefined, aba: 7, abd: 2 },+ },+ ])('keeps caret metrics separate from fixed line metrics for a $name', ({ metrics, expected }) => {+ const font = 'normal normal 12pt FixedLineMetricsRegression';+ FontCache.setFontMeasureCache(font, 'A', {+ width: 16,+ fontBoundingBoxAscent: 30,+ fontBoundingBoxDescent: 9,+ actualBoundingBoxAscent: 24,+ actualBoundingBoxDescent: 6,+ });+ onTestFinished(() => {+ FontCache.clearFontMeasureCache(font);+ });+ const glyph = createSkeletonLetterGlyph('A', {+ fontStyle: {+ fontString: font,+ fontSize: 12,+ originFontSize: 12,+ fontFamily: 'FixedLineMetricsRegression',+ fontCache: font,+ },+ textStyle: { lineAscent: 13, lineDescent: 5 },+ charSpace: 0,+ snapToGrid: 0,+ } as IFontCreateConfig, metrics);++ const { fontAscent, fontDescent, ...expectedMetrics } = expected;+ expect(glyph.bBox).toMatchObject({+ ...expectedMetrics,+ normalLineHeight: 18,+ });+ expect(glyph.bBox.fontAscent).toBe(fontAscent);+ expect(glyph.bBox.fontDescent).toBe(fontDescent);+ });+it('should apply traditional font metric width rules to letter glyphs only when enabled', () => {const config: IFontCreateConfig = {fontStyle: {diff --git a/packages/engine-render/src/components/docs/layout/model/glyph.ts b/packages/engine-render/src/components/docs/layout/model/glyph.tsindex 509a98fc54..c0d2ddb76f 100644--- a/packages/engine-render/src/components/docs/layout/model/glyph.ts+++ b/packages/engine-render/src/components/docs/layout/model/glyph.ts@@ -192,9 +192,11 @@ export function createSkeletonLetterGlyph(if (typeof glyphMetrics === 'object' && config.textStyle.hidden !== true) {if (glyphMetrics.ascent != null) {glyph.bBox.ba = glyph.bBox.aba = glyphMetrics.ascent;+ delete glyph.bBox.fontAscent;}if (glyphMetrics.descent != null) {glyph.bBox.bd = glyph.bBox.abd = glyphMetrics.descent;+ delete glyph.bBox.fontDescent;}}@@ -495,6 +497,25 @@ export function _createSkeletonWordOrLetter(if (spacing) {bBox = { ...bBox, width: spacing.inkWidth };}+ const requestedLineAscent = textStyle.lineAscent;+ const requestedLineDescent = textStyle.lineDescent;+ if (+ typeof requestedLineAscent === 'number'+ && Number.isFinite(requestedLineAscent)+ && requestedLineAscent >= 0+ && typeof requestedLineDescent === 'number'+ && Number.isFinite(requestedLineDescent)+ && requestedLineDescent >= 0+ ) {+ bBox = {+ ...bBox,+ fontAscent: bBox.ba,+ fontDescent: bBox.bd,+ ba: requestedLineAscent,+ bd: requestedLineDescent,+ normalLineHeight: requestedLineAscent + requestedLineDescent,+ };+ }const { width: contentWidth = 0 } = bBox;let width = glyphWidth == null ? spacing?.width ?? contentWidth : glyphWidth * horizontalScale;@@ -506,6 +527,14 @@ export function _createSkeletonWordOrLetter(xOffset = (width - contentWidth) / 2;}}+ const requestedTextAdvance = textStyle.textAdvance;+ const hasFixedTextAdvance = typeof requestedTextAdvance === 'number'+ && Number.isFinite(requestedTextAdvance)+ && requestedTextAdvance >= 0+ && streamType !== DataStreamTreeTokenType.PARAGRAPH;+ if (hasFixedTextAdvance) {+ width = requestedTextAdvance * Array.from(content).length;+ }if (content === DataStreamTreeTokenType.PARAGRAPH && isTraditionalDocumentCompatibility(documentCompatibilityPolicy)) {// The end mark retains its font height, but occupies no grid cell in Word.@@ -513,6 +542,15 @@ export function _createSkeletonWordOrLetter(xOffset = 0;}+ const adjustability = hasFixedTextAdvance+ ? {+ stretchability: [0, 0] as [number, number],+ shrinkability: [0, 0] as [number, number],+ }+ : baseAdjustability(content, width, documentCompatibilityPolicy.mode === 'drawingml' && glyphWidth == null+ ? fontStyle.fontSize * (96 / 72)+ : width);+return {content,ts: textStyle,@@ -524,12 +562,10 @@ export function _createSkeletonWordOrLetter(glyphType,streamType,isJustifiable: isJustifiable(content),- adjustability: baseAdjustability(content, width, documentCompatibilityPolicy.mode === 'drawingml' && glyphWidth == null- ? fontStyle.fontSize * (96 / 72)- : width),+ adjustability,count: raw.length,raw,- ...(glyphWidth == null && !validationGrid(gridType, snapToGrid) && fontStyle.fontKerning === 'normal'+ ...(!hasFixedTextAdvance && glyphWidth == null && !validationGrid(gridType, snapToGrid) && fontStyle.fontKerning === 'normal'? { kerningAdjustment: 0 }: {}),...(spacing && spacing.segments.length > 1 ? { textSpacing: spacing } : {}),diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.tsindex f90ba93cb4..3ae2c5f8ea 100644--- a/packages/engine-render/src/components/docs/layout/tools.ts+++ b/packages/engine-render/src/components/docs/layout/tools.ts@@ -23,11 +23,7 @@ import type {INumberUnit,IObjectPositionH,IObjectPositionV,- IParagraph,IParagraphBorder,- IParagraphStyle,- ISectionBreak,- ITextStyle,Nullable,PositionedObjectLayoutType,} from '@univerjs/core';@@ -48,6 +44,13 @@ import type {import type { IDocsConfig, IParagraphConfig, ISectionBreakConfig } from '../../../basics/interfaces';import type { IBoundRectNoAngle } from '../../../basics/vector2';import type { IDocumentCompatibilityPolicy } from '../document-compatibility';+import type {+ IDocumentLayoutParagraph,+ IDocumentLayoutParagraphStyle,+ IDocumentLayoutSectionBreak,+ IDocumentLayoutStyle,+ IDocumentLayoutTextStyle,+} from '../document-layout-presentation';import type { DataStreamTreeNode } from '../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../view-model/document-view-model';import type { DocumentEndnoteLayout } from './endnote-layout';@@ -85,6 +88,7 @@ import { DEFAULT_DOCUMENT_FONTSIZE } from '../../../basics/const';import { GlyphType, LineType } from '../../../basics/i-document-skeleton-cached';import { getFontStyleString, isFunction, ptToPixel } from '../../../basics/tools';import { getDocumentCompatibilityPolicy } from '../document-compatibility';+import { getDocumentLayoutPresentation } from '../document-layout-presentation';import {getDocsTableRenderViewport,getDocsTableViewportLeft,@@ -769,7 +773,7 @@ export function updateParagraphBorders(segmentId?: string;target: boolean;}> = [];- const bordersByParagraphStyle = new Map<IParagraphStyle, IDocumentSkeletonParagraphBorders>();+ const bordersByParagraphStyle = new Map<IDocumentLayoutParagraphStyle, IDocumentSkeletonParagraphBorders>();lineIterator(pages, (line, _, __, page) => {const { segmentId } = page;@@ -1677,7 +1681,7 @@ export function getGlyphGroupWidth(divide: IDocumentSkeletonDivide, excludeTrailinterface IFontCreateConfig {documentCompatibilityPolicy?: IDocumentCompatibilityPolicy;fontStyle: IDocumentSkeletonFontStyle;- textStyle: ITextStyle;+ textStyle: IDocumentLayoutTextStyle;charSpace: number;gridType: GridType;snapToGrid: BooleanNumber;@@ -1694,7 +1698,7 @@ export function clearFontCreateConfigCache() {export function getFontConfigFromLastGlyph(glyph: IDocumentSkeletonGlyph,sectionBreakConfig: ISectionBreakConfig,- paragraphStyle: IParagraphStyle+ paragraphStyle: IDocumentLayoutParagraphStyle) {const { ts, fontStyle } = glyph;const {@@ -1738,7 +1742,7 @@ export function getFontCreateConfig(viewModel: DocumentViewModel,paragraphNode: DataStreamTreeNode,sectionBreakConfig: ISectionBreakConfig,- paragraph: IParagraph+ paragraph: IDocumentLayoutParagraph) {const {gridType = GridType.LINES,@@ -1769,7 +1773,7 @@ export function getFontCreateConfig(const customRangeStyle = showCustomRange ? getCustomRangeStyle(customRange) : null;const hasAddonStyle = showCustomRange || showCustomDecoration || !!bullet || paragraphStyle?.namedStyleType || paragraphStyle?.textStyle != null || paragraphStyle?.paragraphMarkTextStyle != null;const { st, ed } = textRun;- let textStyle: ITextStyle = textRun.ts ?? {};+ let textStyle: IDocumentLayoutTextStyle = textRun.ts ?? {};const cache = fontCreateConfigCache.getValue(st, ed);if (cache && !hasAddonStyle && originTextRun) {return cache;@@ -1800,7 +1804,7 @@ export function getFontCreateConfig(}: textStyle, sectionBreakConfig.fontFamilyFallbacks);- const mixTextStyle: ITextStyle = {+ const mixTextStyle: IDocumentLayoutTextStyle = {...documentTextStyle,...textStyle,};@@ -1955,7 +1959,7 @@ export interface ILayoutContext {endnoteLayout?: DocumentEndnoteLayout;/** Virtual marker in a note body; it never consumes a persisted character. */noteLabel?: string;- noteReferenceTextStyle?: ITextStyle;+ noteReferenceTextStyle?: IDocumentLayoutTextStyle;/** Preserve the local note segment when the paragraph/table pipeline opens a continuation page. */noteSegmentId?: string;footnoteFirstColumn?: { index: number; top: number };@@ -2009,7 +2013,7 @@ export interface ILayoutContext {languageDetector: LanguageDetector;}-const DEFAULT_SECTION_BREAK: ISectionBreak = {+const DEFAULT_SECTION_BREAK: IDocumentLayoutSectionBreak = {sectionId: 'section_render_default',columnProperties: [],columnSeparatorType: ColumnSeparatorType.NONE,@@ -2048,7 +2052,7 @@ const DEFAULT_MODERN_DOCUMENT_STYLE: IDocumentStyle = {marginFooter: 0,};-const DEFAULT_MODERN_SECTION_BREAK: Partial<ISectionBreak> = {+const DEFAULT_MODERN_SECTION_BREAK: Partial<IDocumentLayoutSectionBreak> = {columnProperties: [],columnSeparatorType: ColumnSeparatorType.NONE,sectionType: SectionType.SECTION_TYPE_UNSPECIFIED,@@ -2065,7 +2069,10 @@ const DEFAULT_MODERN_SECTION_BREAK: Partial<ISectionBreak> = {export function prepareSectionBreakConfig(ctx: ILayoutContext, nodeIndex: number) {const { viewModel, dataModel, docsConfig } = ctx;const sectionNode = viewModel.getChildren()[nodeIndex];- let { documentStyle } = dataModel;+ const presentation = getDocumentLayoutPresentation(dataModel);+ let documentStyle: IDocumentLayoutStyle = presentation+ ? presentation.getSnapshot(dataModel.getSnapshot()).documentStyle+ : dataModel.documentStyle;const { documentFlavor } = documentStyle;const explicitSectionBreak = viewModel.getSectionBreak(sectionNode.endIndex);let sectionBreak = explicitSectionBreak || DEFAULT_SECTION_BREAK;diff --git a/packages/engine-render/src/components/docs/view-model/document-view-model.ts b/packages/engine-render/src/components/docs/view-model/document-view-model.tsindex 89f7a764c8..f1bff01cfb 100644--- a/packages/engine-render/src/components/docs/view-model/document-view-model.ts+++ b/packages/engine-render/src/components/docs/view-model/document-view-model.ts@@ -16,21 +16,25 @@import type {DocumentDataModel,- IColumnGroup,ICustomBlock,- ICustomColumnGroup,ICustomDecorationForInterceptor,ICustomRangeForInterceptor,ICustomTable,IDisposable,- IParagraph,- ISectionBreak,ITable,- ITextRun,JSONXActions,JSONXPath,Nullable,} from '@univerjs/core';+import type {+ IDocumentLayoutBody,+ IDocumentLayoutColumnGroup,+ IDocumentLayoutCustomColumnGroup,+ IDocumentLayoutParagraph,+ IDocumentLayoutSectionBreak,+ IDocumentLayoutSnapshot,+ IDocumentLayoutTextRun,+} from '../document-layout-presentation';import {DataStreamTreeNodeType,DataStreamTreeTokenType,@@ -41,6 +45,7 @@ import {toDisposable,} from '@univerjs/core';import { BehaviorSubject } from 'rxjs';+import { getDocumentLayoutPresentation } from '../document-layout-presentation';import { DataStreamTreeNode } from './data-stream-tree-node';interface ITableCache {@@ -53,7 +58,7 @@ interface ITableNodeCache {}interface ITextRunCacheBucket {- runs: ITextRun[];+ runs: IDocumentLayoutTextRun[];isOrderedAndDisjoint: boolean;}@@ -135,7 +140,7 @@ function findByStartIndex<T extends IStartIndexedItem>(}}-function findOrderedTextRun(textRuns: readonly ITextRun[], index: number): ITextRun | undefined {+function findOrderedTextRun(textRuns: readonly IDocumentLayoutTextRun[], index: number): IDocumentLayoutTextRun | undefined {let low = 0;let high = textRuns.length - 1;while (low <= high) {@@ -502,8 +507,8 @@ interface ITableCoupleCache {}interface IColumnGroupCoupleCache {- columnGroup: ICustomColumnGroup;- columnGroupSource: IColumnGroup;+ columnGroup: IDocumentLayoutCustomColumnGroup;+ columnGroupSource: IDocumentLayoutColumnGroup;}export class DocumentViewModel implements IDisposable {@@ -513,9 +518,9 @@ export class DocumentViewModel implements IDisposable {private _textRunsCache: Map<number, ITextRunCacheBucket> = new Map();- private _paragraphCache: Map<number, IParagraph> = new Map();+ private _paragraphCache: Map<number, IDocumentLayoutParagraph> = new Map();- private _sectionBreakCache: Map<number, ISectionBreak> = new Map();+ private _sectionBreakCache: Map<number, IDocumentLayoutSectionBreak> = new Map();private _customBlockCache: Map<number, ICustomBlock> = new Map();@@ -547,7 +552,7 @@ export class DocumentViewModel implements IDisposable {private _columnGroupsOrdered = true;- private _lastTextRun: Nullable<ITextRun> = null;+ private _lastTextRun: Nullable<IDocumentLayoutTextRun> = null;private _editArea: DocumentEditArea = DocumentEditArea.BODY;@@ -632,12 +637,16 @@ export class DocumentViewModel implements IDisposable {return this._children;}- getBody() {- return this._documentDataModel.getBody();+ getBody(): IDocumentLayoutBody | undefined {+ const presentation = getDocumentLayoutPresentation(this._documentDataModel);+ return presentation+ ? presentation.getSnapshot(this._documentDataModel.getSnapshot()).body+ : this._documentDataModel.getBody();}- getSnapshot() {- return this._documentDataModel.getSnapshot();+ getSnapshot(): IDocumentLayoutSnapshot {+ const snapshot = this._documentDataModel.getSnapshot();+ return getDocumentLayoutPresentation(this._documentDataModel)?.getSnapshot(snapshot) ?? snapshot;}getDataModel() {@@ -760,7 +769,7 @@ export class DocumentViewModel implements IDisposable {return this._paragraphCache.get(index);}- getTextRun(index: number): Nullable<ITextRun> {+ getTextRun(index: number): Nullable<IDocumentLayoutTextRun> {if (this._metadataCachesDirty && this._textRunsOrderedAndDisjoint) {if (this._lastTextRun != null && index >= this._lastTextRun.st && index < this._lastTextRun.ed) {return this._lastTextRun;@@ -1117,7 +1126,7 @@ export class DocumentViewModel implements IDisposable {this._columnGroupCache.set(startIndex, {columnGroup,- columnGroupSource: columnGroup as IColumnGroup,+ columnGroupSource: columnGroup as IDocumentLayoutColumnGroup,});}}diff --git a/packages/engine-render/src/components/extension.ts b/packages/engine-render/src/components/extension.tsindex 87a72db732..15c8a49c5b 100644--- a/packages/engine-render/src/components/extension.ts+++ b/packages/engine-render/src/components/extension.ts@@ -14,10 +14,11 @@* limitations under the License.*/-import type { IDocumentRenderConfig, IRange, IScale, Nullable } from '@univerjs/core';+import type { IRange, IScale, Nullable } from '@univerjs/core';import type { BaseObject } from '../base-object';import type { IBoundRectNoAngle, Vector2 } from '../basics/vector2';import type { UniverRenderingContext } from '../context';+import type { IDocumentLayoutRenderConfig } from './docs/document-layout-presentation';import { Registry } from '@univerjs/core';import { getScale } from '../basics/tools';@@ -27,7 +28,7 @@ export interface IExtensionConfig {spanPointWithFont?: Vector2; // docscenterPoint?: Vector2;alignOffset?: Vector2;- renderConfig?: IDocumentRenderConfig;+ renderConfig?: IDocumentLayoutRenderConfig;}export interface IDrawInfo {diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.tsindex d2ca783540..dad342587f 100644--- a/packages/engine-render/src/index.ts+++ b/packages/engine-render/src/index.ts@@ -45,11 +45,29 @@ export * from './canvas';export * from './components';export type { DocsCustomBlockRenderViewportProvider, IDocsCustomBlockRenderViewport, IDocsCustomBlockRenderViewportInput } from './components/docs/custom-block-render-viewport';export { getDocsCustomBlockRenderViewport, setDocsCustomBlockRenderViewportProvider } from './components/docs/custom-block-render-viewport';+export {+ getDocCustomGlyphRenderer,+ registerDocCustomGlyphRenderer,+} from './components/docs/custom-glyph-renderer';+export type {+ DocCustomGlyphRenderer,+ IDocCustomGlyphRendererRegistration,+ IDocCustomGlyphRenderInput,+} from './components/docs/custom-glyph-renderer';export { DocBackground } from './components/docs/doc-background';export { DOCS_EXTENSION_TYPE } from './components/docs/doc-extension';export { Documents } from './components/docs/document';-export type { IPageRenderConfig } from './components/docs/document';-export type { IDocumentOffsetConfig } from './components/docs/document';+export type { IDocumentGlyphPaint, IDocumentOffsetConfig, IPageRenderConfig } from './components/docs/document';+export { getDocumentLayoutPresentation, registerDocumentLayoutPresentation } from './components/docs/document-layout-presentation';+export type {+ IDocumentLayoutBody,+ IDocumentLayoutParagraph,+ IDocumentLayoutParagraphStyle,+ IDocumentLayoutPresentation,+ IDocumentLayoutSnapshot,+ IDocumentLayoutTextRun,+ IDocumentLayoutTextStyle,+} from './components/docs/document-layout-presentation';export { getTableIdAndSliceIndex } from './components/docs/layout/block/table';export {measureDocumentNoWrapTextRangeWidth,@@ -130,5 +148,6 @@ export * from './scroll-timer';export { CanvasColorService, DumbCanvasColorService, ICanvasColorService } from './services/canvas-color.service';export * from './shape';export * from './viewport';+export { DocumentLayoutSession } from './worker-layout';export type { IDocumentLayoutSessionStartOptions, IDocumentLayoutStepResult } from './worker-layout';