Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(docs): honor paragraph word wrapping without changing cells (#8104)
白熱53dd618171e7
diff --git a/packages/core/src/docs/data-model/__tests__/paragraph-style.spec.ts b/packages/core/src/docs/data-model/__tests__/paragraph-style.spec.tsindex e4f55c1953..c24019d0aa 100644--- a/packages/core/src/docs/data-model/__tests__/paragraph-style.spec.ts+++ b/packages/core/src/docs/data-model/__tests__/paragraph-style.spec.ts@@ -14,11 +14,11 @@* limitations under the License.*/-import type { IDocStyles, IDocumentStyle } from '../../../types/interfaces';import { describe, expect, it } from 'vitest';-import { BooleanNumber } from '../../../types/enum';-import { DocStyleType, DocumentFlavor } from '../../../types/interfaces';-import { resolveDocumentParagraphStyle } from '../paragraph-style';+import type { IDocStyles, IDocumentData, IDocumentStyle, IParagraph } from '../../../types/interfaces/i-document-data';+import { BooleanNumber } from '../../../types/enum/text-style';+import { DocStyleType, DocumentFlavor } from '../../../types/interfaces/i-document-data';+import { resolveDocumentParagraphStyle, resolveDocumentParagraphWordWrap } from '../paragraph-style';describe('resolveDocumentParagraphStyle pagination', () => {const traditionalDocumentStyle: IDocumentStyle = {@@ -118,3 +118,26 @@ describe('resolveDocumentParagraphStyle pagination', () => {});});});++describe('resolveDocumentParagraphWordWrap', () => {+ it('resolves direct overrides, named style chains, document defaults and product defaults without changing source data', () => {+ const document: IDocumentData = {+ id: 'wrapping',+ documentStyle: { documentFlavor: DocumentFlavor.DRAWINGML, defaultParagraphStyle: { wordWrap: BooleanNumber.TRUE } },+ styles: {+ base: { type: DocStyleType.paragraph, name: 'Base', paragraphStyle: { wordWrap: BooleanNumber.FALSE } },+ derived: { type: DocStyleType.paragraph, name: 'Derived', basedOn: 'base' },+ },+ };+ const paragraph: IParagraph = { startIndex: 4, paragraphId: 'word-wrap', styleId: 'derived', paragraphStyle: { wordWrap: BooleanNumber.TRUE } };+ expect(resolveDocumentParagraphWordWrap(document, paragraph)).toBe(BooleanNumber.TRUE);+ delete paragraph.paragraphStyle!.wordWrap;+ expect(resolveDocumentParagraphWordWrap(document, paragraph)).toBe(BooleanNumber.FALSE);+ delete paragraph.styleId;+ expect(resolveDocumentParagraphWordWrap(document, paragraph)).toBe(BooleanNumber.TRUE);+ delete document.documentStyle.defaultParagraphStyle!.wordWrap;+ const snapshot = JSON.stringify({ document, paragraph });+ expect(resolveDocumentParagraphWordWrap(document, paragraph)).toBe(BooleanNumber.FALSE);+ expect(JSON.stringify({ document, paragraph })).toBe(snapshot);+ });+});diff --git a/packages/core/src/docs/data-model/paragraph-style.ts b/packages/core/src/docs/data-model/paragraph-style.tsindex 61a5e468ab..7c26e72aa3 100644--- a/packages/core/src/docs/data-model/paragraph-style.ts+++ b/packages/core/src/docs/data-model/paragraph-style.ts@@ -14,17 +14,17 @@* limitations under the License.*/-import type { Nullable } from '../../shared';-import type { IDocStyles, IDocumentStyle, IParagraphStyle } from '../../types/interfaces';-import { Tools } from '../../shared';+import type { Nullable } from '../../shared/types';+import type { IDocStyles, IDocumentData, IDocumentStyle, IParagraph, IParagraphStyle } from '../../types/interfaces/i-document-data';+import { Tools } from '../../shared/tools';import {DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING,DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE,DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW,NAMED_STYLE_SPACE_MAP,-} from '../../types/const';-import { BooleanNumber } from '../../types/enum';-import { DocStyleType, DocumentFlavor } from '../../types/interfaces';+} from '../../types/const/const';+import { BooleanNumber } from '../../types/enum/text-style';+import { DocStyleType, DocumentFlavor } from '../../types/interfaces/i-document-data';export interface IResolveDocumentParagraphStyleOptions {/** Exclude document-level outer spacing while retaining all other defaults. */@@ -122,3 +122,13 @@ export function resolveDocumentParagraphStyle(...definedParagraphStyle,});}++/** Resolves word splitting without materializing inherited defaults in the snapshot. */+export function resolveDocumentParagraphWordWrap(document: IDocumentData, paragraph?: IParagraph): BooleanNumber {+ const { documentStyle } = document;+ const { wordWrap } = resolveDocumentParagraphStyle(documentStyle, paragraph?.paragraphStyle, {+ styles: document.styles,+ paragraphStyleId: paragraph?.styleId,+ });+ return wordWrap ?? BooleanNumber.FALSE;+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 7f4a9ab3ac..3b20fc7086 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -61,6 +61,7 @@ export { mergeSets } from './common/set';export { UnitModel, UniverInstanceType } from './common/unit';export { isSafeUrl, normalizeUrl, resolveWithBasePath } from './common/url';export * from './docs';+export { resolveDocumentParagraphWordWrap } from './docs/data-model/paragraph-style';export { getSdtBindingKey, getSdtBindingValue } from './docs/sdt-binding';export { EventState, EventSubject, fromEventSubject } from './observer/observable';export type { IEventObserver } from './observer/observable';diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.tsindex 5224634caf..ac28cef35c 100644--- a/packages/core/src/types/interfaces/i-document-data.ts+++ b/packages/core/src/types/interfaces/i-document-data.ts@@ -1250,7 +1250,8 @@ export interface IParagraphProperties extends IIndentStart {* OOXML: 17.3.1.23 `pageBreakBefore`.*/pageBreakBefore?: BooleanNumber;- wordWrap?: BooleanNumber; // 17.3.1.45 wordWrap (Allow Line Breaking At Character Level)+ /** Allow words to split across lines. Absent inherits; DOCX w:wordWrap uses the inverse value. */+ wordWrap?: BooleanNumber;/*** Avoids leaving a single measured first or last line on a separate page* when the paragraph can be adjusted without violating stronger keep rules.diff --git a/packages/design/src/components/checkbox/Checkbox.tsx b/packages/design/src/components/checkbox/Checkbox.tsxindex 6da9ce3da1..1c69e5e450 100644--- a/packages/design/src/components/checkbox/Checkbox.tsx+++ b/packages/design/src/components/checkbox/Checkbox.tsx@@ -100,6 +100,7 @@ export function Checkbox(props: ICheckboxProps) {className="univer-absolute univer-size-0 univer-opacity-0"type="checkbox"checked={checked}+ aria-checked={indeterminate ? 'mixed' : checked}disabled={disabled}onChange={handleChange}/>diff --git a/packages/design/src/components/checkbox/__tests__/index.spec.tsx b/packages/design/src/components/checkbox/__tests__/Checkbox.spec.tsxsimilarity index 68%rename from packages/design/src/components/checkbox/__tests__/index.spec.tsxrename to packages/design/src/components/checkbox/__tests__/Checkbox.spec.tsxindex af6b6bfc48..7777d66bb2 100644--- a/packages/design/src/components/checkbox/__tests__/index.spec.tsx+++ b/packages/design/src/components/checkbox/__tests__/Checkbox.spec.tsx@@ -22,15 +22,18 @@ import { Checkbox } from '../Checkbox';afterEach(cleanup);describe('Checkbox', () => {- it('click Checkbox', async () => {+ it('exposes mixed selection to assistive technology', () => {+ const root = render(<Checkbox indeterminate>Wrapping</Checkbox>);+ expect(root.getByRole('checkbox').getAttribute('aria-checked')).toBe('mixed');+ root.rerender(<Checkbox checked>Wrapping</Checkbox>);+ expect(root.getByRole('checkbox').getAttribute('aria-checked')).toBe('true');+ });++ it('changes the checked state when clicked', () => {function Component() {const [checked, setChecked] = useState(false);- function handleChange(value: string | number | boolean) {- setChecked(value as boolean);- }-- return <Checkbox checked={checked} onChange={handleChange}>text</Checkbox>;+ return <Checkbox checked={checked} onChange={(value) => setChecked(value === true)}>text</Checkbox>;}const root = render(<Component />);diff --git a/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.tsindex 8f360c1f79..bc9c3215a9 100644--- a/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts@@ -14,8 +14,6 @@* limitations under the License.*/-/* eslint-disable ts/no-explicit-any */-import type { Dependency, DocumentDataModel, IDocumentData, Nullable } from '@univerjs/core';import type { DocumentSkeleton, IRenderContext, IRenderModule } from '@univerjs/engine-render';import {@@ -148,10 +146,10 @@ export function createCommandTestBed(docData?: IDocumentData, dependencies?: Depunit: doc,unitId: doc.getUnitId(),type: UniverInstanceType.UNIVER_DOC,- engine: null as any,- scene: null as any,- mainComponent: null as any,- components: null as any,+ engine: null!,+ scene: null!,+ mainComponent: null!,+ components: null!,isMainScene: true,activated$: new BehaviorSubject(true),activate: () => {},@@ -164,9 +162,9 @@ export function createCommandTestBed(docData?: IDocumentData, dependencies?: DeprenderManagerService.addRender(doc.getUnitId(), {unitId: doc.getUnitId(),type: UniverInstanceType.UNIVER_DOC,- engine: new DisposableCollection() as any,- scene: new DisposableCollection() as any,- mainComponent: null as any,+ engine: new DisposableCollection() as unknown as IRenderContext['engine'],+ scene: new DisposableCollection() as unknown as IRenderContext['scene'],+ mainComponent: null!,components: new Map(),isMainScene: true,activated$: new BehaviorSubject(true),diff --git a/packages/docs-ui/src/commands/commands/__tests__/doc-paragraph-setting.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/doc-paragraph-setting.command.spec.tsnew file mode 100644index 0000000000..bb2d9a364a--- /dev/null+++ b/packages/docs-ui/src/commands/commands/__tests__/doc-paragraph-setting.command.spec.ts@@ -0,0 +1,68 @@+/**+ * 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 { ICommand, IDocumentData } from '@univerjs/core';+import { awaitTime, BooleanNumber, DocStyleType, DocumentFlavor, ICommandService, RedoCommand, resolveDocumentParagraphWordWrap, UndoCommand } from '@univerjs/core';+import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';+import { expect, it } from 'vitest';+import { DocParagraphSettingCommand } from '../doc-paragraph-setting.command';+import { createCommandTestBed } from './create-command-test-bed';++it('persists paragraph word wrapping through mutations, undo and redo without changing inherited styles', async () => {+ const data: IDocumentData = {+ id: 'test-doc',+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, defaultParagraphStyle: { wordWrap: BooleanNumber.TRUE } },+ styles: { keep: { name: 'Keep words', type: DocStyleType.paragraph, paragraphStyle: { wordWrap: BooleanNumber.FALSE } } },+ body: {+ dataStream: '오늘 전략을\r오늘 전략을\r\n',+ paragraphs: [+ { startIndex: 6, paragraphId: 'first', styleId: 'keep', paragraphStyle: { spaceAbove: { v: 24 } } },+ { startIndex: 13, paragraphId: 'second' },+ ],+ },+ };+ const { univer, get, doc } = createCommandTestBed(data);+ try {+ const commands = get(ICommandService);+ commands.registerCommand(DocParagraphSettingCommand);+ commands.registerCommand(SetTextSelectionsOperation);+ commands.registerCommand(RichTextEditingMutation as unknown as ICommand);+ const selection = get(DocSelectionManagerService);+ selection.__TEST_ONLY_setCurrentSelection({ unitId: data.id, subUnitId: data.id });+ selection.__TEST_ONLY_add([{ startOffset: 0, endOffset: 13, collapsed: false, isActive: true, segmentId: '', style: null! }]);+ const values = () => doc.getBody()!.paragraphs!.map((paragraph) => resolveDocumentParagraphWordWrap(doc.getSnapshot(), paragraph));+ expect(values()).toEqual([0, 1]);+ for (const wordWrap of [BooleanNumber.FALSE, BooleanNumber.TRUE]) {+ expect(await commands.executeCommand(DocParagraphSettingCommand.id, { paragraph: { wordWrap } })).toBe(true);+ await awaitTime(0);+ expect(values()).toEqual([wordWrap, wordWrap]);+ const saved = JSON.parse(JSON.stringify(doc.getSnapshot())) as IDocumentData;+ expect(saved.body!.paragraphs!.map((paragraph) => paragraph.paragraphStyle?.wordWrap)).toEqual([wordWrap, wordWrap]);+ }+ await commands.executeCommand(UndoCommand.id);+ expect(values()).toEqual([0, 0]);+ await commands.executeCommand(UndoCommand.id);+ expect(values()).toEqual([0, 1]);+ expect(doc.getBody()!.paragraphs!.every((paragraph) => !Object.hasOwn(paragraph.paragraphStyle ?? {}, 'wordWrap'))).toBe(true);+ await commands.executeCommand(RedoCommand.id);+ expect(values()).toEqual([0, 0]);+ expect(doc.getBody()!.paragraphs![0].paragraphStyle?.spaceAbove).toEqual({ v: 24 });+ expect(doc.getSnapshot().styles).toEqual(data.styles);+ expect(doc.getSnapshot().documentStyle.defaultParagraphStyle).toEqual(data.documentStyle.defaultParagraphStyle);+ } finally {+ univer.dispose();+ }+});diff --git a/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.ts b/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.tsindex 3220862e1b..d52053daf5 100644--- a/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.ts+++ b/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.ts@@ -20,7 +20,7 @@ import { BuildTextUtils, CommandType, getRichTextEditPath, ICommandService, IUniimport { DocHistoryAction, DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';export interface IDocParagraphSettingCommandParams {- paragraph?: Partial<Pick<IParagraphStyle, 'hanging' | 'horizontalAlign' | 'spaceBelow' | 'spaceAbove' | 'indentEnd' | 'indentStart' | 'lineSpacing' | 'indentFirstLine' | 'snapToGrid' | 'spacingRule'>>;+ paragraph?: Partial<Pick<IParagraphStyle, 'hanging' | 'horizontalAlign' | 'spaceBelow' | 'spaceAbove' | 'indentEnd' | 'indentStart' | 'lineSpacing' | 'indentFirstLine' | 'snapToGrid' | 'spacingRule' | 'wordWrap'>>;};export const DocParagraphSettingCommand: ICommand<IDocParagraphSettingCommandParams> = {id: 'doc-paragraph-setting.command',@@ -69,6 +69,7 @@ export const DocParagraphSettingCommand: ICommand<IDocParagraphSettingCommandParfor (const paragraph of paragraphs) {const { startIndex } = paragraph;+ const paragraphStyle = { ...paragraph.paragraphStyle, ...config.paragraph };textX.push({t: TextXActionType.RETAIN,len: startIndex - memoryCursor.cursor,@@ -80,10 +81,7 @@ export const DocParagraphSettingCommand: ICommand<IDocParagraphSettingCommandPardataStream: '',paragraphs: [{...paragraph,- paragraphStyle: {- ...paragraph.paragraphStyle,- ...config.paragraph,- },+ paragraphStyle,startIndex: 0,}],},diff --git a/packages/docs-ui/src/locale/ar-SA.ts b/packages/docs-ui/src/locale/ar-SA.tsindex 024e214b3d..e80f51aacd 100644--- a/packages/docs-ui/src/locale/ar-SA.ts+++ b/packages/docs-ui/src/locale/ar-SA.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: 'إعدادات المقطع',},paragraphSetting: {+ wordWrap: 'السماح بالتفاف النص اللاتيني في وسط الكلمة',alignment: 'محاذاة',indentation: 'إزاحة',left: 'يسار',diff --git a/packages/docs-ui/src/locale/ca-ES.ts b/packages/docs-ui/src/locale/ca-ES.tsindex d6764faecd..5c5d149278 100644--- a/packages/docs-ui/src/locale/ca-ES.ts+++ b/packages/docs-ui/src/locale/ca-ES.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: 'Configuració de secció',},paragraphSetting: {+ wordWrap: 'Permet ajustar el text llatí al mig d’una paraula',alignment: 'Alineació',indentation: 'Sagnat',left: 'Esquerra',diff --git a/packages/docs-ui/src/locale/de-DE.ts b/packages/docs-ui/src/locale/de-DE.tsindex 82ea146a8d..230ebdecf8 100644--- a/packages/docs-ui/src/locale/de-DE.ts+++ b/packages/docs-ui/src/locale/de-DE.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: 'Abschnittseinstellungen',},paragraphSetting: {+ wordWrap: 'Textumbruch in der Mitte eines Wortes für westlichen Text zulassen',alignment: 'Ausrichtung',indentation: 'Einzug',left: 'Links',diff --git a/packages/docs-ui/src/locale/en-US.ts b/packages/docs-ui/src/locale/en-US.tsindex 20b21b7bac..5ee7b1949d 100644--- a/packages/docs-ui/src/locale/en-US.ts+++ b/packages/docs-ui/src/locale/en-US.ts@@ -183,6 +183,7 @@ const locale = {sectionSetting: 'Section Settings',},paragraphSetting: {+ wordWrap: 'Allow Latin text to wrap in the middle of a word',alignment: 'Alignment',indentation: 'Indentation',left: 'Left',diff --git a/packages/docs-ui/src/locale/es-ES.ts b/packages/docs-ui/src/locale/es-ES.tsindex 12b32a0f9c..e59b140f78 100644--- a/packages/docs-ui/src/locale/es-ES.ts+++ b/packages/docs-ui/src/locale/es-ES.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: 'Configuración de sección',},paragraphSetting: {+ wordWrap: 'Permitir ajuste de línea con división de palabra en el texto latino',alignment: 'Alineación',indentation: 'Sangría',left: 'Izquierda',diff --git a/packages/docs-ui/src/locale/fa-IR.ts b/packages/docs-ui/src/locale/fa-IR.tsindex 77be4c833d..ddab949972 100644--- a/packages/docs-ui/src/locale/fa-IR.ts+++ b/packages/docs-ui/src/locale/fa-IR.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: 'تنظیمات بخش',},paragraphSetting: {+ wordWrap: 'اجازه شکستن متن لاتین در میانهٔ کلمه',alignment: 'تراز',indentation: 'تورفتگی',left: 'چپ',diff --git a/packages/docs-ui/src/locale/fr-FR.ts b/packages/docs-ui/src/locale/fr-FR.tsindex 307d64586b..08e2231053 100644--- a/packages/docs-ui/src/locale/fr-FR.ts+++ b/packages/docs-ui/src/locale/fr-FR.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: 'Paramètres de section',},paragraphSetting: {+ wordWrap: 'Autoriser la césure en milieu de mot pour le texte en caractères latins',alignment: 'Alignement',indentation: 'Retrait',left: 'Gauche',diff --git a/packages/docs-ui/src/locale/id-ID.ts b/packages/docs-ui/src/locale/id-ID.tsindex 852dfcfa99..8863edcbe6 100644--- a/packages/docs-ui/src/locale/id-ID.ts+++ b/packages/docs-ui/src/locale/id-ID.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: 'Pengaturan bagian',},paragraphSetting: {+ wordWrap: 'Perbolehkan teks Latin untuk dibungkus di tengah kata',alignment: 'Perataan',indentation: 'Indentasi',left: 'Kiri',diff --git a/packages/docs-ui/src/locale/it-IT.ts b/packages/docs-ui/src/locale/it-IT.tsindex 8e7a8d845a..29547239ff 100644--- a/packages/docs-ui/src/locale/it-IT.ts+++ b/packages/docs-ui/src/locale/it-IT.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: 'Impostazioni sezione',},paragraphSetting: {+ wordWrap: 'Consenti sillabazione testo in alfabeto latino',alignment: 'Allineamento',indentation: 'Rientro',left: 'Sinistra',diff --git a/packages/docs-ui/src/locale/ja-JP.ts b/packages/docs-ui/src/locale/ja-JP.tsindex ef8366609d..421023f90f 100644--- a/packages/docs-ui/src/locale/ja-JP.ts+++ b/packages/docs-ui/src/locale/ja-JP.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: 'セクション設定',},paragraphSetting: {+ wordWrap: '英単語の途中で改行する',alignment: '配置',indentation: 'インデント',left: '左',diff --git a/packages/docs-ui/src/locale/ko-KR.ts b/packages/docs-ui/src/locale/ko-KR.tsindex 2e84a869fd..5f46d483f7 100644--- a/packages/docs-ui/src/locale/ko-KR.ts+++ b/packages/docs-ui/src/locale/ko-KR.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: '구역 설정',},paragraphSetting: {+ wordWrap: '영어 단어 잘림 허용',alignment: '정렬',indentation: '들여쓰기',left: '왼쪽',diff --git a/packages/docs-ui/src/locale/pl-PL.ts b/packages/docs-ui/src/locale/pl-PL.tsindex cbf516444b..a12d15185a 100644--- a/packages/docs-ui/src/locale/pl-PL.ts+++ b/packages/docs-ui/src/locale/pl-PL.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: 'Ustawienia sekcji',},paragraphSetting: {+ wordWrap: 'Zezwalaj na zawijanie tekstu łacińskiego w środku wyrazu',alignment: 'Wyrównanie',indentation: 'Wcięcie',left: 'Lewe',diff --git a/packages/docs-ui/src/locale/pt-BR.ts b/packages/docs-ui/src/locale/pt-BR.tsindex 8cdd55e2dc..32d62b0438 100644--- a/packages/docs-ui/src/locale/pt-BR.ts+++ b/packages/docs-ui/src/locale/pt-BR.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: 'Configurações da seção',},paragraphSetting: {+ wordWrap: 'Permitir quebra de texto latino no meio de uma palavra',alignment: 'Alinhamento',indentation: 'Recuo',left: 'Esquerda',diff --git a/packages/docs-ui/src/locale/ru-RU.ts b/packages/docs-ui/src/locale/ru-RU.tsindex 09f2c30e1a..13565246c5 100644--- a/packages/docs-ui/src/locale/ru-RU.ts+++ b/packages/docs-ui/src/locale/ru-RU.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: 'Параметры раздела',},paragraphSetting: {+ wordWrap: 'Разрешить перенос английского текста в середине слова',alignment: 'Выравнивание',indentation: 'Отступ',left: 'Левый',diff --git a/packages/docs-ui/src/locale/sk-SK.ts b/packages/docs-ui/src/locale/sk-SK.tsindex deea89ad83..3ca3473c04 100644--- a/packages/docs-ui/src/locale/sk-SK.ts+++ b/packages/docs-ui/src/locale/sk-SK.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: 'Nastavenia sekcie',},paragraphSetting: {+ wordWrap: 'Povoliť zalamovanie textu v latinke v strede slova',alignment: 'Zarovnanie',indentation: 'Odsadenie',left: 'Vľavo',diff --git a/packages/docs-ui/src/locale/vi-VN.ts b/packages/docs-ui/src/locale/vi-VN.tsindex 87744eee0a..2cc90bfc2d 100644--- a/packages/docs-ui/src/locale/vi-VN.ts+++ b/packages/docs-ui/src/locale/vi-VN.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: 'Cài đặt phần',},paragraphSetting: {+ wordWrap: 'Cho phép ngắt dòng văn bản Latinh ở giữa từ',alignment: 'Căn chỉnh',indentation: 'Thụt lề',left: 'Trái',diff --git a/packages/docs-ui/src/locale/zh-CN.ts b/packages/docs-ui/src/locale/zh-CN.tsindex 39d0f0b57b..ce72fc268a 100644--- a/packages/docs-ui/src/locale/zh-CN.ts+++ b/packages/docs-ui/src/locale/zh-CN.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: '节设置',},paragraphSetting: {+ wordWrap: '允许西文在单词中间换行',alignment: '对齐方式',indentation: '缩进',left: '左边距',diff --git a/packages/docs-ui/src/locale/zh-HK.ts b/packages/docs-ui/src/locale/zh-HK.tsindex c3d0f67f3f..14d5a54290 100644--- a/packages/docs-ui/src/locale/zh-HK.ts+++ b/packages/docs-ui/src/locale/zh-HK.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: '節設定',},paragraphSetting: {+ wordWrap: '允許英文字元在字中換行',alignment: '對齊',indentation: '縮排',left: '左',diff --git a/packages/docs-ui/src/locale/zh-TW.ts b/packages/docs-ui/src/locale/zh-TW.tsindex 845d0d3d78..63651b72d8 100644--- a/packages/docs-ui/src/locale/zh-TW.ts+++ b/packages/docs-ui/src/locale/zh-TW.ts@@ -185,6 +185,7 @@ const locale: typeof enUS = {sectionSetting: '節設定',},paragraphSetting: {+ wordWrap: '允許英文字元在字中換行',alignment: '對齊方式',indentation: '縮排',left: '左',diff --git a/packages/docs-ui/src/views/paragraph-setting/ParagraphWordWrapSetting.tsx b/packages/docs-ui/src/views/paragraph-setting/ParagraphWordWrapSetting.tsxnew file mode 100644index 0000000000..beb93d3240--- /dev/null+++ b/packages/docs-ui/src/views/paragraph-setting/ParagraphWordWrapSetting.tsx@@ -0,0 +1,85 @@+/**+ * 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 } from '@univerjs/core';+import { BooleanNumber, BuildTextUtils, ICommandService, IUniverInstanceService, LocaleService, resolveDocumentParagraphWordWrap, UniverInstanceType } from '@univerjs/core';+import { Checkbox } from '@univerjs/design';+import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';+import { useDependency } from '@univerjs/ui';+import { useCallback, useEffect, useState } from 'react';+import type { LocaleKey } from '../../locale/types';+import { DocParagraphSettingCommand } from '../../commands/commands/doc-paragraph-setting.command';++export function ParagraphWordWrapSetting() {+ const commandService = useDependency(ICommandService);+ const instanceService = useDependency(IUniverInstanceService);+ const selectionService = useDependency(DocSelectionManagerService);+ const localeService = useDependency(LocaleService);+ const label = localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.wordWrap');++ const readState = useCallback(() => {+ const document = instanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ const ranges = selectionService.getDocRanges();+ const body = document?.getSelfOrHeaderFooterModel(ranges[0]?.segmentId)?.getBody();+ const paragraphs = body && ranges.length+ ? BuildTextUtils.range.getParagraphsInRanges(ranges, body.paragraphs ?? [], body.dataStream) ?? []+ : [];+ const values = paragraphs.map((paragraph) => resolveDocumentParagraphWordWrap(document!.getSnapshot(), paragraph));+ return {+ checked: values[0] === BooleanNumber.TRUE,+ mixed: values.some((value) => value !== values[0]),+ disabled: paragraphs.length === 0,+ };+ }, [instanceService, selectionService]);++ const [state, setState] = useState(readState);+ const refresh = useCallback(() => setState(readState()), [readState]);++ useEffect(() => {+ const selection = selectionService.textSelection$.subscribe(refresh);+ const mutation = commandService.onCommandExecuted((command) => {+ if (command.id === RichTextEditingMutation.id) {+ refresh();+ }+ });+ return () => {+ selection.unsubscribe();+ mutation.dispose();+ };+ }, [commandService, refresh, selectionService]);++ const apply = async (checked: boolean) => {+ await commandService.executeCommand(DocParagraphSettingCommand.id, {+ paragraph: { wordWrap: checked ? BooleanNumber.TRUE : BooleanNumber.FALSE },+ });+ refresh();+ };+ return (+ <div+ data-u-editor-interaction-boundary="true"+ onMouseDown={(event) => event.preventDefault()}+ >+ <Checkbox+ checked={state.checked && !state.mixed}+ indeterminate={state.mixed}+ disabled={state.disabled}+ onChange={(checked) => apply(checked === true)}+ >+ {label}+ </Checkbox>+ </div>+ );+}diff --git a/packages/docs-ui/src/views/paragraph-setting/Setting.tsx b/packages/docs-ui/src/views/paragraph-setting/Setting.tsxindex ba51147b7c..e7930a9e3f 100644--- a/packages/docs-ui/src/views/paragraph-setting/Setting.tsx+++ b/packages/docs-ui/src/views/paragraph-setting/Setting.tsx@@ -15,12 +15,12 @@*/import type { ComponentType, ReactNode } from 'react';-import type { LocaleKey } from '../../locale/types';import { HorizontalAlign, LocaleService } from '@univerjs/core';import { borderClassName, Button, clsx, InputNumber, Select, Tooltip } from '@univerjs/design';import { AlignTextBothIcon, HorizontallyIcon, LeftJustifyingIcon, RightJustifyingIcon } from '@univerjs/icons';import { useDependency } from '@univerjs/ui';import { useMemo, useRef } from 'react';+import type { LocaleKey } from '../../locale/types';import {useCurrentParagraph,useFirstParagraphHorizontalAlign,@@ -33,6 +33,7 @@ import {useFirstParagraphSpaceBelow,} from './hook/utils';import { getLineSpacingInputConfig, LINE_SPACING_RULE_OPTIONS } from './line-spacing';+import { ParagraphWordWrapSetting } from './ParagraphWordWrapSetting';const ALIGNMENT_OPTIONS = [{ label: 'docs-ui.toolbar.alignLeft', value: String(HorizontalAlign.LEFT), icon: <LeftJustifyingIcon /> },@@ -244,6 +245,9 @@ export function ParagraphSetting({</RowComponent></div></ParagraphSettingSection>+ <div className="univer-mt-5">+ <ParagraphWordWrapSetting />+ </div></div>);}diff --git a/packages/docs-ui/src/views/paragraph-setting/__tests__/ParagraphWordWrapSetting.spec.tsx b/packages/docs-ui/src/views/paragraph-setting/__tests__/ParagraphWordWrapSetting.spec.tsxnew file mode 100644index 0000000000..9e5766149f--- /dev/null+++ b/packages/docs-ui/src/views/paragraph-setting/__tests__/ParagraphWordWrapSetting.spec.tsx@@ -0,0 +1,89 @@+/**+ * 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 { ICommand } from '@univerjs/core';+import { awaitTime, BooleanNumber, DocumentFlavor, ICommandService, LocaleService, LocaleType, UndoCommand } from '@univerjs/core';+import { ConfigProvider } from '@univerjs/design';+import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';+import { RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { expect, it } from 'vitest';+import { createCommandTestBed } from '../../../commands/commands/__tests__/create-command-test-bed';+import { DocParagraphSettingCommand } from '../../../commands/commands/doc-paragraph-setting.command';+import enUS from '../../../locale/en-US';+import { ParagraphWordWrapSetting } from '../ParagraphWordWrapSetting';++Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });++it('shows mixed paragraph settings, applies the checkbox and restores inherited values on undo', async () => {+ const { univer, injector, doc } = createCommandTestBed({+ id: 'test-doc',+ documentStyle: { documentFlavor: DocumentFlavor.MODERN },+ body: {+ dataStream: 'one\rtwo\r\n',+ paragraphs: [+ { startIndex: 3, paragraphId: 'one', paragraphStyle: { wordWrap: BooleanNumber.TRUE } },+ { startIndex: 7, paragraphId: 'two' },+ ],+ },+ });+ const commands = injector.get(ICommandService);+ commands.registerCommand(DocParagraphSettingCommand);+ commands.registerCommand(SetTextSelectionsOperation);+ commands.registerCommand(RichTextEditingMutation as unknown as ICommand);+ const selection = injector.get(DocSelectionManagerService);+ selection.__TEST_ONLY_setCurrentSelection({ unitId: 'test-doc', subUnitId: 'test-doc' });+ selection.__TEST_ONLY_add([{ startOffset: 0, endOffset: 7, collapsed: false, isActive: true, segmentId: '', style: null! }]);+ const locale = injector.get(LocaleService);+ locale.load({ [LocaleType.EN_US]: enUS });+ locale.setLocale(LocaleType.EN_US);+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);+ try {+ await act(async () => {+ root.render(<RediContext.Provider value={{ injector }}><ConfigProvider mountContainer={container}><ParagraphWordWrapSetting /></ConfigProvider></RediContext.Provider>);+ });+ const checkbox = container.querySelector<HTMLInputElement>('input[type="checkbox"]')!;+ expect(checkbox.getAttribute('aria-checked')).toBe('mixed');+ await act(async () => {+ checkbox.click();+ await awaitTime(0);+ });+ expect(checkbox.getAttribute('aria-checked')).not.toBe('mixed');+ expect(doc.getBody()!.paragraphs!.map((p) => p.paragraphStyle?.wordWrap)).toEqual([1, 1]);+ await act(async () => {+ checkbox.click();+ await awaitTime(0);+ });+ expect(checkbox.checked).toBe(false);+ expect(doc.getBody()!.paragraphs!.map((p) => p.paragraphStyle?.wordWrap)).toEqual([0, 0]);+ await act(async () => {+ await commands.executeCommand(UndoCommand.id);+ });+ expect(checkbox.checked).toBe(true);+ await act(async () => {+ await commands.executeCommand(UndoCommand.id);+ });+ expect(checkbox.getAttribute('aria-checked')).toBe('mixed');+ expect(doc.getBody()!.paragraphs!.map((p) => p.paragraphStyle?.wordWrap)).toEqual([1, undefined]);+ } finally {+ await act(async () => root.unmount());+ container.remove();+ univer.dispose();+ }+});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 a81878a640..0505855346 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@@ -14,11 +14,13 @@* limitations under the License.*/-import type { IDocLayoutExecutor } from '../doc-layout-executor.service';import {+ BooleanNumber,+ CellValueType,CommandService,ConfigService,ContextService,+ createInternalEditorID,DesktopLogService,DOCS_COMMENT_EDITOR_UNIT_ID_KEY,DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,@@ -36,8 +38,9 @@ import {UniverInstanceService,UniverInstanceType,} from '@univerjs/core';-import { registerDocumentLayoutPresentation } from '@univerjs/engine-render';+import { FontCache, registerDocumentLayoutPresentation } from '@univerjs/engine-render';import { afterEach, describe, expect, it, vi } from 'vitest';+import type { IDocLayoutExecutor } from '../doc-layout-executor.service';import {DocLayoutExecutorService,DocLayoutExecutorType,@@ -250,4 +253,61 @@ describe('DocSkeletonManagerService', () => {injector.dispose();}});++ it.each([+ { id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY, initial: ['오늘 전략', '을'], resized: ['오늘 전', '략을'] },+ { id: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, initial: ['오늘 전략', '을'], resized: ['오늘 전', '략을'] },+ { id: 'ordinary-document', initial: ['오늘 ', '전략을'], resized: ['오늘 ', '전략을'] },+ { id: createInternalEditorID('shape-word-wrap'), initial: ['오늘 ', '전략을'], resized: ['오늘 ', '전략을'] },+ ])('keeps host wrapping when alignment metadata is cleared and the editor is resized: $id', ({ id, initial, resized }) => {+ const measure = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text) => ({+ width: text.length * 10,+ fontBoundingBoxAscent: 10,+ fontBoundingBoxDescent: 2,+ actualBoundingBoxAscent: 10,+ actualBoundingBoxDescent: 2,+ }));+ const injector = new Injector();+ const document = injector.createInstance(DocumentDataModel, {+ id,+ body: {+ dataStream: '오늘 전략을\r\n',+ paragraphs: [{ startIndex: 6, paragraphId: 'korean', paragraphStyle: { snapToGrid: BooleanNumber.FALSE } }],+ },+ documentStyle: {+ documentFlavor: DocumentFlavor.UNSPECIFIED,+ textStyle: { lang: 'ko-KR' },+ pageSize: { width: 50, height: Infinity },+ marginTop: 0,+ marginBottom: 0,+ marginLeft: 0,+ marginRight: 0,+ renderConfig: { cellValueType: CellValueType.STRING, zeroWidthParagraphBreak: BooleanNumber.TRUE },+ },+ });+ const before = JSON.stringify(document.getSnapshot());+ const service = createService(document);+ const lines = () => {+ const pages = service.getSkeleton().getSkeletonData()!.pages;+ return pages+ .flatMap((page) => page.sections)+ .flatMap((section) => section.columns)+ .flatMap((column) => column.lines)+ .map((line) => line.divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content)).join('').replace(/\r$/, ''));+ };+ try {+ expect(lines()).toEqual(initial);+ expect(JSON.stringify(document.getSnapshot())).toBe(before);+ document.updateDocumentRenderConfig({ cellValueType: undefined });+ document.updateDocumentDataPageSize(40, Infinity);+ const resizedSnapshot = JSON.stringify(document.getSnapshot());+ service.recalculate();+ expect(lines()).toEqual(resized);+ expect(JSON.stringify(document.getSnapshot())).toBe(resizedSnapshot);+ } finally {+ service.dispose();+ injector.dispose();+ measure.mockRestore();+ }+ });});diff --git a/packages/docs/src/services/doc-skeleton-manager.service.ts b/packages/docs/src/services/doc-skeleton-manager.service.tsindex eb51d77386..12edce270c 100644--- a/packages/docs/src/services/doc-skeleton-manager.service.ts+++ b/packages/docs/src/services/doc-skeleton-manager.service.ts@@ -29,7 +29,7 @@ import {SHEET_TEXT_LINE_GAP,UniverInstanceType,} from '@univerjs/core';-import { DocumentSkeleton, DocumentViewModel, getDocumentLayoutPresentation } from '@univerjs/engine-render';+import { DocumentSkeleton, DocumentViewModel, getDocumentLayoutPresentation, SheetCellDocumentViewModel } from '@univerjs/engine-render';import { BehaviorSubject, takeUntil } from 'rxjs';import { DocLayoutExecutorService } from './doc-layout-executor.service';@@ -76,12 +76,6 @@ export class DocSkeletonManagerService extends RxDisposable implements IRenderMothis._currentSkeletonBefore$.complete();this._currentSkeleton$.complete();- // this._currentViewModel$.complete();-- // this._docViewModel?.dispose();-- //@ts-ignore- // delete this._docViewModel;}getSkeleton(): DocumentSkeleton {@@ -166,6 +160,8 @@ export class DocSkeletonManagerService extends RxDisposable implements IRenderMo}private _buildDocViewModel(documentDataModel: DocumentDataModel) {- return new DocumentViewModel(documentDataModel);+ return this._context.unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY || this._context.unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY+ ? new SheetCellDocumentViewModel(documentDataModel)+ : new DocumentViewModel(documentDataModel);}}diff --git a/packages/engine-render/src/basics/tools.ts b/packages/engine-render/src/basics/tools.tsindex d2ce7651d5..f9ca1c5a8c 100644--- a/packages/engine-render/src/basics/tools.ts+++ b/packages/engine-render/src/basics/tools.ts@@ -22,8 +22,6 @@ import type {ITextStyle,Nullable,} from '@univerjs/core';-import type { IDocumentSkeletonFontStyle } from './i-document-skeleton-cached';-import type { IBoundRectNoAngle } from './vector2';import {BaselineOffset,ColorKit,@@ -32,6 +30,8 @@ import {Rectangle,Tools,} from '@univerjs/core';+import type { IDocumentSkeletonFontStyle } from './i-document-skeleton-cached';+import type { IBoundRectNoAngle } from './vector2';import { FontCache } from '../components/docs/layout/shaping-engine/font-cache';import { DEFAULT_FONTFACE_PLANE } from './const';@@ -407,7 +407,7 @@ export function hasLatinExtendedB(text: string) {}// Emoji check logic-const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });+export const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });export function getFirstGrapheme(text: string): string | null {// One UTF-16 code unit cannot span multiple graphemes. CJK letter glyphs@@ -415,7 +415,7 @@ export function getFirstGrapheme(text: string): string | null {if (text.length <= 1) {return text || null;}- const it = segmenter.segment(text)[Symbol.iterator]();+ const it = graphemeSegmenter.segment(text)[Symbol.iterator]();return it.next().value?.segment ?? null;}diff --git a/packages/engine-render/src/components/docs/layout/__tests__/doc-no-wrap-measure.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/doc-no-wrap-measure.spec.tsindex 6876838933..7e655fabbf 100644--- a/packages/engine-render/src/components/docs/layout/__tests__/doc-no-wrap-measure.spec.ts+++ b/packages/engine-render/src/components/docs/layout/__tests__/doc-no-wrap-measure.spec.ts@@ -22,6 +22,7 @@ import {measureDocumentNoWrapTextRangeWidth,measureDocumentNoWrapTextWidth,measureDocumentUnbreakableTextWidth,+ measureDocumentWrappedTextWidth,} from '../doc-no-wrap-measure';import { FontCache } from '../shaping-engine/font-cache';@@ -204,6 +205,43 @@ describe('measureDocumentNoWrapTextWidth', () => {});describe('measureDocumentUnbreakableTextWidth', () => {+ it.each([+ { flavor: DocumentFlavor.MODERN, wordWidth: 30, wrappedWidth: 30 },+ { flavor: DocumentFlavor.TRADITIONAL, wordWidth: 30, wrappedWidth: 30 },+ { flavor: DocumentFlavor.UNSPECIFIED, wordWidth: 10, wrappedWidth: 50 },+ { flavor: DocumentFlavor.DRAWINGML, wordWidth: 30, wrappedWidth: 30 },+ { flavor: undefined, wordWidth: 10, wrappedWidth: 50 },+ ])('measures Korean wrapping with the host policy: $flavor', ({ flavor, wordWidth, wrappedWidth }) => {+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text) => ({ width: text.length * 10 }) as never);+ try {+ const document = createDocument('오늘 전략을\r\n');+ document.documentStyle.documentFlavor = flavor;+ expect(measureDocumentUnbreakableTextWidth(document)).toBe(wordWidth);+ expect(measureDocumentWrappedTextWidth(document, 50)).toBe(wrappedWidth);+ } finally {+ measureSpy.mockRestore();+ }+ });++ it('resolves each paragraph before measuring wrapping and minimum width', () => {+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text) => ({ width: text.length * 10 }) as never);+ try {+ const document = createDocument('오늘 전략을\r오늘 전략을\r');+ document.documentStyle.documentFlavor = DocumentFlavor.MODERN;+ document.documentStyle.defaultParagraphStyle = { wordWrap: BooleanNumber.TRUE };+ document.body!.paragraphs = [+ { startIndex: 6, paragraphId: 'first', paragraphStyle: { wordWrap: BooleanNumber.FALSE } },+ { startIndex: 13, paragraphId: 'second' },+ ];+ expect(measureDocumentUnbreakableTextWidth(document)).toBe(30);+ expect(measureDocumentWrappedTextWidth(document, 50)).toBe(50);+ document.documentStyle.defaultParagraphStyle.wordWrap = BooleanNumber.FALSE;+ expect(measureDocumentWrappedTextWidth(document, 50)).toBe(30);+ } finally {+ measureSpy.mockRestore();+ }+ });+it('uses the docs line-break policy for words, spaces, and CJK text', () => {const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({width: Array.from(text).reduce((total, char) => total + (/[⺀-鿿豈-]/u.test(char) ? 20 : 10), 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 8b6942940f..45111be410 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@@ -62,6 +62,111 @@ import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bedimport issue1207Snapshot from './fixtures/issue-1207-bullet-style.snapshot.json';describe('layout-ruler', () => {+ it('lays out a long unbroken Korean run without losing glyphs or overflowing the call stack', () => {+ const content = '한'.repeat(20000);+ const bed = createParagraphLayoutTestBed(content, {+ documentStyle: {+ documentFlavor: DocumentFlavor.MODERN,+ pageSize: { width: 100 + 2 * MODERN_DOCUMENT_DEFAULT_MARGIN, height: 800 },+ renderConfig: { zeroWidthParagraphBreak: BooleanNumber.TRUE },+ },+ });+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);+ try {+ skeleton.calculate();+ const lines = skeleton.getSkeletonData()!.pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));+ const text = lines.map((line) => line.divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content)).join(''));+ expect(text.join('')).toBe(`${content}\r`);+ expect(lines.length).toBeGreaterThan(1000);+ expect(lines.every((line) => line.divides.every((divide) => divide.glyphGroup.every((glyph) => glyph.left + glyph.width <= divide.width + 3)))).toBe(true);+ } finally {+ skeleton.dispose();+ bed.viewModel.dispose();+ bed.dataModel.dispose();+ }+ });++ it('retains mixed-font continuation heights when emergency wrapping a long word', () => {+ const measure = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text, font) => {+ const size = Number(font.match(/([\d.]+)(?:pt|px)/)?.[1] ?? 12);+ return { width: text.length * 10, fontBoundingBoxAscent: size, fontBoundingBoxDescent: 0, actualBoundingBoxAscent: size, actualBoundingBoxDescent: 0 };+ });+ const content = '한'.repeat(40);+ const bed = createParagraphLayoutTestBed(content, {+ documentStyle: {+ documentFlavor: DocumentFlavor.MODERN,+ pageSize: { width: 50 + 2 * MODERN_DOCUMENT_DEFAULT_MARGIN, height: 800 },+ renderConfig: { zeroWidthParagraphBreak: BooleanNumber.TRUE },+ },+ body: { textRuns: [{ st: 0, ed: 20, ts: { fs: 12 } }, { st: 20, ed: 40, ts: { fs: 30 } }] },+ });+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);+ try {+ skeleton.calculate();+ const lines = skeleton.getSkeletonData()!.pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));+ expect(lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content))).join('')).toBe(`${content}\r`);+ expect(lines.length).toBeGreaterThan(4);+ expect(lines.slice(1).map((line) => line.contentHeight)).toEqual(lines.slice(1).map(() => lines[0].contentHeight));+ } finally {+ measure.mockRestore();+ skeleton.dispose();+ bed.viewModel.dispose();+ bed.dataModel.dispose();+ }+ });++ it('keeps an oversized word out of narrow divides beside a floating picture in traditional documents', () => {+ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}\r${'한'.repeat(60)}`;+ const bed = createParagraphLayoutTestBed(content, {+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ pageSize: { width: 300, height: 800 },+ marginLeft: 0,+ marginRight: 0,+ marginTop: 0,+ marginBottom: 0,+ },+ body: {+ paragraphs: [{ startIndex: 1, paragraphId: 'anchor' }, { startIndex: content.length, paragraphId: 'text' }],+ customBlocks: [{ startIndex: 0, blockId: 'float' }],+ },+ drawings: {+ float: {+ drawingId: 'float',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ wrapText: WrapTextType.BOTH_SIDES,+ behindDoc: BooleanNumber.FALSE,+ distL: 0,+ distR: 0,+ distT: 0,+ distB: 0,+ docTransform: {+ size: { width: 140, height: 70 },+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 60 },+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 0 },+ angle: 0,+ },+ },+ },+ });+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);+ try {+ skeleton.calculate();+ const lines = skeleton.getSkeletonData()!.pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));+ const besidePicture = lines.filter((line) => line.paragraphIndex === content.length && line.top < 70);+ expect(besidePicture.length).toBeGreaterThan(1);+ for (const line of besidePicture) {+ const textDivides = line.divides.filter((divide) => divide.glyphGroup.some((glyph) => glyph.content === '한'));+ expect(textDivides).toHaveLength(1);+ expect(textDivides[0].left).toBeGreaterThanOrEqual(200);+ }+ } finally {+ skeleton.dispose();+ bed.viewModel.dispose();+ bed.dataModel.dispose();+ }+ });+it('does not skip a fixed tab stop after preceding text crosses it', () => {const tab = createGlyph(DataStreamTreeTokenType.TAB, 36);tab.glyphType = GlyphType.TAB;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 7fc1b3da27..4d515b0598 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@@ -21,6 +21,7 @@ import {CustomRangeType,DataStreamTreeTokenType,DocumentFlavor,+ MODERN_DOCUMENT_DEFAULT_MARGIN,NamedStyleType,PositionedObjectLayoutType,TabStopAlignment,@@ -39,6 +40,101 @@ import { shaping } from '../shaping';import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';describe('shaping', () => {+ it.each([+ { content: '오늘 전략을', inherited: 1, direct: undefined, lines: ['오늘 전략', '을'] },+ { content: '오늘 전략을', inherited: 1, direct: 0, lines: ['오늘 ', '전략을'] },+ { content: '오늘 전략을', inherited: 0, direct: 1, lines: ['오늘 전략', '을'] },+ { content: 'ab cdef', inherited: 1, direct: undefined, lines: ['ab cd', 'ef'] },+ { content: 'ab cdef', inherited: 1, direct: 0, lines: ['ab ', 'cdef'] },+ ])('honors inherited wrapping and direct overrides: $content / $inherited / $direct', ({ content, inherited, direct, lines }) => {+ const bed = createParagraphLayoutTestBed(content, {+ documentStyle: {+ documentFlavor: DocumentFlavor.DRAWINGML,+ defaultParagraphStyle: { wordWrap: inherited },+ pageSize: { width: 90, height: 600 },+ renderConfig: { zeroWidthParagraphBreak: BooleanNumber.TRUE },+ },+ body: {+ textRuns: [{ st: 0, ed: content.length, ts: { textAdvance: 10 } }],+ paragraphs: [{ startIndex: content.length, paragraphStyle: { wordWrap: direct, snapToGrid: BooleanNumber.FALSE } }],+ },+ });+ try {+ const shaped = shaping(bed.ctx, bed.paragraphNode.content!, bed.viewModel, bed.paragraphNode, bed.sectionBreakConfig);+ const pages = lineBreaking(bed.ctx, bed.viewModel, shaped, bed.curPage, bed.paragraphNode, bed.sectionBreakConfig, null);+ expect(pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)))+ .map((line) => line.divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content)).join('').replace(/\r$/, ''))).toEqual(lines);+ } finally {+ bed.viewModel.dispose();+ bed.dataModel.dispose();+ }+ });++ it.each([+ { flavor: DocumentFlavor.MODERN, lines: ['오늘 ', '전략을'] },+ { flavor: DocumentFlavor.TRADITIONAL, lines: ['오늘 ', '전략을'] },+ { flavor: DocumentFlavor.UNSPECIFIED, lines: ['오늘 전략', '을'] },+ { flavor: DocumentFlavor.DRAWINGML, lines: ['오늘 ', '전략을'] },+ { flavor: undefined, lines: ['오늘 ', '전략을'] },+ ])('wraps Korean words according to the host layout: $flavor', ({ flavor, lines }) => {+ const content = '오늘 전략을';+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ documentStyle: {+ documentFlavor: flavor,+ pageSize: { width: 50 + 2 * (flavor == null || flavor === DocumentFlavor.MODERN ? MODERN_DOCUMENT_DEFAULT_MARGIN : 20), height: 600 },+ renderConfig: { zeroWidthParagraphBreak: BooleanNumber.TRUE },+ },+ body: {+ textRuns: [{ st: 0, ed: content.length, ts: { textAdvance: 10 } }],+ paragraphs: [{ startIndex: content.length, paragraphStyle: { snapToGrid: BooleanNumber.FALSE } }],+ },+ });+ try {+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);+ const actual = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)))+ .map((line) => line.divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content)).join('').replace(/\r$/, ''));+ expect(actual).toEqual(lines);+ expect(dataModel.getBody()?.dataStream).toBe(`${content}\r\n`);+ } finally {+ viewModel.dispose();+ dataModel.dispose();+ }+ });++ it.each([DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL])('splits oversized Korean words only between graphemes: %s', (flavor) => {+ const segmenter = new Intl.Segmenter('ko', { granularity: 'grapheme' });+ const measure = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text) => ({+ width: [...segmenter.segment(text)].length * 10,+ fontBoundingBoxAscent: 10,+ fontBoundingBoxDescent: 2,+ actualBoundingBoxAscent: 10,+ actualBoundingBoxDescent: 2,+ }));+ const content = '한글단어'.normalize('NFD').repeat(128);+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {+ documentStyle: {+ documentFlavor: flavor,+ pageSize: { width: 20 + 2 * (flavor === DocumentFlavor.MODERN ? MODERN_DOCUMENT_DEFAULT_MARGIN : 20), height: 600 },+ renderConfig: { zeroWidthParagraphBreak: BooleanNumber.TRUE },+ },+ body: {+ paragraphs: [{ startIndex: content.length, paragraphStyle: { snapToGrid: BooleanNumber.FALSE } }],+ },+ });+ try {+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);+ const lines = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)))+ .map((line) => line.divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content)).join('').replace(/\r$/, ''));+ expect(lines).toEqual(Array.from({ length: 128 }, () => ['한글', '단어'].map((text) => text.normalize('NFD'))).flat());+ } finally {+ measure.mockRestore();+ viewModel.dispose();+ dataModel.dispose();+ }+ });+it.each([{ content: '/\t/\t/\t/', positions: [0, 100, 200, 300] },{ content: '/\t/1\t/\t/', positions: [0, 100, 200, 300] },@@ -1043,9 +1139,11 @@ describe('shaping', () => {];for (const token of columnTokens) {const glyph = createSkeletonLetterGlyph(token, {- fontStyle: {},+ fontStyle: getFontStyleString({}),textStyle: {},- } as any);+ charSpace: 0,+ snapToGrid: BooleanNumber.FALSE,+ });expect(glyph.raw).toBe(token);expect(glyph.streamType).toBe(token);@@ -1087,18 +1185,17 @@ describe('shaping', () => {const paragraph = viewModel.getParagraph(paragraphNode.endIndex)!;paragraph.paragraphStyle = { ...paragraph.paragraphStyle, suppressHyphenation: BooleanNumber.FALSE };- const fakeHyphen = {- hasPattern: vi.fn(() => false),- loadPattern: vi.fn(() => Promise.resolve()),- fetchHyphenCache: vi.fn(),- hyphenate: vi.fn(),- dispose: vi.fn(),- };- ctx.hyphen = fakeHyphen as any;- ctx.languageDetector = { detect: vi.fn(() => Lang.Fr), dispose: vi.fn() } as any;-- shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);- expect(fakeHyphen.loadPattern).toHaveBeenCalledWith(Lang.Fr);+ const hasPattern = vi.spyOn(ctx.hyphen, 'hasPattern').mockReturnValue(false);+ const loadPattern = vi.spyOn(ctx.hyphen, 'loadPattern').mockResolvedValue();+ const detect = vi.spyOn(ctx.languageDetector, 'detect').mockReturnValue(Lang.Fr);+ try {+ shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);+ expect(loadPattern).toHaveBeenCalledWith(Lang.Fr);+ } finally {+ hasPattern.mockRestore();+ loadPattern.mockRestore();+ detect.mockRestore();+ }});it('uses hyphen enhancer when hyphenation is enabled and pattern exists', () => {@@ -1107,18 +1204,15 @@ describe('shaping', () => {const paragraph = viewModel.getParagraph(paragraphNode.endIndex)!;paragraph.paragraphStyle = { ...paragraph.paragraphStyle, suppressHyphenation: BooleanNumber.FALSE };- const fakeHyphen = {- hasPattern: vi.fn(() => true),- loadPattern: vi.fn(() => Promise.resolve()),- fetchHyphenCache: vi.fn(),- hyphenate: vi.fn((word: string) => [word]),- dispose: vi.fn(),- };- ctx.hyphen = fakeHyphen as any;- ctx.languageDetector = { detect: vi.fn(() => Lang.EnUs), dispose: vi.fn() } as any;-- const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);- expect(result.length).toBeGreaterThan(0);- expect(fakeHyphen.loadPattern).not.toHaveBeenCalled();+ const loadPattern = vi.spyOn(ctx.hyphen, 'loadPattern');+ const detect = vi.spyOn(ctx.languageDetector, 'detect').mockReturnValue(Lang.EnUs);+ try {+ const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);+ expect(result.map((run) => run.text)).toEqual(['hy', 'phen', 'ation\r']);+ expect(loadPattern).not.toHaveBeenCalled();+ } finally {+ loadPattern.mockRestore();+ detect.mockRestore();+ }});});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 03729a7691..960774a22a 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@@ -666,9 +666,26 @@ function _appendOverflowingGlyphs(return;}const sliceGlyphGroup: IDocumentSkeletonGlyph[] = [];+ const firstGlyph = glyphGroup[0];+ // shortcut: mixed metrics keep whole-suffix layout until continuation heights can be preserved without rescanning.+ const uniformMetrics = glyphGroup.every((glyph) =>+ !glyph.noteId &&+ (__isStructuralTerminatorGlyph(glyph)+ ? glyph.bBox.ba <= firstGlyph.bBox.ba && glyph.bBox.bd <= firstGlyph.bBox.bd &&+ (glyph.bBox.normalLineHeight ?? 0) <= (firstGlyph.bBox.normalLineHeight ?? 0)+ : glyph.glyphType === GlyphType.LETTER && glyph.fontStyle?.fontString === firstGlyph.fontStyle?.fontString &&+ glyph.bBox.ba === firstGlyph.bBox.ba && glyph.bBox.bd === firstGlyph.bBox.bd &&+ glyph.bBox.normalLineHeight === firstGlyph.bBox.normalLineHeight)+ );+ const snapshot = ctx.viewModel.getSnapshot();+ // Word chooses divides using the remaining word width, including floats in later pages and stories.+ const canStreamGlyphs = uniformMetrics && (!isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)+ || (lastPage.skeDrawings.size === 0 && lastPage.skeTables.size === 0+ && [snapshot.drawings, snapshot.tableSource, snapshot.headers, snapshot.footers].every((source) => !source || Object.keys(source).length === 0)));- while (glyphGroup.length) {- sliceGlyphGroup.push(glyphGroup.shift()!);+ let consumed = 0;+ while (consumed < glyphGroup.length) {+ sliceGlyphGroup.push(glyphGroup[consumed++]);if (isGlyphGroupBeyondDivideWidth(sliceGlyphGroup,@@ -682,11 +699,13 @@ function _appendOverflowingGlyphs()) {// To avoid infinity loop when width is less than one char's width.if (sliceGlyphGroup.length > 1) { // || (sliceGlyphGroup.length > 0 && sliceGlyphGroup[sliceGlyphGroup.length - 1].drawingId)) {- glyphGroup.unshift(sliceGlyphGroup.pop()!);+ sliceGlyphGroup.pop();+ consumed--;}break;}}+ glyphGroup.splice(0, consumed);if (sliceGlyphGroup.length > 0) {// An oversized first glyph still owns its paragraph terminator;@@ -698,18 +717,31 @@ function _appendOverflowingGlyphs(}if (glyphGroup.length) {- // Only Divide in the first paragraph is the beginning of the paragraph- _divideOperator(- ctx,- glyphGroup,- pages,- sectionBreakConfig,- paragraphConfig,- false,-- breakPointType,- defaultSpanMetrics- );+ if (!canStreamGlyphs) {+ _divideOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, false, breakPointType, defaultSpanMetrics);+ return;+ }+ // The word already exceeds an empty line; consume its emergency breaks without rescanning the entire suffix.+ let tail = glyphGroup.length;+ while (tail > 0) {+ const glyph = glyphGroup[tail - 1];+ if (glyph.content !== DataStreamTreeTokenType.SPACE && !(drawingML && glyph.content === '\u3000') && !__isStructuralTerminatorGlyph(glyph)) {+ break;+ }+ tail--;+ }+ for (let index = 0; index < glyphGroup.length && index <= tail; index++) {+ _divideOperator(+ ctx,+ index === tail ? glyphGroup.slice(index) : [glyphGroup[index]],+ pages,+ sectionBreakConfig,+ paragraphConfig,+ false,+ index === tail || index === glyphGroup.length - 1 ? breakPointType : BreakPointType.Normal,+ defaultSpanMetrics+ );+ }}} else if (hyphenLineCount > consecutiveHyphenLimit) {const hyphenSliceGlyphGroup = _popHyphenSlice(divide);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 811a6eb47a..d0959364fb 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@@ -15,12 +15,6 @@*/import type { ICustomRangeForInterceptor, IParagraph, IParagraphStyle, Nullable } from '@univerjs/core';-import type { IDocumentSkeletonGlyph } from '../../../../../basics/i-document-skeleton-cached';-import type { ISectionBreakConfig } from '../../../../../basics/interfaces';-import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';-import type { DocumentViewModel } from '../../../view-model/document-view-model';-import type { IBreakPoints } from '../../line-breaker/line-breaker';-import type { ILayoutContext } from '../../tools';import {BaselineOffset,BooleanNumber,@@ -31,11 +25,17 @@ import {PositionedObjectLayoutType,resolveDocumentParagraphStyle,} from '@univerjs/core';+import type { IDocumentSkeletonGlyph } from '../../../../../basics/i-document-skeleton-cached';+import type { ISectionBreakConfig } from '../../../../../basics/interfaces';+import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';+import type { DocumentViewModel } from '../../../view-model/document-view-model';+import type { IBreakPoints } from '../../line-breaker/line-breaker';+import type { ILayoutContext } from '../../tools';import { cjk } from '../../../../../basics/cjk-regexp';import { GlyphType } from '../../../../../basics/i-document-skeleton-cached';import {- getFirstGrapheme,getFontStyleString,+ graphemeSegmenter,hasArabic,hasThai,hasTibetan,@@ -55,7 +55,6 @@ import { LineBreakerWholeEntityEnhancer } from '../../line-breaker/enhancers/whoimport { customBlockLineBreakExtension } from '../../line-breaker/extensions/custom-block-linebreak-extension';import { eastAsianQuoteLineBreakExtension } from '../../line-breaker/extensions/east-asian-quote-linebreak-extension';import { tabLineBreakExtension } from '../../line-breaker/extensions/tab-linebreak-extension';-import { LineBreaker } from '../../line-breaker/line-breaker';import {createSkeletonCustomBlockGlyph,createSkeletonLetterGlyph,@@ -398,10 +397,11 @@ function createShapingLineBreaker(paragraphNode: DataStreamTreeNode,sectionBreakConfig: ISectionBreakConfig,paragraph: IParagraph,+ resolvedParagraphStyle: IParagraphStyle,traditionalLayout: boolean,measuredWholeEntityRanges: ICustomRangeForInterceptor[]): IBreakPoints {- const lineBreaker = new LineBreaker(content);+ const lineBreaker = viewModel.createLineBreaker(content, resolvedParagraphStyle, paragraphNode.contentStartIndex);const { paragraphStyle = {} } = paragraph;const { hyphen } = ctx;@@ -428,12 +428,8 @@ function createShapingLineBreaker(}}- const documentSnapshot = viewModel.getSnapshot();- const { wordWrap } = resolveDocumentParagraphStyle(documentSnapshot.documentStyle, paragraphStyle, {- styles: documentSnapshot.styles,- paragraphStyleId: paragraph.styleId,- });- let breaker: IBreakPoints = new LineBreakerLinkEnhancer(lineBreaker, !traditionalLayout && wordWrap !== BooleanNumber.FALSE);+ const explicitWordWrap = resolvedParagraphStyle.wordWrap;+ let breaker: IBreakPoints = new LineBreakerLinkEnhancer(lineBreaker, !traditionalLayout && explicitWordWrap !== BooleanNumber.FALSE);const lang = getHyphenationLanguage(ctx, content, paragraphStyle, sectionBreakConfig);const doNotHyphenateCaps = sectionBreakConfig.doNotHyphenateCaps === BooleanNumber.TRUE;@@ -553,6 +549,12 @@ export function shaping(const paragraph = viewModel.getParagraph(endIndex) || { startIndex: 0, paragraphId: 'para_render_fallback' };const { paragraphStyle = {} } = paragraph;const { snapToGrid = BooleanNumber.TRUE } = paragraphStyle;+ const snapshot = viewModel.getSnapshot();+ const resolvedParagraphStyle = resolveDocumentParagraphStyle(snapshot.documentStyle, paragraphStyle, {+ styles: snapshot.styles,+ paragraphStyleId: paragraph.styleId,+ });+ const wordWrap = viewModel.getParagraphWordWrap(resolvedParagraphStyle);const measuredWholeEntityRanges = collectMeasuredWholeEntityRanges(content, viewModel, paragraphNode);const measuredWholeEntityRangeByStart = new Map(measuredWholeEntityRanges.map((range) => [range.startIndex - paragraphNode.contentStartIndex,@@ -571,6 +573,7 @@ export function shaping(paragraphNode,sectionBreakConfig,paragraph,+ resolvedParagraphStyle,traditionalLayout,measuredWholeEntityRanges);@@ -583,7 +586,7 @@ export function shaping(}// Word keeps Western names such as Breyer/Duitsland together. Oversized// words still use the layout ruler's normal emergency-break path.- if (traditionalLayout && bk.type === BreakPointType.Normal+ if (traditionalLayout && wordWrap !== BooleanNumber.TRUE && bk.type === BreakPointType.Normal&& /[a-z]\/[a-z]/i.test(content.slice(bk.position - 2, bk.position + 1))) {continue;}@@ -600,6 +603,7 @@ export function shaping(let src = word;let i = last;+ let graphemes: Intl.Segments | undefined;while (src.length > 0) {while (measuredWholeEntityRangeIndex < measuredWholeEntityRangeStarts.length &&@@ -650,8 +654,11 @@ export function shaping(src = src.substring(char.length);} else if (/\s/.test(char) || cjk.hasCJK(char)) {const config = getFontCreateConfig(i, viewModel, paragraphNode, sectionBreakConfig, paragraph);- if (config.textStyle.sc && cjk.hasCJK(char)) {- char = getFirstGrapheme(src) ?? char;+ if (cjk.hasCJK(char) && (config.textStyle.sc+ || (wordWrap != null && /\p{Script=Hangul}/u.test(char)))) {+ graphemes ??= graphemeSegmenter.segment(word);+ const grapheme = graphemes.containing(i - last);+ char = grapheme ? grapheme.segment.slice(i - last - grapheme.index) : char;}const newGlyph = createWhitespaceGlyph(char, config, i, viewModel, paragraphNode, sectionBreakConfig, snapToGrid, traditionalLayout);if (char === DataStreamTreeTokenType.PARAGRAPHdiff --git a/packages/engine-render/src/components/docs/layout/doc-no-wrap-measure.ts b/packages/engine-render/src/components/docs/layout/doc-no-wrap-measure.tsindex 657b1fa1f3..aaca1506ff 100644--- a/packages/engine-render/src/components/docs/layout/doc-no-wrap-measure.ts+++ b/packages/engine-render/src/components/docs/layout/doc-no-wrap-measure.ts@@ -15,13 +15,13 @@*/import type { IDocumentData, ITextRun, ITextStyle } from '@univerjs/core';+import { BooleanNumber, resolveDocumentParagraphStyle } from '@univerjs/core';import type { IDocumentSkeletonFontStyle } from '../../../basics/i-document-skeleton-cached';import type { IDocumentCompatibilityPolicy } from '../document-compatibility';-import { BooleanNumber } from '@univerjs/core';import { getFirstGrapheme, getFontStyleString, getTextWithCaps } from '../../../basics/tools';import { getDocumentCompatibilityPolicy, getSmallCapsFontStyle } from '../document-compatibility';-import { LineBreaker } from './line-breaker';import { BreakPointType } from './line-breaker/break';+import { createDocumentLineBreaker } from './line-breaker/document-line-breaker';import { getPairKerningAdjustment, measureTextWithCharacterSpacing } from './model/glyph';import { FontCache } from './shaping-engine/font-cache';@@ -257,6 +257,26 @@ export function measureDocumentNoWrapTextWidth(documentData: IDocumentData | nul);}+function* documentBreakPoints(document: IDocumentData) {+ const dataStream = document.body?.dataStream ?? '';+ const paragraphs = document.body?.paragraphs ?? [];+ let start = 0;+ for (const paragraph of [...paragraphs, undefined]) {+ const end = paragraph ? paragraph.startIndex + 1 : dataStream.length;+ const style = resolveDocumentParagraphStyle(document.documentStyle, paragraph?.paragraphStyle, {+ styles: document.styles,+ paragraphStyleId: paragraph?.styleId,+ });+ const breaker = createDocumentLineBreaker(document, style, dataStream.slice(start, end), start);+ let point = breaker.nextBreakPoint();+ while (point) {+ yield { position: start + point.position, type: point.type };+ point = breaker.nextBreakPoint();+ }+ start = end;+ }+}+/*** Measures the widest line after applying the docs Unicode break policy* within a fixed-width host.@@ -270,11 +290,11 @@ export function measureDocumentWrappedTextWidth(return 0;}- const breaker = new LineBreaker(dataStream);+ const breaker = documentBreakPoints(documentData);let lineStart = 0;let lastFittingEnd = 0;let widestLine = 0;- let breakPoint = breaker.nextBreakPoint();+ let breakPoint = breaker.next().value;while (breakPoint) {const candidateEnd = breakPoint.position;@@ -287,7 +307,7 @@ export function measureDocumentWrappedTextWidth(lineStart = candidateEnd;lastFittingEnd = candidateEnd;}- breakPoint = breaker.nextBreakPoint();+ breakPoint = breaker.next().value;continue;}@@ -303,7 +323,7 @@ export function measureDocumentWrappedTextWidth(widestLine = Math.max(widestLine, maxLineWidth);lineStart = candidateEnd;lastFittingEnd = candidateEnd;- breakPoint = breaker.nextBreakPoint();+ breakPoint = breaker.next().value;}if (lineStart < dataStream.length) {@@ -327,15 +347,15 @@ export function measureDocumentUnbreakableTextWidth(documentData: IDocumentDatareturn 0;}- const breaker = new LineBreaker(dataStream);+ const breaker = documentBreakPoints(documentData);let start = 0;let maxWidth = 0;- let breakPoint = breaker.nextBreakPoint();+ let breakPoint = breaker.next().value;while (breakPoint) {maxWidth = Math.max(maxWidth, measureDocumentNoWrapTextRangeWidth(documentData, start, breakPoint.position));start = breakPoint.position;- breakPoint = breaker.nextBreakPoint();+ breakPoint = breaker.next().value;}return maxWidth;diff --git a/packages/engine-render/src/components/docs/layout/doc-simple-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-simple-skeleton.tsindex 7d5799a08f..b6953fdbaa 100644--- a/packages/engine-render/src/components/docs/layout/doc-simple-skeleton.ts+++ b/packages/engine-render/src/components/docs/layout/doc-simple-skeleton.ts@@ -14,8 +14,8 @@* limitations under the License.*/-import { LineBreaker } from './line-breaker';import { BreakPointType } from './line-breaker/break';+import { LineBreaker } from './line-breaker/line-breaker';import { FontCache } from './shaping-engine/font-cache';export interface ILineInfo {diff --git a/packages/engine-render/src/components/docs/layout/line-breaker/__tests__/document-line-breaker.spec.ts b/packages/engine-render/src/components/docs/layout/line-breaker/__tests__/document-line-breaker.spec.tsnew file mode 100644index 0000000000..10437ca708--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/line-breaker/__tests__/document-line-breaker.spec.ts@@ -0,0 +1,102 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IDocumentData } from '@univerjs/core';+import { BooleanNumber, DocumentFlavor, resolveDocumentParagraphStyle } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { createDocumentLineBreaker } from '../document-line-breaker';++function segments(document: IDocumentData, text: string): string[] {+ const paragraph = document.body?.paragraphs?.[0];+ const style = resolveDocumentParagraphStyle(document.documentStyle, paragraph?.paragraphStyle, {+ styles: document.styles,+ paragraphStyleId: paragraph?.styleId,+ });+ const breaker = createDocumentLineBreaker(document, style, text, 0);+ const result: string[] = [];+ let start = 0;+ let point = breaker.nextBreakPoint();+ while (point) {+ result.push(text.slice(start, point.position));+ start = point.position;+ point = breaker.nextBreakPoint();+ }+ return result;+}++describe('document word wrapping', () => {+ it('uses authored Korean language for spreadsheet shapes while preserving Latin words in Korean runs', () => {+ const document: IDocumentData = {+ id: 'shape',+ documentStyle: { documentFlavor: DocumentFlavor.UNSPECIFIED, defaultParagraphStyle: { wordWrap: BooleanNumber.FALSE } },+ body: { dataStream: '오늘 전략을 abcdef', textRuns: [{ st: 0, ed: 13, ts: { lang: 'ko-KR' } }] },+ };+ expect(segments(document, document.body!.dataStream)).toEqual(['오늘 ', '전략을 ', 'abcdef']);+ document.documentStyle.defaultParagraphStyle!.wordWrap = BooleanNumber.TRUE;+ expect(segments(document, document.body!.dataStream)).toEqual(['오', '늘 ', '전', '략', '을 ', 'abcdef']);+ document.body!.textRuns = [];+ document.documentStyle.defaultParagraphStyle!.wordWrap = BooleanNumber.FALSE;+ expect(segments(document, document.body!.dataStream)).toEqual(['오', '늘 ', '전', '략', '을 ', 'abcdef']);+ });++ it('recognizes Korean in Word documents with English document defaults', () => {+ const document: IDocumentData = {+ id: 'doc',+ documentStyle: { documentFlavor: DocumentFlavor.MODERN, textStyle: { lang: 'en-US' } },+ };+ expect(segments(document, '오늘 전략을')).toEqual(['오늘 ', '전략을']);+ });++ it('keeps adjacent Latin and Hangul in one word without joining Chinese characters', () => {+ const document: IDocumentData = {+ id: 'mixed',+ documentStyle: { documentFlavor: DocumentFlavor.MODERN },+ };+ expect(segments(document, 'abc한글xyz 中文')).toEqual(['abc한글xyz ', '中', '文']);+ });++ it('does not require a persisted default to keep authored Korean shape text together', () => {+ const document: IDocumentData = {+ id: 'shape',+ documentStyle: { documentFlavor: DocumentFlavor.UNSPECIFIED, textStyle: { lang: 'ko-KR' } },+ };+ expect(segments(document, '오늘 전략을')).toEqual(['오늘 ', '전략을']);+ expect(document.documentStyle.defaultParagraphStyle).toBeUndefined();+ });++ it('resolves language from the matching run when shaping a later paragraph', () => {+ const text = 'before\r오늘 전략을';+ const document: IDocumentData = {+ id: 'shape',+ documentStyle: { documentFlavor: DocumentFlavor.UNSPECIFIED, defaultParagraphStyle: { wordWrap: BooleanNumber.FALSE } },+ body: { dataStream: text, textRuns: [{ st: 0, ed: 7, ts: { lang: 'en-US' } }, { st: 7, ed: text.length, ts: { lang: 'ko-KR' } }] },+ };+ const breaker = createDocumentLineBreaker(document, {}, text.slice(7), 7);+ expect(breaker.nextBreakPoint()?.position).toBe(3);+ expect(breaker.nextBreakPoint()?.position).toBe(6);+ expect(breaker.nextBreakPoint()).toBeNull();+ });++ it('keeps grapheme clusters intact and resolves language changes in mixed text', () => {+ const text = 'ab e\u0301f 오늘 전략을';+ const document: IDocumentData = {+ id: 'doc',+ documentStyle: { documentFlavor: DocumentFlavor.MODERN, defaultParagraphStyle: { wordWrap: BooleanNumber.TRUE } },+ body: { dataStream: text, textRuns: [{ st: 0, ed: 7, ts: { lang: 'en-US' } }, { st: 7, ed: text.length, ts: { lang: 'ko-KR' } }] },+ };+ expect(segments(document, text)).toEqual(['a', 'b ', 'e\u0301', 'f ', '오', '늘 ', '전', '략', '을']);+ });+});diff --git a/packages/engine-render/src/components/docs/layout/line-breaker/__tests__/linebreak.spec.ts b/packages/engine-render/src/components/docs/layout/line-breaker/__tests__/line-breaker.spec.tssimilarity index 50%rename from packages/engine-render/src/components/docs/layout/line-breaker/__tests__/linebreak.spec.tsrename to packages/engine-render/src/components/docs/layout/line-breaker/__tests__/line-breaker.spec.tsindex 7766cdd3c2..e21aed452d 100644--- a/packages/engine-render/src/components/docs/layout/line-breaker/__tests__/linebreak.spec.ts+++ b/packages/engine-render/src/components/docs/layout/line-breaker/__tests__/line-breaker.spec.ts@@ -14,21 +14,97 @@* limitations under the License.*/-/* eslint-disable antfu/consistent-list-newline */+import { BooleanNumber } from '@univerjs/core';import fs from 'node:fs';import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';+import type { BreakPointType } from '../break';import { eastAsianQuoteLineBreakExtension } from '../extensions/east-asian-quote-linebreak-extension';import { tabLineBreakExtension } from '../extensions/tab-linebreak-extension';-import { LineBreaker } from '../line-breaker';+import { DocumentLineBreaker, LineBreaker } from '../line-breaker';++it.each(['NFC', 'NFD'] as const)('keeps Korean words intact while preserving mandatory breaks (%s)', (normalization) => {+ const words = ['오늘 ', '회의에서 ', '다음 ', '분기 ', '마케팅 ', '전략을 ', '논의했습니다\r\n', '다음 ', '회의'];+ const content = words.join('').normalize(normalization);+ const breaker = new DocumentLineBreaker(content, BooleanNumber.FALSE);+ const parts: string[] = [];+ let start = 0;+ for (let point = breaker.nextBreakPoint(); point; point = breaker.nextBreakPoint()) {+ parts.push(content.slice(start, point.position));+ start = point.position;+ }+ expect(parts).toEqual(words.map((word) => word.normalize(normalization)));+});++it('keeps nonbreaking spaces inside Korean words', () => {+ const content = '오늘\u00A0회의';+ const breaker = new DocumentLineBreaker(content, BooleanNumber.FALSE);+ expect(breaker.nextBreakPoint()?.position).toBe(content.length);+ expect(breaker.nextBreakPoint()).toBeNull();+});it('passes supported Unicode line break tests', () => {// these tests are weird, possibly incorrect or just tailored differently. we skip them.const skip = [- 125, 127, 815, 1161, 1163, 1165, 1167, 1331, 2189, 2191, 2873, 2875, 3567, 3739, 4081, 4083, 4425, 4427, 4473,- 4475, 4597, 4599, 4645, 4647, 4943, 5109, 5111, 5459, 6149, 6151, 6153, 6155, 6489, 6491, 6663, 6833, 6835,- 7005, 7007, 7177, 7179, 7477, 7486, 7491, 7576, 7577, 7578, 7579, 7580, 7581, 7583, 7584, 7585, 7586, 7587,- 7604, 7610, 7611, 7681,+ 125,+ 127,+ 815,+ 1161,+ 1163,+ 1165,+ 1167,+ 1331,+ 2189,+ 2191,+ 2873,+ 2875,+ 3567,+ 3739,+ 4081,+ 4083,+ 4425,+ 4427,+ 4473,+ 4475,+ 4597,+ 4599,+ 4645,+ 4647,+ 4943,+ 5109,+ 5111,+ 5459,+ 6149,+ 6151,+ 6153,+ 6155,+ 6489,+ 6491,+ 6663,+ 6833,+ 6835,+ 7005,+ 7007,+ 7177,+ 7179,+ 7477,+ 7486,+ 7491,+ 7576,+ 7577,+ 7578,+ 7579,+ 7580,+ 7581,+ 7583,+ 7584,+ 7585,+ 7586,+ 7587,+ 7604,+ 7610,+ 7611,+ 7681,];const data = fs.readFileSync(resolve(__dirname, 'LineBreakTest.txt'), 'utf8');@@ -36,12 +112,11 @@ it('passes supported Unicode line break tests', () => {return lines.forEach((line, i) => {const rowNumber = i + 1;- let bk;if (!line || line.startsWith('#') || skip.includes(rowNumber)) {return;}- const [cols, comment] = line.split('#');+ const [cols] = line.split('#');const codePoints = cols.split(/\s*[×÷]\s*/).slice(1, -1)@@ -51,7 +126,7 @@ it('passes supported Unicode line break tests', () => {const breaker = new LineBreaker(str);const breaks: string[] = [];let last = 0;- while ((bk = breaker.nextBreakPoint())) {+ for (let bk = breaker.nextBreakPoint(); bk; bk = breaker.nextBreakPoint()) {breaks.push(str.slice(last, bk.position));last = bk.position;}@@ -72,6 +147,30 @@ it('passes supported Unicode line break tests', () => {});});+it('preserves Unicode break opportunities outside Hangul when word splitting is disabled', () => {+ const lines = fs.readFileSync(resolve(__dirname, 'LineBreakTest.txt'), 'utf8').split('\n');+ for (const line of lines) {+ if (!line || line.startsWith('#')) {+ continue;+ }+ const content = String.fromCodePoint(...line.split('#')[0].split(/\s*[×÷]\s*/)+ .slice(1, -1)+ .map((code) => Number.parseInt(code, 16)));+ if (/\p{Script=Hangul}/u.test(content)) {+ continue;+ }+ const positions = (wordWrap?: BooleanNumber) => {+ const breaker = wordWrap == null ? new LineBreaker(content) : new DocumentLineBreaker(content, wordWrap);+ const result: Array<{ position: number; type: BreakPointType }> = [];+ for (let point = breaker.nextBreakPoint(); point; point = breaker.nextBreakPoint()) {+ result.push({ position: point.position, type: point.type });+ }+ return result;+ };+ expect(positions(BooleanNumber.FALSE), line).toEqual(positions());+ }+});+describe('line break extensions tests', () => {it('should allow an East Asian line to break before a smart opening quote', () => {const data = '力” 、“年度';@@ -79,9 +178,8 @@ describe('line break extensions tests', () => {eastAsianQuoteLineBreakExtension(breaker);const breaks: string[] = [];let last = 0;- let bk;- while ((bk = breaker.nextBreakPoint())) {+ for (let bk = breaker.nextBreakPoint(); bk; bk = breaker.nextBreakPoint()) {breaks.push(data.slice(last, bk.position));last = bk.position;}@@ -95,9 +193,8 @@ describe('line break extensions tests', () => {tabLineBreakExtension(breaker);const breaks: string[] = [];let last = 0;- let bk;- while ((bk = breaker.nextBreakPoint())) {+ for (let bk = breaker.nextBreakPoint(); bk; bk = breaker.nextBreakPoint()) {breaks.push(data.slice(last, bk.position));last = bk.position;}@@ -111,9 +208,8 @@ describe('line break extensions tests', () => {tabLineBreakExtension(breaker);const breaks: string[] = [];let last = 0;- let bk;- while ((bk = breaker.nextBreakPoint())) {+ for (let bk = breaker.nextBreakPoint(); bk; bk = breaker.nextBreakPoint()) {breaks.push(data.slice(last, bk.position));last = bk.position;}diff --git a/packages/engine-render/src/components/docs/layout/line-breaker/document-line-breaker.ts b/packages/engine-render/src/components/docs/layout/line-breaker/document-line-breaker.tsnew file mode 100644index 0000000000..f64c5b6dd3--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/line-breaker/document-line-breaker.ts@@ -0,0 +1,53 @@+/**+ * 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 { IDocumentBody, IDocumentData, IParagraphStyle } from '@univerjs/core';+import { BooleanNumber, DocumentFlavor } from '@univerjs/core';+import { DocumentLineBreaker, LineBreaker } from './line-breaker';++export function createDocumentLineBreaker(document: IDocumentData, paragraphStyle: IParagraphStyle, content: string, start: number, body: IDocumentBody | undefined = document.body): LineBreaker {+ const wordWrap = paragraphStyle.wordWrap ?? BooleanNumber.FALSE;+ if (wordWrap === BooleanNumber.FALSE ? !/\p{Script=Hangul}/u.test(content) : !/\p{Script=Latin}/u.test(content)) {+ return new LineBreaker(content);+ }+ const inferKorean = document.documentStyle?.documentFlavor === DocumentFlavor.MODERN+ || document.documentStyle?.documentFlavor === DocumentFlavor.TRADITIONAL+ || document.documentStyle?.documentFlavor === DocumentFlavor.DRAWINGML;+ if (wordWrap === BooleanNumber.FALSE && inferKorean) {+ return new DocumentLineBreaker(content, wordWrap);+ }+ const defaultLanguage = paragraphStyle.textStyle?.lang ?? document.documentStyle?.textStyle?.lang;+ const runs = body?.textRuns ?? [];+ let runIndex = 0;+ let end = runs.length;+ while (runIndex < end) {+ const middle = (runIndex + end) >>> 1;+ if (runs[middle].ed <= start) {+ runIndex = middle + 1;+ } else {+ end = middle;+ }+ }+ return new DocumentLineBreaker(content, wordWrap, (offset) => {+ const index = start + offset;+ while (runIndex < runs.length && runs[runIndex].ed <= index) {+ runIndex++;+ }+ const run = runs[runIndex];+ // Excel shapes require authored Korean language; Docs and Slides also recognize Hangul without that marker.+ return (run && run.st <= index ? run.ts?.lang : undefined) ?? defaultLanguage;+ }, inferKorean);+}diff --git a/packages/engine-render/src/components/docs/layout/line-breaker/index.ts b/packages/engine-render/src/components/docs/layout/line-breaker/index.tsdeleted file mode 100644index 846737b602..0000000000--- a/packages/engine-render/src/components/docs/layout/line-breaker/index.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * 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.- */--export { LineBreaker } from './line-breaker';diff --git a/packages/engine-render/src/components/docs/layout/line-breaker/line-breaker.ts b/packages/engine-render/src/components/docs/layout/line-breaker/line-breaker.tsindex 65dab9278d..3ef0d46a0f 100644--- a/packages/engine-render/src/components/docs/layout/line-breaker/line-breaker.ts+++ b/packages/engine-render/src/components/docs/layout/line-breaker/line-breaker.ts@@ -14,12 +14,11 @@* limitations under the License.*/-/* eslint-disable ts/naming-convention */-import type { Nullable } from '@univerjs/core';+import { BooleanNumber } from '@univerjs/core';import type { ILineBreakRule } from './rule';import { Break, BreakPointType } from './break';-import { AI, AL, BA, BK, CJ, CR, HL, HY, LF, NL, NS, RI, SA, SG, SP, WJ, XX, ZWJ } from './classes';+import { AI, AL, BA, BK, CJ, CR, H2, H3, HL, HY, ID, JL, JT, JV, LF, NL, NS, RI, SA, SG, SP, WJ, XX, ZWJ } from './classes';import { CI_BRK, CP_BRK, DI_BRK, IN_BRK, pairTable, PR_BRK } from './pairs';import { Rule } from './rule';import data from './trie-data';@@ -69,15 +68,15 @@ export interface IBreakPoints {}export class LineBreaker implements IBreakPoints {- private _pos: number = 0;+ protected _pos: number = 0;private _lastPos: number = 0;private _curClass: Nullable<number> = null;- private _codePoint: Nullable<number> = null;- private _lastCodePoint: Nullable<number> = null;+ protected _codePoint: Nullable<number> = null;+ protected _lastCodePoint: Nullable<number> = null;private _nextClass: Nullable<number> = null;- private _LB8a: boolean = false;- private _LB21a: boolean = false;- private _LB30a: number = 0;+ private _lb8a: boolean = false;+ private _lb21a: boolean = false;+ private _lb30a: number = 0;private _rule: Rule = new Rule();constructor(public content: string) {}@@ -100,8 +99,8 @@ export class LineBreaker implements IBreakPoints {const firstClass = this._nextCharClass();this._curClass = mapFirst(firstClass);this._nextClass = firstClass;- this._LB8a = firstClass === ZWJ;- this._LB30a = 0;+ this._lb8a = firstClass === ZWJ;+ this._lb30a = 0;}while (this._pos < this.content.length) {@@ -126,8 +125,8 @@ export class LineBreaker implements IBreakPoints {shouldBreak = this._getPairTableBreak(lastClass!);}- // Rule _LB8a- this._LB8a = this._nextClass === ZWJ;+ // Rule LB8a+ this._lb8a = this._nextClass === ZWJ;if (shouldBreak) {return new Break(this._lastPos);@@ -142,7 +141,7 @@ export class LineBreaker implements IBreakPoints {return null;}- private _getNextCodePoint() {+ protected _getNextCodePoint() {const code = this.content.charCodeAt(this._pos++);const next = this.content.charCodeAt(this._pos);@@ -155,14 +154,11 @@ export class LineBreaker implements IBreakPoints {return code;}- private _nextCharClass() {+ protected _nextCharClass() {const nextCodePoint = this._getNextCodePoint();- const rawClass = classTrie.get(nextCodePoint);-this._lastCodePoint = this._codePoint;this._codePoint = nextCodePoint;-- return mapClass(rawClass);+ return mapClass(classTrie.get(nextCodePoint));}private _getSimpleBreak() {@@ -216,27 +212,27 @@ export class LineBreaker implements IBreakPoints {break;}- if (this._LB8a) {+ if (this._lb8a) {shouldBreak = false;}- // Rule _LB21a- if (this._LB21a && (this._curClass === HY || this._curClass === BA)) {+ // Rule LB21a+ if (this._lb21a && (this._curClass === HY || this._curClass === BA)) {shouldBreak = false;- this._LB21a = false;+ this._lb21a = false;} else {- this._LB21a = this._curClass === HL;+ this._lb21a = this._curClass === HL;}- // Rule _LB30a+ // Rule LB30aif (this._curClass === RI) {- this._LB30a++;- if (this._LB30a === 2 && this._nextClass === RI) {+ this._lb30a++;+ if (this._lb30a === 2 && this._nextClass === RI) {shouldBreak = true;- this._LB30a = 0;+ this._lb30a = 0;}} else {- this._LB30a = 0;+ this._lb30a = 0;}this._curClass = this._nextClass;@@ -244,3 +240,33 @@ export class LineBreaker implements IBreakPoints {return shouldBreak;}}++export class DocumentLineBreaker extends LineBreaker {+ constructor(+ content: string,+ private readonly _wordWrap: BooleanNumber,+ private readonly _languageAt?: (offset: number) => string | undefined,+ private readonly _inferKorean = true+ ) {+ super(content);+ }++ protected override _nextCharClass() {+ const offset = this._pos;+ const nextCodePoint = this._getNextCodePoint();+ const rawClass = classTrie.get(nextCodePoint);+ this._lastCodePoint = this._codePoint;+ this._codePoint = nextCodePoint;++ if (this._wordWrap === BooleanNumber.FALSE) {+ if ((rawClass === H2 || rawClass === H3 || rawClass === JL || rawClass === JV || rawClass === JT)+ && (this._inferKorean || /^ko(?:-|$)/i.test(this._languageAt?.(offset) ?? ''))) {+ return AL;+ }+ } else if (rawClass === AL && /\p{Script=Latin}/u.test(String.fromCodePoint(nextCodePoint))+ && !/^ko(?:-|$)/i.test(this._languageAt?.(offset) ?? '')) {+ return ID;+ }+ return mapClass(rawClass);+ }+}diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.tsindex 1c657bc3e0..152fa4d862 100644--- a/packages/engine-render/src/components/docs/layout/tools.ts+++ b/packages/engine-render/src/components/docs/layout/tools.ts@@ -27,6 +27,32 @@ import type {Nullable,PositionedObjectLayoutType,} from '@univerjs/core';+import {+ AlignTypeH,+ AlignTypeV,+ BooleanNumber,+ ColumnSeparatorType,+ DataStreamTreeTokenType,+ DEFAULT_STYLES,+ DocumentFlavor,+ GridType,+ HorizontalAlign,+ mergeWith,+ MODERN_DOCUMENT_DEFAULT_MARGIN,+ MODERN_DOCUMENT_WIDTH,+ ModernDocumentWidthMode,+ NAMED_STYLE_MAP,+ NumberUnitType,+ ObjectMatrix,+ ObjectRelativeFromH,+ ObjectRelativeFromV,+ PageOrientType,+ resolveSectionHeaderFooterReferences,+ SectionType,+ SpacingRule,+ VerticalAlign,+ WrapStrategy,+} from '@univerjs/core';import type {IDocumentSkeletonCached,IDocumentSkeletonColumn,@@ -58,32 +84,6 @@ import type { DocumentFootnoteLayout } from './footnote-layout';import type { Hyphen } from './hyphenation/hyphen';import type { LanguageDetector } from './hyphenation/language-detector';import type { INoteReferenceLayout } from './note-numbering';-import {- AlignTypeH,- AlignTypeV,- BooleanNumber,- ColumnSeparatorType,- DataStreamTreeTokenType,- DEFAULT_STYLES,- DocumentFlavor,- GridType,- HorizontalAlign,- mergeWith,- MODERN_DOCUMENT_DEFAULT_MARGIN,- MODERN_DOCUMENT_WIDTH,- ModernDocumentWidthMode,- NAMED_STYLE_MAP,- NumberUnitType,- ObjectMatrix,- ObjectRelativeFromH,- ObjectRelativeFromV,- PageOrientType,- resolveSectionHeaderFooterReferences,- SectionType,- SpacingRule,- VerticalAlign,- WrapStrategy,-} from '@univerjs/core';import { DEFAULT_DOCUMENT_FONTSIZE } from '../../../basics/const';import { GlyphType, LineType } from '../../../basics/i-document-skeleton-cached';import { getFontStyleString, isFunction, ptToPixel } from '../../../basics/tools';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 14a2828bbd..cfc0734ee9 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@@ -21,12 +21,14 @@ import type {ICustomRangeForInterceptor,ICustomTable,IDisposable,+ IParagraphStyle,ITable,JSONXActions,JSONXPath,Nullable,} from '@univerjs/core';import {+ BooleanNumber,DataStreamTreeNodeType,DataStreamTreeTokenType,DocumentFlavor,@@ -49,6 +51,7 @@ import type {} from '../document-layout-presentation';import type { IHeadingSection } from './heading-sections';import { getDocumentLayoutPresentation } from '../document-layout-presentation';+import { createDocumentLineBreaker } from '../layout/line-breaker/document-line-breaker';import { DataStreamTreeNode } from './data-stream-tree-node';import { getHeadingSections } from './heading-sections';@@ -705,6 +708,14 @@ export class DocumentViewModel implements IDisposable {return getDocumentLayoutPresentation(this._documentDataModel)?.getSnapshot(snapshot) ?? snapshot;}+ getParagraphWordWrap(paragraphStyle: IParagraphStyle): BooleanNumber | undefined {+ return paragraphStyle.wordWrap ?? BooleanNumber.FALSE;+ }++ createLineBreaker(content: string, paragraphStyle: IParagraphStyle, start: number) {+ return createDocumentLineBreaker(this.getSnapshot(), paragraphStyle, content, start, this.getBody());+ }+getDataModel() {return this._documentDataModel;}@@ -1234,6 +1245,10 @@ export class DocumentViewModel implements IDisposable {}}+ protected _createChildViewModel(model: DocumentDataModel, tableSource?: Record<string, ITable>): DocumentViewModel {+ return new DocumentViewModel(model, tableSource);+ }+private _buildHeaderFooterViewModel() {for (const [noteId, viewModel] of this._noteTreeMap) {if (viewModel.getDataModel() !== this._documentDataModel.noteModelMap.get(noteId)) {@@ -1245,7 +1260,7 @@ export class DocumentViewModel implements IDisposable {const viewModels = [];const rootTableSource = this.getSnapshot().tableSource;for (const [headerId, headerModel] of headerModelMap) {- this._headerTreeMap.set(headerId, new DocumentViewModel(headerModel, {+ this._headerTreeMap.set(headerId, this._createChildViewModel(headerModel, {...rootTableSource,...headerModel.getSnapshot().tableSource,}));@@ -1253,7 +1268,7 @@ export class DocumentViewModel implements IDisposable {}for (const [footerId, footerModel] of footerModelMap) {- this._footerTreeMap.set(footerId, new DocumentViewModel(footerModel, {+ this._footerTreeMap.set(footerId, this._createChildViewModel(footerModel, {...rootTableSource,...footerModel.getSnapshot().tableSource,}));@@ -1262,7 +1277,7 @@ export class DocumentViewModel implements IDisposable {for (const [noteId, model] of this._documentDataModel.noteModelMap) {const viewModel = this._noteTreeMap.get(noteId)- ?? new DocumentViewModel(model, { ...rootTableSource, ...model.getSnapshot().tableSource });+ ?? this._createChildViewModel(model, { ...rootTableSource, ...model.getSnapshot().tableSource });this._noteTreeMap.set(noteId, viewModel);viewModels.push(viewModel);}diff --git a/packages/engine-render/src/components/sheets/__tests__/sheet-cell-document-view-model.spec.ts b/packages/engine-render/src/components/sheets/__tests__/sheet-cell-document-view-model.spec.tsnew file mode 100644index 0000000000..ef70c67a59--- /dev/null+++ b/packages/engine-render/src/components/sheets/__tests__/sheet-cell-document-view-model.spec.ts@@ -0,0 +1,59 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IDocumentData } from '@univerjs/core';+import { BooleanNumber, DocumentDataModel, DocumentFlavor } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { SheetCellDocumentViewModel } from '../sheet-cell-document-view-model';++describe('SheetCellDocumentViewModel', () => {+ it.each(['header', 'footer', 'note'] as const)('retains cell line breaking in a %s after resetting the editor', (kind) => {+ const text = '오늘 전략을';+ const paragraph = { startIndex: text.length, paragraphId: 'story', paragraphStyle: { wordWrap: BooleanNumber.FALSE } };+ const body = { dataStream: `${text}\r\n`, paragraphs: [paragraph] };+ const snapshot: IDocumentData = {+ id: 'cell-with-story',+ body: { dataStream: 'Cell\r\n', paragraphs: [{ startIndex: 4, paragraphId: 'cell' }] },+ documentStyle: { documentFlavor: DocumentFlavor.UNSPECIFIED, textStyle: { lang: 'ko-KR' } },+ ...(kind === 'header' ? { headers: { story: { headerId: 'story', body } } } : {}),+ ...(kind === 'footer' ? { footers: { story: { footerId: 'story', body } } } : {}),+ ...(kind === 'note' ? { notes: { story: { noteId: 'story', type: 'footnote', body } } } : {}),+ };+ const model = new DocumentDataModel(snapshot);+ const before = JSON.stringify(model.getSnapshot());+ const viewModel = new SheetCellDocumentViewModel(model);+ try {+ for (const reset of [false, true]) {+ if (reset) {+ viewModel.reset(model);+ }+ const story = viewModel.getSelfOrHeaderFooterViewModel('story');+ const breaker = story.createLineBreaker(text, paragraph.paragraphStyle, 0);+ const segments: string[] = [];+ let start = 0;+ for (let point = breaker.nextBreakPoint(); point; point = breaker.nextBreakPoint()) {+ segments.push(text.slice(start, point.position));+ start = point.position;+ }+ expect(segments).toEqual(['오', '늘 ', '전', '략', '을']);+ }+ expect(JSON.stringify(model.getSnapshot())).toBe(before);+ } finally {+ viewModel.dispose();+ model.dispose();+ }+ });+});diff --git a/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.ts b/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.tsindex a2cfeabc89..03b2b9649e 100644--- a/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.ts+++ b/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.ts@@ -16,6 +16,7 @@import type { IWorkbookData, Workbook } from '@univerjs/core';import {+ BooleanNumber,BorderStyleTypes,DataStreamTreeTokenType,DocumentFlavor,@@ -32,6 +33,7 @@ import {import { afterEach, describe, expect, it, vi } from 'vitest';import { setupRenderTestEnv } from '../../../__tests__/render-test-utils';import { BORDER_TYPE } from '../../../basics/const';+import { DocSimpleSkeleton } from '../../docs/layout/doc-simple-skeleton';import { FontCache } from '../../docs/layout/shaping-engine/font-cache';import { getCustomNumberDisplayText, getGeneralNumberDisplayText, SpreadsheetSkeleton } from '../sheet.render-skeleton';@@ -99,6 +101,85 @@ describe('Rich-text render snapshot isolation', () => {});describe('Cell layout and merged styles', () => {+ it.each([+ { documentFlavor: undefined, wordWrap: undefined },+ ...[DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN].flatMap((documentFlavor) => [undefined, BooleanNumber.FALSE, BooleanNumber.TRUE].map((wordWrap) => ({ documentFlavor, wordWrap }))),+ ])('keeps Korean syllable wrapping in cells, including rich text from Docs: $documentFlavor, $wordWrap', ({ documentFlavor, wordWrap }) => {+ const environment = setupRenderTestEnv();+ const measure = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text) => ({+ width: text.length * 10,+ fontBoundingBoxAscent: 10,+ fontBoundingBoxDescent: 2,+ actualBoundingBoxAscent: 10,+ actualBoundingBoxDescent: 2,+ }));+ const univer = new Univer({ locale: LocaleType.EN_US });+ const content = '오늘 전략을';+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {+ id: 'korean-cell-wrapping',+ sheetOrder: ['sheet'],+ sheets: {+ sheet: {+ id: 'sheet',+ name: 'Sheet',+ rowCount: 10,+ columnCount: 10,+ defaultColumnWidth: 50,+ cellData: { 0: { 0: {+ v: content,+ s: { tb: WrapStrategy.WRAP, pd: { t: 0, b: 0, l: 0, r: 0 } },+ p: documentFlavor == null+ ? undefined+ : {+ id: 'korean-rich-cell',+ documentStyle: { documentFlavor, textStyle: { lang: 'ko-KR' } },+ body: {+ dataStream: `${content}\r\n`,+ paragraphs: [{ startIndex: content.length, paragraphId: 'korean-cell-paragraph', paragraphStyle: { wordWrap } }],+ },+ },+ } } },+ },+ },+ });+ const worksheet = workbook.getActiveSheet()!;+ const skeleton = univer.__getInjector().createInstance(SpreadsheetSkeleton, worksheet, workbook.getStyles());+ try {+ skeleton.calculate();+ const before = Tools.deepClone(workbook.getSnapshot());+ const cell = worksheet.getCellRaw(0, 0)!;+ const style = worksheet.getComposedCellStyleByCellData(0, 0, cell);+ skeleton._setFontStylesCache(0, 0, cell, style, true);+ const cache = skeleton.stylesCache.fontMatrix.getValue(0, 0)!;+ let lines: string[];+ let renderedHeight: number;+ if (cache.documentSkeleton) {+ const document = cache.documentSkeleton.getViewModel().getDataModel();+ document.updateDocumentDataPageSize(50);+ cache.documentSkeleton.makeDirty(true);+ cache.documentSkeleton.calculate();+ const pages = cache.documentSkeleton.getSkeletonData()!.pages;+ const layoutLines = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));+ lines = layoutLines+ .map((line) => line.divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content)).join('').replace(/\r$/, ''));+ renderedHeight = layoutLines.reduce((height, line) => Math.max(height, line.top + line.marginTop + line.lineHeight), 0);+ } else {+ const simple = new DocSimpleSkeleton(content, cache.fontString, true, 50, Infinity, skeleton.textLineGap);+ lines = simple.calculate().map((line) => line.text);+ renderedHeight = simple.getTotalHeight();+ }+ expect(lines).toEqual(['오늘 전략', '을']);+ expect(skeleton.calculateAutoHeightForCell(0, 0)).toBeCloseTo(renderedHeight);+ expect(skeleton._getMeasuredWidthByCell(cell, 0, 0, 50)).toBeCloseTo(50);+ expect(workbook.getSnapshot()).toEqual(before);+ } finally {+ skeleton.dispose();+ univer.dispose();+ measure.mockRestore();+ environment.restore();+ }+ });+it('renders justified plain text using the cell width', () => {const environment = setupRenderTestEnv();const univer = new Univer({ locale: LocaleType.EN_US });diff --git a/packages/engine-render/src/components/sheets/sheet-cell-document-view-model.ts b/packages/engine-render/src/components/sheets/sheet-cell-document-view-model.tsnew file mode 100644index 0000000000..a0a013514a--- /dev/null+++ b/packages/engine-render/src/components/sheets/sheet-cell-document-view-model.ts@@ -0,0 +1,34 @@+/**+ * 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, ITable } from '@univerjs/core';+import { LineBreaker } from '../docs/layout/line-breaker/line-breaker';+import { DocumentViewModel } from '../docs/view-model/document-view-model';++export class SheetCellDocumentViewModel extends DocumentViewModel {+ override getParagraphWordWrap(): undefined {+ // Cell layout ignores paragraph word splitting, including formatting pasted from Docs.+ return undefined;+ }++ override createLineBreaker(content: string) {+ return new LineBreaker(content);+ }++ protected override _createChildViewModel(model: DocumentDataModel, tableSource?: Record<string, ITable>): SheetCellDocumentViewModel {+ return new SheetCellDocumentViewModel(model, tableSource);+ }+}diff --git a/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts b/packages/engine-render/src/components/sheets/sheet.render-skeleton.tsindex 2f688d8f93..d62f52e542 100644--- a/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts+++ b/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts@@ -34,11 +34,6 @@ import type {Styles,Worksheet,} from '@univerjs/core';-import type { IDocumentSkeletonColumn } from '../../basics/i-document-skeleton-cached';-import type { ITransformChangeState } from '../../basics/interfaces';-import type { IBoundRectNoAngle, IPoint, IViewportInfo } from '../../basics/vector2';-import type { Scene } from '../../scene';-import type { IBorderCache, IFontCacheItem, IStylesCache } from './interfaces';import {BooleanNumber,CellValueType,@@ -69,6 +64,11 @@ import {WrapStrategy,} from '@univerjs/core';import { distinctUntilChanged, startWith } from 'rxjs';+import type { IDocumentSkeletonColumn } from '../../basics/i-document-skeleton-cached';+import type { ITransformChangeState } from '../../basics/interfaces';+import type { IBoundRectNoAngle, IPoint, IViewportInfo } from '../../basics/vector2';+import type { Scene } from '../../scene';+import type { IBorderCache, IFontCacheItem, IStylesCache } from './interfaces';import { BORDER_TYPE, COLOR_BLACK_RGB, MAXIMUM_COL_WIDTH, MAXIMUM_ROW_HEIGHT, MIN_COL_WIDTH } from '../../basics/const';import { getRotateOffsetAndFarthestHypotenuse } from '../../basics/draw';import { convertTextRotation, VERTICAL_ROTATE_ANGLE } from '../../basics/text-rotation';@@ -77,7 +77,6 @@ import { DocSimpleSkeleton } from '../docs/layout/doc-simple-skeleton';import { DocumentSkeleton } from '../docs/layout/doc-skeleton';import { FontCache } from '../docs/layout/shaping-engine/font-cache';import { columnIterator } from '../docs/layout/tools';-import { DocumentViewModel } from '../docs/view-model/document-view-model';import {EXPAND_SIZE_FOR_RENDER_OVERFLOW,MEASURE_EXTENT,@@ -85,6 +84,7 @@ import {shouldRenderRowText,} from './constants';import { SHEET_VIEWPORT_KEY } from './interfaces';+import { SheetCellDocumentViewModel } from './sheet-cell-document-view-model';interface IRowColumnRange extends IRowRange, IColumnRange { }@@ -784,7 +784,7 @@ export class SpreadsheetSkeleton extends SheetSkeleton {return undefined;}- const documentViewModel = new DocumentViewModel(documentModel);+ const documentViewModel = new SheetCellDocumentViewModel(documentModel);const { vertexAngle: angle } = convertTextRotation(textRotation);if (typeof colWidth === 'number' && wrapStrategy === WrapStrategy.WRAP) {@@ -1013,7 +1013,7 @@ export class SpreadsheetSkeleton extends SheetSkeleton {return measuredWidth;}- const documentViewModel = new DocumentViewModel(documentModel);+ const documentViewModel = new SheetCellDocumentViewModel(documentModel);const { vertexAngle: angle } = convertTextRotation(textRotation);if (style?.tb === WrapStrategy.WRAP) {@@ -1469,7 +1469,7 @@ export class SpreadsheetSkeleton extends SheetSkeleton {if (fontCache.documentSkeleton) {const snapshot = fontCache.documentSkeleton.getViewModel().getDataModel().getSnapshot();const documentModel = new DocumentDataModel(scaleDocumentDataForShrinkToFit(snapshot, scale, fallbackFontSize));- const documentSkeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), this._localeService, { lineGap: this.textLineGap });+ const documentSkeleton = DocumentSkeleton.create(new SheetCellDocumentViewModel(documentModel), this._localeService, { lineGap: this.textLineGap });documentSkeleton.calculate();fontCache.documentSkeleton = documentSkeleton;} else {@@ -1547,7 +1547,7 @@ export class SpreadsheetSkeleton extends SheetSkeleton {if (FULL_WIDTH_HORIZONTAL_ALIGNMENTS.has(horizontalAlign)) {updateDocumentPageWidth(documentModel, this.getCellWithCoordByIndex(row, col, false));}- const documentViewModel = new DocumentViewModel(documentModel);+ const documentViewModel = new SheetCellDocumentViewModel(documentModel);if (documentViewModel) {const documentSkeleton = DocumentSkeleton.create(documentViewModel, this._localeService, { lineGap: this.textLineGap });documentSkeleton.calculate();diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.tsindex 4a44c73bec..f0184e793f 100644--- a/packages/engine-render/src/index.ts+++ b/packages/engine-render/src/index.ts@@ -135,6 +135,7 @@ export * from './components/sheets/extensions/row-header-layout';export * from './components/sheets/extensions/sheet-extension';export * from './components/sheets/interfaces';export * from './components/sheets/row-header';+export { SheetCellDocumentViewModel } from './components/sheets/sheet-cell-document-view-model';export * from './components/sheets/sheet-component';export * from './components/sheets/sheet.render-skeleton';export { RENDER_RAW_FORMULA_KEY } from './components/sheets/sheet.render-skeleton';