Skip to content

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

feat(docs): integrate table of contents and Office layout fidelity (#7670)

Univer3c1bcc176f8d
diff --git a/packages/core/src/docs/__tests__/sdt-binding.spec.ts b/packages/core/src/docs/__tests__/sdt-binding.spec.ts
new file mode 100644
index 0000000000..ee657d908c
--- /dev/null
+++ b/packages/core/src/docs/__tests__/sdt-binding.spec.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 { ISdtCustomRange } from '../../types/interfaces/i-document-data';
+import { describe, expect, it } from 'vitest';
+import { CustomRangeType } from '../../types/interfaces/i-document-data';
+import { getSdtBindingKey, getSdtBindingValue } from '../sdt-binding';
+
+describe('SDT scalar bindings', () => {
+ it('uses the XML value instead of a localized list label or structural cell anchors', () => {
+ const body = { dataStream: '\x1CYes\r\n\x1D' };
+ const range: ISdtCustomRange = {
+ rangeId: 'answer',
+ rangeType: CustomRangeType.SDT,
+ startIndex: 0,
+ endIndex: body.dataStream.length - 1,
+ properties: { kind: 'dropDownList', placement: 'cell', listItems: [{ displayText: 'Yes', value: '1' }] },
+ };
+ expect(getSdtBindingValue(body, range)).toBe('1');
+ range.properties.showingPlaceholder = true;
+ expect(getSdtBindingValue(body, range)).toBe('');
+ });
+
+ it('requires a complete binding and keeps distinct XML stores and namespaces separate', () => {
+ const range: ISdtCustomRange = {
+ rangeId: 'answer',
+ rangeType: CustomRangeType.SDT,
+ startIndex: 0,
+ endIndex: 0,
+ properties: { kind: 'text', placement: 'inline', dataBinding: { xpath: '/x:value' } },
+ };
+ expect(getSdtBindingKey(range)).toBeUndefined();
+ range.properties.dataBinding!.storeItemID = 'STORE';
+ const key = getSdtBindingKey(range);
+ range.properties.dataBinding!.storeItemID = 'store';
+ expect(getSdtBindingKey(range)).toBe(key);
+ range.properties.dataBinding!.prefixMappings = 'xmlns:x="urn:other"';
+ expect(getSdtBindingKey(range)).not.toBe(key);
+ });
+});
diff --git a/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.ts b/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.ts
index 2fe24f0bcb..f0878f2b57 100644
--- a/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.ts
+++ b/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.ts
@@ -14,10 +14,38 @@
* limitations under the License.
*/
+import type { IDocumentData } from '../../../types/interfaces';
import { describe, expect, it } from 'vitest';
+import { BooleanNumber } from '../../../types/enum';
+import { DocumentFlavor } from '../../../types/interfaces';
+import { DocumentDataModel } from '../document-data-model';
import { getEmptySnapshot } from '../empty-snapshot';
describe('getEmptySnapshot', () => {
+ it.each([
+ [DocumentFlavor.DRAWINGML, BooleanNumber.FALSE],
+ [DocumentFlavor.UNSPECIFIED, BooleanNumber.TRUE],
+ [DocumentFlavor.TRADITIONAL, BooleanNumber.TRUE],
+ [DocumentFlavor.MODERN, BooleanNumber.TRUE],
+ ] as const)('defaults hyphenation by flavor without overriding authored settings (%s)', (documentFlavor, expected) => {
+ expect(getEmptySnapshot(undefined, undefined, undefined, documentFlavor).documentStyle.autoHyphenation).toBe(expected);
+
+ for (const autoHyphenation of [undefined, BooleanNumber.FALSE, BooleanNumber.TRUE]) {
+ const source: IDocumentData = {
+ id: 'imported-shape-text',
+ body: { dataStream: 'Representation\r\n' },
+ documentStyle: { documentFlavor },
+ };
+ if (autoHyphenation !== undefined) {
+ source.documentStyle.autoHyphenation = autoHyphenation;
+ }
+ const model = new DocumentDataModel(source);
+ expect(model.getSnapshot().documentStyle.autoHyphenation).toBe(autoHyphenation ?? expected);
+ expect(source.documentStyle.autoHyphenation).toBe(autoHyphenation);
+ model.dispose();
+ }
+ });
+
it('uses the configured paragraph spacing defaults for new docs', () => {
const snapshot = getEmptySnapshot();
diff --git a/packages/core/src/docs/data-model/empty-snapshot.ts b/packages/core/src/docs/data-model/empty-snapshot.ts
index d59985820f..9ff189cade 100644
--- a/packages/core/src/docs/data-model/empty-snapshot.ts
+++ b/packages/core/src/docs/data-model/empty-snapshot.ts
@@ -81,7 +81,7 @@ export function getEmptySnapshot(
marginBottom: TRADITIONAL_DOCUMENT_DEFAULT_MARGIN,
marginRight: TRADITIONAL_DOCUMENT_DEFAULT_MARGIN,
marginLeft: TRADITIONAL_DOCUMENT_DEFAULT_MARGIN,
- autoHyphenation: BooleanNumber.TRUE,
+ autoHyphenation: documentFlavor === DocumentFlavor.DRAWINGML ? BooleanNumber.FALSE : BooleanNumber.TRUE,
doNotHyphenateCaps: BooleanNumber.FALSE,
consecutiveHyphenLimit: 2,
defaultHeaderId: '',
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/body-structure-validator.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/body-structure-validator.spec.ts
index 5e2c9fe38a..bbea4783ea 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/body-structure-validator.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/body-structure-validator.spec.ts
@@ -16,11 +16,48 @@
import type { IDocumentBody } from '../../../../types/interfaces';
import { describe, expect, it } from 'vitest';
-import { DocumentBlockRangeType } from '../../../../types/interfaces';
+import { CustomRangeType, DocumentBlockRangeType } from '../../../../types/interfaces';
import { DataStreamTreeTokenType } from '../../types';
import { validateDocBodyStructure, validateDocumentStructure } from '../structure-validator';
describe('validateDocBodyStructure', () => {
+ it.each([1, 2, 3])('accepts valid tables nested %i levels without accepting duplicate metadata', (depth) => {
+ const T = DataStreamTreeTokenType;
+ let content = 'Cell';
+ for (let level = 0; level < depth; level++) {
+ content = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${content}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ }
+ const body: IDocumentBody = { dataStream: `${content}${T.PARAGRAPH}${T.SECTION_BREAK}`, tables: [] };
+ const starts: number[] = [];
+ Array.from(body.dataStream).forEach((token, index) => {
+ if (token === T.TABLE_START) {
+ starts.push(index);
+ } else if (token === T.TABLE_END) {
+ const startIndex = starts.pop()!;
+ body.tables!.push({ tableId: `table_${startIndex}`, startIndex, endIndex: index + 1 });
+ }
+ });
+
+ expect(validateDocBodyStructure(body)).toEqual([]);
+ body.tables!.push({ ...body.tables![0], tableId: 'duplicate' });
+ expect(validateDocBodyStructure(body).map((issue) => issue.code)).toContain('overlapping-table');
+ });
+
+ it('rejects misplaced table rows, cells and nested tables', () => {
+ const T = DataStreamTreeTokenType;
+ const cell = `${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}`;
+ const table = `${T.TABLE_START}${T.TABLE_ROW_START}${cell}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ for (const dataStream of [
+ `${T.TABLE_ROW_START}${cell}${T.TABLE_ROW_END}`,
+ `${T.TABLE_START}${cell}${T.TABLE_END}`,
+ `${T.TABLE_START}${table}${T.TABLE_END}`,
+ table.replace(T.TABLE_CELL_END, T.TABLE_ROW_END),
+ table.replace(T.TABLE_ROW_END, T.TABLE_CELL_END),
+ ]) {
+ expect(validateDocBodyStructure({ dataStream }).map((issue) => issue.code)).toContain('unbalanced-table');
+ }
+ });
+
it('accepts a valid plain document body', () => {
const body: IDocumentBody = {
dataStream: `A${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,
@@ -31,6 +68,24 @@ describe('validateDocBodyStructure', () => {
expect(validateDocBodyStructure(body)).toEqual([]);
});
+ it('accepts nested marker-backed fields and rejects crossing metadata', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.CUSTOM_RANGE_START}A${T.CUSTOM_RANGE_START}1${T.CUSTOM_RANGE_END}B${T.CUSTOM_RANGE_END}${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 7, paragraphId: 'root' }],
+ sectionBreaks: [{ sectionId: 'section_field', startIndex: 8 }],
+ customRanges: [
+ { startIndex: 0, endIndex: 6, rangeId: 'toc', rangeType: CustomRangeType.FIELD },
+ { startIndex: 2, endIndex: 4, rangeId: 'page-ref', rangeType: CustomRangeType.FIELD },
+ ],
+ };
+
+ expect(validateDocBodyStructure(body)).toEqual([]);
+
+ body.customRanges![1].endIndex = 6;
+ expect(validateDocBodyStructure(body).map((issue) => issue.code)).toContain('custom-range-token-mismatch');
+ });
+
it('reports root bodies without a minimum paragraph and section pair', () => {
const body: IDocumentBody = {
dataStream: 'A',
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts
index 1b29b301f6..bff52d04eb 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts
@@ -14,15 +14,400 @@
* limitations under the License.
*/
-import type { IDocumentBody } from '../../../../types/interfaces/i-document-data';
+import type { IDocumentBody, IDocumentData } from '../../../../types/interfaces/i-document-data';
+import type { IInsertAction, IRetainAction } from '../action-types';
import { describe, expect, it } from 'vitest';
import { UpdateDocsAttributeType } from '../../../../shared/command-enum';
+import { Tools } from '../../../../shared/tools';
import { BooleanNumber } from '../../../../types/enum/text-style';
-import { CustomDecorationType, DocumentBlockRangeType } from '../../../../types/interfaces/i-document-data';
+import {
+ CustomDecorationType,
+ CustomRangeType,
+ DocumentBlockRangeType,
+} from '../../../../types/interfaces/i-document-data';
+import { JSONX } from '../../json-x/json-x';
+import { DataStreamTreeTokenType } from '../../types';
import { TextXActionType } from '../action-types';
+import { BuildTextUtils } from '../build-utils';
import { TextX } from '../text-x';
+import { composeBody } from '../utils';
describe('test TextX methods and branches', () => {
+ it('keeps scalar identity distinct from adjacent typing, different controls and document snapshots', () => {
+ const value = { t: TextXActionType.INSERT, len: 1, body: { dataStream: 'A' }, valueRangeId: 'first' } as IInsertAction;
+ const edit = new TextX().insert(1, { dataStream: 'X' }).push(value).delete(1).serialize();
+ const peer = new TextX().push({ ...value, body: { dataStream: 'B' } }).delete(1).serialize();
+ const original = { dataStream: 'Old\r\n' };
+ for (const priority of ['left', 'right'] as const) {
+ const left = TextX.apply(TextX.apply(Tools.deepClone(original), edit), TextX.transform(peer, edit, priority === 'left' ? 'right' : 'left'));
+ const right = TextX.apply(TextX.apply(Tools.deepClone(original), peer), TextX.transform(edit, peer, priority));
+ expect(left).toEqual(right);
+ expect(left.dataStream.replace('X', '')).toBe(`${priority === 'left' ? 'A' : 'B'}ld\r\n`);
+ expect(left.dataStream).toContain('X');
+ expect(JSON.stringify(left)).not.toContain('valueRangeId');
+ }
+ const independent = new TextX().push({ ...value, valueRangeId: 'second', body: { dataStream: 'C' } }).serialize();
+ const left = TextX.apply(TextX.apply(Tools.deepClone(original), [value]), TextX.transform(independent, [value], 'right'));
+ const right = TextX.apply(TextX.apply(Tools.deepClone(original), independent), TextX.transform([value], independent, 'left'));
+ expect(left).toEqual(right);
+ expect(left.dataStream).toBe('ACOld\r\n');
+ TextX.makeInvertible(edit, original);
+ const applied = TextX.apply(Tools.deepClone(original), edit);
+ TextX.apply(applied, TextX.invert(edit));
+ expect(applied.dataStream).toBe(original.dataStream);
+ });
+
+ it('rejects malformed scalar identities before any text is applied', () => {
+ for (const valueRangeId of ['', null, 1, [], {}]) {
+ const original = { dataStream: 'Old\r\n' };
+ const actions = new TextX().insert(1, { dataStream: 'X' }).push({
+ t: TextXActionType.INSERT,
+ len: 1,
+ body: { dataStream: 'A' },
+ valueRangeId,
+ } as IInsertAction).serialize();
+ expect(() => TextX.apply(original, actions)).toThrow('Invalid scalar value range identity');
+ expect(original.dataStream).toBe('Old\r\n');
+ }
+ });
+
+ it('composes property edits with positional metadata and preserves independent concurrent metadata', () => {
+ const range = { startIndex: 0, endIndex: 4, rangeId: 'sdt', rangeType: CustomRangeType.SDT, properties: { kind: 'text', alias: 'Old', tag: 'Old tag' } };
+ const original: IDocumentBody = { dataStream: 'Value\r\n', customRanges: [range] };
+ const edit = new TextX().updateCustomRangeProperties(range, { ...range.properties, alias: 'New' }).serialize();
+ const legacy = new TextX().retain(5, { dataStream: '', customRanges: [{ ...range, properties: { ...range.properties, tag: 'Peer tag' } }] }).serialize();
+ const left = Tools.deepClone(original);
+ const right = Tools.deepClone(original);
+ TextX.apply(left, edit);
+ TextX.apply(left, TextX.transform(legacy, edit, 'right'));
+ TextX.apply(right, legacy);
+ TextX.apply(right, TextX.transform(edit, legacy, 'left'));
+ expect(left).toEqual(right);
+ expect(left.customRanges![0].properties).toMatchObject({ alias: 'New', tag: 'Peer tag' });
+ const composed = Tools.deepClone(original);
+ const sequential = Tools.deepClone(original);
+ TextX.apply(composed, TextX.compose(edit, legacy));
+ TextX.apply(sequential, edit);
+ TextX.apply(sequential, legacy);
+ expect(composed).toEqual(sequential);
+ });
+
+ it('roundtrips new nested property edits without leaving empty objects or reverting peers', () => {
+ const range = { startIndex: 0, endIndex: 4, rangeId: 'sdt', rangeType: CustomRangeType.SDT, properties: { kind: 'date' } };
+ const original: IDocumentBody = { dataStream: 'Value\r\n', customRanges: [range] };
+ const first = new TextX().updateCustomRangeProperties(range, { ...range.properties, date: { format: 'yyyy' } }).serialize();
+ TextX.makeInvertible(first, original);
+ const body = Tools.deepClone(original);
+ TextX.apply(body, first);
+ TextX.apply(body, TextX.invert(first));
+ expect(body).toEqual(original);
+ const peer = new TextX().updateCustomRangeProperties(range, { ...range.properties, date: { locale: 'zh-CN' } }).serialize();
+ TextX.apply(body, TextX.compose(first, peer));
+ TextX.apply(body, TextX.transform(TextX.invert(first), peer, 'left'));
+ expect(body.customRanges![0].properties).toEqual({ kind: 'date', date: { locale: 'zh-CN' } });
+ });
+
+ it.each(['left', 'right'] as const)('converges on nested property removal versus child edits (%s)', (priority) => {
+ const range = { startIndex: 0, endIndex: 4, rangeId: 'sdt', rangeType: CustomRangeType.SDT, properties: { kind: 'date', date: { format: 'yyyy', locale: 'en-US' } } };
+ const original: IDocumentBody = { dataStream: 'Value\r\n', customRanges: [range] };
+ const remove = new TextX().updateCustomRangeProperties(range, { kind: 'date' }).serialize();
+ const edit = new TextX().updateCustomRangeProperties(range, { ...range.properties, date: { format: 'dd', locale: 'en-US' } }).serialize();
+ const left = Tools.deepClone(original);
+ const right = Tools.deepClone(original);
+ TextX.apply(left, remove);
+ TextX.apply(left, TextX.transform(edit, remove, priority === 'left' ? 'right' : 'left'));
+ TextX.apply(right, edit);
+ TextX.apply(right, TextX.transform(remove, edit, priority));
+ expect(left).toEqual(right);
+ expect(left.customRanges![0].properties).toEqual(priority === 'left' ? { kind: 'date' } : { kind: 'date', date: { format: 'dd', locale: 'en-US' } });
+ });
+
+ it('rejects malformed identity metadata before applying any text edits', () => {
+ const range = { startIndex: 0, endIndex: 4, rangeId: 'sdt', rangeType: CustomRangeType.SDT };
+ const original: IDocumentBody = { dataStream: 'Value\r\n', customRanges: [range] };
+ const invalidUpdates: unknown[] = [
+ ...[{ startIndex: -1 }, { endIndex: 20 }, { rangeId: 'other' }]
+ .map((patch) => ({ rangeId: 'sdt', range: { ...range, ...patch } })),
+ { rangeId: 'sdt' },
+ ...[false, 0, '', []].map((value) => ({ rangeId: 'sdt', range: value })),
+ { rangeId: 'sdt', range, nextRangeId: 0 },
+ ...[null, 'alias', [[]], [['__proto__', 'polluted']], [['alias', 1]]]
+ .map((propertyPaths) => ({ rangeId: 'sdt', range, propertyPaths })),
+ ];
+ for (const update of invalidUpdates) {
+ const body = Tools.deepClone(original);
+ const actions = new TextX().insert(1, { dataStream: 'X' }).updateCustomRanges([
+ update as NonNullable<IRetainAction['rangeUpdates']>[number],
+ ]).serialize();
+ expect(() => TextX.apply(body, actions)).toThrow('Invalid custom range');
+ expect(body).toEqual(original);
+ }
+ });
+ it.each(['', 'Value'])('roundtrips identity removal and history through JSONX for %j', (value) => {
+ const original = {
+ id: 'doc',
+ documentStyle: {},
+ body: {
+ dataStream: `\x1F${value}\x1EAfter\r\n`,
+ customRanges: [{ startIndex: 0, endIndex: value.length + 1, rangeId: 'sdt', rangeType: CustomRangeType.SDT, properties: { kind: 'text', placement: 'inline' } }],
+ },
+ } as IDocumentData;
+ const edit = new TextX().delete(1).retain(value.length).delete(1).updateCustomRanges([{ rangeId: 'sdt', range: null }]).serialize();
+ const op = JSONX.getInstance().editOp(edit);
+ const undo = JSONX.invertWithDoc(op, Tools.deepClone(original));
+ const removed = JSONX.apply(Tools.deepClone(original), JSON.parse(JSON.stringify(op))) as unknown as IDocumentData;
+ expect(removed.body!.dataStream).toBe(`${value}After\r\n`);
+ expect(removed.body!.customRanges).toEqual([]);
+ const restored = JSONX.apply(Tools.deepClone(removed), JSON.parse(JSON.stringify(undo))) as unknown as IDocumentData;
+ expect(restored.body!.dataStream).toBe(original.body!.dataStream);
+ expect(restored.body!.customRanges).toEqual(original.body!.customRanges);
+ const combined = JSONX.apply(Tools.deepClone(original), JSONX.compose(op, undo)) as unknown as IDocumentData;
+ expect(combined.body!.dataStream).toBe(original.body!.dataStream);
+ expect(combined.body!.customRanges).toEqual(original.body!.customRanges);
+
+ const peer = new TextX().retain(1).insert(1, { dataStream: 'X' }).serialize();
+ const peerAfterRemove = TextX.transform(peer, edit, 'right');
+ const afterBoth = Tools.deepClone(removed.body!);
+ TextX.apply(afterBoth, peerAfterRemove);
+ const inverse = (undo![1] as { e: ReturnType<TextX['serialize']> }).e;
+ TextX.apply(afterBoth, TextX.transform(inverse, peerAfterRemove, 'left'));
+ expect(afterBoth.dataStream).toBe(`\x1FX${value}\x1EAfter\r\n`);
+ expect(afterBoth.customRanges).toEqual([{ ...original.body!.customRanges![0], endIndex: value.length + 2 }]);
+ });
+
+ it('composes identity edits with later typing and resolves concurrent identity conflicts', () => {
+ const range = { startIndex: 0, endIndex: 4, rangeId: 'sdt', rangeType: CustomRangeType.SDT, properties: { kind: 'text', alias: 'Old' } };
+ const original: IDocumentBody = { dataStream: 'Value\r\n', customRanges: [range] };
+ const first = new TextX().updateCustomRanges([{ rangeId: 'sdt', range: { ...range, properties: { ...range.properties, alias: 'First' } } }]).serialize();
+ const second = new TextX().updateCustomRanges([{ rangeId: 'sdt', range: { ...range, properties: { ...range.properties, alias: 'Second' } } }]).serialize();
+ const removal = new TextX().updateCustomRanges([{ rangeId: 'sdt', range: null }]).serialize();
+ const insert = new TextX().retain(2).insert(1, { dataStream: 'X' }).serialize();
+ const legacy = new TextX().retain(5, { dataStream: '', customRanges: [{ ...range, properties: { kind: 'text', alias: 'Legacy' } }] }).serialize();
+ for (const next of [second, removal, insert, legacy]) {
+ const composed = Tools.deepClone(original);
+ TextX.apply(composed, TextX.compose(first, next));
+ const sequential = Tools.deepClone(original);
+ TextX.apply(sequential, first);
+ TextX.apply(sequential, next);
+ expect(composed.dataStream).toBe(sequential.dataStream);
+ expect(composed.customRanges).toEqual(sequential.customRanges);
+ for (const priority of ['left', 'right'] as const) {
+ const left = Tools.deepClone(original);
+ const right = Tools.deepClone(original);
+ TextX.apply(left, first);
+ TextX.apply(left, TextX.transform(next, first, priority === 'left' ? 'right' : 'left'));
+ TextX.apply(right, next);
+ TextX.apply(right, TextX.transform(first, next, priority));
+ expect(left.dataStream).toBe(right.dataStream);
+ expect(left.customRanges).toEqual(right.customRanges);
+ }
+ }
+ const reinsert = new TextX().insert(1, { dataStream: 'X', customRanges: [{ ...range, startIndex: 0, endIndex: 0 }] }).serialize();
+ const sequential = Tools.deepClone(original);
+ TextX.apply(sequential, removal);
+ TextX.apply(sequential, reinsert);
+ const composed = Tools.deepClone(original);
+ TextX.apply(composed, TextX.compose(removal, reinsert));
+ expect(composed.dataStream).toBe(sequential.dataStream);
+ expect(composed.customRanges).toEqual(sequential.customRanges);
+ });
+
+ it('joins inserted SDT content with its surviving paragraph anchor', () => {
+ const anchor = {
+ startIndex: 1,
+ endIndex: 1,
+ rangeId: 'control',
+ rangeType: CustomRangeType.SDT,
+ properties: { kind: 'dropDownList', placement: 'block' },
+ };
+ const body: IDocumentBody = { dataStream: 'X\r\n', customRanges: [anchor] };
+ TextX.apply(body, new TextX().retain(1).insert(3, {
+ dataStream: 'New',
+ customRanges: [{ ...anchor, startIndex: 0, endIndex: 2 }],
+ }).serialize());
+ expect(body.dataStream).toBe('XNew\r\n');
+ expect(body.customRanges).toEqual([{ ...anchor, startIndex: 1, endIndex: 4 }]);
+ });
+
+ it('keeps soft page-break tokens anchored through UTF-16 insertion, undo, deletion and redo', () => {
+ const body: IDocumentBody = { dataStream: 'A\fB\fC\fD', renderedPageBreaks: [1, 5] };
+ const inserted = new TextX().retain(1).insert(2, { dataStream: '😀' }).serialize();
+ TextX.makeInvertible(inserted, body);
+ TextX.apply(body, inserted);
+ expect(body.renderedPageBreaks).toEqual([3, 7]);
+ expect(body.renderedPageBreaks?.map((offset) => body.dataStream[offset])).toEqual(['\f', '\f']);
+ TextX.apply(body, TextX.invert(inserted));
+ expect(body.dataStream).toBe('A\fB\fC\fD');
+ expect(body.renderedPageBreaks).toEqual([1, 5]);
+
+ const deleted = new TextX().retain(1).delete(4).serialize();
+ TextX.makeInvertible(deleted, body);
+ TextX.apply(body, deleted);
+ expect(body.dataStream).toBe('A\fD');
+ expect(body.renderedPageBreaks).toEqual([1]);
+ TextX.apply(body, TextX.invert(deleted));
+ expect(body.dataStream).toBe('A\fB\fC\fD');
+ expect(body.renderedPageBreaks).toEqual([1, 5]);
+ TextX.apply(body, deleted);
+ expect(body.renderedPageBreaks).toEqual([1]);
+ });
+
+ it('preserves soft page breaks when an imported insert is split and composed with text formatting', () => {
+ const source: IDocumentBody = { dataStream: 'A\fB\fC\fD', renderedPageBreaks: [1, 5] };
+ const inserted = new TextX().insert(source.dataStream.length, source).serialize();
+ const formatted = new TextX().retain(4, { dataStream: '', textRuns: [{ st: 0, ed: 4, ts: { bl: BooleanNumber.TRUE } }] }).serialize();
+ const body: IDocumentBody = { dataStream: '' };
+ TextX.apply(body, TextX.compose(inserted, formatted));
+ expect(body.dataStream).toBe(source.dataStream);
+ expect(body.renderedPageBreaks).toEqual([1, 5]);
+ expect(source.renderedPageBreaks).toEqual([1, 5]);
+ });
+
+ it('keeps every enclosing field intact when editing a nested field result', () => {
+ const start = DataStreamTreeTokenType.CUSTOM_RANGE_START;
+ const end = DataStreamTreeTokenType.CUSTOM_RANGE_END;
+ const body: IDocumentBody = {
+ dataStream: `${start}A${start}1${end}\rB${end}\0`,
+ customRanges: [
+ {
+ startIndex: 0,
+ endIndex: 7,
+ rangeId: 'toc',
+ rangeType: CustomRangeType.FIELD,
+ wholeEntity: false,
+ properties: { fieldType: 'TOC', instruction: 'TOC \\o "1-3"' },
+ },
+ {
+ startIndex: 2,
+ endIndex: 4,
+ rangeId: 'page-ref',
+ rangeType: CustomRangeType.FIELD,
+ wholeEntity: false,
+ properties: { fieldType: 'PAGEREF', instruction: 'PAGEREF _Toc1 \\h' },
+ },
+ ],
+ };
+
+ TextX.apply(body, new TextX().retain(4).insert(1, { dataStream: '0' }).serialize());
+
+ expect(body.dataStream).toBe(`${start}A${start}10${end}\rB${end}\0`);
+ expect(body.customRanges).toMatchObject([
+ { rangeId: 'toc', startIndex: 0, endIndex: 8 },
+ { rangeId: 'page-ref', startIndex: 2, endIndex: 5 },
+ ]);
+ });
+
+ it('keeps a nested SDT as one entity and expands it when typing inside', () => {
+ const body: IDocumentBody = {
+ dataStream: 'Accept: Value\r',
+ customRanges: [{
+ startIndex: 8,
+ endIndex: 12,
+ rangeId: 'sdt-text-1',
+ rangeType: CustomRangeType.SDT,
+ wholeEntity: false,
+ properties: { kind: 'text', placement: 'inline' },
+ }],
+ };
+
+ TextX.apply(body, new TextX().retain(10).insert(1, { dataStream: 'X' }).serialize());
+
+ expect(body.dataStream).toBe('Accept: VaXlue\r');
+ expect(body.customRanges).toMatchObject([{
+ rangeId: 'sdt-text-1',
+ startIndex: 8,
+ endIndex: 13,
+ }]);
+ });
+
+ it('converges concurrent edits inside one SDT without duplicating the wrapper', () => {
+ const original: IDocumentBody = {
+ dataStream: 'Accept: Value\r',
+ customRanges: [{
+ startIndex: 8,
+ endIndex: 12,
+ rangeId: 'sdt-text-1',
+ rangeType: CustomRangeType.SDT,
+ wholeEntity: false,
+ properties: { kind: 'text', placement: 'inline' },
+ }],
+ };
+ const left = new TextX().retain(10).insert(1, { dataStream: 'X' }).serialize();
+ const right = new TextX().retain(11).insert(1, { dataStream: 'Y' }).serialize();
+ const leftFirst = JSON.parse(JSON.stringify(original)) as IDocumentBody;
+ const rightFirst = JSON.parse(JSON.stringify(original)) as IDocumentBody;
+
+ TextX.apply(leftFirst, TextX.compose(left, TextX.transform(right, left, 'right')));
+ TextX.apply(rightFirst, TextX.compose(right, TextX.transform(left, right, 'left')));
+
+ expect(leftFirst).toEqual(rightFirst);
+ expect(leftFirst.customRanges).toEqual([expect.objectContaining({
+ rangeId: 'sdt-text-1',
+ startIndex: 8,
+ endIndex: 14,
+ })]);
+ });
+
+ it('composes updates for multiple nested custom ranges by range id', () => {
+ const ranges = [
+ { startIndex: 0, endIndex: 7, rangeId: 'toc', rangeType: CustomRangeType.FIELD },
+ { startIndex: 2, endIndex: 4, rangeId: 'page-ref', rangeType: CustomRangeType.FIELD },
+ ];
+ const result = composeBody(
+ { dataStream: '', customRanges: ranges },
+ {
+ dataStream: '',
+ customRanges: ranges.map((range) => ({ ...range, properties: { dirty: BooleanNumber.TRUE } })),
+ },
+ UpdateDocsAttributeType.COVER
+ );
+
+ expect(result.customRanges).toEqual(ranges.map((range) => ({
+ ...range,
+ properties: { dirty: BooleanNumber.TRUE },
+ })));
+ });
+
+ it('updates metadata without splitting an SDT around structural tokens', () => {
+ const body: IDocumentBody = {
+ dataStream: 'X\x1Cdd mmm yyyy\r\n\x1D',
+ customRanges: [{
+ startIndex: 1,
+ endIndex: 15,
+ rangeId: 'date-cell',
+ rangeType: CustomRangeType.SDT,
+ wholeEntity: false,
+ properties: { kind: 'date', placement: 'cell', showingPlaceholder: true },
+ }],
+ };
+ const replacement = BuildTextUtils.selection.delete([{
+ startOffset: 2,
+ endOffset: 13,
+ collapsed: false,
+ }], body, 0, { dataStream: '06 Sep 2026' });
+ const metadata = new TextX().retain(1).retain(15, {
+ dataStream: '',
+ customRanges: [{
+ ...body.customRanges![0],
+ startIndex: 0,
+ endIndex: 14,
+ properties: { kind: 'date', placement: 'cell', showingPlaceholder: false },
+ }],
+ }).serialize();
+
+ TextX.apply(body, TextX.compose(replacement, metadata));
+
+ expect(body.dataStream).toBe('X\x1C06 Sep 2026\r\n\x1D');
+ expect(body.customRanges).toEqual([{
+ startIndex: 1,
+ endIndex: 15,
+ rangeId: 'date-cell',
+ rangeType: CustomRangeType.SDT,
+ wholeEntity: false,
+ properties: { kind: 'date', placement: 'cell', showingPlaceholder: false },
+ }]);
+ });
+
describe('test TextX methods', () => {
it('test TextX insert method', () => {
const textX = new TextX();
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/utils.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/utils.spec.ts
index 5b65f4fed9..f3cbedda4a 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/utils.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/utils.spec.ts
@@ -19,9 +19,10 @@ import type { IRetainAction } from '../action-types';
import { describe, expect, it, vi } from 'vitest';
import { Tools } from '../../../../shared/tools';
import { BooleanNumber } from '../../../../types/enum/text-style';
+import { CustomRangeType } from '../../../../types/interfaces/i-document-data';
import { PresetListType } from '../../preset-list-type';
import { TextXActionType } from '../action-types';
-import { composeBody, getBodySlice, getTextRunSlice, isUselessRetainAction } from '../utils';
+import { composeBody, getBodySlice, getTextRunSlice, isUselessRetainAction, SliceBodyType } from '../utils';
describe('test text-x utils', () => {
it('only clones text runs intersecting the requested slice', () => {
@@ -170,6 +171,34 @@ describe('test text-x utils', () => {
});
});
+ it('drops a clipped outer field while preserving a fully copied nested field', () => {
+ const body: IDocumentBody = {
+ dataStream: '\u001FOld\t\u001F1\u001E\r\u001E',
+ customRanges: [{
+ startIndex: 0,
+ endIndex: 9,
+ rangeId: 'toc',
+ rangeType: CustomRangeType.FIELD,
+ wholeEntity: false,
+ }, {
+ startIndex: 5,
+ endIndex: 7,
+ rangeId: 'page-ref',
+ rangeType: CustomRangeType.FIELD,
+ wholeEntity: false,
+ }],
+ };
+
+ const copied = getBodySlice(body, 1, 9, false, SliceBodyType.copy);
+
+ expect(copied.dataStream).toBe('Old\t\u001F1\u001E\r');
+ expect(copied.customRanges).toEqual([expect.objectContaining({
+ rangeId: 'page-ref',
+ startIndex: 4,
+ endIndex: 6,
+ })]);
+ });
+
it('test composeBody fn with textRuns', () => {
const thisBody: IDocumentBody = {
dataStream: 'hello\nworld',
diff --git a/packages/core/src/docs/data-model/text-x/action-types.ts b/packages/core/src/docs/data-model/text-x/action-types.ts
index 4889aeaa58..52ffdcf14e 100644
--- a/packages/core/src/docs/data-model/text-x/action-types.ts
+++ b/packages/core/src/docs/data-model/text-x/action-types.ts
@@ -15,7 +15,7 @@
*/
import type { UpdateDocsAttributeType } from '../../../shared/command-enum';
-import type { IDocumentBody } from '../../../types/interfaces/i-document-data';
+import type { ICustomRange, IDocumentBody } from '../../../types/interfaces/i-document-data';
// Internal TextX structural-replacement marker. Inserted paragraphs replace the
// same logical paragraphs later in the operation, so their ids must stay stable.
@@ -36,6 +36,20 @@ export interface IRetainAction {
body?: IDocumentBody;
oldBody?: IDocumentBody;
coverType?: UpdateDocsAttributeType;
+ /**
+ * Identity edits applied after the text operation, with absolute result-document offsets.
+ * nextRangeId restores array order by identity (null means the end), including coincident SDT nesting.
+ * Collaboration peers must support this extension; legacy TextX implementations ignore it.
+ */
+ rangeUpdates?: Array<{
+ rangeId: string;
+ range: ICustomRange | null;
+ nextRangeId?: string | null;
+ /** Only these property paths are written; missing values remove properties. Arrays are atomic. */
+ propertyPaths?: string[][];
+ }>;
+ /** Before-document values captured by makeInvertible; never persisted in a document body. */
+ oldRangeUpdates?: IRetainAction['rangeUpdates'];
}
/**
@@ -45,6 +59,8 @@ export interface IInsertAction {
t: TextXActionType.INSERT;
body: IDocumentBody;
len: number;
+ /** Scalar selection intent, not snapshot data. All collaboration peers must support this extension. */
+ valueRangeId?: string;
}
/**
@@ -54,6 +70,8 @@ export interface IDeleteAction {
t: TextXActionType.DELETE;
len: number;
body?: IDocumentBody; // Add a body property to make this action invertible.
+ /** Preserved through inversion so undo participates in scalar conflict resolution. */
+ valueRangeId?: string;
}
export type TextXAction = IRetainAction | IInsertAction | IDeleteAction;
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/__tests__/common.spec.ts b/packages/core/src/docs/data-model/text-x/apply-utils/__tests__/common.spec.ts
new file mode 100644
index 0000000000..7feb1ceace
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/__tests__/common.spec.ts
@@ -0,0 +1,72 @@
+/**
+ * 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, ISdtCustomRange } from '../../../../../types/interfaces/i-document-data';
+import { describe, expect, it } from 'vitest';
+import { CustomRangeType } from '../../../../../types/interfaces/i-document-data';
+import { deleteCustomRanges, insertCustomRanges, mergeContinuousRanges } from '../common';
+
+describe('overlapping bookmark identity', () => {
+ it('merges each bookmark independently of interleaved overlapping ranges', () => {
+ const ranges = [0, 4].flatMap((startIndex) => ['a', 'b'].map((rangeId) => ({
+ rangeId,
+ startIndex,
+ endIndex: startIndex + 3,
+ rangeType: CustomRangeType.BOOKMARK,
+ properties: { bookmarkId: rangeId },
+ })));
+ expect(mergeContinuousRanges(ranges)).toEqual(['a', 'b'].map((rangeId) => ({
+ rangeId,
+ startIndex: 0,
+ endIndex: 7,
+ rangeType: CustomRangeType.BOOKMARK,
+ properties: { bookmarkId: rangeId },
+ })));
+ });
+
+ it('keeps an enclosing bookmark intact when inserting and deleting text inside it', () => {
+ const bookmark = { rangeId: 'bookmark', startIndex: 0, endIndex: 7, rangeType: CustomRangeType.BOOKMARK, properties: { bookmarkId: 'target' } };
+ const body: IDocumentBody = { dataStream: 'abcdefgh', customRanges: [{ ...bookmark }] };
+ insertCustomRanges(body, { dataStream: 'XY' }, 2, 4);
+ expect(body.customRanges).toEqual([{ ...bookmark, endIndex: 9 }]);
+ deleteCustomRanges(body, 2, 4);
+ expect(body.customRanges).toEqual([bookmark]);
+ });
+});
+
+function sdt(rangeId: string, startIndex: number, endIndex: number): ISdtCustomRange {
+ return { rangeId, startIndex, endIndex, rangeType: CustomRangeType.SDT, properties: { kind: 'richText', placement: 'block' } };
+}
+
+describe('SDT nesting through text changes', () => {
+ it('retains child-before-parent order when deletion gives a child the same bounds as its parent', () => {
+ const body: IDocumentBody = { dataStream: 'A\rB\r\n', customRanges: [
+ sdt('first', 0, 0),
+ sdt('parent', 0, 2),
+ sdt('last', 2, 2),
+ ] };
+ deleteCustomRanges(body, 2, 0);
+ expect(body.customRanges?.map((range) => range.rangeId)).toEqual(['last', 'parent']);
+ expect(body.customRanges?.map(({ startIndex, endIndex }) => [startIndex, endIndex])).toEqual([[0, 0], [0, 0]]);
+ });
+
+ it('restores the source nesting order when an inserted child precedes a retained parent fragment', () => {
+ const body: IDocumentBody = { dataStream: 'B\r\n', customRanges: [sdt('last', 0, 0), sdt('parent', 0, 0)] };
+ insertCustomRanges(body, { dataStream: 'A\r', customRanges: [sdt('first', 0, 0), sdt('parent', 0, 1)] }, 2, 0);
+ expect(body.customRanges?.map((range) => range.rangeId)).toEqual(['first', 'parent', 'last']);
+ expect(body.customRanges?.find((range) => range.rangeId === 'parent')).toMatchObject({ startIndex: 0, endIndex: 2 });
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/__tests__/update-apply.spec.ts b/packages/core/src/docs/data-model/text-x/apply-utils/__tests__/update-apply.spec.ts
new file mode 100644
index 0000000000..f416f5932b
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/__tests__/update-apply.spec.ts
@@ -0,0 +1,73 @@
+/**
+ * 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, ISdtCustomRange } from '../../../../../types/interfaces';
+import { describe, expect, it } from 'vitest';
+import { UpdateDocsAttributeType } from '../../../../../shared';
+import { CustomRangeType } from '../../../../../types/interfaces';
+import { updateAttribute } from '../update-apply';
+
+describe('retained SDT metadata boundaries', () => {
+ it('restores child-before-parent order when a retained parent shrinks onto its child', () => {
+ const child: ISdtCustomRange = {
+ rangeId: 'child',
+ rangeType: CustomRangeType.SDT,
+ startIndex: 0,
+ endIndex: 0,
+ properties: { kind: 'repeatingSectionItem', placement: 'block' },
+ };
+ const parent: ISdtCustomRange = {
+ ...child,
+ rangeId: 'parent',
+ endIndex: 4,
+ properties: { kind: 'repeatingSection', placement: 'block' },
+ };
+ const body: IDocumentBody = { dataStream: 'A\rA\rB\r\n', customRanges: [child, parent] };
+ updateAttribute(body, {
+ dataStream: '',
+ customRanges: [child, { ...parent, endIndex: 0 }],
+ }, 2, 0, UpdateDocsAttributeType.REPLACE);
+ expect(body.customRanges?.map((range) => range.rangeId)).toEqual(['child', 'parent']);
+ expect(body.customRanges?.map((range) => range.endIndex)).toEqual([0, 0]);
+ });
+
+ it.each([
+ { name: 'keeps both clipped edges', offset: 2, length: 3, start: 0, end: 2, expectedStart: 0, expectedEnd: 8 },
+ { name: 'restores an explicit end before the retain edge', offset: 0, length: 5, start: 0, end: 2, expectedStart: 0, expectedEnd: 2 },
+ { name: 'restores an explicit start after the retain edge', offset: 2, length: 7, start: 2, end: 6, expectedStart: 4, expectedEnd: 8 },
+ ])('$name', ({ offset, length, start, end, expectedStart, expectedEnd }) => {
+ const range: ISdtCustomRange = {
+ rangeId: 'sdt',
+ rangeType: CustomRangeType.SDT,
+ startIndex: 0,
+ endIndex: 8,
+ properties: { kind: 'repeatingSection', placement: 'block', alias: 'before' },
+ };
+ const body: IDocumentBody = { dataStream: '123456789\r\n', customRanges: [range] };
+ updateAttribute(body, {
+ dataStream: '',
+ customRanges: [{ ...range, startIndex: start, endIndex: end, properties: { ...range.properties, alias: 'after' } }],
+ }, length, offset, UpdateDocsAttributeType.REPLACE);
+
+ expect(body.customRanges).toHaveLength(1);
+ expect(body.customRanges![0]).toMatchObject({
+ rangeId: 'sdt',
+ startIndex: expectedStart,
+ endIndex: expectedEnd,
+ properties: { alias: 'after' },
+ });
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
index 8d7afc544d..5ee255db58 100644
--- a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
@@ -32,6 +32,7 @@ import type {
import { shallowEqual } from '../../../../common/equal';
import { horizontalLineSegmentsSubtraction, sortRulesFactory, Tools } from '../../../../shared';
import { isSameStyleTextRun } from '../../../../shared/compare';
+import { CustomRangeType } from '../../../../types/interfaces';
import { cloneParagraphWithId } from '../../../paragraph-id';
import { cloneSectionBreakWithId } from '../../../section-break-id';
import { DataStreamTreeTokenType } from '../../types';
@@ -688,31 +689,29 @@ const ID_SPLIT_SYMBOL = '$';
const getRootId = (id: string) => id.split(ID_SPLIT_SYMBOL)[0];
export function mergeContinuousRanges(ranges: ICustomRange[]): ICustomRange[] {
- if (ranges.length <= 1) return ranges;
+ if (ranges.length <= 1) {
+ return ranges;
+ }
ranges.sort((a, b) => a.startIndex - b.startIndex);
const mergedRanges: ICustomRange[] = [];
- let currentRange = { ...ranges[0] };
- currentRange.rangeId = getRootId(currentRange.rangeId);
-
- for (let i = 1; i < ranges.length; i++) {
- const nextRange = ranges[i];
- nextRange.rangeId = getRootId(nextRange.rangeId);
+ const latestById = new Map<string, ICustomRange>();
+ for (const range of ranges) {
+ const nextRange = { ...range, rangeId: getRootId(range.rangeId) };
+ const currentRange = latestById.get(nextRange.rangeId);
if (
- nextRange.rangeId === currentRange.rangeId &&
+ currentRange &&
+ nextRange.rangeType === currentRange.rangeType &&
shallowEqual(currentRange.properties, nextRange.properties) &&
currentRange.endIndex + 1 >= nextRange.startIndex
) {
- // Merge continuous ranges with same rangeId
- currentRange.endIndex = nextRange.endIndex;
+ // Overlapping identities can interleave fragments of the same range.
+ currentRange.endIndex = Math.max(currentRange.endIndex, nextRange.endIndex);
} else {
- // Push current range and start a new one
- mergedRanges.push(currentRange);
- currentRange = { ...nextRange };
+ mergedRanges.push(nextRange);
+ latestById.set(nextRange.rangeId, nextRange);
}
}
- // Push the last range
- mergedRanges.push(currentRange);
const idMap: Record<string, number> = Object.create(null);
for (let i = 0, len = mergedRanges.length; i < len; i++) {
@@ -730,20 +729,24 @@ export function mergeContinuousRanges(ranges: ICustomRange[]): ICustomRange[] {
}
export function splitCustomRangesByIndex(customRanges: ICustomRange[], currentIndex: number) {
- const matchedCustomRangeIndex = customRanges.findIndex((c) => c.startIndex < currentIndex && c.endIndex >= currentIndex);
- const matchedCustomRange = customRanges[matchedCustomRangeIndex];
-
- if (matchedCustomRange) {
- customRanges.splice(matchedCustomRangeIndex, 1, {
- ...matchedCustomRange,
- startIndex: matchedCustomRange.startIndex,
+ const matches = customRanges.filter((range) =>
+ range.rangeType !== CustomRangeType.FIELD &&
+ range.rangeType !== CustomRangeType.SDT &&
+ range.rangeType !== CustomRangeType.BOOKMARK &&
+ range.startIndex < currentIndex &&
+ range.endIndex >= currentIndex
+ );
+
+ for (const matched of matches) {
+ const index = customRanges.indexOf(matched);
+ customRanges.splice(index, 1, {
+ ...matched,
endIndex: currentIndex - 1,
- properties: { ...matchedCustomRange.properties },
+ properties: { ...matched.properties },
}, {
- ...matchedCustomRange,
+ ...matched,
startIndex: currentIndex,
- endIndex: matchedCustomRange.endIndex,
- properties: { ...matchedCustomRange.properties },
+ properties: { ...matched.properties },
});
}
}
@@ -810,6 +813,16 @@ export function insertCustomRanges(
for (let i = 0, len = customRanges.length; i < len; i++) {
const customRange = customRanges[i];
const { startIndex } = customRange;
+ if (
+ (customRange.rangeType === CustomRangeType.FIELD ||
+ customRange.rangeType === CustomRangeType.SDT ||
+ customRange.rangeType === CustomRangeType.BOOKMARK) &&
+ startIndex < currentIndex &&
+ customRange.endIndex >= currentIndex
+ ) {
+ customRange.endIndex += textLength;
+ continue;
+ }
// move custom range when insert text before it
if (startIndex >= currentIndex) {
customRange.startIndex += textLength;
@@ -821,6 +834,18 @@ export function insertCustomRanges(
if (insertBody.customRanges) {
for (let i = 0, len = insertBody.customRanges.length; i < len; i++) {
const customRange = insertBody.customRanges[i];
+ const existingSdt = customRange.rangeType === CustomRangeType.SDT
+ ? customRanges.find((range) => range.rangeType === CustomRangeType.SDT && range.rangeId === customRange.rangeId)
+ : undefined;
+ if (existingSdt) {
+ existingSdt.startIndex = Math.min(existingSdt.startIndex, currentIndex + customRange.startIndex);
+ existingSdt.endIndex = Math.max(existingSdt.endIndex, currentIndex + customRange.endIndex);
+ existingSdt.properties = Tools.deepClone(customRange.properties);
+ existingSdt.wholeEntity = customRange.wholeEntity;
+ // An undo fragment carries its original child-before-parent order.
+ customRanges.splice(customRanges.indexOf(existingSdt), 0, ...insertRanges.splice(0));
+ continue;
+ }
customRange.startIndex += currentIndex;
customRange.endIndex += currentIndex;
// new custom range
@@ -1244,7 +1269,11 @@ export function deleteCustomRanges(body: IDocumentBody, textLength: number, curr
const removeCustomRanges: ICustomRange[] = [];
if (customRanges) {
- const newCustomRanges = [];
+ // Preserve nesting before deletion can collapse a parent and child onto identical bounds.
+ const originalSdtLengths = new Map(customRanges.filter((range) => range.rangeType === CustomRangeType.SDT)
+ .map((range) => [range, range.endIndex - range.startIndex]));
+ const coincidentSdts = new Map<string, number[]>();
+ const newCustomRanges: ICustomRange[] = [];
for (let i = 0, len = customRanges.length; i < len; i++) {
const customRange = customRanges[i];
const transformed = shiftInclusiveRangeOnDelete(customRange, currentIndex, textLength);
@@ -1253,8 +1282,24 @@ export function deleteCustomRanges(body: IDocumentBody, textLength: number, curr
continue;
}
Object.assign(customRange, transformed);
+ if (customRange.rangeType === CustomRangeType.SDT) {
+ const key = `${customRange.startIndex}:${customRange.endIndex}`;
+ const positions = coincidentSdts.get(key) ?? [];
+ positions.push(newCustomRanges.length);
+ coincidentSdts.set(key, positions);
+ }
newCustomRanges.push(customRange);
}
+ for (const positions of coincidentSdts.values()) {
+ if (positions.length < 2) {
+ continue;
+ }
+ const ordered = positions.map((index) => newCustomRanges[index])
+ .sort((left, right) => originalSdtLengths.get(left)! - originalSdtLengths.get(right)!);
+ positions.forEach((index, offset) => {
+ newCustomRanges[index] = ordered[offset];
+ });
+ }
body.customRanges = mergeContinuousRanges(newCustomRanges);
}
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts
index 954148d09f..e44a3efbf0 100644
--- a/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { IDocumentBody } from '../../../../types/interfaces';
-import { deleteContent } from '../../../../shared';
+import type { IDocumentBody } from '../../../../types/interfaces/i-document-data';
+import { deleteContent } from '../../../../shared/doc-tool';
import {
deleteBlockRanges,
deleteColumnGroups,
@@ -37,6 +37,15 @@ export function updateAttributeByDelete(body: IDocumentBody, textLength: number,
const startIndex = currentIndex;
const endIndex = currentIndex + textLength;
+ const removedRenderedPageBreaks = body.renderedPageBreaks
+ ?.filter((offset) => offset >= startIndex && offset < endIndex)
+ .map((offset) => offset - startIndex);
+ if (body.renderedPageBreaks != null) {
+ body.renderedPageBreaks = body.renderedPageBreaks
+ .filter((offset) => offset < startIndex || offset >= endIndex)
+ .map((offset) => offset >= endIndex ? offset - textLength : offset);
+ }
+
const removeTextRuns = deleteTextRuns(body, textLength, currentIndex);
const removeParagraphs = deleteParagraphs(body, textLength, currentIndex);
@@ -69,6 +78,7 @@ export function updateAttributeByDelete(body: IDocumentBody, textLength: number,
return {
dataStream: removeDataStream,
+ renderedPageBreaks: removedRenderedPageBreaks,
textRuns: removeTextRuns,
paragraphs: removeParagraphs,
sectionBreaks: removeSectionBreaks,
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts
index e456065aba..b0ad0b8beb 100644
--- a/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { IDocumentBody } from '../../../../types/interfaces';
-import { insertTextToContent } from '../../../../shared';
+import type { IDocumentBody } from '../../../../types/interfaces/i-document-data';
+import { insertTextToContent } from '../../../../shared/doc-tool';
import {
insertBlockRanges,
insertColumnGroups,
@@ -40,6 +40,13 @@ export function updateAttributeByInsert(
const originalDataStream = body.dataStream;
body.dataStream = insertTextToContent(body.dataStream, currentIndex, insertBody.dataStream);
+ if (body.renderedPageBreaks != null || insertBody.renderedPageBreaks != null) {
+ body.renderedPageBreaks = [
+ ...(body.renderedPageBreaks ?? []).map((offset) => offset >= currentIndex ? offset + textLength : offset),
+ ...(insertBody.renderedPageBreaks ?? []).map((offset) => offset + currentIndex),
+ ].sort((left, right) => left - right);
+ }
+
insertTextRuns(body, insertBody, textLength, currentIndex);
insertParagraphs(body, insertBody, textLength, currentIndex, false, originalDataStream);
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts
index 3899483ddd..4c28f0ef6f 100644
--- a/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts
@@ -27,7 +27,7 @@ import type {
ITextRun,
} from '../../../../types/interfaces';
import { Tools, UpdateDocsAttributeType } from '../../../../shared';
-import { CustomDecorationType } from '../../../../types/interfaces';
+import { CustomDecorationType, CustomRangeType } from '../../../../types/interfaces';
import { PresetListType } from '../../preset-list-type';
import {
deleteBlockRanges,
@@ -628,6 +628,27 @@ function updateCustomRanges(
updateDataCustomRanges.forEach((customRange) => {
const { startIndex, endIndex } = customRange;
+ const existingSdt = customRange.rangeType === CustomRangeType.SDT
+ ? newCustomRanges.find((range) => range.rangeType === CustomRangeType.SDT && range.rangeId === customRange.rangeId)
+ : undefined;
+
+ // A retain carrying metadata can cover only one fragment of an enclosing SDT
+ // after TextX composition (for example, a value replacement between cell
+ // boundary tokens). In that case the retained range is a property update for
+ // the existing entity, not a second SDT with clipped boundaries.
+ if (existingSdt) {
+ // A clipped fragment touches the retain edge. An interior boundary is
+ // explicit (for example, undoing an extension past a paragraph mark).
+ if (startIndex > 0) {
+ existingSdt.startIndex = startIndex + currentIndex;
+ }
+ if (endIndex < textLength - 1) {
+ existingSdt.endIndex = endIndex + currentIndex;
+ }
+ existingSdt.properties = Tools.deepClone(customRange.properties);
+ existingSdt.wholeEntity = customRange.wholeEntity;
+ return;
+ }
newCustomRanges.push({
...customRange,
startIndex: startIndex + currentIndex,
@@ -635,6 +656,26 @@ function updateCustomRanges(
});
});
+ // A retained parent can shrink onto a fully replaced child. Preserve the
+ // update's nesting order only for coincident SDTs; leave other ranges alone.
+ const updateOrder = new Map(updateDataCustomRanges.map((range, index) => [range.rangeId, index]));
+ const coincidentSdts = new Map<string, number[]>();
+ newCustomRanges.forEach((range, index) => {
+ if (range.rangeType !== CustomRangeType.SDT || !updateOrder.has(range.rangeId)) {
+ return;
+ }
+ const key = `${range.startIndex}:${range.endIndex}`;
+ const positions = coincidentSdts.get(key) ?? [];
+ positions.push(index);
+ coincidentSdts.set(key, positions);
+ });
+ for (const positions of coincidentSdts.values()) {
+ const ordered = positions.map((index) => newCustomRanges[index])
+ .sort((left, right) => updateOrder.get(left.rangeId)! - updateOrder.get(right.rangeId)!);
+ positions.forEach((position, index) => {
+ newCustomRanges[position] = ordered[index];
+ });
+ }
body.customRanges = mergeContinuousRanges(newCustomRanges);
return removeCustomRanges;
diff --git a/packages/core/src/docs/data-model/text-x/apply.ts b/packages/core/src/docs/data-model/text-x/apply.ts
index 5bbaf4164b..e88a3011ad 100644
--- a/packages/core/src/docs/data-model/text-x/apply.ts
+++ b/packages/core/src/docs/data-model/text-x/apply.ts
@@ -14,15 +14,16 @@
* limitations under the License.
*/
-import type { IDocumentBody } from '../../../types/interfaces';
+import type { IDocumentBody } from '../../../types/interfaces/i-document-data';
import type { TextXAction } from './action-types';
import { MemoryCursor } from '../../../common/memory-cursor';
-import { Tools } from '../../../shared';
import { UpdateDocsAttributeType } from '../../../shared/command-enum';
+import { Tools } from '../../../shared/tools';
import { TextXActionType } from './action-types';
import { updateAttributeByDelete } from './apply-utils/delete-apply';
import { updateAttributeByInsert } from './apply-utils/insert-apply';
import { updateAttribute } from './apply-utils/update-apply';
+import { applyRangeUpdates, getRangeUpdates, validateRangeUpdates } from './custom-range-update';
function updateApply(
doc: IDocumentBody,
@@ -61,6 +62,23 @@ function insertApply(
}
export function textXApply(doc: IDocumentBody, actions: TextXAction[]): IDocumentBody {
+ if (actions.some((action) => action.t !== TextXActionType.RETAIN && action.valueRangeId !== undefined &&
+ (typeof action.valueRangeId !== 'string' || !action.valueRangeId))) {
+ throw new Error('Invalid scalar value range identity.');
+ }
+ const updates = getRangeUpdates(actions);
+ if (updates.length) {
+ const resultLength = actions.reduce((length, action) => {
+ if (action.t === TextXActionType.INSERT) {
+ return length + action.len;
+ }
+ if (action.t === TextXActionType.DELETE) {
+ return length - action.len;
+ }
+ return length;
+ }, doc.dataStream.length);
+ validateRangeUpdates(updates, resultLength);
+ }
const memoryCursor = new MemoryCursor();
memoryCursor.reset();
@@ -98,6 +116,7 @@ export function textXApply(doc: IDocumentBody, actions: TextXAction[]): IDocumen
}
});
+ applyRangeUpdates(doc, updates);
return doc;
}
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/text-x-utils.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/text-x-utils.spec.ts
new file mode 100644
index 0000000000..2996445c93
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/text-x-utils.spec.ts
@@ -0,0 +1,50 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentBody } from '../../../../../types/interfaces/i-document-data';
+import { describe, expect, it } from 'vitest';
+import { CustomRangeType } from '../../../../../types/interfaces/i-document-data';
+import { TextX } from '../../text-x';
+import { deleteSelectionTextX } from '../text-x-utils';
+
+describe('deleteSelectionTextX structural expansion', () => {
+ it.each([0, 3])('preserves an unrelated blank bookmark when deleting character %i', (startOffset) => {
+ const body: IDocumentBody = {
+ dataStream: 'A\r\rB\r\n',
+ paragraphs: [1, 2, 4].map((startIndex) => ({ startIndex, paragraphId: `p-${startIndex}` })),
+ sectionBreaks: [{ startIndex: 5, sectionId: 'body' }],
+ customRanges: [{ startIndex: 2, endIndex: 2, rangeId: 'blank-bookmark', rangeType: CustomRangeType.BOOKMARK }],
+ };
+ const expected = body.dataStream.slice(0, startOffset) + body.dataStream.slice(startOffset + 1);
+ const actions = deleteSelectionTextX([{ startOffset, endOffset: startOffset + 1, collapsed: false }], body);
+ TextX.apply(body, actions);
+ expect(body.dataStream).toBe(expected);
+ expect(body.paragraphs?.map((paragraph) => paragraph.paragraphId)).toEqual(['p-1', 'p-2', 'p-4']);
+ expect(body.customRanges?.map((range) => range.rangeId)).toEqual(['blank-bookmark']);
+ });
+
+ it('still deletes an explicitly selected blank bookmark paragraph', () => {
+ const body: IDocumentBody = {
+ dataStream: 'A\r\rB\r\n',
+ paragraphs: [1, 2, 4].map((startIndex) => ({ startIndex, paragraphId: `p-${startIndex}` })),
+ sectionBreaks: [{ startIndex: 5, sectionId: 'body' }],
+ customRanges: [{ startIndex: 2, endIndex: 2, rangeId: 'blank-bookmark', rangeType: CustomRangeType.BOOKMARK }],
+ };
+ TextX.apply(body, deleteSelectionTextX([{ startOffset: 2, endOffset: 3, collapsed: false }], body));
+ expect(body.dataStream).toBe('A\rB\r\n');
+ expect(body.customRanges).toHaveLength(0);
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts b/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
index 334ebc645f..4c137689ff 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
@@ -220,11 +220,13 @@ function isIntervalCoveredBySelections(
implicitTokens: Set<string>
): boolean {
let cursor = interval.startOffset;
+ let intersectsSelection = false;
for (const selection of selections) {
if (selection.endOffset <= cursor || selection.startOffset >= interval.endOffset) {
continue;
}
+ intersectsSelection = true;
const selectionStart = Math.max(selection.startOffset, interval.startOffset);
const selectionEnd = Math.min(selection.endOffset, interval.endOffset);
@@ -245,7 +247,7 @@ function isIntervalCoveredBySelections(
}
}
- return true;
+ return intersectsSelection;
}
function addCoveredIntervals(
diff --git a/packages/core/src/docs/data-model/text-x/custom-range-update.ts b/packages/core/src/docs/data-model/text-x/custom-range-update.ts
new file mode 100644
index 0000000000..0f32642647
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/custom-range-update.ts
@@ -0,0 +1,306 @@
+/**
+ * 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 { ICustomRange, IDocumentBody } from '../../../types/interfaces/i-document-data';
+import type { IRetainAction, TextXAction } from './action-types';
+import { UpdateDocsAttributeType } from '../../../shared/command-enum';
+import { Tools } from '../../../shared/tools';
+import { DataStreamTreeTokenType } from '../types';
+import { TextXActionType } from './action-types';
+import { deleteCustomRanges, insertCustomRanges } from './apply-utils/common';
+import { updateAttribute } from './apply-utils/update-apply';
+import { getBodySliceForSplitTextXAction } from './utils';
+
+export function getChangedPropertyPaths(before: unknown, after: unknown, path: string[] = []): string[][] {
+ if (Tools.diffValue(before, after)) {
+ return [];
+ }
+ if (after && typeof after === 'object' && !Array.isArray(after) &&
+ (before == null || (typeof before === 'object' && !Array.isArray(before)))) {
+ const previous = (before ?? {}) as Record<string, unknown>;
+ const next = after as Record<string, unknown>;
+ const keys = Array.from(new Set([...Object.keys(previous), ...Object.keys(next)]));
+ if (!keys.length && path.length) {
+ return [path];
+ }
+ return keys
+ .flatMap((key) => getChangedPropertyPaths(previous[key], next[key], [...path, key]));
+ }
+ return [path];
+}
+
+function validatePropertyPaths(paths: string[][]): void {
+ if (!Array.isArray(paths) || paths.some((path) => !Array.isArray(path) || !path.length || path.some((key) =>
+ typeof key !== 'string' || ['__proto__', 'prototype', 'constructor'].includes(key)))) {
+ throw new Error('Invalid custom range property paths.');
+ }
+}
+
+function patchRangeProperties(target: ICustomRange, source: ICustomRange, paths: string[][]): ICustomRange {
+ validatePropertyPaths(paths);
+ const result = Tools.deepClone(target);
+ for (const path of paths) {
+ let current = (result.properties ??= {}) as Record<string, unknown>;
+ let value: unknown = source.properties;
+ const parents: Array<{ object: Record<string, unknown>; key: string; value: unknown }> = [];
+ for (let index = 0; index < path.length; index++) {
+ const key = path[index];
+ value = value && typeof value === 'object' ? (value as Record<string, unknown>)[key] : undefined;
+ if (index === path.length - 1) {
+ if (value === undefined) {
+ delete current[key];
+ } else {
+ current[key] = Tools.deepClone(value);
+ }
+ } else {
+ if (!current[key] || typeof current[key] !== 'object' || Array.isArray(current[key])) {
+ current[key] = {};
+ }
+ parents.push({ object: current, key, value });
+ current = current[key] as Record<string, unknown>;
+ }
+ }
+ for (const parent of parents.reverse()) {
+ if (parent.value === undefined && Object.keys(parent.object[parent.key] as object).length === 0) {
+ delete parent.object[parent.key];
+ }
+ }
+ }
+ if (source.properties === undefined && !Object.keys(result.properties ?? {}).length) {
+ delete result.properties;
+ }
+ return result;
+}
+
+export function composeRangeUpdate(
+ first: NonNullable<IRetainAction['rangeUpdates']>[number] | undefined,
+ second: NonNullable<IRetainAction['rangeUpdates']>[number]
+): NonNullable<IRetainAction['rangeUpdates']>[number] {
+ if (!first || !second.propertyPaths || !second.range) {
+ return second;
+ }
+ if (!first.range) {
+ return first;
+ }
+ const propertyPaths = first.propertyPaths && [...first.propertyPaths, ...second.propertyPaths.filter((path) => !first.propertyPaths!.some((parent) =>
+ parent.length <= path.length && parent.every((key, index) => path[index] === key)))];
+ return { ...first, range: patchRangeProperties(first.range, second.range, second.propertyPaths), propertyPaths };
+}
+
+export function transformRangeUpdate(
+ update: NonNullable<IRetainAction['rangeUpdates']>[number],
+ concurrent: NonNullable<IRetainAction['rangeUpdates']>[number] | undefined,
+ priority: 'left' | 'right'
+): NonNullable<IRetainAction['rangeUpdates']> {
+ if (!concurrent || !update.range) {
+ return [update];
+ }
+ if (!concurrent.range) {
+ return [];
+ }
+ if (!update.propertyPaths || !concurrent.propertyPaths) {
+ return priority === 'left' ? [{ ...update, propertyPaths: undefined }] : [];
+ }
+ const propertyPaths = update.propertyPaths.filter((path) => priority === 'left' ||
+ !concurrent.propertyPaths!.some((other) => path.slice(0, Math.min(path.length, other.length))
+ .every((key, index) => other[index] === key)))
+ .map((path) => concurrent.propertyPaths!.find((other) => other.length < path.length &&
+ other.every((key, index) => path[index] === key)) ?? path);
+ return propertyPaths.length ? [{ ...update, propertyPaths }] : [];
+}
+
+export function getRangeUpdates(actions: TextXAction[]): NonNullable<IRetainAction['rangeUpdates']> {
+ const updates = new Map<string, NonNullable<IRetainAction['rangeUpdates']>[number]>();
+ for (const action of actions) {
+ if (action.t === TextXActionType.RETAIN) {
+ for (const update of action.rangeUpdates ?? []) {
+ updates.set(update.rangeId, composeRangeUpdate(updates.get(update.rangeId), update));
+ }
+ }
+ }
+ return updates.size ? Tools.deepClone(Array.from(updates.values())) : [];
+}
+
+// Identity edits must never enter the positional iterator: an insertion may
+// split every character of a retain, or a deletion may consume it altogether.
+export function withoutRangeUpdates(actions: TextXAction[]): TextXAction[] {
+ return actions.flatMap((action) => {
+ if (action.t === TextXActionType.INSERT && action.len > 1 &&
+ Array.from(action.body.dataStream).every((token) => token === DataStreamTreeTokenType.CUSTOM_RANGE_START || token === DataStreamTreeTokenType.CUSTOM_RANGE_END)) {
+ return Array.from(action.body.dataStream, (_, index) => ({
+ ...action,
+ len: 1,
+ body: getBodySliceForSplitTextXAction(action.body, index, index + 1, false),
+ }));
+ }
+ if (action.t !== TextXActionType.RETAIN || !action.rangeUpdates) {
+ return [action];
+ }
+ const { rangeUpdates, oldRangeUpdates, ...textAction } = action;
+ return textAction.len === 0 && !textAction.body ? [] : [textAction];
+ });
+}
+
+export function appendRangeUpdates(actions: TextXAction[], updates: IRetainAction['rangeUpdates']): TextXAction[] {
+ return updates?.length ? [...actions, { t: TextXActionType.RETAIN, len: 0, rangeUpdates: updates }] : actions;
+}
+
+export function validateRangeUpdates(updates: IRetainAction['rangeUpdates'], resultLength: number): void {
+ for (const { rangeId, range, nextRangeId, propertyPaths } of updates ?? []) {
+ if (propertyPaths !== undefined) {
+ validatePropertyPaths(propertyPaths);
+ if (!range) {
+ throw new Error('Invalid custom range property paths.');
+ }
+ }
+ if (typeof rangeId !== 'string' || !rangeId ||
+ (nextRangeId !== undefined && nextRangeId !== null && typeof nextRangeId !== 'string') ||
+ (range !== null && (range == null || typeof range !== 'object' || Array.isArray(range) ||
+ range.rangeId !== rangeId || !Number.isInteger(range.startIndex) || !Number.isInteger(range.endIndex) ||
+ range.startIndex < 0 || range.endIndex < range.startIndex || range.endIndex >= resultLength))) {
+ throw new Error('Invalid custom range identity or bounds.');
+ }
+ }
+}
+
+export function applyRangeUpdates(doc: IDocumentBody, updates: IRetainAction['rangeUpdates']): void {
+ if (!updates?.length) {
+ return;
+ }
+ const ranges = doc.customRanges ?? [];
+ for (const { rangeId, range, nextRangeId, propertyPaths } of [...updates].reverse()) {
+ const index = ranges.findIndex((item) => item.rangeId === rangeId);
+ if (range && propertyPaths) {
+ if (index >= 0) {
+ ranges[index] = patchRangeProperties(ranges[index], range, propertyPaths);
+ }
+ continue;
+ }
+ if (range) {
+ if (nextRangeId !== undefined) {
+ if (index >= 0) {
+ ranges.splice(index, 1);
+ }
+ const nextIndex = ranges.findIndex((item) => item.rangeId === nextRangeId);
+ ranges.splice(nextIndex < 0 ? ranges.length : nextIndex, 0, Tools.deepClone(range));
+ } else if (index >= 0) {
+ ranges[index] = Tools.deepClone(range);
+ } else {
+ ranges.push(Tools.deepClone(range));
+ }
+ } else if (index >= 0) {
+ ranges.splice(index, 1);
+ }
+ }
+ doc.customRanges = ranges;
+}
+
+export function moveRangeUpdates(
+ updates: NonNullable<IRetainAction['rangeUpdates']>,
+ actions: TextXAction[],
+ preserveProperties = false
+): NonNullable<IRetainAction['rangeUpdates']> {
+ return updates.map((update) => {
+ const { rangeId, range } = update;
+ if (!range && preserveProperties) {
+ return update;
+ }
+ const body: IDocumentBody = { dataStream: '', customRanges: range ? [Tools.deepClone(range)] : [] };
+ let offset = 0;
+ for (const action of actions) {
+ if (action.t === TextXActionType.INSERT) {
+ insertCustomRanges(body, {
+ dataStream: '',
+ customRanges: Tools.deepClone(action.body.customRanges?.filter((item) => item.rangeId === rangeId)),
+ }, action.len, offset);
+ } else if (action.t === TextXActionType.DELETE) {
+ deleteCustomRanges(body, action.len, offset);
+ continue;
+ } else if (action.body?.customRanges) {
+ updateAttribute(body, {
+ dataStream: '',
+ customRanges: Tools.deepClone(action.body.customRanges.filter((item) => item.rangeId === rangeId)),
+ }, action.len, offset, action.coverType ?? UpdateDocsAttributeType.COVER);
+ }
+ offset += action.len;
+ }
+ const moved = body.customRanges?.find((item) => item.rangeId === rangeId);
+ return { ...update, propertyPaths: moved ? update.propertyPaths : undefined, range: moved && range && preserveProperties
+ ? { ...Tools.deepClone(range), startIndex: moved.startIndex, endIndex: moved.endIndex }
+ : moved ?? null };
+ });
+}
+
+/** A concurrent metadata payload must not resurrect an explicitly removed identity. */
+export function reconcileRangeUpdates(actions: TextXAction[], updates: IRetainAction['rangeUpdates']): TextXAction[] {
+ const byId = new Map(updates?.map((update) => [update.rangeId, update]));
+ if (!byId.size) {
+ return actions;
+ }
+ return actions.map((action) => {
+ if (!action.body?.customRanges) {
+ return action;
+ }
+ return { ...action, body: { ...action.body, customRanges: action.body.customRanges.flatMap((range) => {
+ if (!byId.has(range.rangeId)) {
+ return [range];
+ }
+ const updated = byId.get(range.rangeId)!;
+ if (!updated.range) {
+ return [];
+ }
+ const replacement = updated.propertyPaths
+ ? patchRangeProperties(range, updated.range, updated.propertyPaths)
+ : Tools.deepClone(updated.range);
+ return [{ ...replacement, startIndex: range.startIndex, endIndex: range.endIndex }];
+ }) } };
+ });
+}
+
+/** Dropping a concurrent restoration also drops its delimiters, not its text. */
+export function dropRemovedRangeAnchors(
+ actions: TextXAction[],
+ suppressed: ICustomRange[],
+ updates: NonNullable<IRetainAction['rangeUpdates']>
+): TextXAction[] {
+ if (!suppressed.length) {
+ return appendRangeUpdates(actions, updates);
+ }
+ const kept: TextXAction[] = [];
+ const removed: TextXAction[] = [];
+ let offset = 0;
+ let deletedEnd = 0;
+ for (const action of actions) {
+ const token = action.body?.dataStream;
+ const isSuppressedAnchor = action.t === TextXActionType.INSERT && action.len === 1 &&
+ suppressed.some((range) =>
+ (token === DataStreamTreeTokenType.CUSTOM_RANGE_START && offset === range.startIndex) ||
+ (token === DataStreamTreeTokenType.CUSTOM_RANGE_END && offset === range.endIndex));
+ if (isSuppressedAnchor) {
+ if (offset > deletedEnd) {
+ removed.push({ t: TextXActionType.RETAIN, len: offset - deletedEnd });
+ }
+ removed.push({ t: TextXActionType.DELETE, len: 1 });
+ deletedEnd = offset + 1;
+ } else {
+ kept.push(action);
+ }
+ if (action.t !== TextXActionType.DELETE) {
+ offset += action.len;
+ }
+ }
+ return appendRangeUpdates(kept, moveRangeUpdates(updates, removed));
+}
diff --git a/packages/core/src/docs/data-model/text-x/structure-validator.ts b/packages/core/src/docs/data-model/text-x/structure-validator.ts
index 1198ac81e5..6100a3673c 100644
--- a/packages/core/src/docs/data-model/text-x/structure-validator.ts
+++ b/packages/core/src/docs/data-model/text-x/structure-validator.ts
@@ -14,13 +14,12 @@
* limitations under the License.
*/
-import type { ICustomTable, IDocumentBody, IDocumentData, IDocumentNote } from '../../../types/interfaces/i-document-data';
+import type { ICustomRange, ICustomTable, IDocumentBody, IDocumentData, IDocumentNote } from '../../../types/interfaces/i-document-data';
import { CustomRangeType, PositionedObjectLayoutType, TableTextWrapType } from '../../../types/interfaces/i-document-data';
import { DataStreamTreeTokenType } from '../types';
import {
getBlockRangeInterval,
getColumnGroupRangeInterval,
- getTableRangeInterval,
intersectsOperationalIntervals,
} from './build-utils/range-interval';
@@ -54,6 +53,11 @@ export type DocStructureIssueCode =
| 'custom-block-token-mismatch'
| 'missing-custom-block-metadata'
| 'duplicate-custom-block-metadata'
+ | 'custom-range-token-mismatch'
+ | 'missing-custom-range-metadata'
+ | 'duplicate-custom-range-id'
+ | 'crossing-custom-range'
+ | 'unbalanced-custom-range'
| 'empty-column'
| 'empty-table-cell'
| 'unbalanced-column-group'
@@ -278,7 +282,7 @@ function scanDocumentStructuralTokens(dataStream: string): IDocumentStructuralTo
function validateTableMetadata(body: IDocumentBody, scan: IDocumentStructuralTokenScan, issues: IDocStructureIssue[], context: IValidationContext) {
const pairedTables = scan.tableRanges.pairs;
const metadataStarts = new Set<number>();
- let previousTable: ICustomTable | undefined;
+ const parents: ICustomTable[] = [];
const tables = sortStructuralRanges(body.tables ?? []);
for (const table of tables) {
@@ -307,10 +311,14 @@ function validateTableMetadata(body: IDocumentBody, scan: IDocumentStructuralTok
));
}
- if (previousTable && intersectsOperationalIntervals(getTableRangeInterval(previousTable), getTableRangeInterval(table))) {
- issues.push(createIssue(context, 'overlapping-table', 'Table ranges must not overlap.', table.startIndex));
+ while (parents.length > 0 && parents[parents.length - 1].endIndex <= table.startIndex) {
+ parents.pop();
}
- previousTable = table;
+ const parent = parents[parents.length - 1];
+ if (parent && (table.startIndex === parent.startIndex || table.endIndex >= parent.endIndex)) {
+ issues.push(createIssue(context, 'overlapping-table', 'Table ranges may nest but must not cross or duplicate.', table.startIndex));
+ }
+ parents.push(table);
}
for (const startIndex of pairedTables.keys()) {
@@ -452,16 +460,18 @@ function validateCustomBlockMetadata(body: IDocumentBody, scan: IDocumentStructu
function validateStructuralContainers(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {
const columnGroupStack: number[] = [];
const columnStack: Array<{ startIndex: number; hasChild: boolean }> = [];
- const tableStack: number[] = [];
- const tableRowStack: number[] = [];
- const tableCellStack: Array<{ startIndex: number; hasParagraph: boolean; hasSectionBreak: boolean }> = [];
+ const tableStack: Array<{
+ inRow: boolean;
+ cell?: { startIndex: number; hasParagraph: boolean; hasSectionBreak: boolean };
+ }> = [];
const tokenPattern = new RegExp(DOCUMENT_STRUCTURAL_TOKEN_PATTERN_SOURCE, 'g');
for (const match of body.dataStream.matchAll(tokenPattern)) {
const i = match.index;
const char = match[0];
const column = columnStack[columnStack.length - 1];
- const cell = tableCellStack[tableCellStack.length - 1];
+ const table = tableStack[tableStack.length - 1];
+ const cell = table?.cell;
if (char === DataStreamTreeTokenType.PARAGRAPH) {
if (column) {
@@ -498,33 +508,45 @@ function validateStructuralContainers(body: IDocumentBody, issues: IDocStructure
columnGroupStack.pop();
}
} else if (char === DataStreamTreeTokenType.TABLE_START) {
- tableStack.push(i);
+ if (table && !cell) {
+ issues.push(createIssue(context, 'unbalanced-table', 'Nested table must be inside a parent cell.', i));
+ }
+ tableStack.push({ inRow: false });
} else if (char === DataStreamTreeTokenType.TABLE_ROW_START) {
- tableRowStack.push(i);
+ if (!table || table.inRow) {
+ issues.push(createIssue(context, 'unbalanced-table', 'Table row must start inside a table without an open row.', i));
+ }
+ if (table) {
+ table.inRow = true;
+ }
} else if (char === DataStreamTreeTokenType.TABLE_CELL_START) {
- tableCellStack.push({ startIndex: i, hasParagraph: false, hasSectionBreak: false });
+ if (!table?.inRow || cell) {
+ issues.push(createIssue(context, 'unbalanced-table', 'Table cell must start inside a row without an open cell.', i));
+ }
+ if (table) {
+ table.cell = { startIndex: i, hasParagraph: false, hasSectionBreak: false };
+ }
} else if (char === DataStreamTreeTokenType.TABLE_CELL_END) {
- const closedCell = tableCellStack.pop();
- if (!closedCell) {
+ if (!cell) {
issues.push(createIssue(context, 'unbalanced-table', 'Table cell end token has no matching start.', i));
- } else if (!closedCell.hasParagraph || !closedCell.hasSectionBreak) {
- issues.push(createIssue(context, 'empty-table-cell', 'Table cell must contain a paragraph and section break child.', closedCell.startIndex));
+ } else if (!cell.hasParagraph || !cell.hasSectionBreak) {
+ issues.push(createIssue(context, 'empty-table-cell', 'Table cell must contain a paragraph and section break child.', cell.startIndex));
+ }
+ if (table) {
+ table.cell = undefined;
}
} else if (char === DataStreamTreeTokenType.TABLE_ROW_END) {
- if (tableCellStack.length > 0 || tableRowStack.length === 0) {
+ if (!table?.inRow || cell) {
issues.push(createIssue(context, 'unbalanced-table', 'Table row closes while a cell is still open.', i));
- tableCellStack.length = 0;
- } else {
- tableRowStack.pop();
+ }
+ if (table) {
+ table.inRow = false;
}
} else if (char === DataStreamTreeTokenType.TABLE_END) {
- if (tableCellStack.length > 0 || tableRowStack.length > 0 || tableStack.length === 0) {
+ if (!table || table.inRow || cell) {
issues.push(createIssue(context, 'unbalanced-table', 'Table closes while a row or cell is still open.', i));
- tableCellStack.length = 0;
- tableRowStack.length = 0;
- } else {
- tableStack.pop();
}
+ tableStack.pop();
}
}
@@ -532,11 +554,79 @@ function validateStructuralContainers(body: IDocumentBody, issues: IDocStructure
issues.push(createIssue(context, 'unbalanced-column-group', 'Column group or column token is not closed.', body.dataStream.length));
}
- if (tableStack.length > 0 || tableRowStack.length > 0 || tableCellStack.length > 0) {
+ if (tableStack.length > 0) {
issues.push(createIssue(context, 'unbalanced-table', 'Table, row, or cell token is not closed.', body.dataStream.length));
}
}
+function validateCustomRangeMetadata(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {
+ const pairs = new Map<number, number>();
+ const starts: number[] = [];
+ for (let index = 0; index < body.dataStream.length; index++) {
+ const token = body.dataStream[index];
+ if (token === DataStreamTreeTokenType.CUSTOM_RANGE_START) {
+ starts.push(index);
+ } else if (token === DataStreamTreeTokenType.CUSTOM_RANGE_END) {
+ const start = starts.pop();
+ if (start == null) {
+ issues.push(createIssue(context, 'unbalanced-custom-range', 'Custom range end token has no matching start.', index));
+ } else {
+ pairs.set(start, index);
+ }
+ }
+ }
+ for (const start of starts) {
+ issues.push(createIssue(context, 'unbalanced-custom-range', 'Custom range start token has no matching end.', start));
+ }
+
+ const ranges = body.customRanges ?? [];
+ const ids = new Set<string>();
+ for (const range of ranges) {
+ if (ids.has(range.rangeId)) {
+ issues.push(createIssue(context, 'duplicate-custom-range-id', 'Custom range ids must be unique.', range.startIndex));
+ }
+ ids.add(range.rangeId);
+
+ if (range.rangeType !== CustomRangeType.FIELD) {
+ continue;
+ }
+ if (
+ body.dataStream[range.startIndex] !== DataStreamTreeTokenType.CUSTOM_RANGE_START ||
+ body.dataStream[range.endIndex] !== DataStreamTreeTokenType.CUSTOM_RANGE_END ||
+ pairs.get(range.startIndex) !== range.endIndex
+ ) {
+ issues.push(createIssue(
+ context,
+ 'custom-range-token-mismatch',
+ 'Field metadata must point to a matching custom range token pair.',
+ range.startIndex
+ ));
+ }
+ }
+
+ for (const [start, end] of pairs) {
+ if (!ranges.some((range) => range.startIndex === start && range.endIndex === end)) {
+ issues.push(createIssue(context, 'missing-custom-range-metadata', 'Custom range token pair has no metadata.', start));
+ }
+ }
+
+ const sortedFields = ranges
+ .filter((range): range is ICustomRange => range.rangeType === CustomRangeType.FIELD)
+ .slice()
+ .sort((left, right) => left.startIndex - right.startIndex || right.endIndex - left.endIndex);
+ const parents: ICustomRange[] = [];
+ for (const range of sortedFields) {
+ while (parents.length > 0 && parents[parents.length - 1].endIndex < range.startIndex) {
+ parents.pop();
+ }
+ const parent = parents[parents.length - 1];
+ if (parent && range.endIndex > parent.endIndex) {
+ issues.push(createIssue(context, 'crossing-custom-range', 'Field ranges may nest but must not cross.', range.startIndex));
+ }
+ parents.push(range);
+ }
+}
+
export function validateDocBodyStructure(
body: IDocumentBody,
context: IValidationContext = { segmentType: 'body' }
@@ -552,6 +642,7 @@ export function validateDocBodyStructure(
validateColumnGroupMetadata(body, scan, issues, context);
validateCustomBlockMetadata(body, scan, issues, context);
validateStructuralContainers(body, issues, context);
+ validateCustomRangeMetadata(body, issues, context);
if (context.segmentType === 'header' || context.segmentType === 'footer') {
for (const range of body.customRanges ?? []) {
diff --git a/packages/core/src/docs/data-model/text-x/text-x.ts b/packages/core/src/docs/data-model/text-x/text-x.ts
index 6e8588be5c..a07924e452 100644
--- a/packages/core/src/docs/data-model/text-x/text-x.ts
+++ b/packages/core/src/docs/data-model/text-x/text-x.ts
@@ -15,10 +15,11 @@
*/
import type { ITextRange } from '../../../sheets/typedef';
-import type { IDocumentBody } from '../../../types/interfaces/i-document-data';
+import type { ICustomRange, IDocumentBody } from '../../../types/interfaces/i-document-data';
import type { IDeleteAction, IInsertAction, IRetainAction, TextXAction } from './action-types';
import { UpdateDocsAttributeType } from '../../../shared/command-enum';
import { Tools } from '../../../shared/tools';
+import { DataStreamTreeTokenType } from '../types';
import { ActionIterator } from './action-iterator';
import { PRESERVE_INSERTED_PARAGRAPH_IDS, TextXActionType } from './action-types';
import { textXApply } from './apply';
@@ -27,6 +28,17 @@ import {
normalizeInsertedSectionIdsForDocument,
RESTORE_INSERTED_PARAGRAPH_IDS,
} from './apply-utils/common';
+import {
+ appendRangeUpdates,
+ composeRangeUpdate,
+ dropRemovedRangeAnchors,
+ getChangedPropertyPaths,
+ getRangeUpdates,
+ moveRangeUpdates,
+ reconcileRangeUpdates,
+ transformRangeUpdate,
+ withoutRangeUpdates,
+} from './custom-range-update';
import { transformBody } from './transform-utils';
import { composeBody, getBodySlice, getBodySliceForTextXAction, isUselessRetainAction } from './utils';
@@ -34,6 +46,43 @@ function onlyHasDataStream(body: IDocumentBody) {
return Object.keys(body).length === 1;
}
+function getValueRangeIds(actions: TextXAction[]): Set<string> {
+ return new Set(actions.flatMap((action) => action.t !== TextXActionType.RETAIN && action.valueRangeId ? [action.valueRangeId] : []));
+}
+
+function withoutValueRangeMetadata(actions: TextXAction[], suppressed: Set<string>): TextXAction[] {
+ return actions.map((action) => {
+ if (!action.body?.customRanges?.some((range) => suppressed.has(range.rangeId))) {
+ return action;
+ }
+ const body: IDocumentBody = { ...action.body, customRanges: action.body.customRanges.filter((range) => !suppressed.has(range.rangeId)) };
+ if (!body.customRanges?.length) {
+ delete body.customRanges;
+ }
+ return { ...action, body };
+ });
+}
+
+function insertedAnchorPriority(first: TextXAction, second: TextXAction, priority: TPriority): boolean {
+ if (first?.t !== TextXActionType.INSERT || second?.t !== TextXActionType.INSERT) {
+ return priority === 'left';
+ }
+ const firstText = first.body.dataStream;
+ const secondText = second.body.dataStream;
+ if (firstText === secondText) {
+ return priority === 'left';
+ }
+ // Restored delimiters enclose text typed at the collapsed boundary. Neither
+ // side of a removed delimiter remains distinguishable as a text position.
+ if (firstText === DataStreamTreeTokenType.CUSTOM_RANGE_START || secondText === DataStreamTreeTokenType.CUSTOM_RANGE_END) {
+ return true;
+ }
+ if (firstText === DataStreamTreeTokenType.CUSTOM_RANGE_END || secondText === DataStreamTreeTokenType.CUSTOM_RANGE_START) {
+ return false;
+ }
+ return priority === 'left';
+}
+
function normalizeInsertActionParagraphIds(
body: IDocumentBody,
doc: IDocumentBody,
@@ -63,6 +112,17 @@ export class TextX {
// eslint-disable-next-line complexity
static compose(thisActions: TextXAction[], otherActions: TextXAction[]): TextXAction[] {
+ const thisUpdates = getRangeUpdates(thisActions);
+ const otherUpdates = getRangeUpdates(otherActions);
+ if (thisUpdates.length || otherUpdates.length) {
+ const thisText = withoutRangeUpdates(thisActions);
+ const otherText = withoutRangeUpdates(otherActions);
+ const updates = new Map(moveRangeUpdates(thisUpdates, otherText).map((update) => [update.rangeId, update]));
+ for (const update of otherUpdates) {
+ updates.set(update.rangeId, composeRangeUpdate(updates.get(update.rangeId), update));
+ }
+ return appendRangeUpdates(TextX.compose(thisText, otherText), Array.from(updates.values()));
+ }
const thisIter = new ActionIterator(thisActions);
const otherIter = new ActionIterator(otherActions);
@@ -148,26 +208,56 @@ export class TextX {
// priority - if true, this actions takes priority over other, that is, this actions are considered to happen "first".
// thisActions is the target action.
static transform(thisActions: TextXAction[], otherActions: TextXAction[], priority: TPriority = 'right'): TextXAction[] {
+ const thisUpdates = getRangeUpdates(thisActions);
+ const otherUpdates = getRangeUpdates(otherActions);
+ if (thisUpdates.length || otherUpdates.length) {
+ const thisText = withoutRangeUpdates(thisActions);
+ const otherText = withoutRangeUpdates(otherActions);
+ const otherAfterThis = TextX._transform(thisText, otherText, priority, true);
+ const movedUpdates = moveRangeUpdates(thisUpdates, otherAfterThis, true);
+ const updates = movedUpdates.flatMap((update) => transformRangeUpdate(
+ update,
+ otherUpdates.find((item) => item.rangeId === update.rangeId),
+ priority
+ ));
+ const suppressed = movedUpdates.flatMap((update) => update.range &&
+ otherUpdates.some((other) => other.rangeId === update.rangeId && !other.range)
+ ? [update.range]
+ : []);
+ return dropRemovedRangeAnchors(
+ reconcileRangeUpdates(TextX._transform(otherText, thisText, priority === 'left' ? 'right' : 'left', true), otherUpdates),
+ suppressed,
+ updates
+ );
+ }
return this._transform(otherActions, thisActions, priority === 'left' ? 'right' : 'left');
}
// otherActions is the actions to be transformed.
- static _transform(thisActions: TextXAction[], otherActions: TextXAction[], priority: TPriority = 'right'): TextXAction[] {
- const thisIter = new ActionIterator(thisActions);
-
- const otherIter = new ActionIterator(otherActions);
+ static _transform(thisActions: TextXAction[], otherActions: TextXAction[], priority: TPriority = 'right', rangeAnchorAffinity = false): TextXAction[] {
+ const thisValues = getValueRangeIds(thisActions);
+ const conflicts = new Set(Array.from(getValueRangeIds(otherActions)).filter((id) => thisValues.has(id)));
+ const thisIter = new ActionIterator(conflicts.size && priority === 'right' ? withoutValueRangeMetadata(thisActions, conflicts) : thisActions);
+ const otherIter = new ActionIterator(conflicts.size && priority === 'left' ? withoutValueRangeMetadata(otherActions, conflicts) : otherActions);
const textX = new TextX();
while (thisIter.hasNext() || otherIter.hasNext()) {
if (
thisIter.peekType() === TextXActionType.INSERT &&
- (priority === 'left' || otherIter.peekType() !== TextXActionType.INSERT)
+ ((rangeAnchorAffinity ? insertedAnchorPriority(thisIter.peek(), otherIter.peek(), priority) : priority === 'left') || otherIter.peekType() !== TextXActionType.INSERT)
) {
const thisAction = thisIter.next();
- textX.retain(thisAction.len);
+ if (thisAction.t === TextXActionType.INSERT && thisAction.valueRangeId && conflicts.has(thisAction.valueRangeId) && priority === 'right') {
+ textX.push({ t: TextXActionType.DELETE, len: thisAction.len, valueRangeId: thisAction.valueRangeId });
+ } else {
+ textX.retain(thisAction.len);
+ }
} else if (otherIter.peekType() === TextXActionType.INSERT) {
- textX.push(otherIter.next());
+ const otherAction = otherIter.next();
+ if (otherAction.t !== TextXActionType.INSERT || !otherAction.valueRangeId || !conflicts.has(otherAction.valueRangeId) || priority !== 'left') {
+ textX.push(otherAction);
+ }
} else {
const length = Math.min(thisIter.peekLength(), otherIter.peekLength());
const thisAction = thisIter.next(length);
@@ -235,6 +325,18 @@ export class TextX {
}
static invert(actions: TextXAction[]): TextXAction[] {
+ if (getRangeUpdates(actions).length) {
+ const restored = actions.flatMap((action) => {
+ if (action.t !== TextXActionType.RETAIN || !action.rangeUpdates) {
+ return [];
+ }
+ if (!action.oldRangeUpdates) {
+ throw new Error('makeInvertible must capture custom ranges before inversion.');
+ }
+ return action.oldRangeUpdates;
+ });
+ return appendRangeUpdates(TextX.invert(withoutRangeUpdates(actions)), Tools.deepClone(restored));
+ }
const invertedActions: TextXAction[] = [];
for (const action of actions) {
@@ -243,6 +345,7 @@ export class TextX {
t: TextXActionType.DELETE,
len: action.len,
body: action.body,
+ valueRangeId: action.valueRangeId,
});
} else if (action.t === TextXActionType.DELETE) {
if (action.body == null) {
@@ -258,6 +361,7 @@ export class TextX {
t: TextXActionType.INSERT,
body: action.body,
len: action.len,
+ valueRangeId: action.valueRangeId,
});
} else {
if (action.body != null) {
@@ -289,6 +393,17 @@ export class TextX {
const reservedSectionIds = new Set<string>();
for (const action of actions) {
+ if (action.t === TextXActionType.RETAIN && action.rangeUpdates) {
+ action.oldRangeUpdates = action.rangeUpdates.map(({ rangeId, propertyPaths }) => {
+ const index = doc.customRanges?.findIndex((range) => range.rangeId === rangeId) ?? -1;
+ return {
+ rangeId,
+ range: index < 0 ? null : Tools.deepClone(doc.customRanges![index]),
+ nextRangeId: index < 0 ? undefined : doc.customRanges![index + 1]?.rangeId ?? null,
+ propertyPaths: index < 0 ? undefined : propertyPaths,
+ };
+ });
+ }
if (action.t === TextXActionType.INSERT) {
normalizeInsertActionParagraphIds(action.body, doc, index, reservedParagraphIds);
normalizeInsertedSectionIdsForDocument(doc.sectionBreaks, action.body.sectionBreaks, reservedSectionIds);
@@ -331,6 +446,21 @@ export class TextX {
private _actions: TextXAction[] = [];
+ /** Edits only changed property leaves; does not replace range identity, bounds or peer properties. */
+ updateCustomRangeProperties(range: ICustomRange, properties: NonNullable<ICustomRange['properties']>): this {
+ const propertyPaths = getChangedPropertyPaths(range.properties ?? {}, properties);
+ if (propertyPaths.length) {
+ this.updateCustomRanges([{ rangeId: range.rangeId, range: { ...range, properties }, propertyPaths }]);
+ }
+ return this;
+ }
+
+ /** Updates identities after all text edits; range positions refer to the resulting document. */
+ updateCustomRanges(updates: NonNullable<IRetainAction['rangeUpdates']>): this {
+ this.push({ t: TextXActionType.RETAIN, len: 0, rangeUpdates: updates });
+ return this;
+ }
+
insert(len: number, body: IDocumentBody): this {
const insertAction: IInsertAction = {
t: TextXActionType.INSERT,
@@ -397,13 +527,13 @@ export class TextX {
const newAction = Tools.deepClone(args[0]);
// Nothing need to do, if the retain 0 and body is null.
- if (newAction.t === TextXActionType.RETAIN && newAction.len === 0 && newAction.body == null) {
+ if (newAction.t === TextXActionType.RETAIN && newAction.len === 0 && newAction.body == null && !newAction.rangeUpdates) {
return this;
}
if (typeof lastAction === 'object') {
// if lastAction and newAction are both delete action, merge the two actions and return this.
- if (lastAction.t === TextXActionType.DELETE && newAction.t === TextXActionType.DELETE) {
+ if (lastAction.t === TextXActionType.DELETE && newAction.t === TextXActionType.DELETE && lastAction.valueRangeId === newAction.valueRangeId) {
lastAction.len += newAction.len;
return this;
@@ -423,14 +553,14 @@ export class TextX {
}
// if lastAction and newAction are both retain action and has no body, merge the two actions and return this.
- if (lastAction.t === TextXActionType.RETAIN && newAction.t === TextXActionType.RETAIN && lastAction.body == null && newAction.body == null) {
+ if (lastAction.t === TextXActionType.RETAIN && newAction.t === TextXActionType.RETAIN && lastAction.body == null && newAction.body == null && !lastAction.rangeUpdates && !newAction.rangeUpdates) {
lastAction.len += newAction.len;
return this;
}
// Both are insert action, and has no styles, merge it.
- if (lastAction.t === TextXActionType.INSERT && onlyHasDataStream(lastAction.body) && newAction.t === TextXActionType.INSERT && onlyHasDataStream(newAction.body)) {
+ if (lastAction.t === TextXActionType.INSERT && onlyHasDataStream(lastAction.body) && newAction.t === TextXActionType.INSERT && onlyHasDataStream(newAction.body) && lastAction.valueRangeId === newAction.valueRangeId) {
lastAction.len += newAction.len;
lastAction.body.dataStream += newAction.body.dataStream;
diff --git a/packages/core/src/docs/data-model/text-x/utils.ts b/packages/core/src/docs/data-model/text-x/utils.ts
index b30c92eaec..630773ecee 100644
--- a/packages/core/src/docs/data-model/text-x/utils.ts
+++ b/packages/core/src/docs/data-model/text-x/utils.ts
@@ -32,6 +32,7 @@ import type { IRetainAction } from './action-types';
import { merge } from '../../../common/lodash';
import { UpdateDocsAttributeType } from '../../../shared/command-enum';
import { Tools } from '../../../shared/tools';
+import { CustomRangeType } from '../../../types/interfaces/i-document-data';
import { DataStreamTreeTokenType } from '../types';
import { PRESERVE_INSERTED_PARAGRAPH_IDS } from './action-types';
import { normalizeTextRuns } from './apply-utils/common';
@@ -350,6 +351,12 @@ export function getBodySlice(
dataStream: dataStream.slice(startOffset, endOffset),
};
+ if (body.renderedPageBreaks != null) {
+ docBody.renderedPageBreaks = body.renderedPageBreaks
+ .filter((offset) => offset >= startOffset && offset < endOffset)
+ .map((offset) => offset - startOffset);
+ }
+
if ((body as IDocumentBody & Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS]) {
(docBody as IDocumentBody & Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS] = true;
}
@@ -389,7 +396,15 @@ export function getBodySlice(
}
const { customRanges } = getCustomRangeSlice(body, startOffset, endOffset);
if (customRanges) {
- docBody.customRanges = customRanges;
+ docBody.customRanges = type === SliceBodyType.copy
+ ? customRanges.filter((range) =>
+ range.rangeType !== CustomRangeType.FIELD ||
+ (
+ docBody.dataStream[range.startIndex] === DataStreamTreeTokenType.CUSTOM_RANGE_START &&
+ docBody.dataStream[range.endIndex] === DataStreamTreeTokenType.CUSTOM_RANGE_END
+ )
+ )
+ : customRanges;
} else if (returnEmptyArray) {
docBody.customRanges = [];
}
@@ -429,6 +444,9 @@ export function getBodySliceForSplitTextXAction(
}
function shiftBodyMetadata(body: IDocumentBody, leftOffset: number, rightOffset: number): void {
+ if (body.renderedPageBreaks != null) {
+ body.renderedPageBreaks = body.renderedPageBreaks.map((offset) => offset + leftOffset);
+ }
body.textRuns?.forEach((textRun) => {
textRun.st += leftOffset;
textRun.ed += leftOffset;
@@ -577,20 +595,27 @@ function composeCustomRanges(
return updateDataCustomRanges;
}
- if (originCustomRanges.length > 1 || updateDataCustomRanges.length > 1) {
- throw new Error('Cannot cover multiple customRanges');
- }
-
if (coverType === UpdateDocsAttributeType.REPLACE) {
- return [{
- ...updateDataCustomRanges[0],
- }];
- } else {
- return [{
- ...originCustomRanges[0],
- ...updateDataCustomRanges[0],
- }];
- }
+ return updateDataCustomRanges.map((range) => ({ ...range }));
+ }
+
+ const updates = new Map(updateDataCustomRanges.map((range) => [range.rangeId, range]));
+ // Hyperlinks are exclusive: a replacement can have a new id at the same
+ // boundaries. Nested FIELD/SDT entities still compose by their own ids.
+ const composed = originCustomRanges.filter((range) => !updateDataCustomRanges.some((update) =>
+ range.rangeType === CustomRangeType.HYPERLINK &&
+ update.rangeType === CustomRangeType.HYPERLINK &&
+ update.rangeId !== range.rangeId &&
+ update.startIndex === range.startIndex && update.endIndex === range.endIndex
+ )).map((range) => {
+ const update = updates.get(range.rangeId);
+ if (update == null) {
+ return range;
+ }
+ updates.delete(range.rangeId);
+ return { ...range, ...update };
+ });
+ return [...composed, ...updates.values()];
}
function composeCustomDecorations(
@@ -629,6 +654,11 @@ export function composeBody(
dataStream: thisBody.dataStream,
};
+ // Soft-break provenance belongs to the inserted tokens, not to text formatting.
+ if (thisBody.renderedPageBreaks != null) {
+ retBody.renderedPageBreaks = [...thisBody.renderedPageBreaks];
+ }
+
if (
(thisBody as IDocumentBody & Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS] ||
(otherBody as IDocumentBody & Record<string, unknown>)[PRESERVE_INSERTED_PARAGRAPH_IDS]
@@ -749,6 +779,9 @@ function composeColumnGroups(
}
export function isUselessRetainAction(action: IRetainAction): boolean {
+ if (action.rangeUpdates?.length) {
+ return false;
+ }
const { body } = action;
if (body == null) {
diff --git a/packages/core/src/docs/sdt-binding.ts b/packages/core/src/docs/sdt-binding.ts
new file mode 100644
index 0000000000..cc661a1e59
--- /dev/null
+++ b/packages/core/src/docs/sdt-binding.ts
@@ -0,0 +1,44 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentBody, ISdtCustomRange } from '../types/interfaces/i-document-data';
+
+export function getSdtBindingKey(range: ISdtCustomRange): string | undefined {
+ const binding = range.properties?.dataBinding;
+ if (!binding?.storeItemID || !binding.xpath) {
+ return;
+ }
+ return JSON.stringify([binding.storeItemID.toLowerCase(), binding.xpath, binding.prefixMappings ?? '']);
+}
+
+/** Scalar XML values, independent of the control's display label or date format. */
+export function getSdtBindingValue(body: IDocumentBody, range: ISdtCustomRange): string | undefined {
+ if (range.properties.showingPlaceholder) {
+ return '';
+ }
+ if (range.properties.kind === 'checkbox') {
+ return range.properties.checkbox?.checked ? 'true' : 'false';
+ }
+ const text = body.dataStream.slice(range.startIndex, range.endIndex + 1)
+ .replace(/^[\x00-\x08\x0A-\x1F]+|[\x00-\x08\x0A-\x1F]+$/g, '');
+ if (range.properties.kind === 'date') {
+ return range.properties.date?.fullDate ?? text;
+ }
+ if (range.properties.kind === 'dropDownList' || range.properties.kind === 'comboBox') {
+ return range.properties.listItems?.find((item) => item.displayText === text)?.value ?? text;
+ }
+ return ['text', 'richText'].includes(range.properties.kind) ? text : undefined;
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 5d60e3f372..6592bd016d 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 { getSdtBindingKey, getSdtBindingValue } from './docs/sdt-binding';
export { EventState, EventSubject, fromEventSubject } from './observer/observable';
export type { IEventObserver } from './observer/observable';
export { AuthzIoLocalService } from './services/authz-io/authz-io-local.service';
diff --git a/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts b/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts
index 66dab29e06..936327f101 100644
--- a/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts
+++ b/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts
@@ -314,6 +314,7 @@ describe('LocalUndoRedoService', () => {
it('should resolve focused unit id from sheet editor contexts and clear unit stacks', () => {
contextService.setContextValue(FOCUSING_SHEET, true);
contextService.setContextValue(FOCUSING_FX_BAR_EDITOR, true);
+ contextService.setContextValue(EDITOR_ACTIVATED, true);
undoRedoService.pushUndoRedo({
unitID: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
undoMutations: [{ id: MUTATION_ID, params: { label: 'fx-undo' } }],
@@ -322,6 +323,17 @@ describe('LocalUndoRedoService', () => {
});
expect(undoRedoService.pitchTopUndoElement()?.id).toBe('fx');
+ undoRedoService.pushUndoRedo({
+ unitID: 'unit-1',
+ undoMutations: [{ id: MUTATION_ID, params: { label: 'sheet-undo' } }],
+ redoMutations: [{ id: MUTATION_ID, params: { label: 'sheet-redo' } }],
+ });
+ // Committing a formula ends editing even if its focus context outlives the editor.
+ contextService.setContextValue(EDITOR_ACTIVATED, false);
+ expect(commandService.syncExecuteCommand(UndoCommandId)).toBe(true);
+ expect(commandService.syncExecuteCommand(RedoCommandId)).toBe(true);
+ expect(mutationLog).toEqual(['sheet-undo', 'sheet-redo']);
+
contextService.setContextValue(FOCUSING_FX_BAR_EDITOR, false);
contextService.setContextValue(EDITOR_ACTIVATED, true);
undoRedoService.pushUndoRedo({
diff --git a/packages/core/src/services/undoredo/undoredo.service.ts b/packages/core/src/services/undoredo/undoredo.service.ts
index c1cbf6e7b3..f2beb4c5e3 100644
--- a/packages/core/src/services/undoredo/undoredo.service.ts
+++ b/packages/core/src/services/undoredo/undoredo.service.ts
@@ -424,7 +424,7 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
const isFocusEditor = this._contextService.getContextValue(EDITOR_ACTIVATED);
if (isFocusSheet) {
- if (isFocusFormulaEditor) {
+ if (isFocusFormulaEditor && isFocusEditor) {
unitID = DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;
} else if (isFocusEditor) {
unitID = DOCS_NORMAL_EDITOR_UNIT_ID_KEY;
diff --git a/packages/core/src/shared/__tests__/compare.spec.ts b/packages/core/src/shared/__tests__/compare.spec.ts
new file mode 100644
index 0000000000..eb49afeb26
--- /dev/null
+++ b/packages/core/src/shared/__tests__/compare.spec.ts
@@ -0,0 +1,28 @@
+/**
+ * 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 { describe, expect, it } from 'vitest';
+import { isSameStyleTextRun } from '../compare';
+
+describe('isSameStyleTextRun', () => {
+ it.each(['directTextStyle', 'sourceTextStyle'])('preserves different imported %s when display styles match', (key) => {
+ const first = { st: 0, ed: 3, ts: { ff: 'Calibri' }, [key]: { ff: 'Calibri', eastAsiaLanguage: 'nl-NL' } };
+ const second = { st: 3, ed: 6, ts: { ff: 'Calibri' }, [key]: { ff: 'Calibri' } };
+ expect(isSameStyleTextRun(first, second)).toBe(false);
+ expect(isSameStyleTextRun(second, first)).toBe(false);
+ expect(isSameStyleTextRun(first, { ...first, st: 3, ed: 6 })).toBe(true);
+ });
+});
diff --git a/packages/core/src/shared/compare.ts b/packages/core/src/shared/compare.ts
index ba4fa026f2..364deef05b 100644
--- a/packages/core/src/shared/compare.ts
+++ b/packages/core/src/shared/compare.ts
@@ -40,11 +40,23 @@ export function isSameStyleTextRun(tr1: ITextRun, tr2: ITextRun) {
const ts1 = tr1.ts || {};
const ts2 = tr2.ts || {};
- if (tr1.sId !== tr2.sId) {
+ if (tr1.sId !== tr2.sId || !deepCompare(ts1, ts2)) {
return false;
}
- return deepCompare(ts1, ts2);
+ // Importers retain formatting provenance alongside ts; merging different
+ // metadata would silently discard it even outside the edited range.
+ const metadataKeys = new Set([...Object.keys(tr1), ...Object.keys(tr2)]);
+ for (const key of metadataKeys) {
+ if (key === 'st' || key === 'ed' || key === 'ts' || key === 'sId') {
+ continue;
+ }
+ if (!deepCompare((tr1 as IAnyObject)[key], (tr2 as IAnyObject)[key])) {
+ return false;
+ }
+ }
+
+ return true;
}
export function checkForSubstrings(searchString: string, substrings: string[]): boolean {
diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.ts
index 15a9a34c91..f99c5afd33 100644
--- a/packages/core/src/types/interfaces/i-document-data.ts
+++ b/packages/core/src/types/interfaces/i-document-data.ts
@@ -50,6 +50,8 @@ export interface IReferenceSource {
tableSource?: ITables; // Table
footers?: IFooters;
headers?: IHeaders;
+ footnotes?: Record<string, IDocxNoteStory>;
+ endnotes?: Record<string, IDocxNoteStory>;
lists?: ILists;
drawings?: IDrawings;
drawingsOrder?: string[];
@@ -113,10 +115,19 @@ export interface IDocumentNote {
customMark?: string;
/** Style of the generated note marker; it does not affect text inserted at body offset zero. */
referenceTextStyle?: ITextStyle;
+ /** False preserves an imported note body without a reference marker; the main-story anchor is unaffected. */
+ showBodyReference?: boolean;
}
export type IFootnoteCustomRange = ICustomRange<{ noteId: string }>;
+/** A note story keyed by its OOXML id, independently of its displayed number. */
+export interface IDocxNoteStory {
+ noteId: string;
+ type: 'normal' | 'separator' | 'continuationSeparator' | 'continuationNotice';
+ body: IDocumentBody;
+ tableSource?: ITables;
+}
/**
* Set of headers
*/
@@ -431,6 +442,8 @@ export interface IHyperlink {
url?: string;
bookmarkId?: string; // bookmarkId
headingId?: string; // headingId
+ /** Use authored text formatting instead of the default link color and underline. */
+ textStyleMode?: 'link' | 'text';
}
/**
@@ -469,7 +482,123 @@ export interface ICustomRange<T extends Record<string, any> = Record<string, any
properties?: T;
}
-export type IHyperLinkCustomRange = ICustomRange<{ url: string }>;
+export type IHyperLinkCustomRange = ICustomRange<IHyperlink>;
+
+/** Legacy Word form field settings. Macro names are retained as data, never executed by the SDK. */
+export interface IFormFieldData {
+ name?: string;
+ enabled?: BooleanNumber;
+ calcOnExit?: BooleanNumber;
+ entryMacro?: string;
+ exitMacro?: string;
+ helpText?: { type?: 'text' | 'autoText'; value?: string };
+ statusText?: { type?: 'text' | 'autoText'; value?: string };
+ tabIndex?: number;
+ textInput?: { type?: string; default?: string; maxLength?: number; format?: string };
+ checkBox?: { size?: number; sizeAuto?: BooleanNumber; default?: BooleanNumber; checked?: BooleanNumber };
+ ddList?: { default?: number; result?: number; entries?: string[] };
+}
+
+export interface IFieldRangeProperties {
+ /** Original OOXML field instruction. This is the round-trip source of truth. */
+ instruction: string;
+ /** Upper-case first token of `instruction`, used only for field dispatch. */
+ fieldType: string;
+ sourceKind?: 'complex' | 'simple';
+ dirty?: BooleanNumber;
+ locked?: BooleanNumber;
+ formData?: IFormFieldData;
+ cachedResult?: string;
+}
+
+/** A field range includes its CUSTOM_RANGE_START/END sentinels and may contain nested fields. */
+export type IFieldCustomRange = ICustomRange<IFieldRangeProperties> & {
+ rangeType: CustomRangeType.FIELD;
+ wholeEntity?: false;
+};
+
+export type SdtKind =
+ | 'richText'
+ | 'text'
+ | 'checkbox'
+ | 'date'
+ | 'dropDownList'
+ | 'comboBox'
+ | 'picture'
+ | 'group'
+ | 'repeatingSection'
+ | 'repeatingSectionItem'
+ | 'docPartObj';
+
+export type SdtLock = 'unlocked' | 'sdtLocked' | 'contentLocked' | 'sdtContentLocked';
+export type SdtPlacement = 'inline' | 'block' | 'table' | 'row' | 'cell' | 'header' | 'footer';
+
+export interface ISdtListItem {
+ displayText?: string;
+ value: string;
+}
+
+export interface ISdtRangeProperties {
+ kind: SdtKind;
+ placement: SdtPlacement;
+ alias?: string;
+ tag?: string;
+ ooxmlId?: string;
+ lock?: SdtLock;
+ appearance?: string;
+ color?: string;
+ showingPlaceholder?: boolean;
+ temporary?: boolean;
+ placeholder?: string;
+ /** Imported OOXML placeholder reference and its original display text; not user-facing configuration. */
+ placeholderDocPart?: { name?: string; text?: string };
+ checkbox?: {
+ checked: boolean;
+ checkedState?: { value?: string; font?: string };
+ uncheckedState?: { value?: string; font?: string };
+ };
+ text?: {
+ /** Whether a plain-text content control accepts paragraph breaks. */
+ multiLine?: boolean;
+ };
+ date?: {
+ fullDate?: string;
+ format?: string;
+ locale?: string;
+ calendar?: string;
+ storage?: string;
+ };
+ listItems?: ISdtListItem[];
+ repeatingSection?: {
+ sectionTitle?: string;
+ doNotAllowInsertDelete?: boolean;
+ };
+ docPart?: {
+ gallery?: string;
+ category?: string;
+ unique?: boolean;
+ };
+ dataBinding?: {
+ prefixMappings?: string;
+ xpath?: string;
+ storeItemID?: string;
+ /** Visible result captured during import, used to detect direct text edits. */
+ cachedResult?: string;
+ /** Set after a content-control interaction so export updates the bound custom XML node. */
+ dirty?: boolean;
+ };
+ /** Original property XML retained for lossless OOXML round-trip. */
+ rawSdtPr?: string;
+ /** Original end-run properties retained for lossless OOXML round-trip. */
+ rawSdtEndPr?: string;
+}
+
+/** A Word structured document tag. SDTs may nest and span structural table tokens. */
+export type ISdtCustomRange = ICustomRange<ISdtRangeProperties> & {
+ rangeType: CustomRangeType.SDT;
+ wholeEntity?: false;
+ properties: ISdtRangeProperties;
+};
export type IMentionCustomRange = ICustomRange<IMention>;
@@ -517,6 +646,9 @@ export interface ICustomBlock {
blockType?: BlockType;
// A unique ID associated with a custom block.
blockId: string;
+ /** A note reference in the body, or the matching number/rule inside a note story. */
+ noteType?: 'footnote' | 'endnote' | 'separator' | 'continuationSeparator';
+ noteId?: string;
/** Original DOCX run XML retained by the exchange layer for lossless round-trip. */
docxRawXml?: string;
@@ -572,19 +704,39 @@ export enum DocumentFlavor {
UNSPECIFIED,
TRADITIONAL,
MODERN,
+ /** DrawingML text semantics for host-prepared shape and slide text models. */
+ DRAWINGML,
}
-/**
- * Basics properties of doc style
- */
+/** Page border geometry is expressed in 96-DPI layout pixels. */
+export interface IPageBorder {
+ /** Word line/art border style name; separate from table dash patterns. */
+ style?: string;
+ width?: number;
+ padding?: number;
+ color?: IColorStyle;
+}
+
+export interface IPageBorders {
+ offsetFrom?: 'page' | 'text';
+ display?: 'allPages' | 'firstPage' | 'notFirstPage';
+ zOrder?: 'front' | 'back';
+ top?: IPageBorder;
+ left?: IPageBorder;
+ bottom?: IPageBorder;
+ right?: IPageBorder;
+}
+
+/** Basics properties of doc style. */
export interface IDocStyleBase extends IMargin {
+ pageBorders?: IPageBorders;
pageNumberStart?: number; // pageNumberStart
/** Page size in 96-DPI layout pixels. */
pageSize?: ISize;
pageOrient?: PageOrientType;
- documentFlavor?: DocumentFlavor; // DocumentFlavor: TRADITIONAL, MODERN
+ documentFlavor?: DocumentFlavor;
/** Distance from the page edge to the header, in 96-DPI layout pixels. */
marginHeader?: number;
@@ -602,6 +754,8 @@ export interface IDocumentLayout {
useFELayout?: BooleanNumber;
/** OOXML `splitPgBreakAndParaMark`: move a trailing paragraph mark after a manual page break. */
splitPageBreakAndParagraphMark?: BooleanNumber;
+ /** Preserve the OOXML half/full-width space compatibility switch. */
+ balanceSingleByteDoubleByteWidth?: BooleanNumber;
/** Align automatic line height inside tables to the active document line grid. */
adjustLineHeightInTable?: BooleanNumber;
paragraphLineGapDefault?: number; // paragraphLineGapDefault default line spacing
@@ -622,7 +776,13 @@ export enum GridType {
}
export interface IDocumentStyle extends IDocStyleBase, IDocumentLayout, IHeaderAndFooterBase {
+ /** Imported Word on/off compatibility flags, keyed by their OOXML local names. */
+ compatibilityFlags?: Record<string, BooleanNumber>;
+ /** Imported OOXML compatSetting values, including the Word compatibilityMode. */
+ compatibilitySettings?: Record<string, string>;
textStyle?: ITextStyle; // default style for text
+ /** Document-declared alternate families, tried only after the authored font is unavailable. */
+ fontFamilyFallbacks?: Record<string, string>;
defaultParagraphStyle?: IDocumentDefaultParagraphStyle; // default style inherited by paragraphs
background?: IDocumentBackground; // Page background image.
}
@@ -656,8 +816,9 @@ export interface IDocumentRenderConfig {
wrapStrategy?: WrapStrategy; // wrap to the next line, for sheet cell
cellValueType?: CellValueType; // sheet cell type, In a spreadsheet cell, without any alignment settings applied, text should be left-aligned, numbers should be right-aligned, and Boolean values should be center-aligned.
isRenderStyle?: BooleanNumber; // Whether to render the style(textRuns), used in formula bar editor. the default value is TRUE.
- zeroWidthParagraphBreak?: BooleanNumber; // Whether to render the paragraph \r to zero width. the default value is false.
+ zeroWidthParagraphBreak?: BooleanNumber; // Override paragraph-mark width; DrawingML defaults to zero without custom glyph metrics.
shapeTextOpticalVerticalAlign?: BooleanNumber; // Align shape text by visible glyph bounds instead of the font line box.
+ lineWrapTolerance?: number; // Allowed line-width overflow in layout pixels; 0 enforces the content-box boundary.
}
export interface ISectionBreakBase {
@@ -735,6 +896,10 @@ export interface IParagraph {
styleId?: string;
paragraphStyle?: IParagraphStyle; // paragraphStyle
bullet?: IBullet; // bullet
+ /** Imported resolved numbering, used to distinguish later edits from unchanged inheritance. */
+ sourceBullet?: IBullet | null;
+ /** Imported direct numbering. Absent inherits from the style; null explicitly disables numbering. */
+ directBullet?: IBullet | null;
// dIds?: string[]; // drawingIds drawingId
}
@@ -837,6 +1002,10 @@ export interface IDocDrawingBase extends IDrawingParam {
distR?: number; // wrapSquare | wrapThrough | wrapTight
distT?: number; // wrapSquare | wrapTopAndBottom
distB?: number; // wrapSquare | wrapTopAndBottom
+ /** Effect bounds outside the drawing box, in layout pixels (OOXML wp:effectExtent). */
+ effectExtent?: { left?: number; top?: number; right?: number; bottom?: number };
+ /** Picture-local DrawingML size / layout size; retained on resize without changing the layout box. */
+ drawingMLSizeScale?: { width: number; height: number };
}
/**
@@ -951,10 +1120,28 @@ export interface IDocTextOutline {
}
export interface ITextStyle extends IStyleBase {
+ /** Retain text in the document without painting it or reserving layout space (OOXML vanish). Absent inherits. */
+ hidden?: boolean;
+ /** Word font-type hint for characters shared by Latin, East Asian and complex scripts. */
+ fontHint?: 'default' | 'eastAsia' | 'cs';
+ /** Alignment tab anchored to the page margins or paragraph indents. Applies only to a tab character. */
+ positionedTab?: { alignment: TabStopAlignment; relativeTo: 'margin' | 'indent'; leader?: TabStopLeader };
+ /** Original font-specific OOXML symbol; only applies to the matching character. */
+ symbol?: { font: string; code: number };
+ /** Authored text language (BCP 47), used by language-sensitive text layout. Absent inherits. */
+ lang?: string;
+ /** Alternate language from the authored text properties (BCP 47). Absent inherits. */
+ altLang?: string;
+ /** Minimum font size for pair kerning, in the same units as fs. Zero disables it; absent inherits. */
+ kerning?: number;
+ /** Display capital letters without changing the source text. Absent inherits. */
+ caps?: boolean;
+ /** Display lowercase letters as smaller capitals without changing source text. Absent inherits. */
+ smallCaps?: boolean;
// bo?: BaselineOffset; // BaselineOffset, sup, sub
sc?: number; // character spacing in points
pos?: number; // position
- sa?: number; // scale
+ sa?: number; // Horizontal character scale in percent; omitted means 100.
textFill?: IDocTextFill;
textOutline?: IDocTextOutline;
/**
@@ -993,22 +1180,28 @@ export type ParagraphFontAlign = 'auto' | 'top' | 'center' | 'baseline' | 'botto
export interface IParagraphStyle extends IParagraphProperties {
// Not achieved, aligned with Excel's standards.
textStyle?: ITextStyle; // paragraph textStyle
+ /** Formatting of the paragraph terminator only, not inherited by body text. */
+ paragraphMarkTextStyle?: ITextStyle;
}
/**
* Paragraph properties that may be inherited from the document defaults.
* Paragraph identity and named/text styles have their own inheritance mechanisms.
*/
-export type IDocumentDefaultParagraphStyle = Omit<IParagraphStyle, 'headingId' | 'namedStyleType' | 'textStyle'>;
+export type IDocumentDefaultParagraphStyle = Omit<IParagraphStyle, 'headingId' | 'namedStyleType' | 'outlineLevel' | 'textStyle' | 'paragraphMarkTextStyle'>;
export interface IParagraphProperties extends IIndentStart {
headingId?: string; // headingId
namedStyleType?: NamedStyleType; // namedStyleType
+ /** Zero-based OOXML outline level used by TOC generation; 9 denotes body text. */
+ outlineLevel?: number;
defaultTabStop?: number; // Distance between automatic tab stops for this paragraph.
/** Whether East Asian kinsoku line-breaking rules apply to this paragraph. */
eastAsianLineBreak?: BooleanNumber;
/** Whether punctuation may hang outside the paragraph text bounds. */
hangingPunctuation?: BooleanNumber;
+ /** Whether full-width punctuation at a line start may be compressed (OOXML topLinePunct). */
+ topLinePunct?: BooleanNumber;
fontAlign?: ParagraphFontAlign;
horizontalAlign?: HorizontalAlign; // Horizontal alignment
lineSpacing?: number; // lineSpacing 17.3.1.33 spacing (Spacing Between Lines and Above/Below Paragraph)
@@ -1076,6 +1269,17 @@ export interface IParagraphProperties extends IIndentStart {
widowControl?: BooleanNumber;
shading?: IShading; // shading
suppressHyphenation?: BooleanNumber; // 17.3.1.34 suppressAutoHyphens (Suppress Hyphenation for Paragraph)
+ /** Positioned Word frame metadata; legacy snapshots may contain only a presence flag. */
+ paragraphFrame?: BooleanNumber | {
+ horizontalSpace?: number;
+ wrap?: string;
+ verticalAnchor?: string;
+ horizontalAnchor?: string;
+ x?: string;
+ y?: string;
+ xAlign?: string;
+ yAlign?: string;
+ };
}
/**
@@ -1151,6 +1355,7 @@ export interface ITabStop {
offset: number; // offset
alignment: TabStopAlignment; // alignment
leader?: TabStopLeader; // leader drawn between the preceding text and this tab stop
+ clear?: boolean; // removes an inherited stop at this position; not a layout stop
}
/**
@@ -1275,6 +1480,8 @@ export interface ITable {
tableColumns: ITableColumn[]; // tableColumns
align: TableAlignmentType; // 17.4.28 jc (Table Alignment)
indent: INumberUnit; // left align only. leftIndent
+ /** Imported pre-2013 Word text-to-frame indent correction for top-level tables. */
+ legacyIndentAdjustment?: INumberUnit;
textWrap: TableTextWrapType; // 17.4.57 tblpPr (Floating Table Positioning)
position: ITableAnchor; // 17.4.57 tblpPr (Floating Table Positioning)
dist: IDistFromText; // 17.4.57 tblpPr (Floating Table Positioning)
@@ -1314,6 +1521,8 @@ export interface ITableRowSize {
* Properties of row of table
*/
export interface ITableRow {
+ /** Authored row-level default margins (OOXML tblPrEx); imported cells contain resolved margins. */
+ cellMargin?: ITableCellMargin;
/**
* Rows do not persist stream offsets. Their ordinal position must match the
* corresponding `TABLE_ROW_START`/`TABLE_ROW_END` pair in `dataStream`.
@@ -1323,6 +1532,10 @@ export interface ITableRow {
gridBefore?: number;
/** Number of table-grid columns omitted after the last cell in this row. */
gridAfter?: number;
+ /** Preferred width of the omitted leading grid columns (OOXML wBefore). */
+ widthBefore?: IWidthInTableSize;
+ /** Preferred width of the omitted trailing grid columns (OOXML wAfter). */
+ widthAfter?: IWidthInTableSize;
// If omitted, then the table row shall automatically resize its height to the height required by its contents
// (the equivalent of an hRule value of auto)
trHeight: ITableRowSize; // 17.4.80 trHeight (Table Row Height)
@@ -1349,6 +1562,10 @@ export interface ITableCell {
borderBottom?: ITableCellBorder; // borderBottom
size?: IWidthInTableSize; // size
tcFitText?: BooleanNumber; // 17.4.67 tcFitText (Fit Text Within Cell)
+ /** Exclude the cell's final paragraph mark from content height (OOXML w:hideMark). */
+ tcHideMark?: BooleanNumber;
+ /** OOXML table-cell writing direction; independent of paragraph bidirectional ordering. */
+ textDirection?: 'lrTb' | 'tbRl' | 'btLr' | 'lrTbV' | 'tbRlV' | 'tbLrV';
// hAlign: use paragraph align to instead.
vAlign?: VerticalAlignmentType; // 17.4.83 vAlign (Table Cell Vertical Alignment)
}
@@ -1367,6 +1584,15 @@ export interface ITableCellBorder {
color: IColorStyle; // color
width?: INumberUnit; // width
dashStyle?: DashStyleType; // dashStyle
+ /**
+ * Resolved outer table top when borderTop inherits the table's insideH edge.
+ * At the top of a traditional table page fragment, use this instead of the
+ * internal edge. Absent for explicit cell borders and legacy snapshots.
+ * Replacing or editing the cell border must discard this inheritance.
+ */
+ tableTopBorder?: ITableCellBorder;
+ /** Resolved outer bottom for an inherited insideH edge; follows the same editing rules as tableTopBorder. */
+ tableBottomBorder?: ITableCellBorder;
}
// 17.18.101ST_VerticalJc (Vertical Alignment Type)
diff --git a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-transformer-update.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-transformer-update.controller.spec.ts
index b2fbf549d4..0366b06df1 100644
--- a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-transformer-update.controller.spec.ts
+++ b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-transformer-update.controller.spec.ts
@@ -391,7 +391,7 @@ describe('DocDrawingTransformerController business methods', () => {
hostPage: bodyPage,
page: headerPage,
width: 80,
- })).toBe(false);
+ })).toBe(true);
expect(shouldUseDocsDrawingOuterPageOrigin({
drawing: overlayDrawing,
height: 1055,
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts
index 4ffc950a50..be2589e051 100644
--- a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts
@@ -23,17 +23,18 @@ import {
ObjectRelativeFromV,
PositionedObjectLayoutType,
} from '@univerjs/core';
-import { Liquid, setDocsTableRenderViewportProvider } from '@univerjs/engine-render';
+import { DocumentSkeletonPageType, Liquid, setDocsTableRenderViewportProvider } from '@univerjs/engine-render';
+import { Subject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getDocsTableCellAnchorContext } from '../../doc-drawing-transformer-update.controller';
import { doesDocMutationAffectDrawingPresentation, getDocMutationAffectedDrawingIds } from '../doc-drawing-mutation';
import {
DocDrawingPublicationTracker,
DocDrawingTransformUpdateController,
-
getDocsDrawingBehindText,
getDocsDrawingClipPage,
getDocsDrawingPageClipBounds,
+ getDocsOverlayRuntimeDrawing,
getDocsPageRelativeDrawingAnchorPage,
getDocsPageRelativeDrawingLeft,
getDocsPageRelativeDrawingTop,
@@ -46,6 +47,38 @@ describe('DocDrawingTransformUpdateController', () => {
setDocsTableRenderViewportProvider(null);
});
+ it('refreshes drawings when scrolling materializes pages without a layout progress event', () => {
+ vi.stubGlobal('requestAnimationFrame', vi.fn(() => 1));
+ vi.stubGlobal('cancelAnimationFrame', vi.fn());
+ const controller = Object.create(DocDrawingTransformUpdateController.prototype);
+ const currentSkeleton$ = new Subject();
+ const skeleton = {
+ layoutProgress$: new Subject(),
+ layoutPageMaterialized$: new Subject<void>(),
+ };
+ const subscriptions: Array<{ unsubscribe: () => void }> = [];
+ controller.disposeWithMe = (subscription: { unsubscribe: () => void }) => subscriptions.push(subscription);
+ controller._context = { mainComponent: null };
+ controller._docSkeletonManagerService = { currentSkeleton$ };
+ controller._docRefreshDrawingsService = { refreshDrawings$: new Subject() };
+ controller._publicationTracker = new DocDrawingPublicationTracker();
+ controller._refreshDrawing = vi.fn();
+ controller._initialRenderRefresh();
+ try {
+ currentSkeleton$.next(skeleton);
+ expect(controller._refreshDrawing).toHaveBeenCalledTimes(1);
+ skeleton.layoutPageMaterialized$.next();
+ expect(controller._refreshDrawing).toHaveBeenCalledTimes(2);
+ expect(controller._refreshDrawing).toHaveBeenLastCalledWith(skeleton);
+ currentSkeleton$.next(null);
+ skeleton.layoutPageMaterialized$.next();
+ expect(controller._refreshDrawing).toHaveBeenCalledTimes(2);
+ } finally {
+ subscriptions.forEach((subscription) => subscription.unsubscribe());
+ vi.unstubAllGlobals();
+ }
+ });
+
it('does not eagerly refresh drawings for table metadata mutations', () => {
expect(doesDocMutationAffectDrawingPresentation([
'tableSource',
@@ -619,11 +652,11 @@ describe('DocDrawingTransformUpdateController', () => {
}),
expect.objectContaining({
drawingId: 'square-drawing',
- transform: expect.objectContaining({ left: 26, top: 40, width: 30, height: 40, angle: 5 }),
+ transform: expect.objectContaining({ left: 104, top: 95, width: 30, height: 40, angle: 5 }),
}),
expect.objectContaining({
drawingId: 'top-bottom-drawing',
- transform: expect.objectContaining({ left: 28, top: 42, width: 30, height: 40, angle: 5 }),
+ transform: expect.objectContaining({ left: 104, top: 95, width: 30, height: 40, angle: 5 }),
}),
expect.objectContaining({
drawingId: 'inline-drawing',
@@ -704,6 +737,108 @@ describe('DocDrawingTransformUpdateController', () => {
});
});
+ it('does not crop cell-anchored pictures to the vertically aligned text origin', () => {
+ expect(getDocsDrawingPageClipBounds({
+ docsLeft: 20,
+ docsTop: 30,
+ pageOffsetLeft: 100,
+ pageOffsetTop: 200,
+ clipOffsetLeft: 138,
+ clipOffsetTop: 98 + 141,
+ page: {
+ type: DocumentSkeletonPageType.CELL,
+ pageWidth: 321,
+ pageHeight: 300,
+ marginLeft: 8,
+ marginTop: 141,
+ },
+ })).toEqual({ left: 250, top: 328, width: 321, height: 300 });
+ });
+
+ it('restores visibility and presentation when publishing a previously hidden header drawing', () => {
+ const controller = Object.create(DocDrawingTransformUpdateController.prototype);
+ const drawing = { drawingId: 'logo', hidden: true, source: 'image-source' };
+ const update = {
+ drawingId: 'logo',
+ hidden: false,
+ behindText: true,
+ selectable: false,
+ isMultiTransform: BooleanNumber.TRUE,
+ transform: { left: 10, top: 20, width: 30, height: 40 },
+ transforms: [{ left: 10, top: 20, width: 30, height: 40 }],
+ };
+ controller._context = {
+ unitId: 'doc',
+ scene: { getTransformerByCreate: () => ({ getSelectedObjectMap: () => new Map() }) },
+ };
+ controller._drawingManagerService = {
+ getDrawingByParam: () => drawing,
+ getDrawingData: () => ({ logo: drawing }),
+ removeNotification: vi.fn(),
+ addNotification: vi.fn(() => expect(drawing).toMatchObject(update)),
+ };
+ controller._handleMultiDrawingsTransform([update]);
+ expect(controller._drawingManagerService.addNotification).toHaveBeenCalledWith([update]);
+ expect(drawing.source).toBe('image-source');
+ });
+
+ it('anchors footer drawings at the same bottom-aligned origin as footer text', () => {
+ const controller = Object.create(DocDrawingTransformUpdateController.prototype);
+ controller._collectSegmentDrawingPositions = vi.fn();
+ const page = { pageWidth: 800, pageHeight: 1100, marginLeft: 50, marginBottom: 70, footerId: 'footer' };
+ const footer = { height: 16, marginTop: 5, marginBottom: 30 };
+ controller._collectPublishedPageDrawingPositions('doc', page, new Map(), new Map([['footer', new Map([[800, footer]])]]), 0, 0, {});
+ expect(controller._collectSegmentDrawingPositions.mock.calls[0][5]).toBe(1054);
+ });
+
+ it('allows floating pictures to overflow a cell without crossing the document page', () => {
+ const config = {
+ docsLeft: 20,
+ docsTop: 30,
+ pageOffsetLeft: 0,
+ pageOffsetTop: 0,
+ clipOffsetLeft: 60,
+ clipOffsetTop: 900,
+ overflowClipBounds: { left: 20, top: 30, width: 794, height: 1123 },
+ page: { type: DocumentSkeletonPageType.CELL, pageWidth: 200, pageHeight: 155 },
+ };
+ expect(getDocsDrawingPageClipBounds({
+ ...config,
+ drawingLayoutType: PositionedObjectLayoutType.WRAP_NONE,
+ })).toEqual(config.overflowClipBounds);
+ expect(getDocsDrawingPageClipBounds({
+ ...config,
+ drawingLayoutType: PositionedObjectLayoutType.INLINE,
+ })).toEqual({ left: 80, top: 930, width: 200, height: 155 });
+ });
+
+ it('paints measured inline-object dimensions without changing source or overriding live floating transforms', () => {
+ const source = {
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ angle: 0,
+ size: { width: 100, height: 44 },
+ positionH: { relativeFrom: ObjectRelativeFromH.COLUMN },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH },
+ },
+ };
+ const measured = getDocsOverlayRuntimeDrawing(source, undefined, { width: 100, height: 76 });
+ expect(measured.docTransform.size).toEqual({ width: 100, height: 76 });
+ expect(source.docTransform.size.height).toBe(44);
+ const overlay = { ...source, layoutType: PositionedObjectLayoutType.WRAP_NONE };
+ const edited = { ...overlay, docTransform: { ...overlay.docTransform, size: { width: 120, height: 90 } } };
+ expect(getDocsOverlayRuntimeDrawing(overlay, edited, { width: 100, height: 76 })).toBe(edited);
+ });
+
+ it.each([DocumentSkeletonPageType.HEADER, DocumentSkeletonPageType.FOOTER])('clips small foreground story drawings to physical page bounds (story: %s)', (type) => {
+ const hostPage = { pageWidth: 794, pageHeight: 1123 };
+ expect(getDocsDrawingClipPage({
+ page: { type, pageWidth: 602, pageHeight: 510 },
+ hostPage,
+ drawing: { behindText: false, transform: { width: 175, height: 33 } },
+ })).toBe(hostPage);
+ });
+
it('clips page-sized header background drawings to the host document page', () => {
const headerPage = {
pageWidth: 589,
@@ -799,6 +934,29 @@ describe('DocDrawingTransformUpdateController', () => {
})).toBe(1);
});
+ it.each([
+ PositionedObjectLayoutType.WRAP_NONE,
+ PositionedObjectLayoutType.WRAP_SQUARE,
+ PositionedObjectLayoutType.WRAP_POLYGON,
+ PositionedObjectLayoutType.WRAP_THROUGH,
+ PositionedObjectLayoutType.WRAP_TIGHT,
+ PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM,
+ ])('uses page coordinates for floating drawing layout %s regardless of text wrapping', (drawingLayoutType) => {
+ const page = { pageWidth: 793.4, pageHeight: 1121.13 };
+ const anchor = getDocsPageRelativeDrawingAnchorPage({ page, clipPage: page, drawingLayoutType });
+ expect(anchor).toBe(page);
+ expect(getDocsPageRelativeDrawingLeft({
+ hostPage: anchor!,
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 35.4 },
+ width: 755.4,
+ })).toBe(35.4);
+ expect(getDocsPageRelativeDrawingAnchorPage({
+ page,
+ clipPage: page,
+ drawingLayoutType: PositionedObjectLayoutType.INLINE,
+ })).toBeUndefined();
+ });
+
it('uses body pages as page-relative drawing anchors when no host page exists', () => {
const bodyPage = {
pageWidth: 816,
@@ -811,6 +969,15 @@ describe('DocDrawingTransformUpdateController', () => {
})).toBe(bodyPage);
});
+ it('keeps a table-cell drawing in the translated cell coordinate space', () => {
+ const cell = { type: DocumentSkeletonPageType.CELL, pageWidth: 200, pageHeight: 40 };
+ expect(getDocsPageRelativeDrawingAnchorPage({
+ page: cell,
+ clipPage: cell,
+ drawingLayoutType: PositionedObjectLayoutType.WRAP_NONE,
+ })).toBeUndefined();
+ });
+
it('renders header and footer drawings in the host page behind-text layer', () => {
expect(getDocsDrawingBehindText({
drawingOrigin: {
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts
index 4cb6085541..84a1be505a 100644
--- a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts
@@ -498,7 +498,7 @@ describe('DocDrawingUpdateRenderController', () => {
expect(scene.attachTransformerTo).toHaveBeenCalledWith(getShape('body-drawing'));
expect(getShape('body-drawing').setOpacity).toHaveBeenLastCalledWith(1);
- expect(getShape('header-drawing').setOpacity).toHaveBeenLastCalledWith(0.5);
+ expect(getShape('header-drawing').setOpacity).toHaveBeenLastCalledWith(1);
scene.attachTransformerTo.mockClear();
setEditArea(DocumentEditArea.HEADER);
@@ -588,7 +588,7 @@ describe('DocDrawingUpdateRenderController', () => {
expect(scene.attachTransformerTo).toHaveBeenCalledWith(getShape('body-drawing'));
expect(getShape('body-drawing').setOpacity).toHaveBeenLastCalledWith(1);
- expect(getShape('header-drawing').setOpacity).toHaveBeenLastCalledWith(0.5);
+ expect(getShape('header-drawing').setOpacity).toHaveBeenLastCalledWith(1);
setIsFocusing(false);
onBlur$.next({});
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-transform-update.controller.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-transform-update.controller.ts
index 54f692ff36..e7fa7f02f8 100644
--- a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-transform-update.controller.ts
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-transform-update.controller.ts
@@ -51,6 +51,7 @@ import { IEditorService, SetDocZoomRatioOperation } from '@univerjs/docs-ui';
import { IDrawingManagerService } from '@univerjs/drawing';
import {
Documents,
+ DocumentSkeletonPageType,
getDocsTableRenderViewport,
getTableIdAndSliceIndex,
Liquid,
@@ -138,6 +139,7 @@ interface IDrawingPositionContext {
selectable: boolean;
hostPage?: IDocumentSkeletonPage;
clipOffset?: { left: number; top: number };
+ overflowClipBounds?: IDrawingClipBounds;
}
/**
@@ -147,11 +149,15 @@ interface IDrawingPositionContext {
*/
export function getDocsOverlayRuntimeDrawing(
skeletonDrawing: Pick<IDocDrawingBase, 'docTransform' | 'layoutType'> & Partial<IDocDrawingBase>,
- currentDrawing: (Pick<IDocDrawingBase, 'docTransform' | 'layoutType'> & Partial<IDocDrawingBase>) | undefined
+ currentDrawing: (Pick<IDocDrawingBase, 'docTransform' | 'layoutType'> & Partial<IDocDrawingBase>) | undefined,
+ measuredSize?: { width: number; height: number }
): Pick<IDocDrawingBase, 'docTransform' | 'layoutType'> & Partial<IDocDrawingBase> {
- return skeletonDrawing.layoutType === PositionedObjectLayoutType.WRAP_NONE &&
- currentDrawing?.layoutType === PositionedObjectLayoutType.WRAP_NONE
- ? currentDrawing
+ if (skeletonDrawing.layoutType === PositionedObjectLayoutType.WRAP_NONE &&
+ currentDrawing?.layoutType === PositionedObjectLayoutType.WRAP_NONE) {
+ return currentDrawing;
+ }
+ return measuredSize
+ ? { ...skeletonDrawing, docTransform: { ...skeletonDrawing.docTransform, size: measuredSize } }
: skeletonDrawing;
}
@@ -242,17 +248,30 @@ export function getDocsDrawingPageClipBounds(config: {
pageOffsetTop: number;
clipOffsetLeft?: number;
clipOffsetTop?: number;
- page: Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'>;
+ drawingLayoutType?: PositionedObjectLayoutType;
+ overflowClipBounds?: IDrawingClipBounds;
+ page: Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'> &
+ Partial<Pick<IDocumentSkeletonPage, 'type' | 'marginLeft' | 'marginTop'>>;
}): IDrawingClipBounds | undefined {
const { docsLeft, docsTop, pageOffsetLeft, pageOffsetTop, clipOffsetLeft = 0, clipOffsetTop = 0, page } = config;
+ if (
+ page.type === DocumentSkeletonPageType.CELL &&
+ config.drawingLayoutType === PositionedObjectLayoutType.WRAP_NONE &&
+ config.overflowClipBounds != null
+ ) {
+ return config.overflowClipBounds;
+ }
const { pageWidth, pageHeight } = page;
if (!Number.isFinite(pageWidth) || !Number.isFinite(pageHeight) || pageWidth <= 0 || pageHeight <= 0) {
return;
}
+ // A cell clip covers its physical box, not the vertically aligned text origin passed to drawing layout.
+ const cellInsetLeft = page.type === DocumentSkeletonPageType.CELL ? page.marginLeft ?? 0 : 0;
+ const cellInsetTop = page.type === DocumentSkeletonPageType.CELL ? page.marginTop ?? 0 : 0;
return {
- left: docsLeft + pageOffsetLeft + clipOffsetLeft,
- top: docsTop + pageOffsetTop + clipOffsetTop,
+ left: docsLeft + pageOffsetLeft + clipOffsetLeft - cellInsetLeft,
+ top: docsTop + pageOffsetTop + clipOffsetTop - cellInsetTop,
width: pageWidth,
height: pageHeight,
};
@@ -263,9 +282,13 @@ export function getDocsDrawingClipPage(config: {
transform?: Pick<ITransformState, 'width' | 'height'>;
};
hostPage?: Pick<IDocumentSkeletonPage, 'pageWidth' | 'pageHeight'>;
- page: Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'>;
+ page: Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'> &
+ Partial<Pick<IDocumentSkeletonPage, 'type'>>;
}): Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'> {
const { drawing, hostPage, page } = config;
+ if (hostPage && (page.type === DocumentSkeletonPageType.HEADER || page.type === DocumentSkeletonPageType.FOOTER)) {
+ return hostPage;
+ }
if (hostPage == null || drawing.behindText !== true || drawing.transform == null) {
return page;
}
@@ -343,15 +366,21 @@ export function getDocsPageRelativeDrawingTop(config: {
}
export function getDocsPageRelativeDrawingAnchorPage(config: {
- page: Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'>;
+ page: Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'> &
+ Partial<Pick<IDocumentSkeletonPage, 'type'>>;
clipPage: Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'>;
hostPage?: Pick<IDocumentSkeletonPage, 'pageWidth' | 'pageHeight'>;
+ drawingLayoutType?: PositionedObjectLayoutType;
}): Pick<IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter, 'pageWidth' | 'pageHeight'> | undefined {
const { page, clipPage, hostPage } = config;
+ if (config.drawingLayoutType === PositionedObjectLayoutType.INLINE) {
+ return;
+ }
if (hostPage != null && hostPage === clipPage) {
return hostPage;
}
- if (hostPage == null && page === clipPage) {
+ // Cell drawings use the cell's translated origin, not the physical page origin.
+ if (hostPage == null && page === clipPage && page.type !== DocumentSkeletonPageType.CELL) {
return page;
}
}
@@ -555,6 +584,9 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
documentSkeleton.layoutProgress$.pipe(
map((progress) => ({ documentSkeleton, progress }))
),
+ documentSkeleton.layoutPageMaterialized$.pipe(
+ map(() => ({ documentSkeleton, progress: null }))
+ ),
positionRefresh$
);
})
@@ -762,7 +794,7 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
const footerPage = footerId ? skeFooters.get(footerId)?.get(pageWidth) : undefined;
if (footerPage != null) {
- const footerTop = page.pageHeight - page.marginBottom + footerPage.marginTop;
+ const footerTop = page.pageHeight - footerPage.height - footerPage.marginBottom;
this._collectSegmentDrawingPositions(
unitId,
footerPage,
@@ -815,6 +847,13 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
selectable: boolean,
clipOffset?: { left: number; top: number }
): void {
+ const overflowClipBounds = getDocsDrawingPageClipBounds({
+ docsLeft,
+ docsTop,
+ pageOffsetLeft: this._liquid.x,
+ pageOffsetTop: this._liquid.y,
+ page: hostPage ?? page,
+ });
this._calculateDrawingPosition(
unitId,
page,
@@ -825,7 +864,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
marginLeft,
hostPage,
selectable,
- clipOffset
+ clipOffset,
+ overflowClipBounds
);
this._calculateTableCellDrawingPositions(
unitId,
@@ -835,7 +875,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
updateDrawingMap,
marginTop,
marginLeft,
- selectable
+ selectable,
+ overflowClipBounds
);
this._calculateColumnGroupDrawingPositions(
unitId,
@@ -845,7 +886,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
updateDrawingMap,
marginTop,
marginLeft,
- selectable
+ selectable,
+ overflowClipBounds
);
}
@@ -884,9 +926,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
return;
}
- param.transform = updateParam.transform;
- param.transforms = updateParam.transforms;
- param.isMultiTransform = updateParam.isMultiTransform;
+ // A segment drawing may have been hidden before its first layout publication.
+ Object.assign(param, updateParam);
});
// Step 2: remove all drawing shapes.
@@ -921,7 +962,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
marginLeft: number,
hostPage?: IDocumentSkeletonPage,
selectable = true,
- clipOffset?: { left: number; top: number }
+ clipOffset?: { left: number; top: number },
+ overflowClipBounds?: IDrawingClipBounds
) {
const { skeDrawings } = page;
const pageOffsetLeft = this._liquid.x;
@@ -942,6 +984,7 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
hostPage,
selectable,
clipOffset,
+ overflowClipBounds,
};
skeDrawings.forEach((drawing) => this._collectDrawingPosition(drawing, drawingPositionContext));
@@ -957,7 +1000,11 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
): void {
const { aLeft, aTop, angle: skeletonAngle, drawingId, drawingOrigin, height: skeletonHeight, width: skeletonWidth } = drawing;
const currentDrawing = this._context.unit?.getSnapshot?.().drawings?.[drawingId];
- const runtimeDrawing = getDocsOverlayRuntimeDrawing(drawingOrigin, currentDrawing);
+ const runtimeDrawing = getDocsOverlayRuntimeDrawing(
+ drawingOrigin,
+ currentDrawing,
+ drawing.customBlockRenderViewport ? { width: skeletonWidth, height: skeletonHeight } : undefined
+ );
const { angle = skeletonAngle, size } = runtimeDrawing.docTransform;
const height = size?.height ?? skeletonHeight;
const width = size?.width ?? skeletonWidth;
@@ -977,14 +1024,15 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
clipOffsetLeft,
clipOffsetTop,
page: clipPage,
+ drawingLayoutType: runtimeDrawing.layoutType,
+ overflowClipBounds: context.overflowClipBounds,
+ });
+ const anchorPage = getDocsPageRelativeDrawingAnchorPage({
+ page: context.page,
+ clipPage,
+ hostPage: context.hostPage,
+ drawingLayoutType: runtimeDrawing.layoutType,
});
- const anchorPage = runtimeDrawing.layoutType === PositionedObjectLayoutType.WRAP_NONE
- ? getDocsPageRelativeDrawingAnchorPage({
- page: context.page,
- clipPage,
- hostPage: context.hostPage,
- })
- : undefined;
const pageRelativeLeft = anchorPage == null
? undefined
: getDocsPageRelativeDrawingLeft({
@@ -1032,7 +1080,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
updateDrawingMap: Record<string, IDrawingParamsWithBehindText>,
baseMarginTop: number,
baseMarginLeft: number,
- selectable: boolean
+ selectable: boolean,
+ overflowClipBounds?: IDrawingClipBounds
) {
page.skeTables?.forEach((table) => {
table.rows.forEach((row) => {
@@ -1059,7 +1108,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
marginLeft,
undefined,
selectable,
- { left: marginLeft, top: marginTop }
+ { left: marginLeft, top: marginTop },
+ overflowClipBounds
);
this._calculateTableCellDrawingPositions(
unitId,
@@ -1069,7 +1119,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
updateDrawingMap,
marginTop,
marginLeft,
- selectable
+ selectable,
+ overflowClipBounds
);
this._calculateColumnGroupDrawingPositions(
unitId,
@@ -1079,7 +1130,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
updateDrawingMap,
marginTop,
marginLeft,
- selectable
+ selectable,
+ overflowClipBounds
);
});
});
@@ -1094,7 +1146,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
updateDrawingMap: Record<string, IDrawingParamsWithBehindText>,
baseMarginTop: number,
baseMarginLeft: number,
- selectable: boolean
+ selectable: boolean,
+ overflowClipBounds?: IDrawingClipBounds
): void {
page.skeColumnGroups?.forEach((columnGroup) => {
columnGroup.columns.forEach((column) => {
@@ -1113,7 +1166,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
marginLeft,
undefined,
selectable,
- clipOffset
+ clipOffset,
+ overflowClipBounds
);
this._calculateTableCellDrawingPositions(
unitId,
@@ -1123,7 +1177,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
updateDrawingMap,
marginTop,
marginLeft,
- selectable
+ selectable,
+ overflowClipBounds
);
this._calculateColumnGroupDrawingPositions(
unitId,
@@ -1133,7 +1188,8 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
updateDrawingMap,
marginTop,
marginLeft,
- selectable
+ selectable,
+ overflowClipBounds
);
});
});
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
index 5f90880732..1150d1162f 100644
--- a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
@@ -496,7 +496,10 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
scene.detachTransformerFrom(shape);
this._setTransformerEditable(shape, editable);
try {
- (shape as Image).setOpacity(isDocInteractionFocusing ? 0.5 : 1);
+ // Repeated header/footer drawings are faded by the content cover,
+ // never individually: an opaque picture must still hide pictures below it.
+ const fadeBody = isDocInteractionFocusing && drawing.isMultiTransform !== BooleanNumber.TRUE;
+ (shape as Image).setOpacity(fadeBody ? 0.5 : 1);
} catch {
}
if (!isDocInteractionFocusing) {
diff --git a/packages/docs-drawing-ui/src/menu/schema.ts b/packages/docs-drawing-ui/src/menu/schema.ts
index 407151629d..4481079b55 100644
--- a/packages/docs-drawing-ui/src/menu/schema.ts
+++ b/packages/docs-drawing-ui/src/menu/schema.ts
@@ -40,6 +40,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonInsertGroup.MEDIA]: {
[DOCS_IMAGE_MENU_ID]: {
order: 0,
+ gridLayout: { row: 1, column: 4 },
menuItemFactory: ImageMenuFactory,
},
},
diff --git a/packages/docs-drawing/src/commands/commands/__tests__/update-doc-drawing-transform.command.spec.ts b/packages/docs-drawing/src/commands/commands/__tests__/update-doc-drawing-transform.command.spec.ts
index 648dc79383..67b8d5ad60 100644
--- a/packages/docs-drawing/src/commands/commands/__tests__/update-doc-drawing-transform.command.spec.ts
+++ b/packages/docs-drawing/src/commands/commands/__tests__/update-doc-drawing-transform.command.spec.ts
@@ -15,7 +15,18 @@
*/
import type { IUpdateDrawingDocTransformCommandParams } from '../update-doc-drawing-transform.command';
-import { ICommandService, ImageSourceType } from '@univerjs/core';
+import {
+ awaitTime,
+ DocumentFlavor,
+ DrawingTypeEnum,
+ ICommandService,
+ ImageSourceType,
+ ObjectRelativeFromH,
+ ObjectRelativeFromV,
+ PositionedObjectLayoutType,
+ RedoCommand,
+ UndoCommand,
+} from '@univerjs/core';
import { DocHistoryAction, RichTextEditingMutation } from '@univerjs/docs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createFacadeTestBed } from '../../../facade/__tests__/create-test-bed';
@@ -119,4 +130,50 @@ describe('UpdateDrawingDocTransformCommand', () => {
expect.objectContaining({ historyAction: DocHistoryAction.UpdateImage })
);
});
+
+ it('retains picture-local scale through resize, undo and redo', async () => {
+ testBed.univer.dispose();
+ testBed = createFacadeTestBed({
+ id: 'test-doc',
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: {
+ dataStream: '\b\r\n',
+ paragraphs: [{ startIndex: 1, paragraphId: 'paragraph-1' }],
+ customBlocks: [{ startIndex: 0, blockId: 'picture' }],
+ },
+ drawingsOrder: ['picture'],
+ drawings: {
+ picture: {
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ drawingId: 'picture',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ angle: 0,
+ size: { width: 100, height: 50 },
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH },
+ },
+ drawingMLSizeScale: { width: 1.1, height: 1.2 },
+ },
+ },
+ });
+ const commandService = testBed.injector.get(ICommandService);
+ expect(commandService.syncExecuteCommand(UpdateDrawingDocTransformCommand.id, {
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ drawings: [{ drawingId: 'picture', key: 'size', value: { width: 200, height: 75 } }],
+ })).toBe(true);
+ await awaitTime(350);
+ const drawing = () => testBed.documentDataModel.getSnapshot().drawings!.picture;
+ expect(drawing().docTransform.size).toEqual({ width: 200, height: 75 });
+ expect(drawing().drawingMLSizeScale).toEqual({ width: 1.1, height: 1.2 });
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(drawing().docTransform.size).toEqual({ width: 100, height: 50 });
+ expect(drawing().drawingMLSizeScale).toEqual({ width: 1.1, height: 1.2 });
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(drawing().docTransform.size).toEqual({ width: 200, height: 75 });
+ expect(drawing().drawingMLSizeScale).toEqual({ width: 1.1, height: 1.2 });
+ });
});
diff --git a/packages/docs-hyper-link-ui/src/commands/commands/__tests__/update-link.command.spec.ts b/packages/docs-hyper-link-ui/src/commands/commands/__tests__/update-link.command.spec.ts
new file mode 100644
index 0000000000..1ac54337d8
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/commands/commands/__tests__/update-link.command.spec.ts
@@ -0,0 +1,78 @@
+/**
+ * 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, IDocumentData } from '@univerjs/core';
+import type { IRichTextEditingMutationParams } from '@univerjs/docs';
+import type { IUpdateDocHyperLinkCommandParams } from '../update-link.command';
+import { CustomRangeType, ICommandService, IUniverInstanceService, Tools, Univer, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService, DocStateEmitService, RichTextEditingMutation } from '@univerjs/docs';
+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
+import { describe, expect, it } from 'vitest';
+import { UpdateDocHyperLinkCommand } from '../update-link.command';
+
+describe('UpdateDocHyperLinkCommand', () => {
+ it.each([{}, { textStyleMode: 'text' }, { textColorMode: 'text' }])('retains formatting policy %j when changing label and URL', async (policy) => {
+ const univer = new Univer();
+ try {
+ const injector = univer.__getInjector();
+ injector.add([DocSelectionManagerService]);
+ injector.add([DocStateEmitService]);
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: 'link-style',
+ body: {
+ dataStream: 'Mail\r\n',
+ textRuns: [{ st: 0, ed: 4, ts: { cl: { rgb: '#AA1122' }, ul: { s: 0 } } }],
+ customRanges: [{
+ startIndex: 0,
+ endIndex: 3,
+ rangeId: 'link',
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: { url: 'mailto:[email protected]', ...policy },
+ }],
+ },
+ documentStyle: {},
+ });
+ injector.get(IUniverInstanceService).focusUnit('link-style');
+ const commands = injector.get(ICommandService);
+ commands.registerCommand(UpdateDocHyperLinkCommand);
+ commands.registerCommand(RichTextEditingMutation);
+ const selection = injector.get(DocSelectionManagerService);
+ selection.__TEST_ONLY_setCurrentSelection({ unitId: 'link-style', subUnitId: 'link-style' });
+ selection.__TEST_ONLY_add([{ startOffset: 0, endOffset: 4, collapsed: false, isActive: true, segmentId: '', style: null as never }]);
+ const before = Tools.deepClone(doc.getBody());
+ const undo = await commands.executeCommand<IUpdateDocHyperLinkCommandParams, IRichTextEditingMutationParams>(UpdateDocHyperLinkCommand.id, {
+ unitId: 'link-style',
+ linkId: 'link',
+ payload: 'mailto:[email protected]',
+ label: 'New mail',
+ segmentId: '',
+ });
+ expect(undo).toBeTruthy();
+ expect(doc.getBody()?.dataStream).toBe('New mail\r\n');
+ expect(doc.getBody()?.customRanges?.[0].properties).toEqual({ url: 'mailto:[email protected]', ...policy });
+ expect(doc.getBody()?.textRuns?.[0].ts).toEqual({ cl: { rgb: '#AA1122' }, ul: { s: 0 } });
+ const updated = Tools.deepClone(doc.getBody());
+ const redo = commands.syncExecuteCommand<IRichTextEditingMutationParams, IRichTextEditingMutationParams>(RichTextEditingMutation.id, undo);
+ expect(doc.getBody()?.dataStream).toBe(before?.dataStream);
+ expect(doc.getBody()?.customRanges).toEqual(before?.customRanges);
+ commands.syncExecuteCommand(RichTextEditingMutation.id, redo);
+ expect(doc.getBody()).toEqual(updated);
+ } finally {
+ univer.dispose();
+ }
+ });
+});
diff --git a/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts b/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts
index c150a7b1de..5d440d0e37 100644
--- a/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts
+++ b/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts
@@ -49,6 +49,8 @@ export const UpdateDocHyperLinkCommand: ICommand<IUpdateDocHyperLinkCommandParam
return false;
}
+ const oldLink = oldBody.customRanges?.find((range) => range.rangeId === linkId && range.rangeType === CustomRangeType.HYPERLINK);
+
const textRun = getBodySlice(oldBody, currentSelection.startOffset!, currentSelection.endOffset!).textRuns?.[0];
if (textRun) {
textRun.ed = params.label.length + 1;
@@ -65,6 +67,8 @@ export const UpdateDocHyperLinkCommand: ICommand<IUpdateDocHyperLinkCommandParam
endIndex: params.label.length + 1,
properties: {
url: payload,
+ ...(oldLink?.properties?.textStyleMode ? { textStyleMode: oldLink.properties.textStyleMode } : null),
+ ...(oldLink?.properties?.textColorMode ? { textColorMode: oldLink.properties.textColorMode } : null),
},
}],
textRuns: textRun ? [textRun] : undefined,
diff --git a/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts b/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts
index 727550be36..1fef14b992 100644
--- a/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts
+++ b/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts
@@ -21,7 +21,7 @@ import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { IDialogService } from '@univerjs/ui';
import { of } from 'rxjs';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { DocHyperLinkPopupService } from '../../../services/hyper-link-popup.service';
import {
ClickDocHyperLinkOperation,
@@ -44,7 +44,29 @@ function createDocData(): IDocumentData {
properties: {
url: 'javascript:alert(1)',
},
+ }, {
+ rangeId: 'bookmark-link',
+ rangeType: CustomRangeType.HYPERLINK,
+ startIndex: 6,
+ endIndex: 10,
+ properties: { bookmarkId: '_Toc1' },
+ }, {
+ rangeId: 'bookmark-range',
+ rangeType: CustomRangeType.BOOKMARK,
+ startIndex: 11,
+ endIndex: 11,
+ properties: { bookmarkId: '_Toc1' },
+ }, {
+ rangeId: 'heading-link',
+ rangeType: CustomRangeType.HYPERLINK,
+ startIndex: 0,
+ endIndex: 4,
+ properties: { headingId: 'heading-2' },
}],
+ paragraphs: [
+ { startIndex: 5, paragraphId: 'paragraph-1' },
+ { startIndex: 11, paragraphId: 'paragraph-2', paragraphStyle: { headingId: 'heading-2' } },
+ ],
},
documentStyle: {
pageSize: {
@@ -169,4 +191,40 @@ describe('doc hyperlink popup operations', () => {
expect(result).toBe(false);
});
+
+ it('moves the caret to an internal bookmark', async () => {
+ const replaceDocRanges = vi.spyOn(selectionManager, 'replaceDocRanges');
+
+ const result = await commandService.executeCommand(ClickDocHyperLinkOperation.id, {
+ unitId,
+ linkId: 'bookmark-link',
+ segmentId: '',
+ });
+
+ expect(result).toBe(true);
+ expect(replaceDocRanges).toHaveBeenCalledWith(
+ [{ startOffset: 11, endOffset: 11, collapsed: true }],
+ { unitId, subUnitId: unitId },
+ false,
+ { preserveCaret: true }
+ );
+ });
+
+ it('moves the caret to the start of an internal heading', async () => {
+ const replaceDocRanges = vi.spyOn(selectionManager, 'replaceDocRanges');
+
+ const result = await commandService.executeCommand(ClickDocHyperLinkOperation.id, {
+ unitId,
+ linkId: 'heading-link',
+ segmentId: '',
+ });
+
+ expect(result).toBe(true);
+ expect(replaceDocRanges).toHaveBeenCalledWith(
+ [{ startOffset: 6, endOffset: 6, collapsed: true }],
+ { unitId, subUnitId: unitId },
+ false,
+ { preserveCaret: true }
+ );
+ });
});
diff --git a/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts b/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts
index f1202eebc8..1a5b4e34d6 100644
--- a/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts
+++ b/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts
@@ -14,9 +14,11 @@
* limitations under the License.
*/
-import type { DocumentDataModel, IAccessor, ICommand } from '@univerjs/core';
+import type { DocumentDataModel, IAccessor, ICommand, IDocumentBody } from '@univerjs/core';
import { CommandType, CustomRangeType, isSafeUrl, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
-import { DocSelectionManagerService } from '@univerjs/docs';
+import { DOC_SELECTION_OPTION_PRESERVE_CARET, DocSelectionManagerService } from '@univerjs/docs';
+import { DocBackScrollRenderController } from '@univerjs/docs-ui';
+import { IRenderManagerService } from '@univerjs/engine-render';
import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
export const shouldDisableAddLink = (accessor: IAccessor) => {
@@ -74,6 +76,7 @@ export interface IShowDocHyperLinkInfoPopupOperationParams {
segmentPage?: number;
startIndex: number;
endIndex: number;
+ fromHover?: boolean;
}
export const ToggleDocHyperLinkInfoPopupOperation: ICommand<IShowDocHyperLinkInfoPopupOperationParams> = {
@@ -86,7 +89,11 @@ export const ToggleDocHyperLinkInfoPopupOperation: ICommand<IShowDocHyperLinkInf
return true;
}
- hyperLinkService.showInfoPopup(params);
+ if (params.fromHover) {
+ hyperLinkService.showInfoPopupFromHover(params);
+ } else {
+ hyperLinkService.showInfoPopup(params);
+ }
return true;
},
};
@@ -101,13 +108,65 @@ export const ClickDocHyperLinkOperation: ICommand<{ unitId: string; linkId: stri
const { unitId, linkId, segmentId } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
const doc = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- const body = doc?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
- const link = body?.customRanges?.find((range) => range.rangeId === linkId && range.rangeType === CustomRangeType.HYPERLINK)?.properties?.url;
+ const sourceBody = doc?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+ const link = sourceBody?.customRanges?.find((range) => range.rangeId === linkId && range.rangeType === CustomRangeType.HYPERLINK)?.properties;
+
+ if (link?.bookmarkId || link?.headingId) {
+ const targetBody = doc?.getBody();
+ const targetOffset = findInternalLinkTarget(targetBody, link.bookmarkId, link.headingId);
+ if (targetOffset == null) {
+ return false;
+ }
+
+ const range = { startOffset: targetOffset, endOffset: targetOffset, collapsed: true };
+ const selectionManager = accessor.get(DocSelectionManagerService);
+ const selectTarget = (): void => selectionManager.replaceDocRanges(
+ [range],
+ { unitId, subUnitId: unitId },
+ false,
+ { [DOC_SELECTION_OPTION_PRESERVE_CARET]: true }
+ );
+ const render = accessor.get(IRenderManagerService).getRenderUnitById(unitId);
+ const renderInjector = render?.getInjector?.();
+ const backScrollController = renderInjector?.has(DocBackScrollRenderController)
+ ? render?.with(DocBackScrollRenderController)
+ : null;
+
+ if (backScrollController) {
+ backScrollController.scrollToRange(range, selectTarget);
+ } else {
+ selectTarget();
+ }
+ return true;
+ }
- if (!isSafeUrl(link)) {
+ if (!link?.url || !isSafeUrl(link.url)) {
return false;
}
- window.open(link, '_blank', 'noopener noreferrer');
+ window.open(link.url, '_blank', 'noopener noreferrer');
return true;
},
};
+
+function findInternalLinkTarget(body: IDocumentBody | undefined, bookmarkId?: string, headingId?: string): number | undefined {
+ if (!body) {
+ return;
+ }
+
+ if (bookmarkId) {
+ const bookmark = body.customRanges?.find((range) =>
+ range.rangeType === CustomRangeType.BOOKMARK &&
+ (range.rangeId === bookmarkId || range.properties?.bookmarkId === bookmarkId)
+ );
+ if (bookmark) {
+ return bookmark.startIndex;
+ }
+ }
+
+ if (headingId) {
+ const paragraphIndex = body.paragraphs?.findIndex((paragraph) => paragraph.paragraphStyle?.headingId === headingId) ?? -1;
+ if (paragraphIndex >= 0) {
+ return paragraphIndex === 0 ? 0 : body.paragraphs![paragraphIndex - 1].startIndex + 1;
+ }
+ }
+}
diff --git a/packages/docs-hyper-link-ui/src/controllers/__tests__/doc-hyper-link-selection.controller.spec.ts b/packages/docs-hyper-link-ui/src/controllers/__tests__/doc-hyper-link-selection.controller.spec.ts
index a437022ee7..af25d02a6b 100644
--- a/packages/docs-hyper-link-ui/src/controllers/__tests__/doc-hyper-link-selection.controller.spec.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/__tests__/doc-hyper-link-selection.controller.spec.ts
@@ -17,8 +17,16 @@
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
import type { ISetTextSelectionsOperationParams } from '@univerjs/docs';
import type { RenderUnit } from '@univerjs/engine-render';
-import { BooleanNumber, CustomRangeType, DocumentFlavor, ICommandService, Univer, UniverInstanceType } from '@univerjs/core';
-import { DocLayoutExecutorService, DocSelectionManagerService, DocSkeletonManagerService, SetTextSelectionsOperation } from '@univerjs/docs';
+import { BooleanNumber, CustomRangeType, DocumentFlavor, ICommandService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';
+import {
+ DocLayoutExecutorService,
+ DocSelectionManagerService,
+ DocSkeletonManagerService,
+ DocStateEmitService,
+ InsertTextCommand,
+ RichTextEditingMutation,
+ SetTextSelectionsOperation,
+} from '@univerjs/docs';
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { CanvasColorService, Documents, ICanvasColorService, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { CanvasPopupService, DesktopDialogService, ICanvasPopupService, IDialogService, IUIPartsService, UIPartsService } from '@univerjs/ui';
@@ -57,6 +65,7 @@ describe.each([1, 3])('DocHyperLinkSelectionController with a %i-character link'
injector.add([IDialogService, { useClass: DesktopDialogService }]);
injector.add([DocLayoutExecutorService]);
injector.add([DocSelectionManagerService]);
+ injector.add([DocStateEmitService]);
injector.add([DocCanvasPopManagerService]);
injector.add([DocHyperLinkPopupService]);
injector.add([DocHyperLinkSelectionController]);
@@ -81,16 +90,11 @@ describe.each([1, 3])('DocHyperLinkSelectionController with a %i-character link'
marginRight: 20,
},
});
- const render = injector.get(IRenderManagerService).createRender(model.getUnitId()) as RenderUnit;
- render.deactivate();
- render.engine.resizeBySize(300, 400);
- vi.spyOn(render.engine.getCanvasElement()!, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 300, 400));
- render.addRenderDependencies([[DocSkeletonManagerService]]);
- const documents = new Documents('link-selection-document', render.with(DocSkeletonManagerService).getSkeleton());
- render.mainComponent = documents;
- render.scene.addObject(documents);
+ mountDocument(model);
commands = injector.get(ICommandService);
commands.registerCommand(SetTextSelectionsOperation);
+ commands.registerCommand(InsertTextCommand);
+ commands.registerCommand(RichTextEditingMutation);
popup = injector.get(DocHyperLinkPopupService);
injector.get(DocHyperLinkSelectionController);
});
@@ -100,12 +104,23 @@ describe.each([1, 3])('DocHyperLinkSelectionController with a %i-character link'
vi.restoreAllMocks();
});
- async function select(startOffset: number, endOffset = startOffset): Promise<void> {
+ function mountDocument(model: DocumentDataModel): void {
+ const render = univer.__getInjector().get(IRenderManagerService).createRender(model.getUnitId()) as RenderUnit;
+ render.deactivate();
+ render.engine.resizeBySize(300, 400);
+ vi.spyOn(render.engine.getCanvasElement()!, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 300, 400));
+ render.addRenderDependencies([[DocSkeletonManagerService]]);
+ const documents = new Documents('link-selection-document', render.with(DocSkeletonManagerService).getSkeleton());
+ render.mainComponent = documents;
+ render.scene.addObject(documents);
+ }
+
+ async function select(startOffset: number, endOffset = startOffset, isEditing = false): Promise<void> {
const params: ISetTextSelectionsOperationParams = {
unitId: 'doc-unit',
subUnitId: 'doc-unit',
segmentId: '',
- isEditing: false,
+ isEditing,
style: { fill: '', stroke: '', strokeActive: '', strokeWidth: 0 },
ranges: [{ startOffset, endOffset, collapsed: startOffset === endOffset, segmentPage: 0 }],
};
@@ -156,4 +171,42 @@ describe.each([1, 3])('DocHyperLinkSelectionController with a %i-character link'
await select(startIndex, endIndex + 1);
expect(popup.showing).toBeNull();
});
+
+ it('releases link details after editing and does not reopen them on a layout selection refresh', async () => {
+ await select(startIndex);
+ expect(popup.showing?.linkId).toBe('link-1');
+ expect(await commands.executeCommand(InsertTextCommand.id, {
+ unitId: 'doc-unit',
+ body: { dataStream: '!' },
+ range: { startOffset: 5, endOffset: 5, collapsed: true },
+ textRanges: [],
+ noNeedSetTextRange: true,
+ debounce: false,
+ })).toBe(true);
+ expect(popup.showing).toBeNull();
+ await select(startIndex);
+ expect(popup.showing).toBeNull();
+ await select(0);
+ await select(startIndex);
+ expect(popup.showing?.linkId).toBe('link-1');
+ });
+
+ it('does not open link details for an editing caret', async () => {
+ await select(startIndex, startIndex, true);
+ expect(popup.showing).toBeNull();
+ });
+
+ it('opens link details at the same caret after closing and reopening the document', async () => {
+ const instances = univer.__getInjector().get(IUniverInstanceService);
+ const snapshot = instances.getUnit<DocumentDataModel>('doc-unit', UniverInstanceType.UNIVER_DOC)!.getSnapshot();
+ await select(startIndex);
+ expect(popup.showing?.linkId).toBe('link-1');
+ univer.__getInjector().get(IRenderManagerService).removeRender('doc-unit');
+ expect(instances.disposeUnit('doc-unit')).toBe(true);
+ expect(popup.showing).toBeNull();
+
+ mountDocument(univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, snapshot));
+ await select(startIndex);
+ expect(popup.showing?.linkId).toBe('link-1');
+ });
});
diff --git a/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts b/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts
index f5d1aeaa4c..805216f6bf 100644
--- a/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts
@@ -15,7 +15,7 @@
*/
import type { DocumentDataModel } from '@univerjs/core';
-import type { ISetTextSelectionsOperationParams } from '@univerjs/docs';
+import type { IRichTextEditingMutationParams, ISetTextSelectionsOperationParams } from '@univerjs/docs';
import {
CustomRangeType,
Disposable,
@@ -24,10 +24,12 @@ import {
IUniverInstanceService,
UniverInstanceType,
} from '@univerjs/core';
-import { SetTextSelectionsOperation } from '@univerjs/docs';
+import { RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
import { DocHyperLinkPopupService } from '../services/hyper-link-popup.service';
export class DocHyperLinkSelectionController extends Disposable {
+ private _selection: { unitId: string; key: string } | null = null;
+
constructor(
@ICommandService private readonly _commandService: ICommandService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@@ -36,17 +38,38 @@ export class DocHyperLinkSelectionController extends Disposable {
super();
this._initSelectionChange();
+ this.disposeWithMe(this._univerInstanceService.unitDisposed$.subscribe((unit) => {
+ if (this._selection?.unitId === unit.getUnitId()) {
+ this._selection = null;
+ }
+ }));
}
private _initSelectionChange() {
this.disposeWithMe(
this._commandService.onCommandExecuted((commandInfo) => {
+ if (commandInfo.id === RichTextEditingMutation.id) {
+ const params = commandInfo.params as IRichTextEditingMutationParams;
+ if (params.unitId === this._docHyperLinkService.showing?.unitId) {
+ this._docHyperLinkService.hideInfoPopup();
+ }
+ return;
+ }
if (commandInfo.id === SetTextSelectionsOperation.id) {
const params = commandInfo.params as ISetTextSelectionsOperationParams;
const { unitId, ranges, segmentId } = params;
const doc = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
const primary = ranges[0];
+ const selectionKey = JSON.stringify([
+ unitId,
+ segmentId ?? '',
+ primary?.startOffset,
+ primary?.endOffset,
+ primary?.segmentPage,
+ ]);
+ const sameSelection = selectionKey === this._selection?.key;
+ this._selection = { unitId, key: selectionKey };
const editing = this._docHyperLinkService.editing;
// Opening the editor selects its own link; that is not a user dismissal.
if (editing?.unitId === unitId &&
@@ -54,6 +77,15 @@ export class DocHyperLinkSelectionController extends Disposable {
primary?.startOffset === editing.startIndex && primary.endOffset === editing.endIndex + 1) {
return;
}
+ if (params.isEditing) {
+ this._docHyperLinkService.hideInfoPopup();
+ return;
+ }
+ // Layout republishes the current caret. Reopening a popup here
+ // acquires an interaction lock and can suspend Worker publication.
+ if (sameSelection) {
+ return;
+ }
if (primary?.collapsed && doc) {
const { startOffset, endOffset, segmentPage } = primary;
const customRanges = doc.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.customRanges;
diff --git a/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/hyper-link-event.render-controller.spec.ts b/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/hyper-link-event.render-controller.spec.ts
index 74e5a3c567..3496e179a9 100644
--- a/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/hyper-link-event.render-controller.spec.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/hyper-link-event.render-controller.spec.ts
@@ -48,6 +48,45 @@ function createController(
}
describe('DocHyperLinkEventRenderController', () => {
+ it('treats a containing table render segment as the main document body', () => {
+ const hoverCustomRanges$ = new Subject<unknown[]>();
+ const clickCustomRanges$ = new Subject<unknown>();
+ const pointerDownCustomRanges$ = new Subject<unknown[]>();
+ const commandService = {
+ executeCommand: vi.fn(),
+ };
+ const controller = createController(
+ {
+ unitId: 'doc-unit',
+ unit: { getBody: () => ({ tables: [{ tableId: 'table-4' }] }) },
+ } as never,
+ { hoverCustomRanges$, clickCustomRanges$, pointerDownCustomRanges$ } as never,
+ commandService as never,
+ { showing: false } as never,
+ { getSkeleton: vi.fn() } as never,
+ { getTextRanges: () => [{ segmentId: 'table-4' }] } as never
+ );
+
+ hoverCustomRanges$.next([{
+ range: {
+ rangeId: 'link-1',
+ rangeType: CustomRangeType.HYPERLINK,
+ startIndex: 4,
+ endIndex: 10,
+ },
+ segmentId: '',
+ segmentPageIndex: -1,
+ rects: [],
+ }]);
+
+ expect(commandService.executeCommand).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ linkId: 'link-1', fromHover: true })
+ );
+
+ controller.dispose();
+ });
+
it('keeps the mobile event controller independent from the desktop controller', () => {
expect(MobileDocHyperLinkEventRenderController.prototype).not.toBeInstanceOf(DocHyperLinkEventRenderController);
});
diff --git a/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts b/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts
index f861c39033..e6428e633a 100644
--- a/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts
@@ -65,6 +65,14 @@ export class DocHyperLinkEventRenderController extends Disposable implements IRe
}
}
+ private _normalizeSegmentId(segmentId?: string): string {
+ if (!segmentId) {
+ return '';
+ }
+
+ return this._context.unit.getBody()?.tables?.some((table) => table.tableId === segmentId) ? '' : segmentId;
+ }
+
private _initPointerDown() {
this.disposeWithMe(
this._docEventManagerService.pointerDownCustomRanges$.subscribe((ranges) => {
@@ -82,7 +90,7 @@ export class DocHyperLinkEventRenderController extends Disposable implements IRe
const link = ranges.find((range) => range.range.rangeType === CustomRangeType.HYPERLINK);
const activeRanges = this._docSelectionManagerService.getTextRanges();
const currentSegmentId = activeRanges?.[0]?.segmentId;
- if ((link?.segmentId ?? '') !== currentSegmentId) {
+ if (this._normalizeSegmentId(link?.segmentId) !== this._normalizeSegmentId(currentSegmentId)) {
this._hideInfoPopup();
return;
}
@@ -98,7 +106,7 @@ export class DocHyperLinkEventRenderController extends Disposable implements IRe
};
this._commandService.executeCommand(
ToggleDocHyperLinkInfoPopupOperation.id,
- info
+ { ...info, fromHover: true }
);
} else {
this._hideInfoPopup();
diff --git a/packages/docs-hyper-link-ui/src/menu/schema.ts b/packages/docs-hyper-link-ui/src/menu/schema.ts
index edcfe2a730..c1e9caec26 100644
--- a/packages/docs-hyper-link-ui/src/menu/schema.ts
+++ b/packages/docs-hyper-link-ui/src/menu/schema.ts
@@ -24,6 +24,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonInsertGroup.MEDIA]: {
[ShowDocHyperLinkEditPopupOperation.id]: {
order: 1,
+ gridLayout: { row: 1, column: 5 },
menuItemFactory: AddHyperLinkMenuItemFactory,
},
},
diff --git a/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts b/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
index 30491b64f2..6094d13a26 100644
--- a/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
+++ b/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
@@ -265,6 +265,27 @@ describe('DocHyperLinkPopupService', () => {
}
});
+ it('keeps the current popup while the pointer crosses adjacent links', () => {
+ const { service, attached, disposed } = createService();
+ const firstLink = { unitId: 'doc-1', linkId: 'link-1', startIndex: 4, endIndex: 8 };
+ const secondLink = { unitId: 'doc-1', linkId: 'link-2', startIndex: 9, endIndex: 13 };
+
+ service.showInfoPopup(firstLink);
+ service.showInfoPopupFromHover(secondLink);
+
+ expect(service.showing).toEqual(firstLink);
+ expect(attached).toHaveLength(1);
+ expect(disposed).toEqual([]);
+
+ service.hideInfoPopup();
+ service.showInfoPopupFromHover(secondLink);
+ expect(service.showing).toEqual(secondLink);
+ expect(attached).toHaveLength(2);
+ expect(disposed).toEqual([1]);
+
+ service.dispose();
+ });
+
it('does not show link information when the target document is not loaded', () => {
const { service, attached } = createService();
diff --git a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
index 57ef4c23be..4745af8e0e 100644
--- a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
+++ b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
@@ -245,6 +245,16 @@ export class DocHyperLinkPopupService extends Disposable {
);
}
+ showInfoPopupFromHover(info: ILinkInfo): void {
+ this.cancelScheduledHideInfoPopup();
+ if (this._infoPopupPinned || this._infoPopupSuppressed) {
+ return;
+ }
+ if (!this.showing) {
+ this.showInfoPopup(info);
+ }
+ }
+
hideInfoPopup() {
this.cancelScheduledHideInfoPopup();
this._infoPopupPinned = false;
diff --git a/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx b/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
index e88f4e1841..0bed3d062b 100644
--- a/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
+++ b/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
@@ -30,7 +30,7 @@ import { CopyIcon, LinkIcon, UnlinkIcon, WriteIcon } from '@univerjs/icons';
import { UnitAction } from '@univerjs/protocol';
import { IMessageService, useDependency, useObservable } from '@univerjs/ui';
import { DeleteDocHyperLinkCommand } from '../commands/commands/delete-link.command';
-import { ShowDocHyperLinkEditPopupOperation } from '../commands/operations/popup.operation';
+import { ClickDocHyperLinkOperation, ShowDocHyperLinkEditPopupOperation } from '../commands/operations/popup.operation';
import { DocHyperLinkPopupService } from '../services/hyper-link-popup.service';
export const DocLinkPopup = () => {
@@ -56,7 +56,7 @@ export const DocLinkPopup = () => {
return null;
}
- const url = link.properties?.url;
+ const target = link.properties?.url ?? `#${link.properties?.bookmarkId ?? link.properties?.headingId ?? ''}`;
const canEdit = hyperLinkService.canEditLink(unitId, currentPopup);
const canCopy = getDocumentPermissionValue(permissionService, unitId, unitId, UnitAction.Copy);
return (
@@ -81,7 +81,7 @@ export const DocLinkPopup = () => {
univer-flex univer-h-6 univer-flex-1 univer-cursor-pointer univer-items-center univer-truncate
univer-text-sm univer-leading-5 univer-text-primary-500
`}
- onClick={() => window.open(url, undefined, 'noopener noreferrer')}
+ onClick={() => commandService.executeCommand(ClickDocHyperLinkOperation.id, { unitId, linkId, segmentId })}
>
<div
className={`
@@ -92,8 +92,8 @@ export const DocLinkPopup = () => {
>
<LinkIcon />
</div>
- <Tooltip showIfEllipsis title={url}>
- <span className="univer-flex-1 univer-truncate">{url}</span>
+ <Tooltip showIfEllipsis title={target}>
+ <span className="univer-flex-1 univer-truncate">{target}</span>
</Tooltip>
</div>
<div className="univer-flex univer-h-6 univer-flex-[0_0_auto] univer-items-center univer-justify-center">
@@ -111,7 +111,7 @@ export const DocLinkPopup = () => {
"
disabled={!canCopy}
onClick={() => {
- navigator.clipboard.writeText(url);
+ navigator.clipboard.writeText(target);
messageService.show({
content: localeService.t<LocaleKey>('docs-hyper-link-ui.info.coped'),
type: MessageType.Info,
diff --git a/packages/docs-thread-comment-ui/src/locale/en-US.ts b/packages/docs-thread-comment-ui/src/locale/en-US.ts
index 23bff0e330..872afc31d6 100644
--- a/packages/docs-thread-comment-ui/src/locale/en-US.ts
+++ b/packages/docs-thread-comment-ui/src/locale/en-US.ts
@@ -19,7 +19,7 @@ const locale = {
panel: {
title: 'Comment Management',
addComment: 'Add Comment',
- openComments: 'Open Comments',
+ openComments: 'Comments',
},
},
};
diff --git a/packages/docs-thread-comment-ui/src/menu/schema.ts b/packages/docs-thread-comment-ui/src/menu/schema.ts
index cf710a784a..79c12cc0fa 100644
--- a/packages/docs-thread-comment-ui/src/menu/schema.ts
+++ b/packages/docs-thread-comment-ui/src/menu/schema.ts
@@ -25,15 +25,15 @@ import {
import { AddDocCommentMenuItemFactory, AddDocDrawingCommentMenuItemFactory, ToolbarDocCommentMenuItemFactory } from './menu';
export const menuSchema: MenuSchemaType = {
- [RibbonInsertGroup.MEDIA]: {
+ [RibbonInsertGroup.OTHERS]: {
[ToggleCommentPanelOperation.id]: {
- order: 3,
- gridLayout: { row: 1, column: 4, showLabel: true },
+ order: 0,
+ gridLayout: { row: 1, column: 1, showLabel: true },
menuItemFactory: ToolbarDocCommentMenuItemFactory,
},
[StartAddCommentOperation.id]: {
- order: 3.1,
- gridLayout: { row: 2, column: 4, showLabel: true },
+ order: 0.1,
+ gridLayout: { row: 2, column: 1, showLabel: true },
menuItemFactory: AddDocCommentMenuItemFactory,
},
},
diff --git a/packages/docs-toc-ui/README.md b/packages/docs-toc-ui/README.md
new file mode 100644
index 0000000000..7933469f69
--- /dev/null
+++ b/packages/docs-toc-ui/README.md
@@ -0,0 +1,30 @@
+# @univerjs/docs-toc-ui
+
+`@univerjs/docs-toc-ui` adds Ribbon, context-menu, update dialog, and active-range feedback for `@univerjs/docs-toc`.
+
+## Installation
+
+```sh
+pnpm add @univerjs/docs-toc-ui
+```
+
+Keep all `@univerjs/*` packages on the same version.
+
+## Usage
+
+```ts
+import '@univerjs/docs-toc-ui/lib/index.css';
+import EnUS from '@univerjs/docs-toc-ui/locale/en-US';
+import { UniverDocsTocUIPlugin } from '@univerjs/docs-toc-ui';
+
+univer.registerPlugin(UniverDocsTocUIPlugin);
+
+// Merge EnUS into your Univer locale map when this package contributes UI text.
+```
+
+Register this package after Docs, Docs UI, Render Engine, and Docs TOC core packages.
+
+## Resources
+
+- [Documentation](https://docs.univer.ai)
+- [GitHub repository](https://github.com/dream-num/univer)
diff --git a/packages/docs-toc-ui/package.json b/packages/docs-toc-ui/package.json
new file mode 100644
index 0000000000..3726c951ec
--- /dev/null
+++ b/packages/docs-toc-ui/package.json
@@ -0,0 +1,96 @@
+{
+ "name": "@univerjs/docs-toc-ui",
+ "version": "1.0.0-rc.0",
+ "private": false,
+ "description": "Table of contents UI for Univer Docs.",
+ "author": "DreamNum Co., Ltd. <[email protected]>",
+ "license": "Apache-2.0",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/univer"
+ },
+ "homepage": "https://univer.ai",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/dream-num/univer"
+ },
+ "bugs": {
+ "url": "https://github.com/dream-num/univer/issues"
+ },
+ "keywords": [
+ "univer",
+ "docs",
+ "table-of-contents",
+ "toc",
+ "ui"
+ ],
+ "exports": {
+ ".": "./src/index.ts",
+ "./*": "./src/*",
+ "./locale/*": "./src/locale/*.ts"
+ },
+ "main": "./src/index.ts",
+ "types": "./lib/types/index.d.ts",
+ "publishConfig": {
+ "access": "public",
+ "main": "./lib/es/index.js",
+ "module": "./lib/es/index.js",
+ "exports": {
+ ".": {
+ "import": "./lib/es/index.js",
+ "require": "./lib/cjs/index.js",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./*": {
+ "import": "./lib/es/*",
+ "require": "./lib/cjs/*",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./locale/*": {
+ "import": "./lib/es/locale/*.js",
+ "require": "./lib/cjs/locale/*.js",
+ "types": "./lib/types/locale/*.d.ts"
+ },
+ "./lib/*": "./lib/*"
+ }
+ },
+ "directories": {
+ "lib": "lib"
+ },
+ "files": [
+ "lib"
+ ],
+ "scripts": {
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "coverage": "vitest run --coverage",
+ "typecheck": "tsc --noEmit",
+ "build:bundle": "univer-cli build",
+ "build:types": "tsc -p tsconfig.node.json",
+ "build": "pnpm run build:bundle && pnpm run build:types"
+ },
+ "peerDependencies": {
+ "react": "^16.9.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc",
+ "rxjs": ">=7.0.0"
+ },
+ "dependencies": {
+ "@univerjs/core": "workspace:*",
+ "@univerjs/design": "workspace:*",
+ "@univerjs/docs": "workspace:*",
+ "@univerjs/docs-toc": "workspace:*",
+ "@univerjs/docs-ui": "workspace:*",
+ "@univerjs/engine-render": "workspace:*",
+ "@univerjs/protocol": "workspace:*",
+ "@univerjs/ui": "workspace:*"
+ },
+ "devDependencies": {
+ "@univerjs-infra/shared": "workspace:*",
+ "postcss": "^8.5.26",
+ "react": "18.3.1",
+ "react-dom": "18.3.1",
+ "rxjs": "^7.8.2",
+ "tailwindcss": "3.4.18",
+ "typescript": "^6.0.3",
+ "vitest": "^5.0.0"
+ }
+}
diff --git a/packages/docs-toc-ui/postcss.config.mjs b/packages/docs-toc-ui/postcss.config.mjs
new file mode 100644
index 0000000000..7d59f53133
--- /dev/null
+++ b/packages/docs-toc-ui/postcss.config.mjs
@@ -0,0 +1 @@
+export { default } from '@univerjs-infra/shared/postcss';
diff --git a/packages/docs-toc-ui/src/commands/__tests__/table-of-contents-dialog.operation.spec.ts b/packages/docs-toc-ui/src/commands/__tests__/table-of-contents-dialog.operation.spec.ts
new file mode 100644
index 0000000000..3f86fdba6e
--- /dev/null
+++ b/packages/docs-toc-ui/src/commands/__tests__/table-of-contents-dialog.operation.spec.ts
@@ -0,0 +1,92 @@
+/**
+ * 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, IDocumentBody, IDocumentData } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService, LocaleService, LocaleType, Univer, UniverInstanceType } from '@univerjs/core';
+import { UniverDocsPlugin } from '@univerjs/docs';
+import { InsertTableOfContentsCommand } from '@univerjs/docs-toc';
+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
+import { IMessageService } from '@univerjs/ui';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import enUS from '../../locale/en-US';
+import { InsertTableOfContentsOperation } from '../table-of-contents-dialog.operation';
+
+describe('InsertTableOfContentsOperation', () => {
+ let univer: Univer;
+ afterEach(() => univer?.dispose());
+
+ function createAccessor(body: IDocumentBody) {
+ univer = new Univer();
+ univer.registerPlugin(UniverDocsPlugin);
+ const injector = univer.__getInjector();
+ const show = vi.fn(() => ({ dispose: vi.fn() }));
+ // The native notification surface is unavailable in this headless test.
+ injector.add([IMessageService, { useValue: { show, remove: vi.fn(), removeAll: vi.fn() } }]);
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, { id: 'doc-1', body, documentStyle: {} });
+ injector.get(IUniverInstanceService).focusUnit('doc-1');
+ const locale = injector.get(LocaleService);
+ locale.load({ [LocaleType.EN_US]: enUS });
+ locale.setLocale(LocaleType.EN_US);
+ locale.setDirection('ltr');
+ const commands = injector.get(ICommandService);
+ commands.registerCommand(InsertTableOfContentsCommand);
+ commands.registerCommand(InsertTableOfContentsOperation);
+ const dispatched: unknown[] = [];
+ const subscription = commands.beforeCommandExecuted((command) => {
+ if (command.id === InsertTableOfContentsCommand.id) {
+ dispatched.push(command.params);
+ }
+ });
+ return { commands, dispatched, show, subscription };
+ }
+
+ it('shows a localized warning and does not invoke insertion without headings', async () => {
+ const { commands, dispatched, show, subscription } = createAccessor({
+ dataStream: 'Body\r\n',
+ paragraphs: [{ startIndex: 4, paragraphId: 'body' }],
+ });
+
+ expect(await commands.executeCommand(InsertTableOfContentsOperation.id, { mode: 'automatic' })).toBe(false);
+ expect(show).toHaveBeenCalledWith(expect.objectContaining({ content: enUS['docs-toc-ui'].tableOfContents.noHeadings }));
+ expect(dispatched).toHaveLength(0);
+ subscription.dispose();
+ });
+
+ it('dispatches localized automatic options and rejects insertion without rendered layout', async () => {
+ const { commands, dispatched, show, subscription } = createAccessor({
+ dataStream: 'Heading\r\n',
+ paragraphs: [{
+ startIndex: 7,
+ paragraphId: 'heading',
+ paragraphStyle: { headingId: 'heading-1', outlineLevel: 0 },
+ }],
+ });
+
+ expect(await commands.executeCommand(InsertTableOfContentsOperation.id, { mode: 'automatic' })).toBe(false);
+ expect(show).not.toHaveBeenCalled();
+ expect(dispatched).toEqual([expect.objectContaining({
+ unitId: 'doc-1',
+ levels: 3,
+ showPageNumbers: true,
+ rightAlignPageNumbers: true,
+ tabLeader: 'dots',
+ format: 'fromTemplate',
+ title: 'Contents',
+ })]);
+ subscription.dispose();
+ });
+});
diff --git a/packages/docs-toc-ui/src/commands/table-of-contents-dialog.operation.ts b/packages/docs-toc-ui/src/commands/table-of-contents-dialog.operation.ts
new file mode 100644
index 0000000000..12b7689623
--- /dev/null
+++ b/packages/docs-toc-ui/src/commands/table-of-contents-dialog.operation.ts
@@ -0,0 +1,165 @@
+/**
+ * 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, IAccessor, ICommand } from '@univerjs/core';
+import type { LocaleKey } from '../locale/types';
+import type { IInsertTableOfContentsDialogProps, IInsertTableOfContentsDialogValue } from '../views/InsertTableOfContentsDialog';
+import type { ITableOfContentsDialogProps } from '../views/TableOfContentsDialog';
+import {
+ BooleanNumber,
+ CommandType,
+ ICommandService,
+ IConfirmService,
+ IUniverInstanceService,
+ LocaleService,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { MessageType } from '@univerjs/design';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { countTableOfContentsHeadings, findTableOfContentsAtOffset, InsertTableOfContentsCommand, UpdateTableOfContentsCommand } from '@univerjs/docs-toc';
+import { IMessageService } from '@univerjs/ui';
+import { INSERT_TABLE_OF_CONTENTS_DIALOG_COMPONENT } from '../views/InsertTableOfContentsDialog';
+import { TABLE_OF_CONTENTS_DIALOG_COMPONENT } from '../views/TableOfContentsDialog';
+
+const TABLE_OF_CONTENTS_DIALOG_ID = 'doc.dialog.update-table-of-contents';
+const INSERT_TABLE_OF_CONTENTS_DIALOG_ID = 'doc.dialog.insert-table-of-contents';
+
+export interface IInsertTableOfContentsOperationParams {
+ mode: 'automatic' | 'custom';
+}
+
+const DEFAULT_INSERT_VALUE: IInsertTableOfContentsDialogValue = {
+ levels: 3,
+ showPageNumbers: true,
+ rightAlignPageNumbers: true,
+ tabLeader: 'dots',
+ format: 'fromTemplate',
+};
+
+function showNoHeadingsMessage(accessor: IAccessor): void {
+ accessor.get(IMessageService).show({
+ type: MessageType.Warning,
+ content: accessor.get(LocaleService).t<LocaleKey>('docs-toc-ui.tableOfContents.noHeadings'),
+ });
+}
+
+async function insertTableOfContents(accessor: IAccessor, value: IInsertTableOfContentsDialogValue, title?: string): Promise<boolean> {
+ const doc = accessor.get(IUniverInstanceService)
+ .getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ if (!doc || countTableOfContentsHeadings(doc.getBody(), value.levels) === 0) {
+ showNoHeadingsMessage(accessor);
+ return false;
+ }
+ return Boolean(await accessor.get(ICommandService).executeCommand(InsertTableOfContentsCommand.id, {
+ unitId: doc.getUnitId(),
+ ...value,
+ title,
+ }));
+}
+
+export const InsertTableOfContentsOperation: ICommand<IInsertTableOfContentsOperationParams> = {
+ id: 'doc.operation.insert-table-of-contents',
+ type: CommandType.OPERATION,
+ async handler(accessor, params) {
+ if (params?.mode === 'automatic') {
+ const title = accessor.get(LocaleService).t<LocaleKey>('docs-toc-ui.tableOfContents.contentsTitle');
+ return insertTableOfContents(accessor, DEFAULT_INSERT_VALUE, title);
+ }
+ if (params?.mode !== 'custom') {
+ return false;
+ }
+ const doc = accessor.get(IUniverInstanceService)
+ .getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ if (!doc) {
+ return false;
+ }
+ const confirmService = accessor.get(IConfirmService);
+ const localeService = accessor.get(LocaleService);
+ const state: Pick<IInsertTableOfContentsDialogProps, 'options'> = { options: { ...DEFAULT_INSERT_VALUE } };
+ await confirmService.open({
+ id: INSERT_TABLE_OF_CONTENTS_DIALOG_ID,
+ width: 520,
+ title: { title: localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.customTitle') },
+ children: {
+ label: {
+ name: INSERT_TABLE_OF_CONTENTS_DIALOG_COMPONENT,
+ props: {
+ options: state.options,
+ onChange: (value: IInsertTableOfContentsDialogValue) => {
+ state.options = value;
+ },
+ },
+ },
+ },
+ onConfirm: async () => {
+ const inserted = await insertTableOfContents(accessor, state.options);
+ if (inserted) {
+ confirmService.close(INSERT_TABLE_OF_CONTENTS_DIALOG_ID);
+ }
+ },
+ onClose: () => confirmService.close(INSERT_TABLE_OF_CONTENTS_DIALOG_ID),
+ });
+ return true;
+ },
+};
+
+export const OpenTableOfContentsDialogOperation: ICommand = {
+ id: 'doc.operation.open-table-of-contents-dialog',
+ type: CommandType.OPERATION,
+ async handler(accessor: IAccessor) {
+ const doc = accessor.get(IUniverInstanceService)
+ .getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const selection = accessor.get(DocSelectionManagerService).getActiveTextRange();
+ const toc = findTableOfContentsAtOffset(doc?.getBody(), selection?.startOffset);
+ if (!doc || !toc || toc.properties?.locked === BooleanNumber.TRUE) {
+ return false;
+ }
+
+ const confirmService = accessor.get(IConfirmService);
+ const commandService = accessor.get(ICommandService);
+ const localeService = accessor.get(LocaleService);
+ const state: Pick<ITableOfContentsDialogProps, 'mode'> = { mode: 'pageNumbersOnly' };
+ await confirmService.open({
+ id: TABLE_OF_CONTENTS_DIALOG_ID,
+ width: 420,
+ title: { title: localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.updateTitle') },
+ children: {
+ label: {
+ name: TABLE_OF_CONTENTS_DIALOG_COMPONENT,
+ props: {
+ mode: state.mode,
+ onModeChange: (mode: ITableOfContentsDialogProps['mode']) => {
+ state.mode = mode;
+ },
+ },
+ },
+ },
+ onConfirm: async () => {
+ try {
+ await commandService.executeCommand(UpdateTableOfContentsCommand.id, {
+ unitId: doc.getUnitId(),
+ rangeId: toc.rangeId,
+ mode: state.mode,
+ });
+ } finally {
+ confirmService.close(TABLE_OF_CONTENTS_DIALOG_ID);
+ }
+ },
+ onClose: () => confirmService.close(TABLE_OF_CONTENTS_DIALOG_ID),
+ });
+ return true;
+ },
+};
diff --git a/packages/docs-toc-ui/src/config/config.ts b/packages/docs-toc-ui/src/config/config.ts
new file mode 100644
index 0000000000..8bb2b712a2
--- /dev/null
+++ b/packages/docs-toc-ui/src/config/config.ts
@@ -0,0 +1,27 @@
+/**
+ * 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 { MenuConfig } from '@univerjs/ui';
+
+export const DOCS_TOC_UI_PLUGIN_CONFIG_KEY = 'docs-toc-ui.config';
+
+export const configSymbol = Symbol(DOCS_TOC_UI_PLUGIN_CONFIG_KEY);
+
+export interface IUniverDocsTocUIConfig {
+ menu?: MenuConfig;
+}
+
+export const defaultPluginConfig: IUniverDocsTocUIConfig = {};
diff --git a/packages/docs-toc-ui/src/controllers/__tests__/table-of-contents-ribbon.controller.spec.ts b/packages/docs-toc-ui/src/controllers/__tests__/table-of-contents-ribbon.controller.spec.ts
new file mode 100644
index 0000000000..8760781c3e
--- /dev/null
+++ b/packages/docs-toc-ui/src/controllers/__tests__/table-of-contents-ribbon.controller.spec.ts
@@ -0,0 +1,90 @@
+/**
+ * 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, IDocumentData } from '@univerjs/core';
+import { CustomRangeType, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService, UniverDocsPlugin } from '@univerjs/docs';
+import { DesktopRibbonService, IMenuManagerService, IRibbonService, MenuManagerService } from '@univerjs/ui';
+import { afterEach, describe, expect, it } from 'vitest';
+import { DOC_TABLE_OF_CONTENTS_RIBBON_TAB, tableOfContentsRibbonMenuSchema } from '../../menu/schema';
+import { TableOfContentsRibbonController } from '../table-of-contents-ribbon.controller';
+
+describe('TableOfContentsRibbonController', () => {
+ let univer: Univer;
+
+ afterEach(() => univer?.dispose());
+
+ function setup() {
+ univer = new Univer();
+ univer.registerPlugin(UniverDocsPlugin);
+ const injector = univer.__getInjector();
+ injector.add([IMenuManagerService, { useClass: MenuManagerService }]);
+ injector.add([IRibbonService, { useClass: DesktopRibbonService }]);
+ injector.add([TableOfContentsRibbonController]);
+ univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: 'doc-1',
+ body: {
+ dataStream: 'Before\r\u001FContents\u001E\rAfter\r\n',
+ paragraphs: [6, 17, 23].map((startIndex) => ({ startIndex, paragraphId: `p-${startIndex}` })),
+ sectionBreaks: [{ startIndex: 24, sectionId: 's-1' }],
+ customRanges: [{
+ rangeId: 'toc-1',
+ rangeType: CustomRangeType.FIELD,
+ startIndex: 7,
+ endIndex: 16,
+ properties: { fieldType: 'TOC' },
+ }],
+ },
+ documentStyle: {},
+ });
+ injector.get(IUniverInstanceService).focusUnit('doc-1');
+ const selection = injector.get(DocSelectionManagerService);
+ selection.__TEST_ONLY_add([{ startOffset: 0, endOffset: 0, collapsed: true, isActive: true }]);
+ const select = (offset: number) => selection.__replaceTextRangesWithNoRefresh({
+ ...selection.getSelectionInfo()!,
+ textRanges: [{ startOffset: offset, endOffset: offset, collapsed: true, isActive: true }],
+ }, { unitId: 'doc-1', subUnitId: 'doc-1' });
+ const ribbon = injector.get(IRibbonService);
+ injector.get(IMenuManagerService).appendRootMenu(tableOfContentsRibbonMenuSchema);
+ const tabs: string[][] = [];
+ const active: string[] = [];
+ const tabSubscription = ribbon.ribbon$.subscribe((items) => tabs.push(items.map((item) => item.key)));
+ const activeSubscription = ribbon.activatedTab$.subscribe((tab) => active.push(tab));
+ const controller = injector.get(TableOfContentsRibbonController);
+ controller.disposeWithMe(tabSubscription);
+ controller.disposeWithMe(activeSubscription);
+ return { controller, select, tabs, active };
+ }
+
+ it('activates the contextual tab once on entry and hides it on exit', () => {
+ const { controller, select, tabs, active } = setup();
+ select(8);
+ select(10);
+ expect(active.filter((tab) => tab === DOC_TABLE_OF_CONTENTS_RIBBON_TAB)).toHaveLength(1);
+ expect(tabs[tabs.length - 1]).toContain(DOC_TABLE_OF_CONTENTS_RIBBON_TAB);
+ select(20);
+ expect(tabs[tabs.length - 1]).not.toContain(DOC_TABLE_OF_CONTENTS_RIBBON_TAB);
+ controller.dispose();
+ });
+
+ it('hides an active contextual tab when disposed', () => {
+ const { controller, select, tabs } = setup();
+ select(8);
+ expect(tabs[tabs.length - 1]).toContain(DOC_TABLE_OF_CONTENTS_RIBBON_TAB);
+ controller.dispose();
+ expect(tabs[tabs.length - 1]).not.toContain(DOC_TABLE_OF_CONTENTS_RIBBON_TAB);
+ });
+});
diff --git a/packages/docs-toc-ui/src/controllers/components.controller.ts b/packages/docs-toc-ui/src/controllers/components.controller.ts
new file mode 100644
index 0000000000..2d10bf7379
--- /dev/null
+++ b/packages/docs-toc-ui/src/controllers/components.controller.ts
@@ -0,0 +1,28 @@
+/**
+ * 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 { Disposable, Inject } from '@univerjs/core';
+import { ComponentManager } from '@univerjs/ui';
+import { INSERT_TABLE_OF_CONTENTS_DIALOG_COMPONENT, InsertTableOfContentsDialog } from '../views/InsertTableOfContentsDialog';
+import { TABLE_OF_CONTENTS_DIALOG_COMPONENT, TableOfContentsDialog } from '../views/TableOfContentsDialog';
+
+export class ComponentsController extends Disposable {
+ constructor(@Inject(ComponentManager) componentManager: ComponentManager) {
+ super();
+ this.disposeWithMe(componentManager.register(TABLE_OF_CONTENTS_DIALOG_COMPONENT, TableOfContentsDialog));
+ this.disposeWithMe(componentManager.register(INSERT_TABLE_OF_CONTENTS_DIALOG_COMPONENT, InsertTableOfContentsDialog));
+ }
+}
diff --git a/packages/docs-toc-ui/src/controllers/table-of-contents-highlight.render-controller.ts b/packages/docs-toc-ui/src/controllers/table-of-contents-highlight.render-controller.ts
new file mode 100644
index 0000000000..962cefc855
--- /dev/null
+++ b/packages/docs-toc-ui/src/controllers/table-of-contents-highlight.render-controller.ts
@@ -0,0 +1,141 @@
+/**
+ * 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 type { Documents, IPoint, IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import { ColorKit, generateRandomId, Inject, IUniverInstanceService, RxDisposable, ThemeService, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
+import { findTableOfContentsAtOffset } from '@univerjs/docs-toc';
+import { NodePositionConvertToCursor, TEXT_RANGE_LAYER_INDEX } from '@univerjs/docs-ui';
+import { Rect, RegularPolygon } from '@univerjs/engine-render';
+import { takeUntil } from 'rxjs';
+
+const RANGE_PADDING = 4;
+
+export class TableOfContentsHighlightRenderController extends RxDisposable implements IRenderModule {
+ private _range: RegularPolygon | null = null;
+ private _outline: Rect | null = null;
+ private _rangeId: string | null = null;
+
+ constructor(
+ private readonly _context: IRenderContext<DocumentDataModel>,
+ @IUniverInstanceService private readonly _instanceService: IUniverInstanceService,
+ @Inject(DocSelectionManagerService) private readonly _selectionManager: DocSelectionManagerService,
+ @Inject(DocSkeletonManagerService) private readonly _skeletonManager: DocSkeletonManagerService,
+ @Inject(ThemeService) private readonly _themeService: ThemeService
+ ) {
+ super();
+ this._selectionManager.textSelection$.pipe(takeUntil(this.dispose$)).subscribe(() => this._update());
+ this._skeletonManager.currentSkeleton$.pipe(takeUntil(this.dispose$)).subscribe(() => this._update(true));
+ this._instanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
+ .pipe(takeUntil(this.dispose$))
+ .subscribe(() => this._update());
+ this._update();
+ }
+
+ private _update(force = false): void {
+ const currentDoc = this._instanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const selection = this._selectionManager.getActiveTextRange();
+ const toc = currentDoc?.getUnitId() === this._context.unitId && !selection?.segmentId
+ ? findTableOfContentsAtOffset(this._context.unit.getBody(), selection?.startOffset)
+ : undefined;
+ if (!toc) {
+ this._clear();
+ return;
+ }
+ if (!force && toc.rangeId === this._rangeId) {
+ return;
+ }
+
+ this._clear();
+ const document = this._context.mainComponent as Documents | undefined;
+ const endOffset = Math.max(toc.startIndex + 1, toc.endIndex - 1);
+ if (!document) {
+ return;
+ }
+ const primary = this._themeService.getColorFromTheme('primary.600');
+ const skeleton = this._skeletonManager.getSkeleton();
+ const startPosition = skeleton.findNodePositionByCharIndex(toc.startIndex + 1, true, '', -1);
+ const endPosition = skeleton.findNodePositionByCharIndex(endOffset, true, '', -1);
+ if (!startPosition || !endPosition) {
+ return;
+ }
+ const offsetConfig = document.getOffsetConfig();
+ const { borderBoxPointGroup } = new NodePositionConvertToCursor(offsetConfig, skeleton)
+ .getRangePointData(startPosition, endPosition);
+ const bounds = getPointGroupBounds(borderBoxPointGroup);
+ if (!bounds) {
+ return;
+ }
+
+ const range = new RegularPolygon(`__DocTocFill__${generateRandomId()}`, {
+ pointsGroup: borderBoxPointGroup,
+ left: offsetConfig.docsLeft,
+ top: offsetConfig.docsTop,
+ fill: new ColorKit(primary).setAlpha(0.08).toRgbString(),
+ evented: false,
+ debounceParentDirty: false,
+ });
+ const outline = new Rect(`__DocTocRange__${toc.rangeId}`, {
+ left: bounds.left + offsetConfig.docsLeft - RANGE_PADDING,
+ top: bounds.top + offsetConfig.docsTop - RANGE_PADDING,
+ width: bounds.width + RANGE_PADDING * 2,
+ height: bounds.height + RANGE_PADDING * 2,
+ radius: 2,
+ fill: 'rgba(0, 0, 0, 0)',
+ stroke: new ColorKit(primary).setAlpha(0.8).toRgbString(),
+ strokeWidth: 1,
+ evented: false,
+ debounceParentDirty: false,
+ });
+ this._context.scene.addObject(range, TEXT_RANGE_LAYER_INDEX);
+ this._context.scene.addObject(outline, TEXT_RANGE_LAYER_INDEX);
+ this._range = range;
+ this._outline = outline;
+ this._rangeId = toc.rangeId;
+ this._context.scene.makeDirty();
+ }
+
+ private _clear(): void {
+ if (!this._range && !this._outline) {
+ this._rangeId = null;
+ return;
+ }
+ this._range?.dispose();
+ this._outline?.dispose();
+ this._range = null;
+ this._outline = null;
+ this._rangeId = null;
+ this._context.scene.makeDirty();
+ }
+
+ override dispose(): void {
+ this._clear();
+ super.dispose();
+ }
+}
+
+function getPointGroupBounds(pointsGroup: IPoint[][]): { left: number; top: number; width: number; height: number } | null {
+ const points = pointsGroup.flat();
+ if (!points.length) {
+ return null;
+ }
+ const left = Math.min(...points.map((point) => point.x));
+ const top = Math.min(...points.map((point) => point.y));
+ const right = Math.max(...points.map((point) => point.x));
+ const bottom = Math.max(...points.map((point) => point.y));
+ return { left, top, width: right - left, height: bottom - top };
+}
diff --git a/packages/docs-toc-ui/src/controllers/table-of-contents-ribbon.controller.ts b/packages/docs-toc-ui/src/controllers/table-of-contents-ribbon.controller.ts
new file mode 100644
index 0000000000..ab9a94481c
--- /dev/null
+++ b/packages/docs-toc-ui/src/controllers/table-of-contents-ribbon.controller.ts
@@ -0,0 +1,69 @@
+/**
+ * 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 { Disposable, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { findTableOfContentsAtOffset } from '@univerjs/docs-toc';
+import { IRibbonService } from '@univerjs/ui';
+import { DOC_TABLE_OF_CONTENTS_RIBBON_TAB } from '../menu/schema';
+
+export class TableOfContentsRibbonController extends Disposable {
+ private _visible = false;
+
+ constructor(
+ @IUniverInstanceService private readonly _instanceService: IUniverInstanceService,
+ @Inject(DocSelectionManagerService) private readonly _selectionManager: DocSelectionManagerService,
+ @IRibbonService private readonly _ribbonService: IRibbonService
+ ) {
+ super();
+
+ this.disposeWithMe(this._selectionManager.textSelection$.subscribe(() => this._update()));
+ this.disposeWithMe(
+ this._instanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
+ .subscribe(() => this._update())
+ );
+ this._update();
+ }
+
+ private _update(): void {
+ const doc = this._instanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const selection = this._selectionManager.getActiveTextRange();
+ const visible = Boolean(
+ doc &&
+ selection &&
+ !selection.segmentId &&
+ findTableOfContentsAtOffset(doc.getBody(), selection.startOffset)
+ );
+ if (visible === this._visible) {
+ return;
+ }
+
+ this._visible = visible;
+ if (visible) {
+ this._ribbonService.showContextualTab(DOC_TABLE_OF_CONTENTS_RIBBON_TAB, { activate: true });
+ } else {
+ this._ribbonService.hideContextualTab(DOC_TABLE_OF_CONTENTS_RIBBON_TAB);
+ }
+ }
+
+ override dispose(): void {
+ if (this._visible) {
+ this._ribbonService.hideContextualTab(DOC_TABLE_OF_CONTENTS_RIBBON_TAB);
+ }
+ super.dispose();
+ }
+}
diff --git a/packages/docs-toc-ui/src/controllers/ui.controller.ts b/packages/docs-toc-ui/src/controllers/ui.controller.ts
new file mode 100644
index 0000000000..8749e17774
--- /dev/null
+++ b/packages/docs-toc-ui/src/controllers/ui.controller.ts
@@ -0,0 +1,33 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Disposable, ICommandService } from '@univerjs/core';
+import { IMenuManagerService } from '@univerjs/ui';
+import { InsertTableOfContentsOperation, OpenTableOfContentsDialogOperation } from '../commands/table-of-contents-dialog.operation';
+import { DocsTocUIMenuSchema, tableOfContentsRibbonMenuSchema } from '../menu/schema';
+
+export class DocsTocUIController extends Disposable {
+ constructor(
+ @ICommandService commandService: ICommandService,
+ @IMenuManagerService menuManagerService: IMenuManagerService
+ ) {
+ super();
+ this.disposeWithMe(commandService.registerCommand(OpenTableOfContentsDialogOperation));
+ this.disposeWithMe(commandService.registerCommand(InsertTableOfContentsOperation));
+ menuManagerService.appendRootMenu(tableOfContentsRibbonMenuSchema);
+ menuManagerService.mergeMenu(DocsTocUIMenuSchema);
+ }
+}
diff --git a/packages/docs-toc-ui/src/global.css b/packages/docs-toc-ui/src/global.css
new file mode 100644
index 0000000000..7c05d4ddc4
--- /dev/null
+++ b/packages/docs-toc-ui/src/global.css
@@ -0,0 +1,2 @@
+@tailwind components;
+@tailwind utilities;
diff --git a/packages/docs-toc-ui/src/index.ts b/packages/docs-toc-ui/src/index.ts
new file mode 100644
index 0000000000..f02df5340a
--- /dev/null
+++ b/packages/docs-toc-ui/src/index.ts
@@ -0,0 +1,20 @@
+/**
+ * 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 './global.css';
+
+export { DocsTocUIMenuSchema } from './menu/schema';
+export { UniverDocsTocUIPlugin } from './plugin';
diff --git a/packages/docs-toc-ui/src/locale/ar-SA.ts b/packages/docs-toc-ui/src/locale/ar-SA.ts
new file mode 100644
index 0000000000..3cc1ffcd12
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/ar-SA.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: 'جدول المحتويات',
+ insertTitle: 'جدول المحتويات',
+ automaticTitle: 'جدول تلقائي',
+ customTitle: 'جدول محتويات مخصص…',
+ contentsTitle: 'المحتويات',
+ levels: 'إظهار المستويات',
+ showPageNumbers: 'إظهار أرقام الصفحات',
+ rightAlignPageNumbers: 'محاذاة أرقام الصفحات إلى اليمين',
+ tabLeader: 'حرف تعبئة علامات الجدولة',
+ leaderNone: 'بلا',
+ leaderDots: 'نقاط',
+ leaderDashes: 'شرطات',
+ leaderUnderline: 'تسطير',
+ format: 'التنسيقات',
+ formatFromTemplate: 'من القالب',
+ formatClassic: 'كلاسيكي',
+ formatModern: 'حديث',
+ formatSimple: 'بسيط',
+ preview: 'معاينة الطباعة',
+ previewHeading: 'عنوان',
+ noHeadings: 'لم يتم العثور على عناوين. طبّق أنماط العنوان 1–3 أو اختر المستويات المطابقة.',
+ updateTitle: 'تحديث جدول المحتويات',
+ removeTitle: 'إزالة جدول المحتويات',
+ updatePageNumbersOnly: 'تحديث أرقام الصفحات فقط',
+ updateEntireTable: 'تحديث الجدول بالكامل',
+ updateHint: 'اختر كيفية تحديث جدول المحتويات هذا.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/ca-ES.ts b/packages/docs-toc-ui/src/locale/ca-ES.ts
new file mode 100644
index 0000000000..05b93582c7
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/ca-ES.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: 'Taula de continguts',
+ insertTitle: 'Taula de continguts',
+ automaticTitle: 'Taula automàtica',
+ customTitle: 'Taula de continguts personalitzada…',
+ contentsTitle: 'Continguts',
+ levels: 'Mostra els nivells',
+ showPageNumbers: 'Mostra els números de pàgina',
+ rightAlignPageNumbers: 'Alinea els números de pàgina a la dreta',
+ tabLeader: 'Caràcter de farciment',
+ leaderNone: 'Cap',
+ leaderDots: 'Punts',
+ leaderDashes: 'Guions',
+ leaderUnderline: 'Subratllat',
+ format: 'Formats',
+ formatFromTemplate: 'De la plantilla',
+ formatClassic: 'Clàssic',
+ formatModern: 'Modern',
+ formatSimple: 'Simple',
+ preview: 'Visualització prèvia d\'impressió',
+ previewHeading: 'Títol',
+ noHeadings: 'No s\'ha trobat cap títol. Apliqueu els estils Títol 1–3 o trieu els nivells corresponents.',
+ updateTitle: 'Actualitza la taula de continguts',
+ removeTitle: 'Elimina la taula de continguts',
+ updatePageNumbersOnly: 'Actualitza només els números de pàgina',
+ updateEntireTable: 'Actualitza tota la taula',
+ updateHint: 'Trieu com voleu actualitzar aquesta taula de continguts.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/de-DE.ts b/packages/docs-toc-ui/src/locale/de-DE.ts
new file mode 100644
index 0000000000..e543327ca1
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/de-DE.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: 'Inhaltsverzeichnis',
+ insertTitle: 'Inhaltsverzeichnis',
+ automaticTitle: 'Automatisches Verzeichnis',
+ customTitle: 'Benutzerdefiniertes Inhaltsverzeichnis…',
+ contentsTitle: 'Inhalt',
+ levels: 'Ebenen anzeigen',
+ showPageNumbers: 'Seitenzahlen anzeigen',
+ rightAlignPageNumbers: 'Seitenzahlen rechtsbündig',
+ tabLeader: 'Füllzeichen',
+ leaderNone: 'Keine',
+ leaderDots: 'Punkte',
+ leaderDashes: 'Striche',
+ leaderUnderline: 'Unterstrich',
+ format: 'Formate',
+ formatFromTemplate: 'Von Vorlage',
+ formatClassic: 'Klassisch',
+ formatModern: 'Modern',
+ formatSimple: 'Einfach',
+ preview: 'Druckvorschau',
+ previewHeading: 'Überschrift',
+ noHeadings: 'Keine Überschriften gefunden. Wenden Sie Überschrift 1–3 an oder wählen Sie passende Ebenen.',
+ updateTitle: 'Inhaltsverzeichnis aktualisieren',
+ removeTitle: 'Inhaltsverzeichnis entfernen',
+ updatePageNumbersOnly: 'Nur Seitenzahlen aktualisieren',
+ updateEntireTable: 'Gesamtes Verzeichnis aktualisieren',
+ updateHint: 'Wählen Sie die Aktualisierungsmethode.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/en-US.ts b/packages/docs-toc-ui/src/locale/en-US.ts
new file mode 100644
index 0000000000..52c231317e
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/en-US.ts
@@ -0,0 +1,50 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const locale = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: 'Table of contents',
+ insertTitle: 'Table of contents',
+ automaticTitle: 'Automatic table',
+ customTitle: 'Custom table of contents…',
+ contentsTitle: 'Contents',
+ levels: 'Show levels',
+ showPageNumbers: 'Show page numbers',
+ rightAlignPageNumbers: 'Right align page numbers',
+ tabLeader: 'Tab leader',
+ leaderNone: 'None',
+ leaderDots: 'Dots',
+ leaderDashes: 'Dashes',
+ leaderUnderline: 'Underline',
+ format: 'Formats',
+ formatFromTemplate: 'From template',
+ formatClassic: 'Classic',
+ formatModern: 'Modern',
+ formatSimple: 'Simple',
+ preview: 'Print preview',
+ previewHeading: 'Heading',
+ noHeadings: 'No headings were found. Apply Heading 1–3 styles first, or choose matching levels.',
+ updateTitle: 'Update table of contents',
+ removeTitle: 'Remove table of contents',
+ updatePageNumbersOnly: 'Update page numbers only',
+ updateEntireTable: 'Update entire table',
+ updateHint: 'Choose how Univer should refresh this table of contents.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/es-ES.ts b/packages/docs-toc-ui/src/locale/es-ES.ts
new file mode 100644
index 0000000000..7d69bb9f21
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/es-ES.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: 'Tabla de contenido',
+ insertTitle: 'Tabla de contenido',
+ automaticTitle: 'Tabla automática',
+ customTitle: 'Tabla de contenido personalizada…',
+ contentsTitle: 'Contenido',
+ levels: 'Mostrar niveles',
+ showPageNumbers: 'Mostrar números de página',
+ rightAlignPageNumbers: 'Alinear números de página a la derecha',
+ tabLeader: 'Carácter de relleno',
+ leaderNone: 'Ninguno',
+ leaderDots: 'Puntos',
+ leaderDashes: 'Guiones',
+ leaderUnderline: 'Subrayado',
+ format: 'Formatos',
+ formatFromTemplate: 'De la plantilla',
+ formatClassic: 'Clásico',
+ formatModern: 'Moderno',
+ formatSimple: 'Sencillo',
+ preview: 'Vista previa de impresión',
+ previewHeading: 'Título',
+ noHeadings: 'No se encontraron títulos. Aplique los estilos Título 1–3 o elija los niveles correspondientes.',
+ updateTitle: 'Actualizar tabla de contenido',
+ removeTitle: 'Quitar tabla de contenido',
+ updatePageNumbersOnly: 'Actualizar solo los números de página',
+ updateEntireTable: 'Actualizar toda la tabla',
+ updateHint: 'Elija cómo actualizar esta tabla de contenido.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/fa-IR.ts b/packages/docs-toc-ui/src/locale/fa-IR.ts
new file mode 100644
index 0000000000..411a7bd6d7
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/fa-IR.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: 'فهرست مطالب',
+ insertTitle: 'فهرست مطالب',
+ automaticTitle: 'فهرست خودکار',
+ customTitle: 'فهرست مطالب سفارشی…',
+ contentsTitle: 'مطالب',
+ levels: 'نمایش سطوح',
+ showPageNumbers: 'نمایش شماره صفحات',
+ rightAlignPageNumbers: 'تراز شماره صفحات به راست',
+ tabLeader: 'نویسهٔ راهنمای تب',
+ leaderNone: 'هیچ‌کدام',
+ leaderDots: 'نقطه',
+ leaderDashes: 'خط تیره',
+ leaderUnderline: 'زیرخط',
+ format: 'قالب‌ها',
+ formatFromTemplate: 'از الگو',
+ formatClassic: 'کلاسیک',
+ formatModern: 'مدرن',
+ formatSimple: 'ساده',
+ preview: 'پیش‌نمایش چاپ',
+ previewHeading: 'عنوان',
+ noHeadings: 'عنوانی یافت نشد. سبک‌های عنوان ۱ تا ۳ را اعمال کنید یا سطوح منطبق را انتخاب کنید.',
+ updateTitle: 'به‌روزرسانی فهرست مطالب',
+ removeTitle: 'حذف فهرست مطالب',
+ updatePageNumbersOnly: 'فقط به‌روزرسانی شماره صفحات',
+ updateEntireTable: 'به‌روزرسانی کل فهرست',
+ updateHint: 'روش به‌روزرسانی این فهرست مطالب را انتخاب کنید.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/fr-FR.ts b/packages/docs-toc-ui/src/locale/fr-FR.ts
new file mode 100644
index 0000000000..b3a4d31f9f
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/fr-FR.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: 'Table des matières',
+ insertTitle: 'Table des matières',
+ automaticTitle: 'Table automatique',
+ customTitle: 'Table des matières personnalisée…',
+ contentsTitle: 'Sommaire',
+ levels: 'Afficher les niveaux',
+ showPageNumbers: 'Afficher les numéros de page',
+ rightAlignPageNumbers: 'Aligner les numéros de page à droite',
+ tabLeader: 'Caractères de suite',
+ leaderNone: 'Aucun',
+ leaderDots: 'Points',
+ leaderDashes: 'Tirets',
+ leaderUnderline: 'Soulignement',
+ format: 'Formats',
+ formatFromTemplate: 'Depuis le modèle',
+ formatClassic: 'Classique',
+ formatModern: 'Moderne',
+ formatSimple: 'Simple',
+ preview: 'Aperçu avant impression',
+ previewHeading: 'Titre',
+ noHeadings: 'Aucun titre trouvé. Appliquez les styles Titre 1–3 ou choisissez les niveaux correspondants.',
+ updateTitle: 'Mettre à jour la table des matières',
+ removeTitle: 'Supprimer la table des matières',
+ updatePageNumbersOnly: 'Mettre à jour uniquement les numéros de page',
+ updateEntireTable: 'Mettre à jour toute la table',
+ updateHint: 'Choisissez comment mettre à jour cette table des matières.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/id-ID.ts b/packages/docs-toc-ui/src/locale/id-ID.ts
new file mode 100644
index 0000000000..b8bb141f40
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/id-ID.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: 'Daftar isi',
+ insertTitle: 'Daftar isi',
+ automaticTitle: 'Daftar otomatis',
+ customTitle: 'Daftar isi kustom…',
+ contentsTitle: 'Daftar isi',
+ levels: 'Tampilkan tingkat',
+ showPageNumbers: 'Tampilkan nomor halaman',
+ rightAlignPageNumbers: 'Ratakan nomor halaman ke kanan',
+ tabLeader: 'Pengisi tab',
+ leaderNone: 'Tidak ada',
+ leaderDots: 'Titik',
+ leaderDashes: 'Garis putus-putus',
+ leaderUnderline: 'Garis bawah',
+ format: 'Format',
+ formatFromTemplate: 'Dari templat',
+ formatClassic: 'Klasik',
+ formatModern: 'Modern',
+ formatSimple: 'Sederhana',
+ preview: 'Pratinjau cetak',
+ previewHeading: 'Judul',
+ noHeadings: 'Tidak ada judul yang ditemukan. Terapkan gaya Judul 1–3 atau pilih tingkat yang sesuai.',
+ updateTitle: 'Perbarui daftar isi',
+ removeTitle: 'Hapus daftar isi',
+ updatePageNumbersOnly: 'Perbarui nomor halaman saja',
+ updateEntireTable: 'Perbarui seluruh daftar',
+ updateHint: 'Pilih cara memperbarui daftar isi ini.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/it-IT.ts b/packages/docs-toc-ui/src/locale/it-IT.ts
new file mode 100644
index 0000000000..a424bd3e37
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/it-IT.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: 'Sommario',
+ insertTitle: 'Sommario',
+ automaticTitle: 'Sommario automatico',
+ customTitle: 'Sommario personalizzato…',
+ contentsTitle: 'Sommario',
+ levels: 'Mostra livelli',
+ showPageNumbers: 'Mostra numeri di pagina',
+ rightAlignPageNumbers: 'Allinea i numeri di pagina a destra',
+ tabLeader: 'Carattere di riempimento',
+ leaderNone: 'Nessuno',
+ leaderDots: 'Punti',
+ leaderDashes: 'Trattini',
+ leaderUnderline: 'Sottolineatura',
+ format: 'Formati',
+ formatFromTemplate: 'Da modello',
+ formatClassic: 'Classico',
+ formatModern: 'Moderno',
+ formatSimple: 'Semplice',
+ preview: 'Anteprima di stampa',
+ previewHeading: 'Titolo',
+ noHeadings: 'Nessun titolo trovato. Applica gli stili Titolo 1–3 o scegli i livelli corrispondenti.',
+ updateTitle: 'Aggiorna sommario',
+ removeTitle: 'Rimuovi sommario',
+ updatePageNumbersOnly: 'Aggiorna solo i numeri di pagina',
+ updateEntireTable: 'Aggiorna intero sommario',
+ updateHint: 'Scegli come aggiornare questo sommario.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/ja-JP.ts b/packages/docs-toc-ui/src/locale/ja-JP.ts
new file mode 100644
index 0000000000..b3343c4b2f
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/ja-JP.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: '目次',
+ insertTitle: '目次',
+ automaticTitle: '自動作成の目次',
+ customTitle: 'ユーザー設定の目次…',
+ contentsTitle: '目次',
+ levels: '表示するレベル',
+ showPageNumbers: 'ページ番号を表示する',
+ rightAlignPageNumbers: 'ページ番号を右揃えにする',
+ tabLeader: 'タブリーダー',
+ leaderNone: 'なし',
+ leaderDots: '点線',
+ leaderDashes: '破線',
+ leaderUnderline: '下線',
+ format: '書式',
+ formatFromTemplate: 'テンプレートから',
+ formatClassic: 'クラシック',
+ formatModern: 'モダン',
+ formatSimple: 'シンプル',
+ preview: '印刷プレビュー',
+ previewHeading: '見出し',
+ noHeadings: '見出しが見つかりません。見出し 1~3 のスタイルを適用するか、対応するレベルを選択してください。',
+ updateTitle: '目次の更新',
+ removeTitle: '目次の削除',
+ updatePageNumbersOnly: 'ページ番号だけを更新する',
+ updateEntireTable: '目次をすべて更新する',
+ updateHint: 'この目次の更新方法を選択してください。',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/ko-KR.ts b/packages/docs-toc-ui/src/locale/ko-KR.ts
new file mode 100644
index 0000000000..6146c98cf2
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/ko-KR.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: '목차',
+ insertTitle: '목차',
+ automaticTitle: '자동 목차',
+ customTitle: '사용자 지정 목차…',
+ contentsTitle: '목차',
+ levels: '표시할 수준',
+ showPageNumbers: '페이지 번호 표시',
+ rightAlignPageNumbers: '페이지 번호 오른쪽 맞춤',
+ tabLeader: '탭 채움선',
+ leaderNone: '없음',
+ leaderDots: '점선',
+ leaderDashes: '파선',
+ leaderUnderline: '밑줄',
+ format: '서식',
+ formatFromTemplate: '서식 파일에서',
+ formatClassic: '클래식',
+ formatModern: '모던',
+ formatSimple: '간단',
+ preview: '인쇄 미리 보기',
+ previewHeading: '제목',
+ noHeadings: '제목을 찾을 수 없습니다. 제목 1–3 스타일을 적용하거나 해당 수준을 선택하세요.',
+ updateTitle: '목차 업데이트',
+ removeTitle: '목차 제거',
+ updatePageNumbersOnly: '페이지 번호만 업데이트',
+ updateEntireTable: '목차 전체 업데이트',
+ updateHint: '이 목차를 업데이트할 방법을 선택하세요.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/pl-PL.ts b/packages/docs-toc-ui/src/locale/pl-PL.ts
new file mode 100644
index 0000000000..36c649fb52
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/pl-PL.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: 'Spis treści',
+ insertTitle: 'Spis treści',
+ automaticTitle: 'Automatyczny spis treści',
+ customTitle: 'Niestandardowy spis treści…',
+ contentsTitle: 'Spis treści',
+ levels: 'Pokaż poziomy',
+ showPageNumbers: 'Pokaż numery stron',
+ rightAlignPageNumbers: 'Wyrównaj numery stron do prawej',
+ tabLeader: 'Znak wiodący',
+ leaderNone: 'Brak',
+ leaderDots: 'Kropki',
+ leaderDashes: 'Kreski',
+ leaderUnderline: 'Podkreślenie',
+ format: 'Formaty',
+ formatFromTemplate: 'Z szablonu',
+ formatClassic: 'Klasyczny',
+ formatModern: 'Nowoczesny',
+ formatSimple: 'Prosty',
+ preview: 'Podgląd wydruku',
+ previewHeading: 'Nagłówek',
+ noHeadings: 'Nie znaleziono nagłówków. Zastosuj style Nagłówek 1–3 lub wybierz odpowiednie poziomy.',
+ updateTitle: 'Aktualizuj spis treści',
+ removeTitle: 'Usuń spis treści',
+ updatePageNumbersOnly: 'Aktualizuj tylko numery stron',
+ updateEntireTable: 'Aktualizuj cały spis',
+ updateHint: 'Wybierz sposób aktualizacji tego spisu treści.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/pt-BR.ts b/packages/docs-toc-ui/src/locale/pt-BR.ts
new file mode 100644
index 0000000000..26dc27d6b3
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/pt-BR.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: 'Sumário',
+ insertTitle: 'Sumário',
+ automaticTitle: 'Sumário automático',
+ customTitle: 'Sumário personalizado…',
+ contentsTitle: 'Sumário',
+ levels: 'Mostrar níveis',
+ showPageNumbers: 'Mostrar números de página',
+ rightAlignPageNumbers: 'Alinhar números de página à direita',
+ tabLeader: 'Preenchimento de tabulação',
+ leaderNone: 'Nenhum',
+ leaderDots: 'Pontos',
+ leaderDashes: 'Traços',
+ leaderUnderline: 'Sublinhado',
+ format: 'Formatos',
+ formatFromTemplate: 'Do modelo',
+ formatClassic: 'Clássico',
+ formatModern: 'Moderno',
+ formatSimple: 'Simples',
+ preview: 'Visualização de impressão',
+ previewHeading: 'Título',
+ noHeadings: 'Nenhum título encontrado. Aplique os estilos Título 1–3 ou escolha os níveis correspondentes.',
+ updateTitle: 'Atualizar sumário',
+ removeTitle: 'Remover sumário',
+ updatePageNumbersOnly: 'Atualizar apenas os números de página',
+ updateEntireTable: 'Atualizar o sumário inteiro',
+ updateHint: 'Escolha como atualizar este sumário.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/ru-RU.ts b/packages/docs-toc-ui/src/locale/ru-RU.ts
new file mode 100644
index 0000000000..d6c3f05581
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/ru-RU.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: 'Оглавление',
+ insertTitle: 'Оглавление',
+ automaticTitle: 'Автособираемое оглавление',
+ customTitle: 'Настраиваемое оглавление…',
+ contentsTitle: 'Содержание',
+ levels: 'Показать уровни',
+ showPageNumbers: 'Показать номера страниц',
+ rightAlignPageNumbers: 'Номера страниц по правому краю',
+ tabLeader: 'Заполнитель',
+ leaderNone: 'Нет',
+ leaderDots: 'Точки',
+ leaderDashes: 'Тире',
+ leaderUnderline: 'Подчёркивание',
+ format: 'Форматы',
+ formatFromTemplate: 'Из шаблона',
+ formatClassic: 'Классический',
+ formatModern: 'Современный',
+ formatSimple: 'Простой',
+ preview: 'Предварительный просмотр',
+ previewHeading: 'Заголовок',
+ noHeadings: 'Заголовки не найдены. Примените стили «Заголовок 1–3» или выберите соответствующие уровни.',
+ updateTitle: 'Обновить оглавление',
+ removeTitle: 'Удалить оглавление',
+ updatePageNumbersOnly: 'Обновить только номера страниц',
+ updateEntireTable: 'Обновить целиком',
+ updateHint: 'Выберите способ обновления оглавления.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/sk-SK.ts b/packages/docs-toc-ui/src/locale/sk-SK.ts
new file mode 100644
index 0000000000..70649633ba
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/sk-SK.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: 'Obsah',
+ insertTitle: 'Obsah',
+ automaticTitle: 'Automatický obsah',
+ customTitle: 'Vlastný obsah…',
+ contentsTitle: 'Obsah',
+ levels: 'Zobraziť úrovne',
+ showPageNumbers: 'Zobraziť čísla strán',
+ rightAlignPageNumbers: 'Zarovnať čísla strán doprava',
+ tabLeader: 'Vodiaci znak',
+ leaderNone: 'Žiadny',
+ leaderDots: 'Bodky',
+ leaderDashes: 'Pomlčky',
+ leaderUnderline: 'Podčiarknutie',
+ format: 'Formáty',
+ formatFromTemplate: 'Zo šablóny',
+ formatClassic: 'Klasický',
+ formatModern: 'Moderný',
+ formatSimple: 'Jednoduchý',
+ preview: 'Ukážka pred tlačou',
+ previewHeading: 'Nadpis',
+ noHeadings: 'Nenašli sa žiadne nadpisy. Použite štýly Nadpis 1–3 alebo vyberte zodpovedajúce úrovne.',
+ updateTitle: 'Aktualizovať obsah',
+ removeTitle: 'Odstrániť obsah',
+ updatePageNumbersOnly: 'Aktualizovať iba čísla strán',
+ updateEntireTable: 'Aktualizovať celý obsah',
+ updateHint: 'Vyberte spôsob aktualizácie tohto obsahu.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/types.ts b/packages/docs-toc-ui/src/locale/types.ts
new file mode 100644
index 0000000000..b83cb8e9ce
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/types.ts
@@ -0,0 +1,20 @@
+/**
+ * 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 { LocaleLeafKeys } from '@univerjs/core';
+import type enUS from './en-US';
+
+export type LocaleKey = LocaleLeafKeys<typeof enUS>;
diff --git a/packages/docs-toc-ui/src/locale/vi-VN.ts b/packages/docs-toc-ui/src/locale/vi-VN.ts
new file mode 100644
index 0000000000..198d761ac5
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/vi-VN.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: 'Mục lục',
+ insertTitle: 'Mục lục',
+ automaticTitle: 'Mục lục tự động',
+ customTitle: 'Mục lục tùy chỉnh…',
+ contentsTitle: 'Mục lục',
+ levels: 'Hiển thị cấp độ',
+ showPageNumbers: 'Hiển thị số trang',
+ rightAlignPageNumbers: 'Căn phải số trang',
+ tabLeader: 'Ký tự dẫn tab',
+ leaderNone: 'Không có',
+ leaderDots: 'Dấu chấm',
+ leaderDashes: 'Dấu gạch ngang',
+ leaderUnderline: 'Gạch dưới',
+ format: 'Định dạng',
+ formatFromTemplate: 'Từ mẫu',
+ formatClassic: 'Cổ điển',
+ formatModern: 'Hiện đại',
+ formatSimple: 'Đơn giản',
+ preview: 'Xem trước khi in',
+ previewHeading: 'Tiêu đề',
+ noHeadings: 'Không tìm thấy tiêu đề. Hãy áp dụng kiểu Tiêu đề 1–3 hoặc chọn cấp độ phù hợp.',
+ updateTitle: 'Cập nhật mục lục',
+ removeTitle: 'Xóa mục lục',
+ updatePageNumbersOnly: 'Chỉ cập nhật số trang',
+ updateEntireTable: 'Cập nhật toàn bộ mục lục',
+ updateHint: 'Chọn cách cập nhật mục lục này.',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/zh-CN.ts b/packages/docs-toc-ui/src/locale/zh-CN.ts
new file mode 100644
index 0000000000..d6a79d604c
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/zh-CN.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: '目录',
+ insertTitle: '插入目录',
+ automaticTitle: '自动目录',
+ customTitle: '自定义目录…',
+ contentsTitle: '目录',
+ levels: '显示级别',
+ showPageNumbers: '显示页码',
+ rightAlignPageNumbers: '页码右对齐',
+ tabLeader: '制表符前导符',
+ leaderNone: '无',
+ leaderDots: '点线',
+ leaderDashes: '短划线',
+ leaderUnderline: '下划线',
+ format: '格式',
+ formatFromTemplate: '来自模板',
+ formatClassic: '经典',
+ formatModern: '现代',
+ formatSimple: '简洁',
+ preview: '打印预览',
+ previewHeading: '标题',
+ noHeadings: '未找到标题。请先应用标题 1–3 样式,或选择匹配的标题级别。',
+ updateTitle: '更新目录',
+ removeTitle: '删除目录',
+ updatePageNumbersOnly: '只更新页码',
+ updateEntireTable: '更新整个目录',
+ updateHint: '请选择 Univer 更新此目录的方式。',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/zh-HK.ts b/packages/docs-toc-ui/src/locale/zh-HK.ts
new file mode 100644
index 0000000000..8d1edba789
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/zh-HK.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: '目錄',
+ insertTitle: '插入目錄',
+ automaticTitle: '自動目錄',
+ customTitle: '自訂目錄…',
+ contentsTitle: '目錄',
+ levels: '顯示級別',
+ showPageNumbers: '顯示頁碼',
+ rightAlignPageNumbers: '頁碼靠右對齊',
+ tabLeader: '定位點前置字元',
+ leaderNone: '無',
+ leaderDots: '點線',
+ leaderDashes: '短劃線',
+ leaderUnderline: '底線',
+ format: '格式',
+ formatFromTemplate: '來自範本',
+ formatClassic: '傳統',
+ formatModern: '現代',
+ formatSimple: '簡潔',
+ preview: '預覽列印',
+ previewHeading: '標題',
+ noHeadings: '找不到標題。請先套用標題 1–3 樣式,或選擇相符的標題級別。',
+ updateTitle: '更新目錄',
+ removeTitle: '刪除目錄',
+ updatePageNumbersOnly: '只更新頁碼',
+ updateEntireTable: '更新整個目錄',
+ updateHint: '請選擇 Univer 更新此目錄的方式。',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/locale/zh-TW.ts b/packages/docs-toc-ui/src/locale/zh-TW.ts
new file mode 100644
index 0000000000..640264ec0e
--- /dev/null
+++ b/packages/docs-toc-ui/src/locale/zh-TW.ts
@@ -0,0 +1,52 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ title: '目錄',
+ insertTitle: '目錄',
+ automaticTitle: '自動目錄',
+ customTitle: '自訂目錄…',
+ contentsTitle: '目錄',
+ levels: '顯示階層',
+ showPageNumbers: '顯示頁碼',
+ rightAlignPageNumbers: '頁碼靠右對齊',
+ tabLeader: '定位點前置字元',
+ leaderNone: '無',
+ leaderDots: '點線',
+ leaderDashes: '虛線',
+ leaderUnderline: '底線',
+ format: '格式',
+ formatFromTemplate: '來自範本',
+ formatClassic: '傳統',
+ formatModern: '現代',
+ formatSimple: '簡單',
+ preview: '預覽列印',
+ previewHeading: '標題',
+ noHeadings: '找不到標題。請先套用標題 1–3 樣式,或選擇相符的階層。',
+ updateTitle: '更新目錄',
+ removeTitle: '移除目錄',
+ updatePageNumbersOnly: '只更新頁碼',
+ updateEntireTable: '更新整個目錄',
+ updateHint: '選擇此目錄的更新方式。',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/docs-toc-ui/src/menu/__tests__/menu.spec.ts b/packages/docs-toc-ui/src/menu/__tests__/menu.spec.ts
new file mode 100644
index 0000000000..a33f064914
--- /dev/null
+++ b/packages/docs-toc-ui/src/menu/__tests__/menu.spec.ts
@@ -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 { DocumentDataModel, IDocumentData } from '@univerjs/core';
+import { BooleanNumber, CustomRangeType, ICommandService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService, UniverDocsPlugin } from '@univerjs/docs';
+import { MenuItemType } from '@univerjs/ui';
+import { firstValueFrom } from 'rxjs';
+import { afterEach, describe, expect, it } from 'vitest';
+import { OpenTableOfContentsDialogOperation } from '../../commands/table-of-contents-dialog.operation';
+import { DeleteTableOfContentsMenuFactory, InsertTableOfContentsMenuFactory, UpdateTableOfContentsMenuFactory } from '../menu';
+
+describe('table of contents menu factories', () => {
+ let univer: Univer;
+ afterEach(() => univer?.dispose());
+
+ it.each([undefined, BooleanNumber.FALSE, BooleanNumber.TRUE])('switches insert and manage actions with field lock %s', async (locked) => {
+ univer = new Univer();
+ univer.registerPlugin(UniverDocsPlugin);
+ const accessor = univer.__getInjector();
+ univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: 'doc-1',
+ body: {
+ dataStream: '\u001FContents\u001E\rBody\r\n',
+ paragraphs: [{ startIndex: 10, paragraphId: 'toc-p' }, { startIndex: 15, paragraphId: 'body-p' }],
+ sectionBreaks: [{ startIndex: 16, sectionId: 's-1' }],
+ customRanges: [{
+ rangeId: 'toc',
+ rangeType: CustomRangeType.FIELD,
+ startIndex: 0,
+ endIndex: 9,
+ properties: { fieldType: 'TOC', locked },
+ }],
+ },
+ documentStyle: {},
+ });
+ accessor.get(IUniverInstanceService).focusUnit('doc-1');
+ const selection = accessor.get(DocSelectionManagerService);
+ selection.__TEST_ONLY_add([{ startOffset: 5, endOffset: 5, collapsed: true, isActive: true }]);
+ const select = (startOffset: number, endOffset = startOffset) => selection.__replaceTextRangesWithNoRefresh({
+ ...selection.getSelectionInfo()!,
+ textRanges: [{ startOffset, endOffset, collapsed: startOffset === endOffset, isActive: true }],
+ }, { unitId: 'doc-1', subUnitId: 'doc-1' });
+ const manageHidden = [
+ UpdateTableOfContentsMenuFactory(accessor).hidden$,
+ DeleteTableOfContentsMenuFactory(accessor).hidden$,
+ ];
+ const insertMenu = InsertTableOfContentsMenuFactory(accessor);
+ expect(insertMenu.icon).toBe('UnorderIcon');
+ expect(insertMenu.type).toBe(MenuItemType.SUBITEMS);
+ expect(Array.isArray(insertMenu.selections) ? insertMenu.selections.map((selection) => selection.value) : []).toEqual(['automatic', 'custom']);
+ expect(UpdateTableOfContentsMenuFactory(accessor).icon).toBe('UnorderIcon');
+ if (manageHidden.some((state) => !state)) {
+ throw new Error('TOC menus must expose hidden state.');
+ }
+ expect(await Promise.all(manageHidden.map((state) => firstValueFrom(state!)))).toEqual([false, false]);
+ expect(await firstValueFrom(UpdateTableOfContentsMenuFactory(accessor).disabled$!)).toBe(locked === BooleanNumber.TRUE);
+ expect(await firstValueFrom(DeleteTableOfContentsMenuFactory(accessor).disabled$!)).toBe(false);
+ if (locked === BooleanNumber.TRUE) {
+ const commands = accessor.get(ICommandService);
+ commands.registerCommand(OpenTableOfContentsDialogOperation);
+ expect(await commands.executeCommand(OpenTableOfContentsDialogOperation.id)).toBe(false);
+ }
+ expect(await firstValueFrom(insertMenu.hidden$!)).toBe(false);
+ expect(await firstValueFrom(insertMenu.disabled$!)).toBe(true);
+
+ select(11);
+ expect(await Promise.all(manageHidden.map((state) => firstValueFrom(state!)))).toEqual([true, true]);
+ expect(await firstValueFrom(insertMenu.hidden$!)).toBe(false);
+ expect(await firstValueFrom(insertMenu.disabled$!)).toBe(false);
+
+ select(11, 12);
+ expect(await firstValueFrom(insertMenu.hidden$!)).toBe(false);
+ expect(await firstValueFrom(insertMenu.disabled$!)).toBe(true);
+ });
+});
diff --git a/packages/docs-toc-ui/src/menu/menu.ts b/packages/docs-toc-ui/src/menu/menu.ts
new file mode 100644
index 0000000000..d160167d14
--- /dev/null
+++ b/packages/docs-toc-ui/src/menu/menu.ts
@@ -0,0 +1,133 @@
+/**
+ * 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, IAccessor, ICustomRange } from '@univerjs/core';
+import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';
+import type { LocaleKey } from '../locale/types';
+import { BooleanNumber, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService, DocStateChangeManagerService } from '@univerjs/docs';
+import { DeleteTableOfContentsCommand, findTableOfContentsAtOffset } from '@univerjs/docs-toc';
+import { disableMenuWithoutDocumentUnitPermission } from '@univerjs/docs-ui';
+import { UnitAction } from '@univerjs/protocol';
+import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
+import { combineLatest, map, Observable } from 'rxjs';
+import {
+ InsertTableOfContentsOperation,
+ OpenTableOfContentsDialogOperation,
+} from '../commands/table-of-contents-dialog.operation';
+
+export const INSERT_TABLE_OF_CONTENTS_MENU_ID = 'doc.menu.insert-table-of-contents';
+
+function getActiveTableOfContentsObservable(accessor: IAccessor): Observable<ICustomRange | undefined> {
+ const selectionManager = accessor.get(DocSelectionManagerService);
+ const instanceService = accessor.get(IUniverInstanceService);
+ return new Observable((subscriber) => {
+ const emit = () => {
+ const doc = instanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const selection = selectionManager.getActiveTextRange();
+ subscriber.next(selection?.segmentId ? undefined : findTableOfContentsAtOffset(doc?.getBody(), selection?.startOffset));
+ };
+ emit();
+ const selectionSubscription = selectionManager.textSelection$.subscribe(emit);
+ const unitSubscription = instanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_DOC).subscribe(emit);
+ const documentSubscription = accessor.get(DocStateChangeManagerService).docStateChange$.subscribe(emit);
+ return () => {
+ selectionSubscription.unsubscribe();
+ unitSubscription.unsubscribe();
+ documentSubscription.unsubscribe();
+ };
+ });
+}
+
+function getInsertTableOfContentsDisabledObservable(accessor: IAccessor): Observable<boolean> {
+ const selectionManager = accessor.get(DocSelectionManagerService);
+ const instanceService = accessor.get(IUniverInstanceService);
+ return new Observable((subscriber) => {
+ const emit = () => {
+ const doc = instanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const selection = selectionManager.getActiveTextRange();
+ subscriber.next(!selection || selection.startOffset !== selection.endOffset || Boolean(selection.segmentId) ||
+ Boolean(findTableOfContentsAtOffset(doc?.getBody(), selection.startOffset)));
+ };
+ emit();
+ const selectionSubscription = selectionManager.textSelection$.subscribe(emit);
+ const unitSubscription = instanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_DOC).subscribe(emit);
+ return () => {
+ selectionSubscription.unsubscribe();
+ unitSubscription.unsubscribe();
+ };
+ });
+}
+
+export function InsertTableOfContentsMenuFactory(accessor: IAccessor): IMenuSelectorItem<LocaleKey> {
+ const permissionDisabled$ = disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit);
+ return {
+ id: INSERT_TABLE_OF_CONTENTS_MENU_ID,
+ type: MenuItemType.SUBITEMS,
+ icon: 'UnorderIcon',
+ title: 'docs-toc-ui.tableOfContents.insertTitle',
+ selectionsCommandId: InsertTableOfContentsOperation.id,
+ selections: [{
+ value: 'automatic',
+ label: 'docs-toc-ui.tableOfContents.automaticTitle',
+ icon: 'UnorderIcon',
+ params: { mode: 'automatic' },
+ }, {
+ value: 'custom',
+ label: 'docs-toc-ui.tableOfContents.customTitle',
+ icon: 'DocSettingIcon',
+ params: { mode: 'custom' },
+ }],
+ disabled$: combineLatest([
+ permissionDisabled$,
+ getInsertTableOfContentsDisabledObservable(accessor),
+ ]).pipe(map(([permissionDisabled, unavailable]) => permissionDisabled || unavailable)),
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
+ };
+}
+
+export function UpdateTableOfContentsMenuFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
+ return {
+ id: OpenTableOfContentsDialogOperation.id,
+ commandId: OpenTableOfContentsDialogOperation.id,
+ type: MenuItemType.BUTTON,
+ icon: 'UnorderIcon',
+ title: 'docs-toc-ui.tableOfContents.updateTitle',
+ disabled$: combineLatest([
+ disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit),
+ getActiveTableOfContentsObservable(accessor),
+ ]).pipe(map(([permissionDisabled, toc]) => permissionDisabled || !toc || toc.properties?.locked === BooleanNumber.TRUE)),
+ hidden$: combineLatest([
+ getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
+ getActiveTableOfContentsObservable(accessor),
+ ]).pipe(map(([hidden, toc]) => hidden || !toc)),
+ };
+}
+
+export function DeleteTableOfContentsMenuFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
+ return {
+ id: DeleteTableOfContentsCommand.id,
+ commandId: DeleteTableOfContentsCommand.id,
+ type: MenuItemType.BUTTON,
+ icon: 'DeleteIcon',
+ title: 'docs-toc-ui.tableOfContents.removeTitle',
+ disabled$: disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit),
+ hidden$: combineLatest([
+ getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
+ getActiveTableOfContentsObservable(accessor),
+ ]).pipe(map(([hidden, toc]) => hidden || !toc)),
+ };
+}
diff --git a/packages/docs-toc-ui/src/menu/schema.ts b/packages/docs-toc-ui/src/menu/schema.ts
new file mode 100644
index 0000000000..fee2f7c997
--- /dev/null
+++ b/packages/docs-toc-ui/src/menu/schema.ts
@@ -0,0 +1,69 @@
+/**
+ * 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 { MenuSchemaType } from '@univerjs/ui';
+import { DeleteTableOfContentsCommand } from '@univerjs/docs-toc';
+import { ContextMenuGroup, ContextMenuPosition, MenuManagerPosition, RibbonInsertGroup } from '@univerjs/ui';
+import { OpenTableOfContentsDialogOperation } from '../commands/table-of-contents-dialog.operation';
+import { DeleteTableOfContentsMenuFactory, INSERT_TABLE_OF_CONTENTS_MENU_ID, InsertTableOfContentsMenuFactory, UpdateTableOfContentsMenuFactory } from './menu';
+
+export const DOC_TABLE_OF_CONTENTS_RIBBON_TAB = 'ribbon.table-of-contents';
+const DOC_TABLE_OF_CONTENTS_RIBBON_GROUP = 'ribbon.table-of-contents.manage';
+
+export const tableOfContentsRibbonMenuSchema: MenuSchemaType = {
+ [MenuManagerPosition.RIBBON]: {
+ [DOC_TABLE_OF_CONTENTS_RIBBON_TAB]: {
+ order: 100,
+ title: 'docs-toc-ui.tableOfContents.title',
+ contextual: true,
+ [DOC_TABLE_OF_CONTENTS_RIBBON_GROUP]: {
+ order: 0,
+ [OpenTableOfContentsDialogOperation.id]: {
+ order: 0,
+ gridLayout: { row: 1, column: 1, rowSpan: 2, showLabel: true },
+ menuItemFactory: UpdateTableOfContentsMenuFactory,
+ },
+ [DeleteTableOfContentsCommand.id]: {
+ order: 1,
+ gridLayout: { row: 1, column: 2, rowSpan: 2, showLabel: true },
+ menuItemFactory: DeleteTableOfContentsMenuFactory,
+ },
+ },
+ },
+ },
+};
+
+export const DocsTocUIMenuSchema: MenuSchemaType = {
+ [RibbonInsertGroup.CELL]: {
+ [INSERT_TABLE_OF_CONTENTS_MENU_ID]: {
+ order: 7,
+ gridLayout: { row: 1, column: 1, showLabel: true },
+ menuItemFactory: InsertTableOfContentsMenuFactory,
+ },
+ },
+ [ContextMenuPosition.MAIN_AREA]: {
+ [ContextMenuGroup.LAYOUT]: {
+ [OpenTableOfContentsDialogOperation.id]: {
+ order: -1,
+ menuItemFactory: UpdateTableOfContentsMenuFactory,
+ },
+ [DeleteTableOfContentsCommand.id]: {
+ order: -0.5,
+ menuItemFactory: DeleteTableOfContentsMenuFactory,
+ },
+ },
+ },
+};
diff --git a/packages/docs-toc-ui/src/plugin.ts b/packages/docs-toc-ui/src/plugin.ts
new file mode 100644
index 0000000000..0114f86a1b
--- /dev/null
+++ b/packages/docs-toc-ui/src/plugin.ts
@@ -0,0 +1,72 @@
+/**
+ * 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 { Dependency } from '@univerjs/core';
+import type { IUniverDocsTocUIConfig } from './config/config';
+import { DependentOn, IConfigService, Inject, Injector, merge, Plugin, UniverInstanceType } from '@univerjs/core';
+import { UniverDocsPlugin } from '@univerjs/docs';
+import { UniverDocsTocPlugin } from '@univerjs/docs-toc';
+import { UniverDocsUIPlugin } from '@univerjs/docs-ui';
+import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import pkg from '../package.json';
+import { defaultPluginConfig, DOCS_TOC_UI_PLUGIN_CONFIG_KEY } from './config/config';
+import { ComponentsController } from './controllers/components.controller';
+import { TableOfContentsHighlightRenderController } from './controllers/table-of-contents-highlight.render-controller';
+import { TableOfContentsRibbonController } from './controllers/table-of-contents-ribbon.controller';
+import { DocsTocUIController } from './controllers/ui.controller';
+
+@DependentOn(UniverDocsPlugin, UniverRenderEnginePlugin, UniverDocsTocPlugin, UniverDocsUIPlugin)
+export class UniverDocsTocUIPlugin extends Plugin {
+ static override pluginName = 'DOCS_TOC_UI_PLUGIN';
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+ static override type = UniverInstanceType.UNIVER_DOC;
+
+ constructor(
+ private readonly _config: IUniverDocsTocUIConfig = defaultPluginConfig,
+ @Inject(Injector) protected override _injector: Injector,
+ @IConfigService private readonly _configService: IConfigService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ ) {
+ super();
+ const { menu, ...rest } = merge({}, defaultPluginConfig, this._config);
+ if (menu) {
+ this._configService.setConfig('menu', menu, { merge: true });
+ }
+ this._configService.setConfig(DOCS_TOC_UI_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ ([
+ [ComponentsController],
+ [DocsTocUIController],
+ [TableOfContentsRibbonController],
+ ] as Dependency[]).forEach((dependency) => this._injector.add(dependency));
+ this._injector.get(ComponentsController);
+ this._injector.get(DocsTocUIController);
+ }
+
+ override onReady(): void {
+ this._injector.get(TableOfContentsRibbonController);
+ }
+
+ override onRendered(): void {
+ this.disposeWithMe(this._renderManagerService.registerRenderModule(
+ UniverInstanceType.UNIVER_DOC,
+ [TableOfContentsHighlightRenderController]
+ ));
+ }
+}
diff --git a/packages/docs-toc-ui/src/views/InsertTableOfContentsDialog.tsx b/packages/docs-toc-ui/src/views/InsertTableOfContentsDialog.tsx
new file mode 100644
index 0000000000..c76655f59b
--- /dev/null
+++ b/packages/docs-toc-ui/src/views/InsertTableOfContentsDialog.tsx
@@ -0,0 +1,168 @@
+/**
+ * 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 { TableOfContentsFormat, TableOfContentsTabLeader } from '@univerjs/docs-toc';
+import type { LocaleKey } from '../locale/types';
+import { LocaleService } from '@univerjs/core';
+import { useDependency } from '@univerjs/ui';
+import { useState } from 'react';
+
+export const INSERT_TABLE_OF_CONTENTS_DIALOG_COMPONENT = 'doc.insert-table-of-contents-dialog';
+
+export interface IInsertTableOfContentsDialogValue {
+ levels: number;
+ showPageNumbers: boolean;
+ rightAlignPageNumbers: boolean;
+ tabLeader: TableOfContentsTabLeader;
+ format: TableOfContentsFormat;
+}
+
+export interface IInsertTableOfContentsDialogProps {
+ options: IInsertTableOfContentsDialogValue;
+ onChange: (value: IInsertTableOfContentsDialogValue) => void;
+}
+
+const FORMAT_OPTIONS: Array<[TableOfContentsFormat, LocaleKey]> = [
+ ['fromTemplate', 'docs-toc-ui.tableOfContents.formatFromTemplate'],
+ ['classic', 'docs-toc-ui.tableOfContents.formatClassic'],
+ ['modern', 'docs-toc-ui.tableOfContents.formatModern'],
+ ['simple', 'docs-toc-ui.tableOfContents.formatSimple'],
+];
+
+const LEADER_OPTIONS: Array<[TableOfContentsTabLeader, LocaleKey]> = [
+ ['none', 'docs-toc-ui.tableOfContents.leaderNone'],
+ ['dots', 'docs-toc-ui.tableOfContents.leaderDots'],
+ ['dashes', 'docs-toc-ui.tableOfContents.leaderDashes'],
+ ['underline', 'docs-toc-ui.tableOfContents.leaderUnderline'],
+];
+
+export function InsertTableOfContentsDialog(props: IInsertTableOfContentsDialogProps) {
+ const localeService = useDependency(LocaleService);
+ const [value, setValue] = useState(props.options);
+ const update = (patch: Partial<IInsertTableOfContentsDialogValue>) => {
+ const next = { ...value, ...patch };
+ setValue(next);
+ props.onChange(next);
+ };
+ const leader = value.tabLeader === 'dots' ? '··········' : value.tabLeader === 'dashes' ? '----------' : value.tabLeader === 'underline' ? '__________' : '';
+
+ return (
+ <div className="univer-grid univer-gap-4 univer-py-2" data-testid="table-of-contents-insert-dialog">
+ <div className="univer-grid univer-grid-cols-2 univer-gap-3">
+ <label className="univer-grid univer-gap-1 univer-text-sm">
+ <span>{localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.levels')}</span>
+ <select
+ className="univer-h-8 univer-rounded-md univer-border univer-bg-transparent univer-px-2"
+ value={value.levels}
+ onChange={(event) => update({ levels: Number(event.target.value) })}
+ >
+ {Array.from({ length: 9 }, (_, index) => index + 1).map((level) => (
+ <option key={level} value={level}>{level}</option>
+ ))}
+ </select>
+ </label>
+ <label className="univer-grid univer-gap-1 univer-text-sm">
+ <span>{localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.format')}</span>
+ <select
+ className="univer-h-8 univer-rounded-md univer-border univer-bg-transparent univer-px-2"
+ value={value.format}
+ onChange={(event) => update({ format: event.target.value as TableOfContentsFormat })}
+ >
+ {FORMAT_OPTIONS.map(([format, label]) => (
+ <option key={format} value={format}>{localeService.t<LocaleKey>(label)}</option>
+ ))}
+ </select>
+ </label>
+ </div>
+ <div className="univer-grid univer-gap-2 univer-text-sm">
+ <label className="univer-flex univer-items-center univer-gap-2">
+ <input
+ type="checkbox"
+ checked={value.showPageNumbers}
+ onChange={(event) => update({
+ showPageNumbers: event.target.checked,
+ rightAlignPageNumbers: event.target.checked && value.rightAlignPageNumbers,
+ })}
+ />
+ <span>{localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.showPageNumbers')}</span>
+ </label>
+ <label className="univer-flex univer-items-center univer-gap-2">
+ <input
+ type="checkbox"
+ checked={value.rightAlignPageNumbers}
+ disabled={!value.showPageNumbers}
+ onChange={(event) => update({ rightAlignPageNumbers: event.target.checked })}
+ />
+ <span>{localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.rightAlignPageNumbers')}</span>
+ </label>
+ <label className="univer-flex univer-items-center univer-justify-between univer-gap-3">
+ <span>{localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.tabLeader')}</span>
+ <select
+ className="
+ univer-h-8 univer-min-w-40 univer-rounded-md univer-border univer-bg-transparent univer-px-2
+ "
+ value={value.tabLeader}
+ disabled={!value.showPageNumbers || !value.rightAlignPageNumbers}
+ onChange={(event) => update({ tabLeader: event.target.value as TableOfContentsTabLeader })}
+ >
+ {LEADER_OPTIONS.map(([tabLeader, label]) => (
+ <option key={tabLeader} value={tabLeader}>{localeService.t<LocaleKey>(label)}</option>
+ ))}
+ </select>
+ </label>
+ </div>
+ <section
+ className="
+ univer-rounded-lg univer-border univer-bg-gray-50 univer-p-4
+ dark:univer-bg-gray-900
+ "
+ >
+ <div className="univer-mb-3 univer-text-xs univer-font-medium univer-text-gray-500">
+ {localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.preview')}
+ </div>
+ {Array.from({ length: Math.min(value.levels, 3) }, (_, index) => index).map((level) => (
+ <div
+ key={level}
+ className={`
+ univer-flex univer-items-baseline univer-text-sm
+ ${value.format === 'modern'
+ ? 'univer-mb-2'
+ : 'univer-mb-1'}
+ `}
+ style={{ marginInlineStart: `${level * (value.format === 'simple' ? 12 : value.format === 'classic' ? 14 : value.format === 'modern' ? 20 : 18)}px` }}
+ >
+ <span>
+ {localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.previewHeading')}
+ {' '}
+ {level + 1}
+ </span>
+ {value.showPageNumbers && value.rightAlignPageNumbers && (
+ <span
+ className="
+ univer-mx-2 univer-flex-1 univer-overflow-hidden univer-whitespace-nowrap
+ univer-text-gray-400
+ "
+ >
+ {leader}
+ </span>
+ )}
+ {value.showPageNumbers && <span className={value.rightAlignPageNumbers ? '' : 'univer-ml-2'}>{level + 1}</span>}
+ </div>
+ ))}
+ </section>
+ </div>
+ );
+}
diff --git a/packages/docs-toc-ui/src/views/TableOfContentsDialog.tsx b/packages/docs-toc-ui/src/views/TableOfContentsDialog.tsx
new file mode 100644
index 0000000000..6c4cfb6f8a
--- /dev/null
+++ b/packages/docs-toc-ui/src/views/TableOfContentsDialog.tsx
@@ -0,0 +1,66 @@
+/**
+ * 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 { LocaleKey } from '../locale/types';
+import { LocaleService } from '@univerjs/core';
+import { useDependency } from '@univerjs/ui';
+import { useState } from 'react';
+
+export const TABLE_OF_CONTENTS_DIALOG_COMPONENT = 'doc.table-of-contents-dialog';
+
+export interface ITableOfContentsDialogProps {
+ mode: 'pageNumbersOnly' | 'entireTable';
+ onModeChange: (mode: ITableOfContentsDialogProps['mode']) => void;
+}
+
+export function TableOfContentsDialog(props: ITableOfContentsDialogProps) {
+ const localeService = useDependency(LocaleService);
+ const [mode, setMode] = useState(props.mode);
+ const options = [
+ ['pageNumbersOnly', 'docs-toc-ui.tableOfContents.updatePageNumbersOnly'],
+ ['entireTable', 'docs-toc-ui.tableOfContents.updateEntireTable'],
+ ] as const;
+
+ return (
+ <div className="univer-grid univer-gap-4 univer-py-2" data-testid="table-of-contents-update-dialog">
+ <p className="univer-m-0 univer-text-sm">
+ {localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.updateHint')}
+ </p>
+ <fieldset className="univer-grid univer-gap-3 univer-border-0 univer-p-0">
+ {options.map(([value, label]) => (
+ <label
+ key={value}
+ className="univer-flex univer-gap-3 univer-rounded-lg univer-border univer-p-3"
+ >
+ <input
+ type="radio"
+ name="toc-update-mode"
+ value={value}
+ checked={mode === value}
+ onChange={() => {
+ setMode(value);
+ props.onModeChange(value);
+ }}
+ />
+ <span className="univer-text-sm">
+ {localeService.t<LocaleKey>(label)}
+ </span>
+ </label>
+ ))}
+ </fieldset>
+ </div>
+ );
+}
diff --git a/packages/docs-toc-ui/src/views/__tests__/TableOfContentsDialog.spec.tsx b/packages/docs-toc-ui/src/views/__tests__/TableOfContentsDialog.spec.tsx
new file mode 100644
index 0000000000..30abca4037
--- /dev/null
+++ b/packages/docs-toc-ui/src/views/__tests__/TableOfContentsDialog.spec.tsx
@@ -0,0 +1,121 @@
+/**
+ * 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 { Root } from 'react-dom/client';
+import { Injector, LocaleService, LocaleType } from '@univerjs/core';
+import { RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { InsertTableOfContentsDialog } from '../InsertTableOfContentsDialog';
+import { TableOfContentsDialog } from '../TableOfContentsDialog';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe('TableOfContentsDialog', () => {
+ let root: Root | undefined;
+ let container: HTMLDivElement | undefined;
+
+ afterEach(async () => {
+ if (root) await act(async () => root?.unmount());
+ container?.remove();
+ });
+
+ it('defaults to page-only update and allows selecting a full update', async () => {
+ const injector = new Injector();
+ injector.add([LocaleService, { useClass: LocaleService }]);
+ injector.get(LocaleService).load({
+ [LocaleType.EN_US]: {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ updatePageNumbersOnly: 'Update page numbers only',
+ updateEntireTable: 'Update entire table',
+ updateHint: 'Choose an update mode.',
+ },
+ },
+ },
+ });
+ const onModeChange = vi.fn();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () => root?.render(
+ <RediContext.Provider value={{ injector }}>
+ <TableOfContentsDialog mode="pageNumbersOnly" onModeChange={onModeChange} />
+ </RediContext.Provider>
+ ));
+
+ const radios = [...container.querySelectorAll<HTMLInputElement>('input[type="radio"]')];
+ expect(radios.map((radio) => radio.checked)).toEqual([true, false]);
+ await act(async () => radios[1].click());
+ expect(radios.map((radio) => radio.checked)).toEqual([false, true]);
+ expect(onModeChange).toHaveBeenCalledWith('entireTable');
+
+ injector.dispose();
+ });
+
+ it('edits custom TOC options and updates the preview', async () => {
+ const injector = new Injector();
+ injector.add([LocaleService, { useClass: LocaleService }]);
+ injector.get(LocaleService).load({
+ [LocaleType.EN_US]: {
+ 'docs-toc-ui': {
+ tableOfContents: {
+ levels: 'Show levels',
+ format: 'Formats',
+ formatFromTemplate: 'From template',
+ formatClassic: 'Classic',
+ formatModern: 'Modern',
+ formatSimple: 'Simple',
+ showPageNumbers: 'Show page numbers',
+ rightAlignPageNumbers: 'Right align page numbers',
+ tabLeader: 'Tab leader',
+ leaderNone: 'None',
+ leaderDots: 'Dots',
+ leaderDashes: 'Dashes',
+ leaderUnderline: 'Underline',
+ preview: 'Print preview',
+ previewHeading: 'Heading',
+ },
+ },
+ },
+ });
+ const onChange = vi.fn();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () => root?.render(
+ <RediContext.Provider value={{ injector }}>
+ <InsertTableOfContentsDialog
+ options={{ levels: 3, showPageNumbers: true, rightAlignPageNumbers: true, tabLeader: 'dots', format: 'fromTemplate' }}
+ onChange={onChange}
+ />
+ </RediContext.Provider>
+ ));
+
+ const checkboxes = [...container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')];
+ const selects = [...container.querySelectorAll<HTMLSelectElement>('select')];
+ expect(container.textContent).toContain('··········');
+ await act(async () => {
+ checkboxes[0].click();
+ });
+ expect(checkboxes.map((checkbox) => checkbox.checked)).toEqual([false, false]);
+ expect(selects[2].disabled).toBe(true);
+ expect(onChange).toHaveBeenLastCalledWith(expect.objectContaining({ showPageNumbers: false, rightAlignPageNumbers: false }));
+
+ injector.dispose();
+ });
+});
diff --git a/packages/docs-toc-ui/tailwind.config.ts b/packages/docs-toc-ui/tailwind.config.ts
new file mode 100644
index 0000000000..75967f186f
--- /dev/null
+++ b/packages/docs-toc-ui/tailwind.config.ts
@@ -0,0 +1,27 @@
+/**
+ * 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 { Config } from 'tailwindcss';
+import preset from '@univerjs-infra/shared/tailwind';
+
+const config: Config = {
+ presets: [preset],
+ content: [
+ './src/**/*.{js,ts,jsx,tsx}',
+ ],
+};
+
+export default config;
diff --git a/packages/docs-toc-ui/tsconfig.json b/packages/docs-toc-ui/tsconfig.json
new file mode 100644
index 0000000000..d4f9172636
--- /dev/null
+++ b/packages/docs-toc-ui/tsconfig.json
@@ -0,0 +1,8 @@
+{
+ "extends": "@univerjs-infra/shared/tsconfigs/base",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "lib/types"
+ },
+ "include": ["src"]
+}
diff --git a/packages/docs-toc-ui/tsconfig.node.json b/packages/docs-toc-ui/tsconfig.node.json
new file mode 100644
index 0000000000..2abfa07367
--- /dev/null
+++ b/packages/docs-toc-ui/tsconfig.node.json
@@ -0,0 +1,18 @@
+{
+ "extends": "@univerjs-infra/shared/tsconfigs/node",
+ "compilerOptions": {
+ "rootDir": "src",
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmit": false,
+ "outDir": "lib/types"
+ },
+ "include": [
+ "src"
+ ],
+ "exclude": [
+ "src/**/__tests__/**",
+ "src/**/*.spec.ts",
+ "src/**/*.test.ts"
+ ]
+}
diff --git a/packages/docs-toc-ui/vitest.config.ts b/packages/docs-toc-ui/vitest.config.ts
new file mode 100644
index 0000000000..af97c6d7a2
--- /dev/null
+++ b/packages/docs-toc-ui/vitest.config.ts
@@ -0,0 +1,3 @@
+import createConfig from '@univerjs-infra/shared/vitest';
+
+export default createConfig();
diff --git a/packages/docs-toc/README.md b/packages/docs-toc/README.md
new file mode 100644
index 0000000000..799866d284
--- /dev/null
+++ b/packages/docs-toc/README.md
@@ -0,0 +1,28 @@
+# @univerjs/docs-toc
+
+`@univerjs/docs-toc` provides table-of-contents insertion, update, deletion, and FIELD-range lookup for Univer Docs.
+
+## Installation
+
+```sh
+pnpm add @univerjs/docs-toc
+```
+
+Keep all `@univerjs/*` packages on the same version.
+
+## Usage
+
+```ts
+import { UniverDocsTocPlugin } from '@univerjs/docs-toc';
+
+univer.registerPlugin(UniverDocsTocPlugin);
+```
+
+Use this package with `@univerjs/docs-toc-ui` when users need Ribbon, context-menu, dialog, and active-range feedback.
+
+The updater currently evaluates outline-based TOC instructions (`\\o`). Other Word TOC switches are retained in FIELD metadata but are not all evaluated.
+
+## Resources
+
+- [Documentation](https://docs.univer.ai)
+- [GitHub repository](https://github.com/dream-num/univer)
diff --git a/packages/docs-toc/package.json b/packages/docs-toc/package.json
new file mode 100644
index 0000000000..8ffac29e89
--- /dev/null
+++ b/packages/docs-toc/package.json
@@ -0,0 +1,80 @@
+{
+ "name": "@univerjs/docs-toc",
+ "version": "1.0.0-rc.0",
+ "private": false,
+ "description": "Table of contents commands for Univer Docs.",
+ "author": "DreamNum Co., Ltd. <[email protected]>",
+ "license": "Apache-2.0",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/univer"
+ },
+ "homepage": "https://univer.ai",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/dream-num/univer"
+ },
+ "bugs": {
+ "url": "https://github.com/dream-num/univer/issues"
+ },
+ "keywords": [
+ "univer",
+ "docs",
+ "table-of-contents",
+ "toc",
+ "plugin"
+ ],
+ "exports": {
+ ".": "./src/index.ts",
+ "./*": "./src/*"
+ },
+ "main": "./src/index.ts",
+ "types": "./lib/types/index.d.ts",
+ "publishConfig": {
+ "access": "public",
+ "main": "./lib/es/index.js",
+ "module": "./lib/es/index.js",
+ "exports": {
+ ".": {
+ "import": "./lib/es/index.js",
+ "require": "./lib/cjs/index.js",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./*": {
+ "import": "./lib/es/*",
+ "require": "./lib/cjs/*",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./lib/*": "./lib/*"
+ }
+ },
+ "directories": {
+ "lib": "lib"
+ },
+ "files": [
+ "lib"
+ ],
+ "scripts": {
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "coverage": "vitest run --coverage",
+ "typecheck": "tsc --noEmit",
+ "build:bundle": "univer-cli build",
+ "build:types": "tsc -p tsconfig.node.json",
+ "build": "pnpm run build:bundle && pnpm run build:types"
+ },
+ "peerDependencies": {
+ "rxjs": ">=7.0.0"
+ },
+ "dependencies": {
+ "@univerjs/core": "workspace:*",
+ "@univerjs/docs": "workspace:*",
+ "@univerjs/engine-render": "workspace:*"
+ },
+ "devDependencies": {
+ "@univerjs-infra/shared": "workspace:*",
+ "rxjs": "^7.8.2",
+ "typescript": "^6.0.3",
+ "vitest": "^5.0.0"
+ }
+}
diff --git a/packages/docs-toc/src/commands/__tests__/table-of-contents.command.spec.ts b/packages/docs-toc/src/commands/__tests__/table-of-contents.command.spec.ts
new file mode 100644
index 0000000000..b9cdec4da3
--- /dev/null
+++ b/packages/docs-toc/src/commands/__tests__/table-of-contents.command.spec.ts
@@ -0,0 +1,463 @@
+/**
+ * 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, ICustomRange, IDocumentBody, IDocumentData } from '@univerjs/core';
+import {
+ BooleanNumber,
+ CustomRangeType,
+ getBodySlice,
+ ICommandService,
+ NamedStyleType,
+ SliceBodyType,
+ TabStopAlignment,
+ TabStopLeader,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { UniverDocsPlugin } from '@univerjs/docs';
+import { describe, expect, it } from 'vitest';
+import {
+ buildPageNumberOnlyTableOfContentsBody,
+ buildTableOfContentsBody,
+ buildTableOfContentsInstruction,
+ countTableOfContentsHeadings,
+ findTableOfContentsAtOffset,
+ UpdateTableOfContentsCommand,
+} from '../table-of-contents.command';
+
+function createBody(): { body: IDocumentBody; toc: ICustomRange } {
+ const dataStream = '\u001FOld\t\u001F1\u001E\r\u001EHeading One\rSubheading\r\n';
+ const tocEnd = dataStream.indexOf('\u001E', dataStream.indexOf('\u001E') + 1);
+ const firstHeadingStart = tocEnd + 1;
+ const firstHeadingEnd = dataStream.indexOf('\r', firstHeadingStart);
+ const secondHeadingStart = firstHeadingEnd + 1;
+ const secondHeadingEnd = dataStream.indexOf('\r', secondHeadingStart);
+ const toc: ICustomRange = {
+ startIndex: 0,
+ endIndex: tocEnd,
+ rangeId: 'toc',
+ rangeType: CustomRangeType.FIELD,
+ wholeEntity: false,
+ properties: { fieldType: 'TOC', instruction: 'TOC \\o "1-2" \\h \\z \\u' },
+ };
+ return {
+ toc,
+ body: {
+ dataStream,
+ paragraphs: [{
+ startIndex: dataStream.indexOf('\r'),
+ paragraphId: 'toc-1',
+ styleId: 'TOC1',
+ }, {
+ startIndex: firstHeadingEnd,
+ paragraphId: 'heading-1-paragraph',
+ paragraphStyle: {
+ headingId: 'heading-1',
+ namedStyleType: NamedStyleType.HEADING_1,
+ outlineLevel: 0,
+ },
+ }, {
+ startIndex: secondHeadingEnd,
+ paragraphId: 'heading-2-paragraph',
+ paragraphStyle: {
+ headingId: 'heading-2',
+ namedStyleType: NamedStyleType.HEADING_2,
+ outlineLevel: 1,
+ },
+ }],
+ customRanges: [toc, {
+ startIndex: firstHeadingStart,
+ endIndex: firstHeadingEnd - 1,
+ rangeId: 'bookmark-1',
+ rangeType: CustomRangeType.BOOKMARK,
+ properties: { bookmarkId: '_Toc1' },
+ }],
+ },
+ };
+}
+
+describe('table of contents body builder', () => {
+ it('rejects a locked update before acquiring the layout renderer or modifying the document', async () => {
+ const univer = new Univer();
+ try {
+ univer.registerPlugin(UniverDocsPlugin);
+ const { body, toc } = createBody();
+ toc.properties!.locked = BooleanNumber.TRUE;
+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: 'locked-toc-doc',
+ body,
+ documentStyle: {},
+ });
+ const commands = univer.__getInjector().get(ICommandService);
+ commands.registerCommand(UpdateTableOfContentsCommand);
+ const before = JSON.stringify(doc.getBody());
+
+ expect(await commands.executeCommand(UpdateTableOfContentsCommand.id, {
+ unitId: doc.getUnitId(),
+ rangeId: toc.rangeId,
+ mode: 'entireTable',
+ })).toBe(false);
+ expect(JSON.stringify(doc.getBody())).toBe(before);
+ } finally {
+ univer.dispose();
+ }
+ });
+
+ it('does not recalculate a locked TOC in either update mode', () => {
+ const { body, toc } = createBody();
+ toc.properties!.locked = BooleanNumber.TRUE;
+ const before = JSON.stringify(body);
+ const resolvePageNumber = () => {
+ throw new Error('Locked fields must not resolve page numbers');
+ };
+
+ expect(buildTableOfContentsBody(body, toc, resolvePageNumber)).toBeNull();
+ expect(buildPageNumberOnlyTableOfContentsBody(body, toc, resolvePageNumber)).toBeNull();
+ expect(JSON.stringify(body)).toBe(before);
+ });
+
+ it('encodes page-number options in Word TOC switches for OOXML round trips', () => {
+ expect(buildTableOfContentsInstruction()).toBe('TOC \\o "1-3" \\h \\z \\u');
+ expect(buildTableOfContentsInstruction({ levels: 5, showPageNumbers: false })).toBe('TOC \\o "1-5" \\h \\z \\u \\n');
+ expect(buildTableOfContentsInstruction({ levels: 2, rightAlignPageNumbers: false })).toBe('TOC \\o "1-2" \\h \\z \\u \\p " "');
+ });
+
+ it('rebuilds an outline TOC with nested PAGEREF fields and internal links', () => {
+ const { body, toc } = createBody();
+ let id = 0;
+ const result = buildTableOfContentsBody(
+ body,
+ toc,
+ (offset) => offset < body.dataStream.indexOf('Subheading') ? 6 : 12,
+ () => `generated-${++id}`
+ )!;
+
+ expect(result.dataStream).toBe('\u001FHeading One\t\u001F6\u001E\rSubheading\t\u001F12\u001E\r\u001E');
+ expect(result.paragraphs).toEqual([
+ expect.objectContaining({ startIndex: 16, styleId: 'TOC1' }),
+ expect.objectContaining({ startIndex: 32, styleId: 'TOC1' }),
+ ]);
+ expect(result.customRanges).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ rangeId: 'toc',
+ rangeType: CustomRangeType.FIELD,
+ startIndex: 0,
+ endIndex: 33,
+ properties: expect.objectContaining({
+ fieldType: 'TOC',
+ cachedResult: 'Heading One\t6\rSubheading\t12\r',
+ }),
+ }),
+ expect.objectContaining({
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: { bookmarkId: '_Toc1', textStyleMode: 'text' },
+ }),
+ expect.objectContaining({
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: { headingId: 'heading-2', textStyleMode: 'text' },
+ }),
+ expect.objectContaining({
+ rangeType: CustomRangeType.FIELD,
+ properties: expect.objectContaining({ fieldType: 'PAGEREF', cachedResult: '12' }),
+ }),
+ ]));
+ });
+
+ it('keeps distinct, stable paragraph identities when entries share a formatting template', () => {
+ const { body, toc } = createBody();
+ body.paragraphs![0].paragraphId = 'para_toc-entry';
+ toc.properties!.title = 'Contents';
+ let id = 0;
+ const generateId = () => `identity-${++id}`;
+ const first = buildTableOfContentsBody(body, toc, () => 1, generateId)!;
+ const firstIds = first.paragraphs!.map((paragraph) => paragraph.paragraphId);
+ expect(new Set(firstIds).size).toBe(3);
+ expect(firstIds[1]).toBe('para_toc-entry');
+ expect(firstIds.every((paragraphId) => paragraphId.startsWith('para_'))).toBe(true);
+
+ const delta = first.dataStream.length - toc.endIndex - 1;
+ const updatedBody: IDocumentBody = {
+ dataStream: first.dataStream + body.dataStream.slice(toc.endIndex + 1),
+ paragraphs: [
+ ...first.paragraphs!,
+ ...body.paragraphs!.filter((paragraph) => paragraph.startIndex > toc.endIndex)
+ .map((paragraph) => ({ ...paragraph, startIndex: paragraph.startIndex + delta })),
+ ],
+ customRanges: first.customRanges,
+ };
+ const updatedToc = updatedBody.customRanges!.find((range) => range.rangeId === toc.rangeId)!;
+ const second = buildTableOfContentsBody(updatedBody, updatedToc, () => 2, generateId)!;
+ expect(second.paragraphs!.map((paragraph) => paragraph.paragraphId)).toEqual(firstIds);
+ expect(second.paragraphs!.slice(1).every((paragraph) => paragraph.styleId === 'TOC1')).toBe(true);
+ });
+
+ it('leaves caption tables of contents unchanged until SEQ fields are supported', () => {
+ const { body, toc } = createBody();
+ toc.properties = { fieldType: 'TOC', instruction: 'TOC \\h \\z \\c "图"' };
+
+ expect(buildTableOfContentsBody(body, toc, () => 1)).toBeNull();
+ });
+
+ it('creates default TOC indentation and a right-aligned dot leader when inserting', () => {
+ const body: IDocumentBody = {
+ dataStream: 'Heading One\rSubheading\r\n',
+ paragraphs: [{
+ startIndex: 11,
+ paragraphId: 'heading-1-paragraph',
+ paragraphStyle: { headingId: 'heading-1', outlineLevel: 0 },
+ }, {
+ startIndex: 22,
+ paragraphId: 'heading-2-paragraph',
+ paragraphStyle: { headingId: 'heading-2', outlineLevel: 1 },
+ }],
+ };
+ const toc: ICustomRange = {
+ startIndex: 0,
+ endIndex: 0,
+ rangeId: 'new-toc',
+ rangeType: CustomRangeType.FIELD,
+ properties: { fieldType: 'TOC', instruction: 'TOC \\o "1-2" \\h' },
+ };
+
+ const result = buildTableOfContentsBody(body, toc, () => 1, () => 'generated', { tabStopOffset: 414 })!;
+
+ expect(result.paragraphs?.map((paragraph) => paragraph.paragraphStyle)).toEqual([{
+ indentStart: { v: 0 },
+ tabStops: [{ offset: 414, alignment: TabStopAlignment.END, leader: TabStopLeader.DOT }],
+ }, {
+ indentStart: { v: 18 },
+ tabStops: [{ offset: 414, alignment: TabStopAlignment.END, leader: TabStopLeader.DOT }],
+ }]);
+ });
+
+ it('does not create an empty field when no matching headings exist', () => {
+ const body: IDocumentBody = {
+ dataStream: 'Body text\r\n',
+ paragraphs: [{ startIndex: 9, paragraphId: 'body' }],
+ };
+ const toc: ICustomRange = {
+ startIndex: 0,
+ endIndex: 0,
+ rangeId: 'new-toc',
+ rangeType: CustomRangeType.FIELD,
+ properties: { fieldType: 'TOC', instruction: 'TOC \\o "1-3" \\h' },
+ };
+
+ expect(countTableOfContentsHeadings(body, 3)).toBe(0);
+ expect(buildTableOfContentsBody(body, toc, () => 1)).toBeNull();
+ });
+
+ it('supports a localized title and a TOC without page numbers', () => {
+ const body: IDocumentBody = {
+ dataStream: 'Heading One\r\n',
+ paragraphs: [{
+ startIndex: 11,
+ paragraphId: 'heading',
+ paragraphStyle: { headingId: 'heading-1', outlineLevel: 0 },
+ }],
+ };
+ const toc: ICustomRange = {
+ startIndex: 0,
+ endIndex: 0,
+ rangeId: 'new-toc',
+ rangeType: CustomRangeType.FIELD,
+ properties: {
+ fieldType: 'TOC',
+ instruction: 'TOC \\o "1-3" \\h \\n',
+ title: 'Contents',
+ showPageNumbers: false,
+ },
+ };
+
+ const result = buildTableOfContentsBody(body, toc, () => undefined, () => 'generated')!;
+
+ expect(result.dataStream).toBe('\u001FContents\rHeading One\r\u001E');
+ expect(result.paragraphs?.[0]).toEqual(expect.objectContaining({ styleId: 'TOCHeading' }));
+ expect(result.customRanges?.some((range) => range.properties?.fieldType === 'PAGEREF')).toBe(false);
+ expect(result.customRanges?.find((range) => range.rangeId === 'new-toc')?.properties?.cachedResult).toBe('Contents\rHeading One\r');
+ });
+
+ it('preserves an imported TOCHeading title when OOXML has no Univer title property', () => {
+ const dataStream = '\u001FContents\rOld\t\u001F1\u001E\r\u001EHeading One\r\n';
+ const outerEnd = dataStream.indexOf('\u001E', dataStream.indexOf('\u001E') + 1);
+ const headingStart = outerEnd + 1;
+ const headingEnd = dataStream.indexOf('\r', headingStart);
+ const toc: ICustomRange = {
+ startIndex: 0,
+ endIndex: outerEnd,
+ rangeId: 'toc',
+ rangeType: CustomRangeType.FIELD,
+ properties: { fieldType: 'TOC', instruction: 'TOC \\o "1-3" \\h' },
+ };
+ const body: IDocumentBody = {
+ dataStream,
+ paragraphs: [{
+ startIndex: 9,
+ paragraphId: 'toc-title',
+ styleId: 'TOCHeading',
+ }, {
+ startIndex: outerEnd - 1,
+ paragraphId: 'toc-entry',
+ styleId: 'TOC1',
+ }, {
+ startIndex: headingEnd,
+ paragraphId: 'heading',
+ paragraphStyle: { headingId: 'heading-1', outlineLevel: 0 },
+ }],
+ customRanges: [toc],
+ };
+
+ const result = buildTableOfContentsBody(body, toc, () => 2, () => 'generated')!;
+
+ expect(result.dataStream).toBe('\u001FContents\rHeading One\t\u001F2\u001E\r\u001E');
+ expect(result.paragraphs?.[0].styleId).toBe('TOCHeading');
+ });
+
+ it.each([
+ ['none', TabStopLeader.NONE, 'simple', 12],
+ ['dashes', TabStopLeader.HYPHEN, 'classic', 14],
+ ['underline', TabStopLeader.UNDERSCORE, 'modern', 20],
+ ] as const)('applies the %s leader and %s format', (leader, expectedLeader, format, expectedIndent) => {
+ const body: IDocumentBody = {
+ dataStream: 'Subheading\r\n',
+ paragraphs: [{
+ startIndex: 10,
+ paragraphId: 'heading',
+ paragraphStyle: { headingId: 'heading-2', outlineLevel: 1 },
+ }],
+ };
+ const toc: ICustomRange = {
+ startIndex: 0,
+ endIndex: 0,
+ rangeId: 'new-toc',
+ rangeType: CustomRangeType.FIELD,
+ properties: {
+ fieldType: 'TOC',
+ instruction: 'TOC \\o "1-3" \\h',
+ tabLeader: leader,
+ format,
+ },
+ };
+
+ const result = buildTableOfContentsBody(body, toc, () => 2, () => 'generated', { tabStopOffset: 414 })!;
+
+ expect(result.paragraphs?.[0].paragraphStyle?.indentStart?.v).toBe(expectedIndent);
+ expect(result.paragraphs?.[0].paragraphStyle?.tabStops?.[0].leader).toBe(expectedLeader);
+ });
+
+ it('places page numbers next to entry text when right alignment is disabled', () => {
+ const body: IDocumentBody = {
+ dataStream: 'Heading One\r\n',
+ paragraphs: [{
+ startIndex: 11,
+ paragraphId: 'heading',
+ paragraphStyle: { headingId: 'heading-1', outlineLevel: 0 },
+ }],
+ };
+ const toc: ICustomRange = {
+ startIndex: 0,
+ endIndex: 0,
+ rangeId: 'new-toc',
+ rangeType: CustomRangeType.FIELD,
+ properties: {
+ fieldType: 'TOC',
+ instruction: 'TOC \\o "1-3" \\h \\p " "',
+ rightAlignPageNumbers: false,
+ },
+ };
+
+ const result = buildTableOfContentsBody(body, toc, () => 4, () => 'generated', { tabStopOffset: 414 })!;
+
+ expect(result.dataStream).toBe('\u001FHeading One \u001F4\u001E\r\u001E');
+ expect(result.paragraphs?.[0].paragraphStyle?.tabStops).toBeUndefined();
+ });
+
+ it.each([undefined, BooleanNumber.FALSE, BooleanNumber.TRUE].flatMap((locked) =>
+ [6, 9, 42].map((pageNumber) => ({ locked, pageNumber }))
+ ))('preserves manual text and detects unchanged page fields (lock $locked, page $pageNumber)', ({ locked, pageNumber }) => {
+ const dataStream = '\u001FManual title\t\u001F6\u001E\r\u001EHeading One\r\n';
+ const tocEnd = dataStream.indexOf('\u001E', dataStream.indexOf('\u001E') + 1);
+ const pageStart = dataStream.indexOf('\u001F', 1);
+ const pageEnd = dataStream.indexOf('\u001E');
+ const headingStart = tocEnd + 1;
+ const headingEnd = dataStream.indexOf('\r', headingStart);
+ const toc: ICustomRange = {
+ startIndex: 0,
+ endIndex: tocEnd,
+ rangeId: 'toc',
+ rangeType: CustomRangeType.FIELD,
+ properties: { fieldType: 'TOC', instruction: 'TOC \\o "1-3" \\h', cachedResult: 'Manual title\t6\r' },
+ };
+ const body: IDocumentBody = {
+ dataStream,
+ paragraphs: [
+ { startIndex: tocEnd - 1, paragraphId: 'toc-paragraph' },
+ { startIndex: headingEnd, paragraphId: 'heading-paragraph', paragraphStyle: { headingId: 'heading-1', outlineLevel: 0 } },
+ ],
+ customRanges: [toc, {
+ startIndex: pageStart,
+ endIndex: pageEnd,
+ rangeId: 'page',
+ rangeType: CustomRangeType.FIELD,
+ properties: { fieldType: 'PAGEREF', instruction: 'PAGEREF _Toc1 \\h', cachedResult: '6', locked },
+ }, {
+ startIndex: 1,
+ endIndex: pageEnd,
+ rangeId: 'link',
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: { bookmarkId: '_Toc1' },
+ }, {
+ startIndex: headingStart,
+ endIndex: headingEnd - 1,
+ rangeId: 'bookmark',
+ rangeType: CustomRangeType.BOOKMARK,
+ properties: { bookmarkId: '_Toc1' },
+ }],
+ };
+
+ const before = JSON.stringify(body);
+ const result = buildPageNumberOnlyTableOfContentsBody(body, toc, () => locked === BooleanNumber.TRUE ? undefined : pageNumber)!;
+ const expectedPage = locked === BooleanNumber.TRUE ? '6' : String(pageNumber);
+ const expectedEnd = pageEnd + expectedPage.length - 1;
+
+ expect(result.dataStream).toBe(`\u001FManual title\t\u001F${expectedPage}\u001E\r\u001E`);
+ expect(result.customRanges?.find((range) => range.rangeId === 'page')).toEqual(expect.objectContaining({
+ endIndex: expectedEnd,
+ properties: expect.objectContaining({ cachedResult: expectedPage, locked }),
+ }));
+ expect(result.customRanges?.find((range) => range.rangeId === 'link')?.endIndex).toBe(expectedEnd);
+ expect(findTableOfContentsAtOffset(body, 5)?.rangeId).toBe('toc');
+ const current = getBodySlice(body, toc.startIndex, toc.endIndex + 1, true, SliceBodyType.cut);
+ if (expectedPage === '6') {
+ expect(result).toEqual(current);
+ toc.properties!.cachedResult = 'Stale cache';
+ expect(buildPageNumberOnlyTableOfContentsBody(body, toc, () => pageNumber))
+ .not
+ .toEqual(getBodySlice(body, toc.startIndex, toc.endIndex + 1, true, SliceBodyType.cut));
+ toc.properties!.cachedResult = 'Manual title\t6\r';
+ if (locked !== BooleanNumber.TRUE) {
+ const pageField = body.customRanges!.find((range) => range.rangeId === 'page')!;
+ pageField.properties!.cachedResult = 'Stale page cache';
+ expect(buildPageNumberOnlyTableOfContentsBody(body, toc, () => pageNumber)).toEqual(result);
+ expect(pageField.properties!.cachedResult).toBe('Stale page cache');
+ pageField.properties!.cachedResult = '6';
+ }
+ } else {
+ expect(result).not.toEqual(current);
+ }
+ expect(JSON.stringify(body)).toBe(before);
+ });
+});
diff --git a/packages/docs-toc/src/commands/table-of-contents.command.ts b/packages/docs-toc/src/commands/table-of-contents.command.ts
new file mode 100644
index 0000000000..dd5ae6686e
--- /dev/null
+++ b/packages/docs-toc/src/commands/table-of-contents.command.ts
@@ -0,0 +1,702 @@
+/**
+ * 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, IAccessor, ICommand, ICustomRange, IDocumentBody, IParagraph, ITextRange, ITextRun } from '@univerjs/core';
+import type { DocumentSkeleton } from '@univerjs/engine-render';
+import {
+ BooleanNumber,
+ BuildTextUtils,
+ cloneParagraphWithId,
+ CommandType,
+ createParagraphId,
+ CustomRangeType,
+ generateRandomId,
+ getBodySlice,
+ getPlainText,
+ getRichTextEditPath,
+ ICommandService,
+ IUndoRedoService,
+ IUniverInstanceService,
+ JSONX,
+ NamedStyleType,
+ SliceBodyType,
+ TabStopAlignment,
+ TabStopLeader,
+ TextX,
+ Tools,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DocSelectionManagerService, DocSkeletonManagerService, DocStateChangeManagerService, RichTextEditingMutation } from '@univerjs/docs';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { filter, firstValueFrom, take, timeout } from 'rxjs';
+
+const FIELD_START = '\u001F';
+const FIELD_END = '\u001E';
+
+async function replaceBodyRange(
+ accessor: IAccessor,
+ doc: DocumentDataModel,
+ unitId: string,
+ selection: ITextRange,
+ body: IDocumentBody,
+ historyAction: string,
+ historyGroupId = generateRandomId()
+): Promise<boolean> {
+ const textX = new TextX();
+ textX.push(...BuildTextUtils.selection.delete([selection], doc.getBody()!, 0, body));
+ const caretOffset = selection.startOffset + body.dataStream.length;
+ accessor.get(DocStateChangeManagerService).flushPendingChanges(unitId);
+ const group = accessor.get(IUndoRedoService).beginUndoRedoGroup(unitId, historyGroupId, 'append');
+ try {
+ return Boolean(accessor.get(ICommandService).syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId,
+ historyAction,
+ actions: JSONX.getInstance().editOp(textX.serialize(), getRichTextEditPath(doc)),
+ textRanges: [{
+ startOffset: caretOffset,
+ endOffset: caretOffset,
+ collapsed: true,
+ }],
+ debounce: false,
+ trigger: historyAction,
+ }));
+ } finally {
+ group.dispose();
+ }
+}
+
+export interface IUpdateTableOfContentsCommandParams {
+ unitId?: string;
+ rangeId?: string;
+ mode?: 'pageNumbersOnly' | 'entireTable';
+}
+
+export interface IInsertTableOfContentsCommandParams {
+ unitId?: string;
+ levels?: number;
+ showPageNumbers?: boolean;
+ rightAlignPageNumbers?: boolean;
+ tabLeader?: TableOfContentsTabLeader;
+ format?: TableOfContentsFormat;
+ title?: string;
+}
+
+export type TableOfContentsTabLeader = 'none' | 'dots' | 'dashes' | 'underline';
+export type TableOfContentsFormat = 'fromTemplate' | 'classic' | 'modern' | 'simple';
+
+export interface IDeleteTableOfContentsCommandParams {
+ unitId?: string;
+ rangeId?: string;
+}
+
+interface ITableOfContentsHeading {
+ bookmarkId?: string;
+ headingId: string;
+ level: number;
+ paragraph: IParagraph;
+ startOffset: number;
+ text: string;
+}
+
+export const UpdateTableOfContentsCommand: ICommand<IUpdateTableOfContentsCommandParams> = {
+ id: 'doc.command.update-table-of-contents',
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => updateTableOfContents(accessor, params),
+};
+
+async function updateTableOfContents(
+ accessor: IAccessor,
+ params?: IUpdateTableOfContentsCommandParams,
+ historyGroupId = generateRandomId()
+): Promise<boolean> {
+ const instanceService = accessor.get(IUniverInstanceService);
+ const doc = params?.unitId
+ ? instanceService.getUnit<DocumentDataModel>(params.unitId, UniverInstanceType.UNIVER_DOC)
+ : instanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const body = doc?.getBody();
+ const selection = accessor.get(DocSelectionManagerService).getActiveTextRange();
+ const toc = params?.rangeId
+ ? body?.customRanges?.find((range) => range.rangeId === params.rangeId && isTableOfContentsRange(range))
+ : findTableOfContentsAtOffset(body, selection?.startOffset);
+ const unitId = doc?.getUnitId();
+ if (!doc || !body || !toc || toc.properties?.locked === BooleanNumber.TRUE || !unitId) {
+ return false;
+ }
+ const render = accessor.get(IRenderManagerService).getRenderUnitById(unitId);
+ const renderInjector = render?.getInjector?.();
+ if (!render || !renderInjector?.has(DocSkeletonManagerService)) {
+ return false;
+ }
+
+ const skeleton = render.with(DocSkeletonManagerService).getSkeleton();
+ if (!await waitForCompleteLayout(skeleton)) {
+ return false;
+ }
+ let updated = false;
+ for (let iteration = 0; iteration < 3; iteration += 1) {
+ const currentBody = doc.getBody();
+ const currentToc = currentBody?.customRanges?.find((range) => range.rangeId === toc.rangeId && isTableOfContentsRange(range));
+ if (!currentBody || !currentToc || currentToc.properties?.locked === BooleanNumber.TRUE) {
+ return false;
+ }
+ const resolvePageNumber = (offset: number) => {
+ const pageIndex = skeleton.findBodyPageIndexByCharIndex(offset);
+ return skeleton.getSkeletonData()?.pages[pageIndex]?.pageNumber;
+ };
+ const replacement = params?.mode === 'pageNumbersOnly'
+ ? buildPageNumberOnlyTableOfContentsBody(currentBody, currentToc, resolvePageNumber)
+ : buildTableOfContentsBody(currentBody, currentToc, resolvePageNumber);
+ if (!replacement) {
+ return false;
+ }
+ // An accurate page-only update must not create history or restart pagination.
+ // Compare metadata too: identical visible text can still have stale field caches.
+ if (params?.mode === 'pageNumbersOnly' && Tools.diffValue(
+ getBodySlice(currentBody, currentToc.startIndex, currentToc.endIndex + 1, true, SliceBodyType.cut),
+ replacement
+ )) {
+ return true;
+ }
+ if (updated && currentBody.dataStream.slice(currentToc.startIndex, currentToc.endIndex + 1) === replacement.dataStream) {
+ return true;
+ }
+ const generation = skeleton.getLayoutProgress()?.generation ?? -1;
+ updated = await replaceBodyRange(accessor, doc, unitId, {
+ startOffset: currentToc.startIndex,
+ endOffset: currentToc.endIndex + 1,
+ collapsed: false,
+ }, replacement, UpdateTableOfContentsCommand.id, historyGroupId);
+ if (!updated || iteration === 2) {
+ return updated;
+ }
+ if (!await waitForNextCompleteLayout(skeleton, generation)) {
+ return false;
+ }
+ }
+ return updated;
+}
+
+export const DeleteTableOfContentsCommand: ICommand<IDeleteTableOfContentsCommandParams> = {
+ id: 'doc.command.delete-table-of-contents',
+ type: CommandType.COMMAND,
+ async handler(accessor, params) {
+ const instanceService = accessor.get(IUniverInstanceService);
+ const doc = params?.unitId
+ ? instanceService.getUnit<DocumentDataModel>(params.unitId, UniverInstanceType.UNIVER_DOC)
+ : instanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const body = doc?.getBody();
+ const selection = accessor.get(DocSelectionManagerService).getActiveTextRange();
+ const toc = params?.rangeId
+ ? body?.customRanges?.find((range) => range.rangeId === params.rangeId && isTableOfContentsRange(range))
+ : findTableOfContentsAtOffset(body, selection?.startOffset);
+ const unitId = doc?.getUnitId();
+ if (!toc || !unitId) {
+ return false;
+ }
+
+ return replaceBodyRange(accessor, doc!, unitId, {
+ startOffset: toc.startIndex,
+ endOffset: toc.endIndex + 1,
+ collapsed: false,
+ }, { dataStream: '' }, DeleteTableOfContentsCommand.id);
+ },
+};
+
+export const InsertTableOfContentsCommand: ICommand<IInsertTableOfContentsCommandParams> = {
+ id: 'doc.command.insert-table-of-contents',
+ type: CommandType.COMMAND,
+ async handler(accessor, params) {
+ const instanceService = accessor.get(IUniverInstanceService);
+ const doc = params?.unitId
+ ? instanceService.getUnit<DocumentDataModel>(params.unitId, UniverInstanceType.UNIVER_DOC)
+ : instanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const selection = accessor.get(DocSelectionManagerService).getActiveTextRange();
+ const body = doc?.getBody();
+ const unitId = doc?.getUnitId();
+ const render = unitId ? accessor.get(IRenderManagerService).getRenderUnitById(unitId) : undefined;
+ const renderInjector = render?.getInjector?.();
+ if (!doc || !body || !unitId || !selection || selection.segmentId || selection.startOffset !== selection.endOffset ||
+ findTableOfContentsAtOffset(body, selection.startOffset) || !render || !renderInjector?.has(DocSkeletonManagerService)) {
+ return false;
+ }
+
+ const skeleton = render.with(DocSkeletonManagerService).getSkeleton();
+ if (!await waitForCompleteLayout(skeleton)) {
+ return false;
+ }
+ const levels = Math.min(9, Math.max(1, Math.trunc(params?.levels ?? 3)));
+ const showPageNumbers = params?.showPageNumbers ?? true;
+ const rightAlignPageNumbers = showPageNumbers && (params?.rightAlignPageNumbers ?? true);
+ const tabLeader = params?.tabLeader ?? 'dots';
+ const format = params?.format ?? 'fromTemplate';
+ const rangeId = generateRandomId();
+ const toc: ICustomRange = {
+ rangeId,
+ rangeType: CustomRangeType.FIELD,
+ startIndex: selection.startOffset,
+ endIndex: selection.startOffset,
+ wholeEntity: false,
+ properties: {
+ fieldType: 'TOC',
+ instruction: buildTableOfContentsInstruction({ levels, showPageNumbers, rightAlignPageNumbers }),
+ sourceKind: 'complex',
+ showPageNumbers,
+ rightAlignPageNumbers,
+ tabLeader,
+ format,
+ title: params?.title,
+ },
+ };
+ const { pageSize, marginLeft = 0, marginRight = 0 } = doc.getDocumentStyle();
+ const replacement = buildTableOfContentsBody(body, toc, (offset) => {
+ const pageIndex = skeleton.findBodyPageIndexByCharIndex(offset);
+ return skeleton.getSkeletonData()?.pages[pageIndex]?.pageNumber;
+ }, generateRandomId, { tabStopOffset: Math.max(72, (pageSize?.width ?? 594.3) - marginLeft - marginRight) });
+ if (!replacement) {
+ return false;
+ }
+
+ const historyGroupId = generateRandomId();
+ const inserted = await replaceBodyRange(accessor, doc, unitId, {
+ startOffset: selection.startOffset,
+ endOffset: selection.startOffset,
+ collapsed: true,
+ }, replacement, InsertTableOfContentsCommand.id, historyGroupId);
+ if (!inserted) {
+ return false;
+ }
+ await updateTableOfContents(accessor, {
+ unitId,
+ rangeId,
+ mode: 'entireTable',
+ }, historyGroupId);
+ return true;
+ },
+};
+
+export function buildTableOfContentsInstruction(
+ options: Pick<IInsertTableOfContentsCommandParams, 'levels' | 'showPageNumbers' | 'rightAlignPageNumbers'> = {}
+): string {
+ const levels = Math.min(9, Math.max(1, Math.trunc(options.levels ?? 3)));
+ const showPageNumbers = options.showPageNumbers ?? true;
+ const rightAlignPageNumbers = showPageNumbers && (options.rightAlignPageNumbers ?? true);
+ const switches = [
+ `\\o "1-${levels}"`,
+ '\\h',
+ '\\z',
+ '\\u',
+ ...(!showPageNumbers ? ['\\n'] : []),
+ ...(showPageNumbers && !rightAlignPageNumbers ? ['\\p " "'] : []),
+ ];
+ return `TOC ${switches.join(' ')}`;
+}
+
+function isTableOfContentsRange(range: ICustomRange): boolean {
+ return range.rangeType === CustomRangeType.FIELD && range.properties?.fieldType === 'TOC';
+}
+
+export function findTableOfContentsAtOffset(body: IDocumentBody | null | undefined, offset: number | undefined): ICustomRange | undefined {
+ if (offset == null) {
+ return undefined;
+ }
+ return body?.customRanges
+ ?.filter((range) => isTableOfContentsRange(range) && range.startIndex <= offset && offset <= range.endIndex)
+ .sort((left, right) => left.endIndex - left.startIndex - (right.endIndex - right.startIndex))[0];
+}
+
+async function waitForCompleteLayout(skeleton: DocumentSkeleton): Promise<boolean> {
+ const progress = skeleton.getLayoutProgress();
+ if (progress == null || progress.complete) {
+ return true;
+ }
+ try {
+ await firstValueFrom(skeleton.layoutProgress$.pipe(
+ filter((next) => next.complete),
+ take(1),
+ timeout({ first: 30_000 })
+ ));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+async function waitForNextCompleteLayout(skeleton: DocumentSkeleton, generation: number): Promise<boolean> {
+ try {
+ await firstValueFrom(skeleton.layoutProgress$.pipe(
+ filter((next) => next.generation > generation && next.complete),
+ take(1),
+ timeout({ first: 30_000 })
+ ));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function buildPageNumberOnlyTableOfContentsBody(
+ body: IDocumentBody,
+ toc: ICustomRange,
+ resolvePageNumber: (offset: number) => number | undefined
+): IDocumentBody | null {
+ if (toc.properties?.locked === BooleanNumber.TRUE) {
+ return null;
+ }
+ // Slice metadata may share nested range properties with the source. Build the
+ // replacement in isolation so history captures the unmodified field caches.
+ const result = Tools.deepClone(getBodySlice(body, toc.startIndex, toc.endIndex + 1, true, SliceBodyType.cut));
+ const pageFields = result.customRanges
+ ?.filter((range) => range.rangeType === CustomRangeType.FIELD && range.properties?.fieldType === 'PAGEREF' &&
+ range.properties?.locked !== BooleanNumber.TRUE)
+ .sort((left, right) => right.startIndex - left.startIndex) ?? [];
+
+ for (const pageField of pageFields) {
+ const originalField = body.customRanges?.find((range) => range.rangeId === pageField.rangeId);
+ const targetOffset = originalField && resolvePageReferenceOffset(body, originalField);
+ const pageNumber = targetOffset == null ? undefined : resolvePageNumber(targetOffset);
+ if (pageNumber == null) {
+ return null;
+ }
+ replaceFieldResult(result, pageField, String(pageNumber));
+ }
+ const outer = result.customRanges?.find((range) => range.rangeId === toc.rangeId);
+ if (outer?.properties) {
+ outer.properties.cachedResult = getPlainText(result.dataStream.slice(1, -1))
+ .replaceAll(FIELD_START, '')
+ .replaceAll(FIELD_END, '');
+ }
+ return result;
+}
+
+function resolvePageReferenceOffset(body: IDocumentBody, pageField: ICustomRange): number | undefined {
+ const targetId = String(pageField.properties?.instruction ?? '').match(/PAGEREF\s+"?([^"\s\\]+)"?/i)?.[1];
+ if (targetId) {
+ const bookmark = body.customRanges?.find((range) =>
+ range.rangeType === CustomRangeType.BOOKMARK && range.properties?.bookmarkId === targetId
+ );
+ if (bookmark) {
+ return bookmark.startIndex;
+ }
+ }
+ const link = body.customRanges?.find((range) =>
+ range.rangeType === CustomRangeType.HYPERLINK &&
+ range.startIndex <= pageField.startIndex && pageField.endIndex <= range.endIndex
+ );
+ const headingId = link?.properties?.headingId;
+ return body.paragraphs?.find((paragraph) => paragraph.paragraphStyle?.headingId === headingId)?.startIndex;
+}
+
+function replaceFieldResult(body: IDocumentBody, field: ICustomRange, value: string): void {
+ const start = field.startIndex + 1;
+ const end = field.endIndex;
+ if (field.properties) {
+ field.properties.cachedResult = value;
+ }
+ // Unchanged text can still need a cache repair, but cannot shift any ranges.
+ if (body.dataStream.slice(start, end) === value) {
+ return;
+ }
+ const delta = value.length - (end - start);
+ body.dataStream = `${body.dataStream.slice(0, start)}${value}${body.dataStream.slice(end)}`;
+ shiftRuns(body.textRuns, start, end, delta);
+ body.paragraphs?.forEach((paragraph) => {
+ if (paragraph.startIndex >= end) {
+ paragraph.startIndex += delta;
+ }
+ });
+ body.customRanges?.forEach((range) => {
+ if (range.startIndex >= end) {
+ range.startIndex += delta;
+ range.endIndex += delta;
+ } else if (range.endIndex >= end) {
+ range.endIndex += delta;
+ }
+ });
+}
+
+function shiftRuns(runs: ITextRun[] | undefined, start: number, end: number, delta: number): void {
+ runs?.forEach((run) => {
+ if (run.st >= end) {
+ run.st += delta;
+ run.ed += delta;
+ } else if (run.ed > start) {
+ run.ed += delta;
+ }
+ });
+}
+
+export function buildTableOfContentsBody(
+ body: IDocumentBody,
+ toc: ICustomRange,
+ resolvePageNumber: (offset: number) => number | undefined,
+ idFactory: () => string = generateRandomId,
+ options?: { tabStopOffset?: number }
+): IDocumentBody | null {
+ if (toc.properties?.locked === BooleanNumber.TRUE) {
+ return null;
+ }
+ const instruction = String(toc.properties?.instruction ?? '');
+ if (/\\c\s+/i.test(instruction)) {
+ return null;
+ }
+ const [minLevel, maxLevel] = parseOutlineLevelRange(instruction);
+ const headings = collectHeadings(body, toc, minLevel, maxLevel);
+ if (headings.length === 0) {
+ return null;
+ }
+ const showPageNumbers = toc.properties?.showPageNumbers !== false && !/\\n(?:\s|$)/i.test(instruction);
+ const rightAlignPageNumbers = showPageNumbers && toc.properties?.rightAlignPageNumbers !== false && !/\\p\s+/i.test(instruction);
+ const tabLeader = normalizeTabLeader(toc.properties?.tabLeader);
+ const format = normalizeFormat(toc.properties?.format);
+ const isExistingToc = body.customRanges?.some((range) => range.rangeId === toc.rangeId) ?? false;
+ const oldParagraphs = isExistingToc
+ ? body.paragraphs?.filter((paragraph) =>
+ paragraph.startIndex >= toc.startIndex && paragraph.startIndex <= toc.endIndex
+ ) ?? []
+ : [];
+ const title = typeof toc.properties?.title === 'string'
+ ? toc.properties.title.trim()
+ : getExistingTableOfContentsTitle(body, oldParagraphs);
+ const result: IDocumentBody = { dataStream: FIELD_START, paragraphs: [], customRanges: [] };
+ const ranges = result.customRanges!;
+ const oldTitleParagraph = oldParagraphs.find((paragraph) => paragraph.styleId?.toLowerCase() === 'tocheading');
+ const oldEntryParagraphs = oldParagraphs.filter((paragraph) => paragraph !== oldTitleParagraph);
+ const usedParagraphIds = new Set<string>();
+ let cachedResult = '';
+
+ if (title) {
+ result.dataStream += `${title}\r`;
+ cachedResult += `${title}\r`;
+ result.paragraphs!.push(cloneParagraphWithId({
+ startIndex: result.dataStream.length - 1,
+ paragraphId: oldTitleParagraph?.paragraphId ?? '',
+ styleId: 'TOCHeading',
+ }, usedParagraphIds));
+ }
+
+ for (const [index, heading] of headings.entries()) {
+ const pageNumber = showPageNumbers ? resolvePageNumber(heading.startOffset) : undefined;
+ if (showPageNumbers && pageNumber == null) {
+ return null;
+ }
+ const entryStart = result.dataStream.length;
+ const separator = showPageNumbers ? (rightAlignPageNumbers ? '\t' : ' ') : '';
+ const visibleEntry = `${heading.text}${separator}${pageNumber ?? ''}`;
+ result.dataStream += `${heading.text}${separator}`;
+ const targetId = heading.bookmarkId ?? heading.headingId;
+ const link: ICustomRange = {
+ startIndex: entryStart,
+ endIndex: result.dataStream.length - 1,
+ rangeId: idFactory(),
+ rangeType: CustomRangeType.HYPERLINK,
+ wholeEntity: false,
+ properties: {
+ ...(heading.bookmarkId ? { bookmarkId: targetId } : { headingId: targetId }),
+ textStyleMode: 'text',
+ },
+ };
+ ranges.push(link);
+ if (showPageNumbers) {
+ const pageFieldStart = result.dataStream.length;
+ result.dataStream += `${FIELD_START}${pageNumber}${FIELD_END}`;
+ const pageFieldEnd = result.dataStream.length - 1;
+ link.endIndex = pageFieldEnd;
+ ranges.push({
+ startIndex: pageFieldStart,
+ endIndex: pageFieldEnd,
+ rangeId: idFactory(),
+ rangeType: CustomRangeType.FIELD,
+ wholeEntity: false,
+ properties: {
+ fieldType: 'PAGEREF',
+ instruction: `PAGEREF ${targetId} \\h`,
+ cachedResult: String(pageNumber),
+ sourceKind: 'complex',
+ },
+ });
+ }
+ result.dataStream += '\r';
+ cachedResult += `${visibleEntry}\r`;
+ result.paragraphs!.push(copyTocParagraph(
+ oldEntryParagraphs,
+ index,
+ heading.level,
+ result.dataStream.length - 1,
+ usedParagraphIds,
+ rightAlignPageNumbers ? options?.tabStopOffset : undefined,
+ tabLeader,
+ format
+ ));
+ }
+
+ result.dataStream += FIELD_END;
+ ranges.push({
+ startIndex: 0,
+ endIndex: result.dataStream.length - 1,
+ rangeId: toc.rangeId,
+ rangeType: CustomRangeType.FIELD,
+ wholeEntity: false,
+ properties: {
+ ...Tools.deepClone(toc.properties ?? {}),
+ fieldType: 'TOC',
+ instruction,
+ cachedResult,
+ },
+ });
+ ranges.sort((left, right) => left.startIndex - right.startIndex || right.endIndex - left.endIndex);
+ return result;
+}
+
+function getExistingTableOfContentsTitle(body: IDocumentBody, paragraphs: IParagraph[]): string {
+ const titleParagraph = paragraphs.find((paragraph) => paragraph.styleId?.toLowerCase() === 'tocheading');
+ if (!titleParagraph) {
+ return '';
+ }
+ const allParagraphs = [...(body.paragraphs ?? [])].sort((left, right) => left.startIndex - right.startIndex);
+ const index = allParagraphs.findIndex((paragraph) => paragraph === titleParagraph || paragraph.paragraphId === titleParagraph.paragraphId);
+ let start = index > 0 ? allParagraphs[index - 1].startIndex + 1 : 0;
+ while (body.dataStream[start] === FIELD_START || body.dataStream[start] === FIELD_END) {
+ start += 1;
+ }
+ return getPlainText(body.dataStream.slice(start, titleParagraph.startIndex)).trim();
+}
+
+export function countTableOfContentsHeadings(body: IDocumentBody | null | undefined, levels = 3): number {
+ if (!body) {
+ return 0;
+ }
+ const maxLevel = Math.min(9, Math.max(1, Math.trunc(levels)));
+ return collectHeadings(body, undefined, 1, maxLevel).length;
+}
+
+function parseOutlineLevelRange(instruction: string): [number, number] {
+ const match = instruction.match(/\\o\s+"(\d+)\s*-\s*(\d+)"/i);
+ const min = Math.max(1, Number(match?.[1] ?? 1));
+ const max = Math.min(9, Math.max(min, Number(match?.[2] ?? 3)));
+ return [min, max];
+}
+
+function collectHeadings(body: IDocumentBody, toc: ICustomRange | undefined, minLevel: number, maxLevel: number): ITableOfContentsHeading[] {
+ const paragraphs = [...(body.paragraphs ?? [])].sort((left, right) => left.startIndex - right.startIndex);
+ let paragraphStart = 0;
+ return paragraphs.flatMap((paragraph) => {
+ let startOffset = paragraphStart;
+ while (body.dataStream[startOffset] === FIELD_START || body.dataStream[startOffset] === FIELD_END) {
+ startOffset += 1;
+ }
+ paragraphStart = paragraph.startIndex + 1;
+ const level = getOutlineLevel(paragraph);
+ const headingId = paragraph.paragraphStyle?.headingId;
+ if (!headingId || level == null || level < minLevel || level > maxLevel ||
+ (toc && startOffset >= toc.startIndex && paragraph.startIndex <= toc.endIndex)) {
+ return [];
+ }
+ const text = getPlainText(body.dataStream.slice(startOffset, paragraph.startIndex)).trim();
+ if (!text) {
+ return [];
+ }
+ const bookmark = body.customRanges?.find((range) =>
+ range.rangeType === CustomRangeType.BOOKMARK &&
+ range.startIndex <= paragraph.startIndex &&
+ range.endIndex >= startOffset &&
+ range.properties?.bookmarkId
+ );
+ return [{
+ bookmarkId: bookmark?.properties?.bookmarkId,
+ headingId,
+ level,
+ paragraph,
+ startOffset,
+ text,
+ }];
+ });
+}
+
+function getOutlineLevel(paragraph: IParagraph): number | undefined {
+ const outlineLevel = paragraph.paragraphStyle?.outlineLevel;
+ if (outlineLevel != null && outlineLevel >= 0 && outlineLevel <= 8) {
+ return outlineLevel + 1;
+ }
+ const namedStyle = paragraph.paragraphStyle?.namedStyleType;
+ if (namedStyle != null && namedStyle >= NamedStyleType.HEADING_1 && namedStyle <= NamedStyleType.HEADING_5) {
+ return namedStyle - NamedStyleType.HEADING_1 + 1;
+ }
+}
+
+function copyTocParagraph(
+ oldParagraphs: IParagraph[],
+ index: number,
+ level: number,
+ startIndex: number,
+ usedParagraphIds: Set<string>,
+ tabStopOffset?: number,
+ tabLeader: TableOfContentsTabLeader = 'dots',
+ format: TableOfContentsFormat = 'fromTemplate'
+): IParagraph {
+ const byStyleLevel = oldParagraphs.find((paragraph) => paragraph.styleId?.match(/TOC(\d+)/i)?.[1] === String(level));
+ const source = byStyleLevel ?? oldParagraphs[Math.min(index, oldParagraphs.length - 1)];
+ // A same-level paragraph is a formatting template, not the identity of every
+ // entry. Keep distinct existing row IDs and allocate only for additional rows.
+ if (source) {
+ return cloneParagraphWithId({
+ ...source,
+ startIndex,
+ paragraphId: oldParagraphs[index]?.paragraphId ?? '',
+ }, usedParagraphIds);
+ }
+ return {
+ startIndex,
+ paragraphId: createParagraphId(usedParagraphIds),
+ styleId: `TOC${level}`,
+ paragraphStyle: {
+ indentStart: { v: Math.max(0, level - 1) * getFormatIndent(format) },
+ spaceBelow: format === 'modern' ? { v: 4 } : format === 'classic' ? { v: 2 } : undefined,
+ tabStops: tabStopOffset == null
+ ? undefined
+ : [{
+ offset: tabStopOffset,
+ alignment: TabStopAlignment.END,
+ leader: getTabStopLeader(tabLeader),
+ }],
+ },
+ };
+}
+
+function normalizeTabLeader(value: unknown): TableOfContentsTabLeader {
+ return value === 'none' || value === 'dashes' || value === 'underline' ? value : 'dots';
+}
+
+function getTabStopLeader(value: TableOfContentsTabLeader): TabStopLeader {
+ return {
+ none: TabStopLeader.NONE,
+ dots: TabStopLeader.DOT,
+ dashes: TabStopLeader.HYPHEN,
+ underline: TabStopLeader.UNDERSCORE,
+ }[value];
+}
+
+function normalizeFormat(value: unknown): TableOfContentsFormat {
+ return value === 'classic' || value === 'modern' || value === 'simple' ? value : 'fromTemplate';
+}
+
+function getFormatIndent(format: TableOfContentsFormat): number {
+ return {
+ fromTemplate: 18,
+ classic: 14,
+ modern: 20,
+ simple: 12,
+ }[format];
+}
diff --git a/packages/docs-toc/src/config/config.ts b/packages/docs-toc/src/config/config.ts
new file mode 100644
index 0000000000..42b83c69c6
--- /dev/null
+++ b/packages/docs-toc/src/config/config.ts
@@ -0,0 +1,24 @@
+/**
+ * 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 const DOCS_TOC_PLUGIN_CONFIG_KEY = 'docs-toc.config';
+
+export const configSymbol = Symbol(DOCS_TOC_PLUGIN_CONFIG_KEY);
+
+export interface IUniverDocsTocConfig {
+}
+
+export const defaultPluginConfig: IUniverDocsTocConfig = {};
diff --git a/packages/docs-toc/src/index.ts b/packages/docs-toc/src/index.ts
new file mode 100644
index 0000000000..505c2592b8
--- /dev/null
+++ b/packages/docs-toc/src/index.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.
+ */
+
+export {
+ buildPageNumberOnlyTableOfContentsBody,
+ buildTableOfContentsBody,
+ buildTableOfContentsInstruction,
+ countTableOfContentsHeadings,
+ DeleteTableOfContentsCommand,
+ findTableOfContentsAtOffset,
+ InsertTableOfContentsCommand,
+ UpdateTableOfContentsCommand,
+} from './commands/table-of-contents.command';
+export type {
+ IDeleteTableOfContentsCommandParams,
+ IInsertTableOfContentsCommandParams,
+ IUpdateTableOfContentsCommandParams,
+ TableOfContentsFormat,
+ TableOfContentsTabLeader,
+} from './commands/table-of-contents.command';
+export { UniverDocsTocPlugin } from './plugin';
diff --git a/packages/docs-toc/src/plugin.ts b/packages/docs-toc/src/plugin.ts
new file mode 100644
index 0000000000..b2d7c6107c
--- /dev/null
+++ b/packages/docs-toc/src/plugin.ts
@@ -0,0 +1,47 @@
+/**
+ * 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 { IUniverDocsTocConfig } from './config/config';
+import { DependentOn, ICommandService, IConfigService, Inject, Injector, merge, Plugin, UniverInstanceType } from '@univerjs/core';
+import { UniverDocsPlugin } from '@univerjs/docs';
+import { UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import pkg from '../package.json';
+import { DeleteTableOfContentsCommand, InsertTableOfContentsCommand, UpdateTableOfContentsCommand } from './commands/table-of-contents.command';
+import { defaultPluginConfig, DOCS_TOC_PLUGIN_CONFIG_KEY } from './config/config';
+
+@DependentOn(UniverDocsPlugin, UniverRenderEnginePlugin)
+export class UniverDocsTocPlugin extends Plugin {
+ static override pluginName = 'DOCS_TOC_PLUGIN';
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+ static override type = UniverInstanceType.UNIVER_DOC;
+
+ constructor(
+ private readonly _config: IUniverDocsTocConfig = defaultPluginConfig,
+ @Inject(Injector) protected override _injector: Injector,
+ @IConfigService private readonly _configService: IConfigService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+ const { ...rest } = merge({}, defaultPluginConfig, this._config);
+ this._configService.setConfig(DOCS_TOC_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ [InsertTableOfContentsCommand, UpdateTableOfContentsCommand, DeleteTableOfContentsCommand]
+ .forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+ }
+}
diff --git a/packages/docs-toc/tsconfig.json b/packages/docs-toc/tsconfig.json
new file mode 100644
index 0000000000..d4f9172636
--- /dev/null
+++ b/packages/docs-toc/tsconfig.json
@@ -0,0 +1,8 @@
+{
+ "extends": "@univerjs-infra/shared/tsconfigs/base",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "lib/types"
+ },
+ "include": ["src"]
+}
diff --git a/packages/docs-toc/tsconfig.node.json b/packages/docs-toc/tsconfig.node.json
new file mode 100644
index 0000000000..2abfa07367
--- /dev/null
+++ b/packages/docs-toc/tsconfig.node.json
@@ -0,0 +1,18 @@
+{
+ "extends": "@univerjs-infra/shared/tsconfigs/node",
+ "compilerOptions": {
+ "rootDir": "src",
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmit": false,
+ "outDir": "lib/types"
+ },
+ "include": [
+ "src"
+ ],
+ "exclude": [
+ "src/**/__tests__/**",
+ "src/**/*.spec.ts",
+ "src/**/*.test.ts"
+ ]
+}
diff --git a/packages/docs-toc/vitest.config.ts b/packages/docs-toc/vitest.config.ts
new file mode 100644
index 0000000000..af97c6d7a2
--- /dev/null
+++ b/packages/docs-toc/vitest.config.ts
@@ -0,0 +1,3 @@
+import createConfig from '@univerjs-infra/shared/vitest';
+
+export default createConfig();
diff --git a/packages/docs-ui/package.json b/packages/docs-ui/package.json
index 5a6cdfa689..c0f1bd5a82 100644
--- a/packages/docs-ui/package.json
+++ b/packages/docs-ui/package.json
@@ -88,6 +88,7 @@
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
"@univerjs/docs": "workspace:*",
+ "@univerjs/drawing": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/icons": "1.39.0",
"@univerjs/protocol": "workspace:*",
diff --git a/packages/docs-ui/src/commands/commands/__tests__/clipboard.inner.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/clipboard.inner.command.spec.ts
index 49d76fc2ba..5c26f5794d 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/clipboard.inner.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/clipboard.inner.command.spec.ts
@@ -14,13 +14,76 @@
* limitations under the License.
*/
-import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
-import { CustomRangeType, DocumentFlavor, ICommandService, IUniverInstanceService, RedoCommand, UndoCommand, Univer, UniverInstanceType, validateDocumentStructure } from '@univerjs/core';
-import { DocSelectionManagerService, DocStateChangeManagerService, DocStateEmitService, RichTextEditingMutation } from '@univerjs/docs';
-import { IRenderManagerService, NORMAL_TEXT_SELECTION_PLUGIN_STYLE, RenderManagerService } from '@univerjs/engine-render';
+import type { IDocumentData } from '@univerjs/core';
+import {
+ CustomRangeType,
+ DocumentDataModel,
+ DocumentFlavor,
+ HorizontalAlign,
+ ICommandService,
+ IUniverInstanceService,
+ JSONX,
+ RedoCommand,
+ UndoCommand,
+ Univer,
+ UniverInstanceType,
+ validateDocumentStructure,
+} from '@univerjs/core';
+import {
+ DocSelectionManagerService,
+ DocStateChangeManagerService,
+ DocStateEmitService,
+ RichTextEditingMutation,
+} from '@univerjs/docs';
+import {
+ DocumentViewModel,
+ IRenderManagerService,
+ NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ RenderManagerService,
+} from '@univerjs/engine-render';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { createInternalClipboardDocData } from '../../../services/clipboard/internal-fragment';
-import { InnerPasteCommand } from '../clipboard.inner.command';
+import { getCutActionsFromDocRanges, InnerPasteCommand } from '../clipboard.inner.command';
+
+describe('getCutActionsFromDocRanges', () => {
+ it.each([false, true])('keeps formatting only for embedded-editor clearing (%s), with reversible actions', (preserveFormatting) => {
+ const model = new DocumentDataModel({
+ id: 'shape-text',
+ body: {
+ dataStream: 'AB\rCD\r\n',
+ customBlocks: [],
+ customDecorations: [],
+ customRanges: [],
+ paragraphs: [
+ { startIndex: 2, paragraphId: 'first', paragraphStyle: { horizontalAlign: HorizontalAlign.CENTER } },
+ { startIndex: 5, paragraphId: 'second', paragraphStyle: { horizontalAlign: HorizontalAlign.RIGHT } },
+ ],
+ textRuns: [{ st: 0, ed: 2, ts: { fs: 16, bl: 1, cl: { rgb: '#ee8800' } } }],
+ },
+ });
+ const before = structuredClone(model.getSnapshot());
+ const actions = getCutActionsFromDocRanges(
+ [{ startOffset: 0, endOffset: 6, collapsed: false }],
+ [],
+ model,
+ new DocumentViewModel(model),
+ '',
+ true,
+ preserveFormatting
+ );
+ const undo = JSONX.invertWithDoc(actions, before);
+ model.apply(actions);
+ expect(model.getBody()?.dataStream).toBe('\r\n');
+ expect(model.getBody()?.paragraphs?.[0].paragraphStyle).toEqual(preserveFormatting ? { horizontalAlign: HorizontalAlign.CENTER } : undefined);
+ expect(model.getBody()?.textRuns ?? []).toEqual(preserveFormatting ? [{ st: 0, ed: 1, ts: before.body!.textRuns![0].ts }] : []);
+ const cleared = structuredClone(model.getSnapshot());
+ model.apply(undo);
+ expect(model.getSnapshot()).toEqual(before);
+ model.apply(actions);
+ expect(model.getSnapshot()).toEqual(cleared);
+ model.dispose();
+ });
+});
const SOURCE: IDocumentData = {
id: 'source',
diff --git a/packages/docs-ui/src/commands/commands/__tests__/doc-delete.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/doc-delete.command.spec.ts
index 6f05c76629..59d977b490 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/doc-delete.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/doc-delete.command.spec.ts
@@ -15,11 +15,82 @@
*/
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
-import { DeleteDirection, DocumentFlavor, ICommandService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';
-import { DocSelectionManagerService, DocStateEmitService, RichTextEditingMutation } from '@univerjs/docs';
-import { IRenderManagerService, NORMAL_TEXT_SELECTION_PLUGIN_STYLE, RenderManagerService } from '@univerjs/engine-render';
+import {
+ DeleteDirection,
+ DocumentFlavor,
+ HorizontalAlign,
+ ICommandService,
+ IUniverInstanceService,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ DocLayoutExecutorService,
+ DocSelectionManagerService,
+ DocSkeletonManagerService,
+ DocStateEmitService,
+ RichTextEditingMutation,
+ UpdateTextCommand,
+} from '@univerjs/docs';
+import {
+ IRenderManagerService,
+ NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ RenderManagerService,
+} from '@univerjs/engine-render';
import { describe, expect, it } from 'vitest';
-import { MergeTwoParagraphCommand } from '../doc-delete.command';
+import { EditorService, IEditorService } from '../../../services/editor/editor-manager.service';
+import { DeleteLeftCommand, DeleteRightCommand, MergeTwoParagraphCommand } from '../doc-delete.command';
+
+describe('empty editor deletion', () => {
+ it.each([DeleteLeftCommand, DeleteRightCommand])('keeps registered embedded editor formatting for $id', async (command) => {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ // The headless test has no canvas. Editor registration can precede render creation.
+ let skeletonManager: DocSkeletonManagerService | undefined;
+ injector.add([IRenderManagerService, { useValue: {
+ createRender: () => null,
+ getRenderUnitById: () => skeletonManager ? { with: () => skeletonManager } : undefined,
+ } as unknown as IRenderManagerService }]);
+ injector.add([DocSelectionManagerService]);
+ injector.add([DocStateEmitService]);
+ injector.add([DocLayoutExecutorService]);
+ injector.add([IEditorService, { useClass: EditorService }]);
+ const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: 'shape-editor',
+ documentStyle: {},
+ body: {
+ dataStream: '\r\n',
+ paragraphs: [{ startIndex: 0, paragraphId: 'empty', paragraphStyle: { horizontalAlign: HorizontalAlign.CENTER } }],
+ textRuns: [{ st: 0, ed: 1, ts: { fs: 16, bl: 1 } }],
+ },
+ });
+ const registration = injector.get(IEditorService).register({ initialSnapshot: model.getSnapshot() }, document.createElement('div'));
+ try {
+ injector.get(IUniverInstanceService).focusUnit(model.getUnitId());
+ skeletonManager = injector.createInstance(DocSkeletonManagerService, { unit: model, unitId: model.getUnitId(), type: UniverInstanceType.UNIVER_DOC });
+ const commands = injector.get(ICommandService);
+ [command, UpdateTextCommand, RichTextEditingMutation].forEach((entry) => commands.registerCommand(entry));
+ const selections = injector.get(DocSelectionManagerService);
+ selections.__TEST_ONLY_setCurrentSelection({ unitId: model.getUnitId(), subUnitId: model.getUnitId() });
+ selections.replaceSelectionInfoWithoutRefresh({
+ textRanges: [{ startOffset: 0, endOffset: 0, collapsed: true, isActive: true }],
+ rectRanges: [],
+ segmentId: '',
+ segmentPage: 0,
+ isEditing: true,
+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ });
+ const before = structuredClone(model.getSnapshot());
+ expect(await commands.executeCommand(command.id)).toBe(true);
+ expect(await commands.executeCommand(command.id)).toBe(true);
+ expect(model.getSnapshot()).toEqual(before);
+ } finally {
+ registration.dispose();
+ skeletonManager?.dispose();
+ univer.dispose();
+ }
+ });
+});
describe('MergeTwoParagraphCommand segment selection', () => {
it.each([DeleteDirection.LEFT, DeleteDirection.RIGHT])('keeps the footnote caret after merging in direction %s', async (direction) => {
diff --git a/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts
index 4785dbf3b4..d28a26f223 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts
@@ -15,7 +15,7 @@
*/
import type { ICommand, IDocumentData, Univer } from '@univerjs/core';
-import { awaitTime, DataStreamTreeTokenType, DocumentBlockRangeType, ICommandService } from '@univerjs/core';
+import { awaitTime, DataStreamTreeTokenType, DocumentBlockRangeType, ICommandService, UndoCommandId } from '@univerjs/core';
import {
DocContentInsertService,
DocSelectionManagerService,
@@ -438,6 +438,44 @@ describe('doc table create command helpers', () => {
expect(getDeleteTableActionParams(asRange(getOutsideTableOffset(fixture)), viewModel)).toBeNull();
});
+ it('targets the innermost table for nested table commands and Tab navigation', () => {
+ const firstCell = { startIndex: 5, endIndex: 10 };
+ const secondCell = { startIndex: 11, endIndex: 19 };
+ const firstRow = { startIndex: 4, endIndex: 20, children: [firstCell, secondCell] };
+ const secondRow = { startIndex: 21, endIndex: 56, children: [{ startIndex: 22, endIndex: 30 }, { startIndex: 31, endIndex: 55 }] };
+ const innerTable = { startIndex: 3, endIndex: 57, children: [firstRow, secondRow] };
+ const outerTable = { startIndex: 0, endIndex: 100, children: [] };
+ const tables = [
+ { tableId: 'outer', startIndex: 0, endIndex: 100 },
+ { tableId: 'inner', startIndex: 3, endIndex: 57 },
+ ];
+ const vm = {
+ findTableNodeById: (tableId: string) => tableId === 'inner' ? innerTable : outerTable,
+ getBody: () => ({ tables }),
+ };
+ const viewModel = {
+ ...vm,
+ getSelfOrHeaderFooterViewModel: () => vm,
+ } as never;
+
+ expect(getDeleteTableActionParams(asRange(6), viewModel)).toEqual({
+ tableId: 'inner',
+ offset: 3,
+ len: 55,
+ cursor: 3,
+ });
+ expect(getInsertRowActionsParams(asRange(6), INSERT_ROW_POSITION.ABOVE, viewModel)).toEqual({
+ tableId: 'inner',
+ offset: 4,
+ colCount: 2,
+ insertRowIndex: 0,
+ });
+ expect(getCellOffsets(viewModel, asRange(6), CellPosition.NEXT)).toEqual({
+ startOffset: 12,
+ endOffset: 17,
+ });
+ });
+
it('computes delete row-content params for the selected cells in one row', () => {
const fixture = createTableFixture();
const viewModel = createTableViewModel(fixture);
@@ -551,6 +589,9 @@ describe('doc table create command helpers', () => {
expect(await commandService.executeCommand(DocTableDeleteRowsCommand.id)).toBe(true);
await awaitTime(0);
expect(rowTestBed.doc.getSnapshot().tableSource?.[TABLE_ID].tableRows).toHaveLength(2);
+ expect(await commandService.executeCommand(UndoCommandId)).toBe(true);
+ await awaitTime(0);
+ expect(rowTestBed.doc.getSnapshot().tableSource?.[TABLE_ID].tableRows).toHaveLength(3);
rowTestBed.univer.dispose();
const columnFixture = createTableFixture();
@@ -562,6 +603,10 @@ describe('doc table create command helpers', () => {
await awaitTime(0);
expect(columnTestBed.doc.getSnapshot().tableSource?.[TABLE_ID].tableColumns).toHaveLength(2);
expect(columnTestBed.doc.getSnapshot().tableSource?.[TABLE_ID].tableRows.map((row) => row.tableCells.length)).toEqual([2, 2, 2]);
+ expect(await commandService.executeCommand(UndoCommandId)).toBe(true);
+ await awaitTime(0);
+ expect(columnTestBed.doc.getSnapshot().tableSource?.[TABLE_ID].tableColumns).toHaveLength(3);
+ expect(columnTestBed.doc.getSnapshot().tableSource?.[TABLE_ID].tableRows.map((row) => row.tableCells.length)).toEqual([3, 3, 3]);
columnTestBed.univer.dispose();
const tableFixture = createTableFixture();
@@ -580,6 +625,11 @@ describe('doc table create command helpers', () => {
await awaitTime(0);
expect(tableTestBed.doc.getBody()?.dataStream).toBe(TABLE_SUFFIX);
expect(testBedSnapshotTableIds(tableTestBed)).toEqual([]);
+
+ expect(await commandService.executeCommand(UndoCommandId)).toBe(true);
+ await awaitTime(0);
+ expect(tableTestBed.doc.getBody()?.dataStream).toBe(tableFixture.documentData.body?.dataStream);
+ expect(testBedSnapshotTableIds(tableTestBed)).toEqual([TABLE_ID]);
});
it('creates a table at the current document selection and fits it to page content width', async () => {
diff --git a/packages/docs-ui/src/commands/commands/__tests__/ime-input.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/ime-input.command.spec.ts
new file mode 100644
index 0000000000..e90f1f9cf2
--- /dev/null
+++ b/packages/docs-ui/src/commands/commands/__tests__/ime-input.command.spec.ts
@@ -0,0 +1,92 @@
+/**
+ * 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 { CustomRangeType, ICommandService, Tools } from '@univerjs/core';
+import { RichTextEditingMutation } from '@univerjs/docs';
+import { describe, expect, it } from 'vitest';
+import { DocIMEInputManagerService } from '../../../services/doc-ime-input-manager.service';
+import { IMEInputCommand } from '../ime-input.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('IME composition range preservation', () => {
+ it.each([CustomRangeType.SDT, CustomRangeType.HYPERLINK].flatMap((rangeType) =>
+ ['中', '中文'].flatMap((previous) => ['你', '中文测试'].flatMap((next) =>
+ [false, true].map((nested) => ({ rangeType, previous, next, nested }))))
+ ))('retains range $rangeType when replacing $previous with $next (nested $nested)', async ({ rangeType, previous, next, nested }) => {
+ const properties = rangeType === CustomRangeType.SDT
+ ? { kind: 'text', showingPlaceholder: false }
+ : { url: 'https://example.com' };
+ const bed = createCommandTestBed({
+ id: 'ime-range',
+ body: {
+ dataStream: `A${previous}B\r\n`,
+ paragraphs: [{ startIndex: previous.length + 2, paragraphId: 'paragraph' }],
+ customRanges: [...(nested
+ ? [{
+ rangeId: 'outer-control',
+ rangeType: CustomRangeType.SDT,
+ startIndex: 0,
+ endIndex: previous.length + 1,
+ wholeEntity: false,
+ properties: { kind: 'richText', showingPlaceholder: false },
+ }]
+ : []), {
+ rangeId: 'preceding-link',
+ rangeType: CustomRangeType.HYPERLINK,
+ startIndex: 0,
+ endIndex: 0,
+ properties: { url: 'https://example.org' },
+ }, {
+ rangeId: 'composition',
+ rangeType,
+ startIndex: 1,
+ endIndex: previous.length,
+ wholeEntity: false,
+ properties,
+ }],
+ },
+ documentStyle: {},
+ });
+ try {
+ const commands = bed.get(ICommandService);
+ commands.registerCommand(IMEInputCommand);
+ commands.registerCommand(RichTextEditingMutation);
+ const ime = bed.get(DocIMEInputManagerService);
+ ime.setActiveRange({ startOffset: 1, endOffset: 1, collapsed: true, segmentId: '' });
+ const before = Tools.deepClone(bed.doc.getBody());
+
+ expect(await commands.executeCommand(IMEInputCommand.id, {
+ unitId: bed.doc.getUnitId(),
+ newText: next,
+ oldTextLen: previous.length,
+ isCompositionStart: false,
+ isCompositionEnd: true,
+ })).toBe(true);
+ expect(bed.doc.getBody()?.dataStream).toBe(`A${next}B\r\n`);
+ expect(bed.doc.getBody()?.customRanges).toEqual(before!.customRanges!.map((range) => ({
+ ...range,
+ endIndex: range.rangeId === 'preceding-link' ? range.endIndex : range.endIndex + next.length - previous.length,
+ })));
+
+ const undo = ime.getUndoRedoMutationParamsCache().undoCache[0];
+ commands.syncExecuteCommand(RichTextEditingMutation.id, { ...undo, noHistory: true });
+ expect(bed.doc.getBody()?.dataStream).toBe(before!.dataStream);
+ expect(bed.doc.getBody()?.customRanges).toEqual(before!.customRanges);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+});
diff --git a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
index 7b76593f2a..741b9c604d 100644
--- a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
+++ b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
@@ -45,6 +45,7 @@ import {
IDocClipboardPasteAdapterService,
} from '../../services/clipboard/doc-paste-mutation-adapter.service';
import { cloneClipboardNotes, omitClipboardNotes } from '../../services/clipboard/internal-fragment';
+import { IEditorService } from '../../services/editor/editor-manager.service';
import { getCommandSkeleton } from '../util';
import { getDeleteRowContentActionParams, getDeleteRowsActionsParams, getDeleteTableActionParams } from './table/table';
@@ -546,23 +547,36 @@ function isWholeBodySelected(
return editableEnd > 0;
}
+function createClearedBody(body: IDocumentBody, preserveFormatting: boolean): IDocumentBody {
+ const emptyBody: IDocumentBody = {
+ dataStream: DataStreamTreeTokenType.PARAGRAPH,
+ paragraphs: [{
+ ...(preserveFormatting ? Tools.deepClone(body.paragraphs?.[0]) : {}),
+ paragraphId: createParagraphId(new Set((body.paragraphs ?? []).map((paragraph) => paragraph.paragraphId))),
+ startIndex: 0,
+ }],
+ };
+ if (preserveFormatting) {
+ const firstRun = body.textRuns?.find((run) => run.st === 0);
+ if (firstRun) {
+ emptyBody.textRuns = [{ st: 0, ed: 1, ts: Tools.deepClone(firstRun.ts) }];
+ }
+ }
+ return emptyBody;
+}
+
function getWholeBodyCutActions(
selections: readonly ITextRangeWithStyle[],
docDataModel: DocumentDataModel,
- segmentId: string
+ segmentId: string,
+ preserveFormatting: boolean
): JSONXActions {
const body = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (!body) {
return [];
}
- const emptyBody: IDocumentBody = {
- dataStream: DataStreamTreeTokenType.PARAGRAPH,
- paragraphs: [{
- paragraphId: createParagraphId(new Set((body.paragraphs ?? []).map((paragraph) => paragraph.paragraphId))),
- startIndex: 0,
- }],
- };
+ const emptyBody = createClearedBody(body, preserveFormatting);
const deleteLength = Math.max(0, body.dataStream.length - 1);
const textX = new TextX();
textX.push({ t: TextXActionType.INSERT, len: emptyBody.dataStream.length, body: emptyBody });
@@ -734,7 +748,8 @@ export function getCutActionsFromDocRanges(
docDataModel: DocumentDataModel,
viewModel: DocumentViewModel,
segmentId: string,
- wholeBodySelected = false
+ wholeBodySelected = false,
+ preserveFormatting = false
): JSONXActions {
let rawActions: JSONXActions = [];
const body = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
@@ -745,7 +760,7 @@ export function getCutActionsFromDocRanges(
Array.isArray(rectRanges) &&
(wholeBodySelected || isWholeBodySelected(textRanges, rectRanges, body))
) {
- return getWholeBodyCutActions(textRanges, docDataModel, segmentId);
+ return getWholeBodyCutActions(textRanges, docDataModel, segmentId, preserveFormatting);
}
if (Array.isArray(textRanges) && textRanges?.length !== 0) {
@@ -913,7 +928,8 @@ export const CutContentCommand: ICommand<IInnerCutCommandParams> = {
docDataModel,
viewModel,
segmentId,
- wholeBodySelected
+ wholeBodySelected,
+ accessor.has(IEditorService) && accessor.get(IEditorService).isEditor(unitId)
);
const result = commandService.syncExecuteCommand<
diff --git a/packages/docs-ui/src/commands/commands/doc-delete.command.ts b/packages/docs-ui/src/commands/commands/doc-delete.command.ts
index c274ef984c..193b1bae42 100644
--- a/packages/docs-ui/src/commands/commands/doc-delete.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-delete.command.ts
@@ -48,6 +48,7 @@ import {
} from '@univerjs/docs';
import { getParagraphByGlyph, hasListGlyph, isFirstGlyph, isIndentByGlyph } from '@univerjs/engine-render';
import { DocAutoFormatService } from '../../services/doc-auto-format.service';
+import { IEditorService } from '../../services/editor/editor-manager.service';
import { isHorizontalLineParagraph } from '../../utils/horizontal-line';
import { getCommandSkeleton } from '../util';
import { CutContentCommand } from './clipboard.inner.command';
@@ -484,7 +485,7 @@ export const DeleteLeftCommand: ICommand = {
const actualRange = activeRange;
const { startOffset, collapsed } = actualRange;
- if (collapsed && shouldResetEmptyCenteredParagraphAlignment(docDataModel)) {
+ if (collapsed && shouldResetEmptyCenteredParagraphAlignment(accessor, docDataModel)) {
const emptyCenteredParagraph = getEmptyCenteredParagraphAtOffset(body, startOffset);
if (emptyCenteredParagraph != null) {
return resetEmptyCenteredParagraphAlignment(commandService, docDataModel, segmentId ?? '', emptyCenteredParagraph, style);
@@ -711,7 +712,7 @@ export const DeleteRightCommand: ICommand = {
const actualRange = activeRange;
const { startOffset, endOffset, collapsed } = actualRange;
- if (collapsed && shouldResetEmptyCenteredParagraphAlignment(docDataModel)) {
+ if (collapsed && shouldResetEmptyCenteredParagraphAlignment(accessor, docDataModel)) {
const emptyCenteredParagraph = getEmptyCenteredParagraphAtOffset(body, startOffset);
if (emptyCenteredParagraph != null) {
return resetEmptyCenteredParagraphAlignment(commandService, docDataModel, segmentId ?? '', emptyCenteredParagraph, style);
@@ -853,8 +854,10 @@ function getEmptyCenteredParagraphAtOffset(body: IDocumentBody, offset: number)
}
}
-function shouldResetEmptyCenteredParagraphAlignment(docDataModel: DocumentDataModel) {
- return !SHEET_EDITOR_UNITS.includes(docDataModel.getUnitId());
+function shouldResetEmptyCenteredParagraphAlignment(accessor: IAccessor, docDataModel: DocumentDataModel) {
+ const unitId = docDataModel.getUnitId();
+ const isEditor = accessor.has(IEditorService) && accessor.get(IEditorService).isEditor(unitId);
+ return !isEditor && !SHEET_EDITOR_UNITS.includes(unitId);
}
function resetEmptyCenteredParagraphAlignment(
diff --git a/packages/docs-ui/src/commands/commands/ime-input.command.ts b/packages/docs-ui/src/commands/commands/ime-input.command.ts
index de9d0b73a2..f54333a98b 100644
--- a/packages/docs-ui/src/commands/commands/ime-input.command.ts
+++ b/packages/docs-ui/src/commands/commands/ime-input.command.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ICommand, ICommandInfo } from '@univerjs/core';
+import type { DocumentDataModel, ICommand, ICommandInfo, ICustomRange } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';
import { BuildTextUtils, CommandType, getRichTextEditPath, ICommandService, IUniverInstanceService, JSONX, SHEET_EDITOR_UNITS, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';
@@ -39,7 +39,6 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
type: CommandType.COMMAND,
- // eslint-disable-next-line max-lines-per-function
handler: async (accessor, params: IIMEInputCommandParams) => {
const { unitId, newText, oldTextLen, isCompositionEnd, isCompositionStart, isCompositionCanceled } = params;
const commandService = accessor.get(ICommandService);
@@ -135,7 +134,16 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
const defaultTextStyle = docMenuStyleService.getDefaultStyle();
const styleCache = docMenuStyleService.getStyleCache();
const styleOffset = replacesComplexSelection ? replacementOffset : startOffset + oldTextLen;
- const curCustomRange = getCustomRangeAtPosition(body.customRanges ?? [], styleOffset, SHEET_EDITOR_UNITS.includes(unitId));
+ let inheritedRanges: ICustomRange[];
+ // The end caret is outside a whole-composition range. Preserve every
+ // enclosing editable wrapper, including nested controls and links.
+ if (!isCompositionStart && oldTextLen > 0) {
+ inheritedRanges = body.customRanges?.filter((range) => !range.wholeEntity &&
+ range.startIndex <= startOffset && range.endIndex >= startOffset + oldTextLen - 1) ?? [];
+ } else {
+ const range = getCustomRangeAtPosition(body.customRanges ?? [], styleOffset, SHEET_EDITOR_UNITS.includes(unitId));
+ inheritedRanges = range ? [range] : [];
+ }
const curTextRun = getTextRunAtPosition(
body,
replacesComplexSelection ? replacementOffset : isCompositionStart ? endOffset : startOffset + oldTextLen,
@@ -154,13 +162,11 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
ed: newText.length,
}]
: [],
- customRanges: curCustomRange
- ? [{
- ...curCustomRange,
- startIndex: 0,
- endIndex: newText.length - 1,
- }]
- : [],
+ customRanges: inheritedRanges.map((range) => ({
+ ...range,
+ startIndex: 0,
+ endIndex: newText.length - 1,
+ })),
customDecorations: customDecorations.map((customDecoration) => ({
...customDecoration,
startIndex: 0,
diff --git a/packages/docs-ui/src/commands/commands/set-heading.command.ts b/packages/docs-ui/src/commands/commands/set-heading.command.ts
index c0a51d1724..5b80b8242a 100644
--- a/packages/docs-ui/src/commands/commands/set-heading.command.ts
+++ b/packages/docs-ui/src/commands/commands/set-heading.command.ts
@@ -38,6 +38,12 @@ export interface ISetParagraphNamedStyleCommandParams {
textRanges?: ITextRangeParam[];
}
+function namedStyleToOutlineLevel(namedStyleType: NamedStyleType): number | undefined {
+ if (namedStyleType >= NamedStyleType.HEADING_1 && namedStyleType <= NamedStyleType.HEADING_5) {
+ return namedStyleType - NamedStyleType.HEADING_1;
+ }
+}
+
export const SetParagraphNamedStyleCommand: ICommand<ISetParagraphNamedStyleCommandParams> = {
id: 'doc.command.set-paragraph-named-style',
type: CommandType.COMMAND,
@@ -82,6 +88,7 @@ export const SetParagraphNamedStyleCommand: ICommand<ISetParagraphNamedStyleComm
style: {
namedStyleType: params.value,
headingId: !params.value || params.value === NamedStyleType.NORMAL_TEXT ? undefined : generateRandomId(6),
+ outlineLevel: namedStyleToOutlineLevel(params.value),
spaceAbove: undefined,
spaceBelow: undefined,
lineSpacing: undefined,
@@ -134,6 +141,7 @@ function insertNamedStyleParagraph(
paragraphStyle: {
namedStyleType,
headingId: !namedStyleType || namedStyleType === NamedStyleType.NORMAL_TEXT ? undefined : generateRandomId(6),
+ outlineLevel: namedStyleToOutlineLevel(namedStyleType),
},
}],
},
@@ -224,6 +232,7 @@ export const QuickHeadingCommand: ICommand<ISetParagraphNamedStyleCommandParams>
...paragraphStyle,
headingId: generateRandomId(6),
namedStyleType: value,
+ outlineLevel: namedStyleToOutlineLevel(value),
lineSpacing: undefined,
spacingRule: undefined,
},
diff --git a/packages/docs-ui/src/commands/commands/table/doc-table-delete.command.ts b/packages/docs-ui/src/commands/commands/table/doc-table-delete.command.ts
index dda00d64e8..cb4291773c 100644
--- a/packages/docs-ui/src/commands/commands/table/doc-table-delete.command.ts
+++ b/packages/docs-ui/src/commands/commands/table/doc-table-delete.command.ts
@@ -88,6 +88,8 @@ export const DocTableDeleteRowsCommand: ICommand<IDocTableDeleteRowsCommandParam
unitId,
actions: [],
textRanges,
+ segmentId,
+ trigger: DocTableDeleteRowsCommand.id,
},
};
@@ -191,6 +193,8 @@ export const DocTableDeleteColumnsCommand: ICommand<IDocTableDeleteColumnsComman
unitId,
actions: [],
textRanges,
+ segmentId,
+ trigger: DocTableDeleteColumnsCommand.id,
},
};
@@ -241,6 +245,7 @@ export const DocTableDeleteColumnsCommand: ICommand<IDocTableDeleteColumnsComman
export interface IDocTableDeleteTableCommandParams {
targetRange?: ITextRangeWithStyle;
+ unitId?: string;
}
export const DocTableDeleteTableCommand: ICommand<IDocTableDeleteTableCommandParams> = {
@@ -266,7 +271,9 @@ export const DocTableDeleteTableCommand: ICommand<IDocTableDeleteTableCommandPar
const { segmentId } = rangeInfo;
- const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const docDataModel = params?.unitId
+ ? univerInstanceService.getUnit<DocumentDataModel>(params.unitId, UniverInstanceType.UNIVER_DOC)
+ : univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (docDataModel == null || body == null) {
@@ -305,6 +312,8 @@ export const DocTableDeleteTableCommand: ICommand<IDocTableDeleteTableCommandPar
unitId,
actions: [],
textRanges,
+ segmentId,
+ trigger: DocTableDeleteTableCommand.id,
},
};
diff --git a/packages/docs-ui/src/commands/commands/table/table.ts b/packages/docs-ui/src/commands/commands/table/table.ts
index a82043980d..2ac98fbe80 100644
--- a/packages/docs-ui/src/commands/commands/table/table.ts
+++ b/packages/docs-ui/src/commands/commands/table/table.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { IParagraph, ISectionBreak, ITable, ITableCell, ITableColumn, ITableRow, Nullable } from '@univerjs/core';
-import type { DataStreamTreeNode, DocumentViewModel, ITextRangeWithStyle } from '@univerjs/engine-render';
+import type { ICustomTable, IParagraph, ISectionBreak, ITable, ITableCell, ITableColumn, ITableRow, Nullable } from '@univerjs/core';
+import type { DocumentViewModel, ITextRangeWithStyle } from '@univerjs/engine-render';
import { createParagraphId, createSectionId, DataStreamTreeTokenType, generateRandomId, ObjectRelativeFromH, ObjectRelativeFromV, TableAlignmentType, TableRowHeightRule, TableSizeType, TableTextWrapType, Tools } from '@univerjs/core';
export enum INSERT_ROW_POSITION {
@@ -217,6 +217,24 @@ export function getRangeInfoFromRanges(textRange: Nullable<ITextRangeWithStyle>,
}
}
+function getInnermostTable(rangeInfo: IRangeInfo, viewModel: DocumentViewModel) {
+ const { startOffset, endOffset, segmentId } = rangeInfo;
+ const vm = viewModel.getSelfOrHeaderFooterViewModel(segmentId);
+ const tableRange = vm.getBody()?.tables?.reduce((current, table) =>
+ startOffset >= table.startIndex &&
+ endOffset <= table.endIndex &&
+ (current == null || table.endIndex - table.startIndex < current.endIndex - current.startIndex)
+ ? table
+ : current, null as Nullable<ICustomTable>);
+
+ if (!tableRange) {
+ return null;
+ }
+
+ const table = vm.findTableNodeById(tableRange.tableId);
+ return table ? { table, tableId: tableRange.tableId } : null;
+}
+
export function getInsertRowBody(col: number) {
let dataStream: string = DataStreamTreeTokenType.TABLE_ROW_START;
const paragraphs: IParagraph[] = [];
@@ -277,43 +295,16 @@ export function getInsertColumnBody() {
}
export function getInsertRowActionsParams(rangeInfo: IRangeInfo, position: INSERT_ROW_POSITION, viewModel: DocumentViewModel) {
- const { startOffset, endOffset, segmentId } = rangeInfo;
- const vm = viewModel.getSelfOrHeaderFooterViewModel(segmentId);
+ const { startOffset, endOffset } = rangeInfo;
const index = position === INSERT_ROW_POSITION.ABOVE ? startOffset : endOffset;
+ const target = getInnermostTable(rangeInfo, viewModel);
+ const tableRow = target?.table.children.find((row) => row.startIndex <= index && index <= row.endIndex);
- let tableRow = null;
- const tableId = viewModel.getBody()?.tables?.find((t) => index >= t.startIndex && index <= t.endIndex)?.tableId;
- let rowIndex = 0;
-
- // TODO: handle nested tables
- for (const section of vm.getChildren()) {
- for (const paragraph of section.children) {
- const { children } = paragraph;
- const table = children[0];
-
- if (table) {
- for (const row of table.children) {
- if (row.startIndex <= index && index <= row.endIndex) {
- rowIndex = table.children.indexOf(row);
- tableRow = row;
- break;
- }
- }
- }
-
- if (tableRow) {
- break;
- }
- }
-
- if (tableRow) {
- break;
- }
- }
-
- if (tableRow == null || tableId == null) {
+ if (!target || !tableRow) {
return null;
}
+ const { table, tableId } = target;
+ const rowIndex = table.children.indexOf(tableRow);
return {
offset: position === INSERT_ROW_POSITION.ABOVE ? tableRow.startIndex : tableRow.endIndex + 1,
@@ -323,56 +314,30 @@ export function getInsertRowActionsParams(rangeInfo: IRangeInfo, position: INSER
};
}
-// eslint-disable-next-line complexity
export function getInsertColumnActionsParams(rangeInfo: IRangeInfo, position: INSERT_COLUMN_POSITION, viewModel: DocumentViewModel) {
- const { startOffset, endOffset, segmentId } = rangeInfo;
- const vm = viewModel.getSelfOrHeaderFooterViewModel(segmentId);
+ const { startOffset, endOffset } = rangeInfo;
const index = position === INSERT_COLUMN_POSITION.LEFT ? startOffset : endOffset;
-
- const tableId = viewModel.getBody()?.tables?.find((t) => index >= t.startIndex && index <= t.endIndex)?.tableId;
+ const target = getInnermostTable(rangeInfo, viewModel);
const offsets: number[] = [];
- let table: Nullable<DataStreamTreeNode> = null;
let columnIndex = -1;
- for (const section of vm.getChildren()) {
- for (const paragraph of section.children) {
- const { children } = paragraph;
- const tableNode = children[0];
-
- if (tableNode) {
- if (index < tableNode.startIndex || index > tableNode.endIndex) {
- continue;
- }
-
- table = tableNode;
-
- for (const row of tableNode.children) {
- for (const cell of row.children) {
- const cellIndex = row.children.indexOf(cell);
-
- if (index >= cell.startIndex && index <= cell.endIndex) {
- columnIndex = cellIndex;
- break;
- }
- }
-
- if (columnIndex !== -1) {
- break;
- }
- }
- }
-
- if (table) {
+ if (!target) {
+ return null;
+ }
+ const { table, tableId } = target;
+ for (const row of table.children) {
+ for (const cell of row.children) {
+ if (index >= cell.startIndex && index <= cell.endIndex) {
+ columnIndex = row.children.indexOf(cell);
break;
}
}
-
- if (table) {
+ if (columnIndex !== -1) {
break;
}
}
- if (table == null || tableId == null || columnIndex === -1) {
+ if (columnIndex === -1) {
return null;
}
@@ -417,62 +382,39 @@ export function getColumnWidths(pageWidth: number, tableColumns: ITableColumn[],
};
}
-// eslint-disable-next-line complexity
export function getDeleteRowsActionsParams(rangeInfo: IRangeInfo, viewModel: DocumentViewModel) {
- const { startOffset, endOffset, segmentId } = rangeInfo;
- const vm = viewModel.getSelfOrHeaderFooterViewModel(segmentId);
- const tableId = viewModel.getBody()?.tables?.find((t) => startOffset >= t.startIndex && endOffset <= t.endIndex)?.tableId;
+ const { startOffset, endOffset } = rangeInfo;
+ const target = getInnermostTable(rangeInfo, viewModel);
const rowIndexes: number[] = [];
let offset = -1;
let len = 0;
let cursor = -1;
let selectWholeTable = false;
- for (const section of vm.getChildren()) {
- for (const paragraph of section.children) {
- const { children } = paragraph;
- const table = children[0];
-
- if (table) {
- if (startOffset < table.startIndex || endOffset > table.endIndex) {
- continue;
- }
-
- cursor = table.startIndex + 3;
-
- for (const row of table.children) {
- const rowIndex = table.children.indexOf(row);
- const { startIndex, endIndex } = row;
-
- if (startOffset >= startIndex && startOffset <= endIndex) {
- offset = startIndex;
- rowIndexes.push(rowIndex);
- len += endIndex - startIndex + 1;
- } else if (startIndex > startOffset && endIndex < endOffset) {
- rowIndexes.push(rowIndex);
- len += endIndex - startIndex + 1;
- } else if (endOffset >= startIndex && endOffset <= endIndex) {
- rowIndexes.push(rowIndex);
- len += endIndex - startIndex + 1;
- }
-
- if (rowIndexes.length === table.children.length) {
- selectWholeTable = true;
- }
- }
- }
-
- if (rowIndexes.length) {
- break;
- }
- }
-
- if (rowIndexes.length) {
- break;
+ if (!target) {
+ return null;
+ }
+ const { table, tableId } = target;
+ cursor = table.startIndex + 3;
+ for (const row of table.children) {
+ const rowIndex = table.children.indexOf(row);
+ const { startIndex: rowStartIndex, endIndex: rowEndIndex } = row;
+
+ if (startOffset >= rowStartIndex && startOffset <= rowEndIndex) {
+ offset = rowStartIndex;
+ rowIndexes.push(rowIndex);
+ len += rowEndIndex - rowStartIndex + 1;
+ } else if (rowStartIndex > startOffset && rowEndIndex < endOffset) {
+ rowIndexes.push(rowIndex);
+ len += rowEndIndex - rowStartIndex + 1;
+ } else if (endOffset >= rowStartIndex && endOffset <= rowEndIndex) {
+ rowIndexes.push(rowIndex);
+ len += rowEndIndex - rowStartIndex + 1;
}
}
+ selectWholeTable = rowIndexes.length === table.children.length;
- if (tableId == null || rowIndexes.length === 0) {
+ if (rowIndexes.length === 0) {
return null;
}
@@ -491,57 +433,34 @@ interface IRetainDeleteOffset {
delete: number;
}
-// eslint-disable-next-line max-lines-per-function, complexity
export function getDeleteColumnsActionParams(rangeInfo: IRangeInfo, viewModel: DocumentViewModel) {
- const { startOffset, endOffset, segmentId } = rangeInfo;
- const vm = viewModel.getSelfOrHeaderFooterViewModel(segmentId);
-
- const tableId = viewModel.getBody()?.tables?.find((t) => startOffset >= t.startIndex && endOffset <= t.endIndex)?.tableId;
+ const { startOffset, endOffset } = rangeInfo;
+ const target = getInnermostTable(rangeInfo, viewModel);
const offsets: IRetainDeleteOffset[] = [];
- let table: Nullable<DataStreamTreeNode> = null;
const columnIndexes: number[] = [];
let cursor = -1;
let startColumnIndex = -1;
let endColumnIndex = -1;
- for (const section of vm.getChildren()) {
- for (const paragraph of section.children) {
- const { children } = paragraph;
- const tableNode = children[0];
-
- if (tableNode) {
- if (startOffset < tableNode.startIndex || endOffset > tableNode.endIndex) {
- continue;
- }
-
- table = tableNode;
-
- for (const row of tableNode.children) {
- for (const cell of row.children) {
- const cellIndex = row.children.indexOf(cell);
-
- if (startOffset >= cell.startIndex && startOffset <= cell.endIndex) {
- startColumnIndex = cellIndex;
- }
+ if (!target) {
+ return null;
+ }
+ const { table, tableId } = target;
+ for (const row of table.children) {
+ for (const cell of row.children) {
+ const cellIndex = row.children.indexOf(cell);
- if (endOffset >= cell.startIndex && endOffset <= cell.endIndex) {
- endColumnIndex = cellIndex;
- }
- }
- }
+ if (startOffset >= cell.startIndex && startOffset <= cell.endIndex) {
+ startColumnIndex = cellIndex;
}
- if (table) {
- break;
+ if (endOffset >= cell.startIndex && endOffset <= cell.endIndex) {
+ endColumnIndex = cellIndex;
}
}
-
- if (table) {
- break;
- }
}
- if (table == null || tableId == null) {
+ if (startColumnIndex === -1 || endColumnIndex === -1) {
return null;
}
@@ -575,107 +494,51 @@ export function getDeleteColumnsActionParams(rangeInfo: IRangeInfo, viewModel: D
}
export function getDeleteTableActionParams(rangeInfo: IRangeInfo, viewModel: DocumentViewModel) {
- const { startOffset, endOffset, segmentId } = rangeInfo;
- const vm = viewModel.getSelfOrHeaderFooterViewModel(segmentId);
-
- const tableId = viewModel.getBody()?.tables?.find((t) => startOffset >= t.startIndex && endOffset <= t.endIndex)?.tableId;
- let offset = -1;
- let len = 0;
- let cursor = -1;
-
- for (const section of vm.getChildren()) {
- for (const paragraph of section.children) {
- const { children } = paragraph;
- const table = children[0];
-
- if (table) {
- if (startOffset < table.startIndex || endOffset > table.endIndex) {
- continue;
- }
-
- offset = table.startIndex;
- len = table.endIndex - table.startIndex + 1;
- cursor = table.startIndex;
- }
-
- if (table) {
- break;
- }
- }
-
- if (len > 0) {
- break;
- }
- }
-
- if (tableId == null) {
+ const target = getInnermostTable(rangeInfo, viewModel);
+ if (!target) {
return null;
}
+ const { table, tableId } = target;
return {
tableId,
- offset,
- len,
- cursor,
+ offset: table.startIndex,
+ len: table.endIndex - table.startIndex + 1,
+ cursor: table.startIndex,
};
}
-// eslint-disable-next-line complexity
export function getDeleteRowContentActionParams(rangeInfo: IRangeInfo, viewModel: DocumentViewModel) {
- const { startOffset, endOffset, segmentId } = rangeInfo;
- const vm = viewModel.getSelfOrHeaderFooterViewModel(segmentId);
-
- const tableId = viewModel.getBody()?.tables?.find((t) => startOffset >= t.startIndex && endOffset <= t.endIndex)?.tableId;
+ const { startOffset, endOffset } = rangeInfo;
+ const target = getInnermostTable(rangeInfo, viewModel);
const offsets: IRetainDeleteOffset[] = [];
- let table: Nullable<DataStreamTreeNode> = null;
-
let cursor = -1;
let rowIndex = -1;
let startColumnIndex = -1;
let endColumnIndex = -1;
- for (const section of vm.getChildren()) {
- for (const paragraph of section.children) {
- const { children } = paragraph;
- const tableNode = children[0];
-
- if (tableNode) {
- if (startOffset < tableNode.startIndex || endOffset > tableNode.endIndex) {
- continue;
- }
-
- table = tableNode;
-
- for (const row of tableNode.children) {
- const rIndex = tableNode.children.indexOf(row);
-
- for (const cell of row.children) {
- const cellIndex = row.children.indexOf(cell);
+ if (!target) {
+ return null;
+ }
+ const { table, tableId } = target;
+ for (const row of table.children) {
+ const rIndex = table.children.indexOf(row);
- if (startOffset >= cell.startIndex && startOffset <= cell.endIndex) {
- rowIndex = rIndex;
- startColumnIndex = cellIndex;
- }
+ for (const cell of row.children) {
+ const cellIndex = row.children.indexOf(cell);
- if (endOffset >= cell.startIndex && endOffset <= cell.endIndex) {
- // StartOffset and endOffset are in the same row.
- endColumnIndex = cellIndex;
- }
- }
- }
+ if (startOffset >= cell.startIndex && startOffset <= cell.endIndex) {
+ rowIndex = rIndex;
+ startColumnIndex = cellIndex;
}
- if (table) {
- break;
+ if (endOffset >= cell.startIndex && endOffset <= cell.endIndex) {
+ endColumnIndex = cellIndex;
}
}
-
- if (table) {
- break;
- }
}
- if (table == null || tableId == null || rowIndex === -1) {
+ if (rowIndex === -1) {
return null;
}
@@ -710,31 +573,13 @@ export enum CellPosition {
PREV,
}
-// eslint-disable-next-line complexity, max-lines-per-function
export function getCellOffsets(viewModel: DocumentViewModel, range: ITextRangeWithStyle, position: CellPosition): Nullable<IOffsets> {
- const { startOffset } = range;
-
- let targetTable = null;
-
- for (const section of viewModel.getChildren()) {
- for (const paragraph of section.children) {
- const table = paragraph.children[0];
- if (table) {
- if (startOffset > table.startIndex && startOffset < table.endIndex) {
- targetTable = table;
- break;
- }
- }
- }
-
- if (targetTable) {
- break;
- }
- }
-
- if (targetTable == null) {
+ const { startOffset, endOffset, segmentId = '' } = range;
+ const target = getInnermostTable({ startOffset, endOffset, segmentId }, viewModel);
+ if (!target) {
return null;
}
+ const targetTable = target.table;
let cellIndex = -1;
let rowIndex = -1;
diff --git a/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.spec.ts
index 1b434928e5..46c0518639 100644
--- a/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.spec.ts
+++ b/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.spec.ts
@@ -14,269 +14,255 @@
* limitations under the License.
*/
+import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
+import type { RenderUnit } from '@univerjs/engine-render';
+import type { HeaderFooterContentCover } from '../../views/header-footer/content-cover';
import {
+ BooleanNumber,
DocumentFlavor,
+ DrawingTypeEnum,
ICommandService,
- Injector,
IUniverInstanceService,
LocaleService,
+ LocaleType,
+ PositionedObjectLayoutType,
ThemeService,
+ Univer,
+ UniverInstanceType,
} from '@univerjs/core';
-import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
-import { DocumentEditArea, IRenderManagerService, Path, Rect } from '@univerjs/engine-render';
-import { BehaviorSubject, Subject } from 'rxjs';
+import {
+ DocLayoutExecutorService,
+ DocSelectionManagerService,
+ DocSkeletonManagerService,
+ DocStateEmitService,
+ RichTextEditingMutation,
+} from '@univerjs/docs';
+import { getDrawingShapeKeyByDrawingSearch } from '@univerjs/drawing';
+import {
+ CanvasColorService,
+ DocumentEditArea,
+ Documents,
+ ICanvasColorService,
+ IRenderManagerService,
+ Rect,
+ RenderManagerService,
+ Vector2,
+} from '@univerjs/engine-render';
+import { DesktopLayoutService, DesktopSidebarService, ILayoutService, ISidebarService } from '@univerjs/ui';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CloseHeaderFooterCommand } from '../../commands/commands/doc-header-footer.command';
-import { IEditorService } from '../../services/editor/editor-manager.service';
+import { SidebarDocHeaderFooterPanelOperation } from '../../commands/operations/doc-header-footer-panel.operation';
+import enUS from '../../locale/en-US';
+import { EditorService, IEditorService } from '../../services/editor/editor-manager.service';
import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';
-import { TextBubbleShape } from '../../views/header-footer/text-bubble';
import { DocHeaderFooterController } from '../doc-header-footer.controller';
-const neoGetDocObjectMock = vi.hoisted(() => vi.fn());
-
-vi.mock('../../basics/component-tools', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../basics/component-tools')>();
+const cleanups: Array<() => void> = [];
- return {
- ...actual,
- neoGetDocObject: neoGetDocObjectMock,
- };
-});
-
-function createCtx() {
- return {
- save: vi.fn(),
- restore: vi.fn(),
- translate: vi.fn(),
- };
-}
-
-function createController(options: {
- editArea?: DocumentEditArea;
- documentFlavor?: DocumentFlavor;
- editor?: boolean;
-} = {}) {
- const pageRender$ = new Subject<{
- ctx: ReturnType<typeof createCtx>;
- pageLeft: number;
- pageTop: number;
- page: {
- pageWidth: number;
- pageHeight: number;
- marginTop: number;
- marginBottom: number;
- };
- }>();
- const commandHandlers: Array<(command: { id: string; params?: unknown }) => void> = [];
- const document = {
- pageRender$,
- onDblclick$: {
- subscribeEvent: vi.fn(() => ({ dispose: vi.fn() })),
+function createTestBed(documentFlavor = DocumentFlavor.TRADITIONAL, overrides: Partial<IDocumentData> = {}) {
+ vi.useFakeTimers();
+ const univer = new Univer();
+ const root = document.createElement('div');
+ document.body.appendChild(root);
+ cleanups.push(() => {
+ univer.dispose();
+ root.remove();
+ });
+ const injector = univer.__getInjector();
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);
+ injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
+ injector.add([IEditorService, { useClass: EditorService }]);
+ injector.add([DocLayoutExecutorService]);
+ injector.add([DocSelectionManagerService]);
+ injector.add([DocStateEmitService]);
+ injector.get(ILayoutService).registerRootContainerElement(root);
+ const locale = injector.get(LocaleService);
+ locale.load({ [LocaleType.EN_US]: enUS });
+ locale.setLocale(LocaleType.EN_US);
+ root.dir = locale.getDirection();
+ const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: 'header-footer-document',
+ body: {
+ dataStream: 'D\r\n',
+ paragraphs: [{ startIndex: 1, paragraphId: 'body-p' }],
+ sectionBreaks: [{ startIndex: 2, sectionId: 'body-section' }],
},
- getOffsetConfig: vi.fn(() => ({ documentTransform: { clone: vi.fn() } })),
- };
- const scene = {
- getViewports: vi.fn(() => []),
- };
- neoGetDocObjectMock.mockReturnValue({ document, scene });
- const unit = {
- getSnapshot: vi.fn(() => ({
- documentStyle: {
- documentFlavor: options.documentFlavor ?? DocumentFlavor.TRADITIONAL,
- },
- })),
- };
- const viewModel = {
- getEditArea: vi.fn(() => options.editArea ?? DocumentEditArea.BODY),
- };
- const commandService = {
- onCommandExecuted: vi.fn((handler) => {
- commandHandlers.push(handler);
- return { dispose: vi.fn() };
- }),
- executeCommand: vi.fn(),
- };
- const context = {
- unitId: 'doc-1',
- unit,
- mainComponent: document,
- } as never;
- const injector = new Injector([
- [ICommandService, { useValue: commandService }],
- [IEditorService, { useValue: {
- isEditor: vi.fn(() => options.editor ?? false),
- getEditor: vi.fn(() => null),
- } }],
- [IUniverInstanceService, { useValue: {
- getCurrentTypeOfUnit$: vi.fn(() => new BehaviorSubject({ getUnitId: () => 'doc-1' })),
- getUnit: vi.fn(() => unit),
- } }],
- [IRenderManagerService, { useValue: {
- getRenderUnitById: vi.fn(() => ({ mainComponent: document })),
- } }],
- [DocSkeletonManagerService, { useValue: {
- getViewModel: vi.fn(() => viewModel),
- } }],
- [DocSelectionRenderService, { useValue: {
- setSegment: vi.fn(),
- setSegmentPage: vi.fn(),
- setCursorManually: vi.fn(),
- } }],
- [LocaleService, { useValue: {
- t: vi.fn((key: string) => key),
- } }],
- [ThemeService],
- ]);
- const controller = injector.createInstance(DocHeaderFooterController, context);
-
- return { controller, pageRender$, commandHandlers, commandService, document, themeService: injector.get(ThemeService) };
+ ...overrides,
+ documentStyle: {
+ documentFlavor,
+ pageSize: { width: 300, height: 400 },
+ marginTop: 50,
+ marginBottom: 50,
+ ...overrides.documentStyle,
+ },
+ });
+ injector.get(IUniverInstanceService).setCurrentUnitForType(model.getUnitId());
+ const render = injector.get(IRenderManagerService).createRender(model.getUnitId()) as RenderUnit;
+ render.deactivate();
+ render.engine.resizeBySize(300, 400);
+ render.addRenderDependencies([[DocSkeletonManagerService]]);
+ const manager = render.with(DocSkeletonManagerService);
+ const documents = new Documents(model.getUnitId(), manager.getSkeleton());
+ render.mainComponent = documents;
+ render.scene.addObject(documents);
+ render.addRenderDependencies([[DocSelectionRenderService]]);
+ const ctx = render.engine.getCanvas().getContext();
+ const paints: Array<{ text: string; alpha: number }> = [];
+ vi.spyOn(ctx, 'fillText').mockImplementation((text) => {
+ paints.push({ text: String(text), alpha: ctx.globalAlpha });
+ });
+ return { univer, injector, model, render, documents, manager, ctx, paints };
}
describe('DocHeaderFooterController', () => {
afterEach(() => {
+ cleanups.splice(0).reverse().forEach((dispose) => dispose());
vi.restoreAllMocks();
- neoGetDocObjectMock.mockReset();
+ vi.useRealTimers();
});
- it('closes header/footer editing after rich text changes in modern document mode', () => {
- const { controller, commandHandlers, commandService } = createController({
- editArea: DocumentEditArea.HEADER,
- documentFlavor: DocumentFlavor.MODERN,
- });
-
- commandHandlers[0]({ id: RichTextEditingMutation.id });
-
- expect(commandService.executeCommand).toHaveBeenCalledWith(CloseHeaderFooterCommand.id, {
- unitId: 'doc-1',
- });
-
- controller.dispose();
+ it('keeps body content in page margins at full opacity without painting a covering rectangle', () => {
+ const { render, documents, ctx, paints } = createTestBed();
+ render.addRenderDependencies([[DocHeaderFooterController]]);
+ render.with(DocHeaderFooterController);
+ const fill = vi.spyOn(ctx, 'fill');
+ documents.draw(ctx);
+ expect(paints).toContainEqual({ text: 'D', alpha: 1 });
+ expect(fill).not.toHaveBeenCalled();
});
- it('covers header and footer areas while editing the document body', () => {
- const { controller, pageRender$, themeService } = createController({ editArea: DocumentEditArea.BODY });
- const rectSpy = vi.spyOn(Rect, 'drawWith').mockImplementation(() => undefined);
- const pathSpy = vi.spyOn(Path, 'drawWith').mockImplementation(() => undefined);
- const textSpy = vi.spyOn(TextBubbleShape, 'drawWith').mockImplementation(() => undefined);
- const ctx = createCtx();
- const theme = themeService.getCurrentTheme();
-
- themeService.setTheme({
- ...theme,
- gray: {
- ...theme.gray,
- 0: '#123456',
- },
- });
-
- pageRender$.next({
- ctx,
- pageLeft: 12,
- pageTop: 24,
- page: {
- pageWidth: 200,
- pageHeight: 300,
- marginTop: 30,
- marginBottom: 40,
- },
+ it('covers only header/footer ink bounds, stays transparent to picking, and is removed on disposal', () => {
+ const { render, documents, ctx, paints, manager } = createTestBed(DocumentFlavor.TRADITIONAL, {
+ headers: { header: { headerId: 'header', body: { dataStream: 'Logo\r\n', paragraphs: [{ startIndex: 4, paragraphId: 'header-p' }] } } },
+ footers: { footer: { footerId: 'footer', body: { dataStream: 'Page\r\n', paragraphs: [{ startIndex: 4, paragraphId: 'footer-p' }] } } },
+ documentStyle: { defaultHeaderId: 'header', defaultFooterId: 'footer', marginLeft: 40, marginRight: 40 },
});
+ render.addRenderDependencies([[DocHeaderFooterController]]);
+ const controller = render.with(DocHeaderFooterController);
+ const cover = render.scene.getObject('header-footer-document-header-footer-cover') as HeaderFooterContentCover;
+ const rects = vi.spyOn(ctx, 'rect');
+ const fill = vi.spyOn(ctx, 'fill');
+ documents.draw(ctx);
+ expect(paints.filter(({ text }) => /[LogoPage]/.test(text)).every(({ alpha }) => alpha === 1)).toBe(true);
+ rects.mockClear();
+ fill.mockClear();
+ cover.render(ctx);
+ const bounds = rects.mock.calls;
+ expect(bounds.length).toBeGreaterThan(0);
+ expect(bounds.every(([x, , width]) => x > 0 && width < 150)).toBe(true);
+ expect(bounds.some(([, y]) => y < 50)).toBe(true);
+ expect(bounds.some(([, y]) => y > 300)).toBe(true);
+ expect(fill).toHaveBeenCalledTimes(1);
+ expect(cover.evented).toBe(false);
+ expect(render.scene.pick(new Vector2(bounds[0][0] + 1, bounds[0][1] + 1))).not.toBe(cover);
- expect(ctx.translate).toHaveBeenCalledWith(11.5, 23.5);
- expect(rectSpy).toHaveBeenCalledTimes(2);
- expect(rectSpy.mock.calls[0][1]).toMatchObject({
- width: 200,
- height: 30,
- fill: 'rgba(18,52,86,0.5)',
- });
- expect(rectSpy.mock.calls[1][1]).toMatchObject({
- width: 200,
- height: 40,
- fill: 'rgba(18,52,86,0.5)',
- });
- expect(pathSpy).not.toHaveBeenCalled();
- expect(textSpy).not.toHaveBeenCalled();
-
+ manager.getViewModel().setEditArea(DocumentEditArea.HEADER);
+ fill.mockClear();
+ cover.render(ctx);
+ expect(fill).not.toHaveBeenCalled();
controller.dispose();
+ expect(render.scene.getObject(cover.oKey)).toBeUndefined();
});
- it('covers the body and draws header/footer guides while editing header or footer', () => {
- const { controller, pageRender$, themeService } = createController({ editArea: DocumentEditArea.HEADER });
- const rectSpy = vi.spyOn(Rect, 'drawWith').mockImplementation(() => undefined);
- const pathSpy = vi.spyOn(Path, 'drawWith').mockImplementation(() => undefined);
- const textSpy = vi.spyOn(TextBubbleShape, 'drawWith').mockImplementation(() => undefined);
- const ctx = createCtx();
- const theme = themeService.getCurrentTheme();
-
- themeService.setTheme({
- ...theme,
- primary: {
- ...theme.primary,
- 600: '#123456',
+ it('uses live repeated drawing bounds without covering the horizontal gap or painting overlaps twice', () => {
+ const drawingDefaults = {
+ unitId: 'header-footer-document',
+ subUnitId: 'header-footer-document',
+ isMultiTransform: BooleanNumber.TRUE,
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ size: { width: 30, height: 20 },
+ positionH: { relativeFrom: 0, posOffset: 0 },
+ positionV: { relativeFrom: 0, posOffset: 0 },
+ angle: 0,
},
- });
-
- pageRender$.next({
- ctx,
- pageLeft: 0,
- pageTop: 0,
- page: {
- pageWidth: 200,
- pageHeight: 300,
- marginTop: 30,
- marginBottom: 40,
+ };
+ const { render, ctx, documents } = createTestBed(DocumentFlavor.TRADITIONAL, {
+ drawings: {
+ first: { ...drawingDefaults, drawingId: 'first' },
+ second: { ...drawingDefaults, drawingId: 'second' },
},
});
+ render.addRenderDependencies([[DocHeaderFooterController]]);
+ render.with(DocHeaderFooterController);
+ const first = new Rect(getDrawingShapeKeyByDrawingSearch({ unitId: documents.oKey, subUnitId: documents.oKey, drawingId: 'first' }, 0), { left: 40, top: 10, width: 30, height: 20 });
+ const second = new Rect(getDrawingShapeKeyByDrawingSearch({ unitId: documents.oKey, subUnitId: documents.oKey, drawingId: 'second' }, 0), { left: 220, top: 10, width: 40, height: 20 });
+ render.scene.addObjects([first, second], 4);
+ const cover = render.scene.getObject('header-footer-document-header-footer-cover') as HeaderFooterContentCover;
+ const rects = vi.spyOn(ctx, 'rect');
+ const fill = vi.spyOn(ctx, 'fill');
+ cover.render(ctx);
+ expect(rects.mock.calls).toEqual([[40, 10, 30, 20], [220, 10, 40, 20]]);
+ expect(fill).toHaveBeenCalledTimes(1);
+ second.transformByState({ left: 50 });
+ rects.mockClear();
+ fill.mockClear();
+ cover.render(ctx);
+ expect(rects.mock.calls).toEqual([[40, 10, 30, 20], [50, 10, 40, 20]]);
+ expect(fill).toHaveBeenCalledTimes(1);
+ });
- expect(rectSpy).toHaveBeenCalledWith(ctx, expect.objectContaining({
- top: 30,
- width: 200,
- height: 230,
- }));
- expect(pathSpy).toHaveBeenCalledTimes(2);
- expect(pathSpy).toHaveBeenCalledWith(ctx, expect.objectContaining({ stroke: '#123456' }));
- expect(textSpy).toHaveBeenCalledWith(ctx, expect.objectContaining({
- text: 'docs-ui.headerFooter.header',
- color: 'rgba(18,52,86,0.08)',
- }));
- expect(textSpy).toHaveBeenCalledWith(ctx, expect.objectContaining({
- text: 'docs-ui.headerFooter.footer',
- color: 'rgba(18,52,86,0.08)',
- }));
+ it('dims the body during header editing, redraws on edit-area changes, and restores opacity on disposal', () => {
+ const { render, documents, manager, ctx, paints } = createTestBed();
+ render.addRenderDependencies([[DocHeaderFooterController]]);
+ const controller = render.with(DocHeaderFooterController);
+ documents.makeDirty(false);
+ manager.getViewModel().setEditArea(DocumentEditArea.HEADER);
+ expect(documents.isDirty()).toBe(true);
+ documents.draw(ctx);
+ expect(paints).toContainEqual({ text: 'D', alpha: 0.5 });
controller.dispose();
+ paints.length = 0;
+ const stroke = vi.spyOn(ctx, 'stroke');
+ documents.draw(ctx);
+ expect(paints.filter(({ text }) => text.trim())).toEqual([{ text: 'D', alpha: 1 }]);
+ expect(stroke).not.toHaveBeenCalled();
});
- it('keeps theme color lookups out of the page render hot path', () => {
- const { controller, pageRender$, themeService } = createController({ editArea: DocumentEditArea.BODY });
- const getColorFromTheme = vi.spyOn(themeService, 'getColorFromTheme');
- vi.spyOn(Rect, 'drawWith').mockImplementation(() => undefined);
+ it('draws localized guides using current theme tokens without resolving colors per page', () => {
+ const { injector, render, documents, manager, ctx, paints } = createTestBed();
+ render.addRenderDependencies([[DocHeaderFooterController]]);
+ render.with(DocHeaderFooterController);
+ manager.getViewModel().setEditArea(DocumentEditArea.HEADER);
+ const themeService = injector.get(ThemeService);
const theme = themeService.getCurrentTheme();
- const config = {
- ctx: createCtx(),
- pageLeft: 0,
- pageTop: 0,
- page: {
- pageWidth: 200,
- pageHeight: 300,
- marginTop: 30,
- marginBottom: 40,
- },
- };
-
- themeService.setTheme({
- ...theme,
- gray: {
- ...theme.gray,
- 0: '#123456',
- },
+ themeService.setTheme({ ...theme, primary: { ...theme.primary, 600: '#123456' } });
+ const colors = vi.spyOn(themeService, 'getColorFromTheme');
+ const strokes: Array<string | CanvasGradient | CanvasPattern> = [];
+ vi.spyOn(ctx, 'stroke').mockImplementation(() => {
+ strokes.push(ctx.strokeStyle);
});
- getColorFromTheme.mockClear();
-
- pageRender$.next(config);
- pageRender$.next(config);
+ documents.draw(ctx);
+ documents.draw(ctx);
+ expect(colors).not.toHaveBeenCalled();
+ expect(strokes.filter((color) => color === '#123456')).toHaveLength(4);
+ expect(paints).toContainEqual({ text: enUS['docs-ui'].headerFooter.header, alpha: 1 });
+ expect(paints).toContainEqual({ text: enUS['docs-ui'].headerFooter.footer, alpha: 1 });
+ });
- expect(getColorFromTheme).not.toHaveBeenCalled();
+ it('does not apply editing emphasis or guides to modern documents', () => {
+ const { render, documents, manager, ctx, paints } = createTestBed(DocumentFlavor.MODERN);
+ render.addRenderDependencies([[DocHeaderFooterController]]);
+ render.with(DocHeaderFooterController);
+ manager.getViewModel().setEditArea(DocumentEditArea.HEADER);
+ documents.draw(ctx);
+ expect(paints.filter(({ text }) => text.trim())).toEqual([{ text: 'D', alpha: 1 }]);
+ });
- controller.dispose();
+ it('closes header/footer editing after rich-text changes in modern document mode', async () => {
+ const { injector, render, manager, model } = createTestBed(DocumentFlavor.MODERN);
+ const commands = injector.get(ICommandService);
+ commands.registerCommand(RichTextEditingMutation);
+ commands.registerCommand(CloseHeaderFooterCommand);
+ commands.registerCommand(SidebarDocHeaderFooterPanelOperation);
+ render.addRenderDependencies([[DocHeaderFooterController]]);
+ render.with(DocHeaderFooterController);
+ manager.getViewModel().setEditArea(DocumentEditArea.HEADER);
+ await commands.executeCommand(RichTextEditingMutation.id, { unitId: model.getUnitId(), actions: [], textRanges: [] });
+ expect(manager.getViewModel().getEditArea()).toBe(DocumentEditArea.BODY);
});
});
diff --git a/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts
index e90662d327..9048362103 100644
--- a/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts
+++ b/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts
@@ -440,6 +440,15 @@ describe('DocMoveCursorController movement helpers', () => {
expect(skipTokens).not.toContain(DataStreamTreeTokenType.COLUMN_GROUP_END);
});
+ it('keeps field boundary tokens out of cursor positions', () => {
+ const controller = createControllerHarness();
+
+ const skipTokens = controller._getCursorSkipTokens();
+
+ expect(skipTokens).toContain(DataStreamTreeTokenType.CUSTOM_RANGE_START);
+ expect(skipTokens).toContain(DataStreamTreeTokenType.CUSTOM_RANGE_END);
+ });
+
it('resolves document start and end offsets', () => {
const controller = createControllerHarness();
diff --git a/packages/docs-ui/src/controllers/doc-header-footer.controller.ts b/packages/docs-ui/src/controllers/doc-header-footer.controller.ts
index 8b459bd96f..e1c0e25e73 100644
--- a/packages/docs-ui/src/controllers/doc-header-footer.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-header-footer.controller.ts
@@ -33,26 +33,26 @@ import {
generateRandomId,
ICommandService,
Inject,
- IUniverInstanceService,
LocaleService,
ThemeService,
toDisposable,
- UniverInstanceType,
} from '@univerjs/core';
import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
-import { DocumentEditArea, IRenderManagerService, PageLayoutType, Path, Rect, Vector2 } from '@univerjs/engine-render';
+import { DocumentEditArea, DRAWING_OBJECT_UPPER_LAYER_INDEX, PageLayoutType, Path, Vector2 } from '@univerjs/engine-render';
import { neoGetDocObject } from '../basics/component-tools';
import { CloseHeaderFooterCommand, CoreHeaderFooterCommand } from '../commands/commands/doc-header-footer.command';
import { IEditorService } from '../services/editor/editor-manager.service';
import { DocSelectionRenderService } from '../services/selection/doc-selection-render.service';
import { getHeaderFooterTarget } from '../utils/section-header-footer';
+import { HeaderFooterContentCover } from '../views/header-footer/content-cover';
import { TextBubbleShape } from '../views/header-footer/text-bubble';
-const HEADER_FOOTER_COVER_ALPHA = 0.5;
+const INACTIVE_AREA_OPACITY = 0.5;
const HEADER_FOOTER_LABEL_ALPHA = 0.08;
export class DocHeaderFooterController extends Disposable implements IRenderModule {
private _loadedMap = new WeakSet<RenderComponentType>();
+ private _contentCover?: HeaderFooterContentCover;
private _headerFooterColors = {
primary: '',
cover: '',
@@ -63,8 +63,6 @@ export class DocHeaderFooterController extends Disposable implements IRenderModu
private readonly _context: IRenderContext<DocumentDataModel>,
@ICommandService private readonly _commandService: ICommandService,
@IEditorService private readonly _editorService: IEditorService,
- @IUniverInstanceService private readonly _instanceSrv: IUniverInstanceService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
@Inject(DocSelectionRenderService) private readonly _docSelectionRenderService: DocSelectionRenderService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
@@ -89,12 +87,16 @@ export class DocHeaderFooterController extends Disposable implements IRenderModu
this._headerFooterColors = {
primary,
cover: new ColorKit(this._themeService.getColorFromTheme('gray.0'))
- .setAlpha(HEADER_FOOTER_COVER_ALPHA)
+ .setAlpha(INACTIVE_AREA_OPACITY)
.toRgbString(),
label: new ColorKit(primary)
.setAlpha(HEADER_FOOTER_LABEL_ALPHA)
.toRgbString(),
};
+ if (this._contentCover) {
+ this._contentCover.color = this._headerFooterColors.cover;
+ this._contentCover.makeDirty(true);
+ }
}));
}
@@ -244,31 +246,28 @@ export class DocHeaderFooterController extends Disposable implements IRenderModu
}
private _drawHeaderFooterLabel() {
- this.disposeWithMe(this._instanceSrv.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_DOC).subscribe((unit) => {
- if (unit == null) {
- return;
- }
-
- const unitId = unit.getUnitId();
- const currentRender = this._renderManagerService.getRenderUnitById(unitId);
- if (this._editorService.isEditor(unitId) || this._instanceSrv.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC) == null) {
- return;
- }
-
- if (currentRender == null) {
- return;
- }
-
- const { mainComponent } = currentRender;
-
- const docsComponent = mainComponent as Documents;
+ const { unitId, mainComponent } = this._context;
+ if (this._editorService.isEditor(unitId) || mainComponent == null) {
+ return;
+ }
- this.disposeWithMe(
- toDisposable(
- docsComponent.pageRender$.subscribe((config: IPageRenderConfig) => this._drawHeaderFooterPage(config, unitId))
- )
- );
+ const docsComponent = mainComponent as Documents;
+ const cover = new HeaderFooterContentCover(`${unitId}-header-footer-cover`, docsComponent, this._context.scene);
+ cover.color = this._headerFooterColors.cover;
+ this._contentCover = cover;
+ this._context.scene.addObject(cover, DRAWING_OBJECT_UPPER_LAYER_INDEX);
+ this.disposeWithMe(cover);
+ this.disposeWithMe(toDisposable(() => {
+ this._contentCover = undefined;
}));
+ docsComponent.setInactiveAreaOpacity(INACTIVE_AREA_OPACITY);
+ this.disposeWithMe(toDisposable(() => docsComponent.setInactiveAreaOpacity(1)));
+ this.disposeWithMe(this._docSkeletonManagerService.getViewModel().editAreaChange$.subscribe(() => {
+ docsComponent.makeDirty(true);
+ }));
+ this.disposeWithMe(
+ docsComponent.pageRender$.subscribe((config: IPageRenderConfig) => this._drawHeaderFooterPage(config, unitId))
+ );
}
private _drawHeaderFooterPage(config: IPageRenderConfig, unitId: string): void {
@@ -277,53 +276,15 @@ export class DocHeaderFooterController extends Disposable implements IRenderModu
}
const editArea = this._docSkeletonManagerService.getViewModel().getEditArea();
- const isEditBody = editArea === DocumentEditArea.BODY;
+ if (editArea === DocumentEditArea.BODY) {
+ return;
+ }
const { pageLeft, pageTop, ctx } = config;
ctx.save();
ctx.translate(pageLeft - 0.5, pageTop - 0.5);
- this._drawHeaderFooterCover(config, isEditBody);
-
- if (!isEditBody) {
- this._drawHeaderFooterGuides(config);
- }
-
- ctx.restore();
- }
+ this._drawHeaderFooterGuides(config);
- private _drawHeaderFooterCover({ page, ctx }: IPageRenderConfig, isEditBody: boolean): void {
- const { pageWidth, pageHeight, marginTop, marginBottom } = page;
-
- if (isEditBody) {
- Rect.drawWith(ctx, {
- left: 0,
- top: 0,
- width: pageWidth,
- height: marginTop,
- fill: this._headerFooterColors.cover,
- });
- ctx.save();
- ctx.translate(0, pageHeight - marginBottom);
- Rect.drawWith(ctx, {
- left: 0,
- top: 0,
- width: pageWidth,
- height: marginBottom,
- fill: this._headerFooterColors.cover,
- });
- ctx.restore();
- return;
- }
-
- ctx.save();
- ctx.translate(0, marginTop);
- Rect.drawWith(ctx, {
- left: 0,
- top: marginTop,
- width: pageWidth,
- height: pageHeight - marginTop - marginBottom,
- fill: this._headerFooterColors.cover,
- });
ctx.restore();
}
diff --git a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
index 8a3594b200..e0f404fe89 100644
--- a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
@@ -387,6 +387,10 @@ export class DocMoveCursorController extends Disposable {
return;
}
+ if (this._deferUnmaterializedCursorMove(docDataModel, skeleton, cursor, normalizedSegmentId, () => this._handleMoveCursor(direction, granularity))) {
+ return;
+ }
+
cursor = this._normalizeRenderableCursorOffset(
skeleton,
body.dataStream,
@@ -564,6 +568,40 @@ export class DocMoveCursorController extends Disposable {
}
}
+ private _deferUnmaterializedCursorMove(
+ doc: DocumentDataModel,
+ skeleton: DocumentSkeleton,
+ offset: number,
+ segmentId: string,
+ resume: () => void
+ ): boolean {
+ if (segmentId !== '') {
+ return false;
+ }
+ const pageIndex = skeleton.findBodyPageIndexByCharIndex(offset);
+ const page = skeleton.getSkeletonData()?.pages[pageIndex];
+ if (pageIndex >= 0 && !page?.isMaterializationPlaceholder) {
+ return false;
+ }
+ const render = this._renderManagerService.getRenderUnitById(doc.getUnitId());
+ if (!render?.getInjector?.().has(DocBackScrollRenderController)) {
+ return false;
+ }
+ const selection = this._textSelectionManagerService.getActiveTextRange();
+ const dataStream = doc.getBody()?.dataStream;
+ // An offscreen page has no glyphs yet; it is not an invalid cursor target.
+ // Reuse bounded navigation and its pointer/scroll cancellation before finding caret geometry.
+ render.with(DocBackScrollRenderController).scrollToRange({ startOffset: offset, endOffset: offset, collapsed: true }, () => {
+ const current = this._textSelectionManagerService.getActiveTextRange();
+ if (doc.getBody()?.dataStream === dataStream && current?.startOffset === selection?.startOffset &&
+ current?.endOffset === selection?.endOffset && current?.segmentId === selection?.segmentId &&
+ this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)?.getUnitId() === doc.getUnitId()) {
+ resume();
+ }
+ });
+ return true;
+ }
+
private _getCursorOffsetByGranularity(
skeleton: DocumentSkeleton,
focusOffset: number,
@@ -869,6 +907,8 @@ export class DocMoveCursorController extends Disposable {
DataStreamTreeTokenType.SECTION_BREAK,
DataStreamTreeTokenType.BLOCK_START,
DataStreamTreeTokenType.BLOCK_END,
+ DataStreamTreeTokenType.CUSTOM_RANGE_START,
+ DataStreamTreeTokenType.CUSTOM_RANGE_END,
];
if (includeParagraph) {
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/back-scroll.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/back-scroll.render-controller.spec.ts
index 9b88b9885f..16ff2a3fb9 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/back-scroll.render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/back-scroll.render-controller.spec.ts
@@ -132,13 +132,17 @@ beforeEach(() => {
const context = new Proxy({
font: '',
webkitBackingStorePixelRatio: 1,
- measureText: (text: string) => ({
- width: text.length * 8,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
- fontBoundingBoxAscent: 8,
- fontBoundingBoxDescent: 2,
- }),
+ measureText(text: string) {
+ const font = /([\d.]+)(px|pt)/.exec(this.font);
+ const fontSize = Number(font?.[1] ?? 10) * (font?.[2] === 'pt' ? 4 / 3 : 1);
+ return {
+ width: text.length * fontSize * 0.6,
+ actualBoundingBoxAscent: fontSize * 0.8,
+ actualBoundingBoxDescent: fontSize * 0.2,
+ fontBoundingBoxAscent: fontSize * 0.8,
+ fontBoundingBoxDescent: fontSize * 0.2,
+ };
+ },
}, { get: (target, key) => key in target ? Reflect.get(target, key) : () => {} });
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context as never);
});
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts
index 6e2268ec22..40426cc8c2 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts
@@ -17,7 +17,7 @@
// @vitest-environment jsdom
import type { IDocumentData } from '@univerjs/core';
-import type { RenderUnit } from '@univerjs/engine-render';
+import type { IDocSelectionInnerParam, RenderUnit } from '@univerjs/engine-render';
import {
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
DocumentFlavor,
@@ -97,7 +97,7 @@ function createEventSubject() {
};
}
-function createController(options: { readonly?: boolean; hasEditor?: boolean; preserveHostFocus?: boolean; embedRecentInteraction?: boolean; embedContains?: boolean; mobile?: boolean; editing?: boolean; mobileEditMode?: boolean; focusing?: boolean; activeOffset?: number; nextActiveOffset?: number; documentFlavor?: DocumentFlavor; scale?: number; unitId?: string; currentSelectionUnitId?: string; embedRuntimeFocusCoordinator?: EmbedRuntimeFocusCoordinator } = {}) {
+function createController(options: { readonly?: boolean; hasEditor?: boolean; preserveHostFocus?: boolean; embedRecentInteraction?: boolean; embedContains?: boolean; mobile?: boolean; editing?: boolean; mobileEditMode?: boolean; focusing?: boolean; activeOffset?: number; nextActiveOffset?: number; documentFlavor?: DocumentFlavor; scale?: number; unitId?: string; currentSelectionUnitId?: string; currentSelection?: Pick<IDocSelectionInnerParam, 'isEditing' | 'rectRanges' | 'textRanges'>; embedRuntimeFocusCoordinator?: EmbedRuntimeFocusCoordinator } = {}) {
const refreshSelection$ = new Subject<any>();
const textSelectionInner$ = new Subject<any>();
const currentSkeleton$ = new Subject<any>();
@@ -175,6 +175,7 @@ function createController(options: { readonly?: boolean; hasEditor?: boolean; pr
addDocRanges: vi.fn(),
replaceDocRanges: vi.fn(),
textSelectionInner$,
+ canFocusing: true,
focus: vi.fn(),
__onPointDown: vi.fn(),
__handleDblClick: vi.fn(),
@@ -196,6 +197,7 @@ function createController(options: { readonly?: boolean; hasEditor?: boolean; pr
refreshSelection$,
__replaceTextRangesWithNoRefresh: vi.fn(),
__getCurrentSelection: vi.fn(() => ({ unitId: options.currentSelectionUnitId ?? options.unitId ?? 'doc-1' })),
+ getSelectionInfo: vi.fn(() => options.currentSelection),
refreshSelection: vi.fn(),
replaceDocRanges: vi.fn(),
replaceSelectionInfoWithoutRefresh: vi.fn(),
@@ -419,8 +421,13 @@ describe('DocSelectionRenderController', () => {
render.scene.addObject(documents);
const viewport = new Viewport(VIEWPORT_KEY.VIEW_MAIN, render.scene, { left: 0, top: 0, width: 400, height: 600, active: true });
viewport.resetCanvasSizeAndUpdateScroll();
+ const peerEditor = document.createElement('textarea');
+ peerEditor.dataset.uComp = 'editor';
+ root.appendChild(peerEditor);
+ peerEditor.focus();
render.addRenderDependencies([[DocSelectionRenderService], [DocSelectionRenderController]]);
render.with(DocSelectionRenderController);
+ expect(document.activeElement).toBe(peerEditor);
const selections = injector.get(DocSelectionManagerService);
expect(selections.getActiveTextRange()?.startOffset).toBe(0);
@@ -494,6 +501,25 @@ describe('DocSelectionRenderController', () => {
controller.dispose();
});
+ it('preserves an existing caret when a document edit rebuilds the skeleton', () => {
+ const currentSelection = {
+ textRanges: [{ startOffset: 242, endOffset: 242, collapsed: true, isActive: true }],
+ rectRanges: [],
+ isEditing: true,
+ };
+ const { controller, currentSkeleton$, docSelectionManagerService } = createController({ currentSelection });
+
+ currentSkeleton$.next({ id: 'rebuilt-skeleton' });
+
+ expect(docSelectionManagerService.replaceSelectionInfoWithoutRefresh).not.toHaveBeenCalled();
+ expect(docSelectionManagerService.refreshSelection).toHaveBeenCalledWith(
+ { unitId: 'doc-1', subUnitId: 'doc-1' },
+ true
+ );
+
+ controller.dispose();
+ });
+
it('does not refresh host document selection while a child session owns focus during zoom refreshes', () => {
const focusCoordinator = new EmbedRuntimeFocusCoordinator();
const lease = focusCoordinator.acquireLease({
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts
index ef47252654..e999c601c2 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts
@@ -33,6 +33,7 @@ import {
ObjectRelativeFromH,
ObjectRelativeFromV,
PositionedObjectLayoutType,
+ SpacingRule,
Univer,
UniverInstanceType,
} from '@univerjs/core';
@@ -47,6 +48,7 @@ import {
} from '@univerjs/docs';
import {
CanvasColorService,
+ FontCache,
ICanvasColorService,
IRenderManagerService,
RenderManagerService,
@@ -79,7 +81,7 @@ import { MobileDocBackScrollRenderController } from '../mobile/back-scroll.rende
import { MobileDocSelectionRenderController } from '../mobile/doc-selection-render.controller';
import { MobileDocRenderController } from '../mobile/doc.render-controller';
-function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayout = false, documentFlavor = DocumentFlavor.TRADITIONAL, withFootnote = false, mobile = false) {
+function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayout = false, documentFlavor = DocumentFlavor.TRADITIONAL, withFootnote = false, mobile = false, renderingFontsReady?: Promise<void>) {
if (workerBeforeLayout) {
// Model computation cost separately from fake timers so foreground work yields before Worker handoff.
let elapsed = 0;
@@ -104,6 +106,7 @@ function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayout
// must still hand off before Main paginates the entire document.
const registerWorker = () => injector.get(DocLayoutExecutorService).register({
type: 'worker',
+ renderingFontsReady,
initialize: () => new Promise<void>(() => {}),
disposeSession: async () => {},
} as unknown as IDocLayoutExecutor);
@@ -146,7 +149,12 @@ function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayout
notes: withFootnote
? { note: { type: 'footnote' as const, noteId: 'note', body: {
dataStream: noteStream,
- paragraphs: [...noteStream.matchAll(/\r/g)].map((match, index) => ({ startIndex: match.index!, paragraphId: `note-${index}` })),
+ // Explicit leading guarantees a continuation page independently of mocked glyph advances.
+ paragraphs: [...noteStream.matchAll(/\r/g)].map((match, index) => ({
+ startIndex: match.index!,
+ paragraphId: `note-${index}`,
+ paragraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: 24 },
+ })),
} } }
: undefined,
body: {
@@ -263,28 +271,33 @@ describe('DocRenderController bounded input publication', () => {
const context = new Proxy({
font: '',
webkitBackingStorePixelRatio: 1,
- measureText: (text: string) => ({
- width: text.length * 8,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
- fontBoundingBoxAscent: 8,
- fontBoundingBoxDescent: 2,
- }),
+ measureText(text: string) {
+ const fontSize = /(\d+(?:\.\d+)?)(pt|px)/.exec(this.font);
+ const points = fontSize ? Number(fontSize[1]) * (fontSize[2] === 'px' ? 0.75 : 1) : 14;
+ const scale = points / 14;
+ return {
+ width: text.length * 8 * scale,
+ actualBoundingBoxAscent: 8 * scale,
+ actualBoundingBoxDescent: 2 * scale,
+ fontBoundingBoxAscent: 8 * scale,
+ fontBoundingBoxDescent: 2 * scale,
+ };
+ },
}, { get: (target, key) => key in target ? Reflect.get(target, key) : () => {} });
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context as never);
const getBoundingClientRect = HTMLElement.prototype.getBoundingClientRect;
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
// Match the fixture's 14pt Canvas metrics; jsdom returns zero and cannot cache normal leading.
if (this.style.visibility === 'hidden' && this.style.whiteSpace === 'pre' && this.style.lineHeight === 'normal') {
- const fontSize = Number.parseFloat(this.style.fontSize);
- const pointsPerUnit = this.style.fontSize.endsWith('px') ? 3 / 4 : 1;
const lineCount = (this.textContent ?? '').split('\n').length;
- const metrics = context.measureText('Hg');
+ const metrics = context.measureText.call({ font: this.style.font }, 'Hg');
const lineHeight = metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent;
- return new DOMRect(0, 0, 0, fontSize * pointsPerUnit / 14 * lineHeight * lineCount);
+ return new DOMRect(0, 0, 0, lineHeight * lineCount);
}
return getBoundingClientRect.call(this);
});
+ Reflect.set(FontCache, '_context', null);
+ FontCache.invalidateMetrics(() => true);
});
afterEach(() => {
vi.restoreAllMocks();
@@ -299,6 +312,7 @@ describe('DocRenderController bounded input publication', () => {
const pages = editor.skeleton.getSkeletonData()!.pages;
const oldPage = pages.findIndex((page) => page.notes?.some((note) => note.noteId === 'note'));
const boundary = pages[oldPage].notes![0].page.ed;
+ expect(boundary).toBeLessThan(editor.model.getSnapshot().notes!.note.body.dataStream.length - 2);
editor.selectionManager.replaceDocRanges([{
startOffset: boundary,
endOffset: boundary,
@@ -306,6 +320,7 @@ describe('DocRenderController bounded input publication', () => {
segmentPage: oldPage,
}], { unitId: editor.unitId, subUnitId: editor.unitId }, true);
expect(await editor.commands.executeCommand(BreakLineCommand.id)).toBe(true);
+ expect(editor.selectionManager.getActiveTextRange()?.endOffset).toBe(boundary + 1);
for (const text of ['A', ' ', '中', 'B']) {
editor.input.textContent = text;
editor.input.dispatchEvent(new InputEvent('input', { data: text, inputType: 'insertText' }));
@@ -396,6 +411,39 @@ describe('DocRenderController bounded input publication', () => {
}
});
+ it('does not publish fallback-font pages while explicitly configured fonts are pending', async () => {
+ let finishFonts!: () => void;
+ const fontsReady = new Promise<void>((resolve) => {
+ finishFonts = resolve;
+ });
+ const editor = createEditor(1, false, true, DocumentFlavor.TRADITIONAL, false, false, fontsReady);
+ try {
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(editor.skeleton.getSkeletonData()?.pages.length ?? 0).toBe(0);
+ expect(editor.startWorkerLayout).not.toHaveBeenCalled();
+ finishFonts();
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(editor.skeleton.hasCompleteLayout()).toBe(true);
+ expect(editor.skeleton.getSkeletonData()!.pages.length).toBe(1);
+ } finally {
+ editor.dispose();
+ }
+ });
+
+ it('does not restart a disposed document when its configured fonts finish loading', async () => {
+ let finishFonts!: () => void;
+ const fontsReady = new Promise<void>((resolve) => {
+ finishFonts = resolve;
+ });
+ const editor = createEditor(1, false, true, DocumentFlavor.TRADITIONAL, false, false, fontsReady);
+ await vi.advanceTimersByTimeAsync(1_000);
+ editor.dispose();
+ finishFonts();
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(editor.startWorkerLayout).not.toHaveBeenCalled();
+ expect(editor.skeleton.getSkeletonData()?.pages.length ?? 0).toBe(0);
+ });
+
it('publishes the initial caret as soon as the first foreground page is ready', async () => {
const editor = createEditor(500, false, true);
try {
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts
index 7f445d6574..33ffadc204 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts
@@ -358,8 +358,10 @@ export class DocSelectionRenderController extends Disposable implements IRenderM
}
this._initialSelectionReady = true;
- //TODO: @JOCS Only for docs. move to docs in the future.
- this._docSelectionRenderService.focus();
+ // A background document may finish its first layout after the user switches editors.
+ if (this._docSelectionRenderService.canFocusing) {
+ this._docSelectionRenderService.focus();
+ }
const docDataModel = this._context.unit;
const snapshot = docDataModel.getSnapshot();
const offset = findFirstCursorOffset(snapshot);
@@ -367,6 +369,14 @@ export class DocSelectionRenderController extends Disposable implements IRenderM
unitId,
subUnitId: unitId,
};
+ const currentSelection = this._docSelectionManagerService.getSelectionInfo(selectionTarget);
+ if (currentSelection && (currentSelection.textRanges.length > 0 || currentSelection.rectRanges.length > 0)) {
+ this._docSelectionManagerService.refreshSelection(
+ selectionTarget,
+ currentSelection.isEditing
+ );
+ return;
+ }
this._docSelectionManagerService.replaceSelectionInfoWithoutRefresh({
textRanges: [{
startOffset: offset,
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
index 1c84b2c2d3..33eed86873 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
@@ -508,6 +508,7 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
private _isMaterializingPages = false;
private _reservedLayoutWidth = 0;
private _reservedLayoutHeight = 0;
+ private _fontInitialization: Promise<void> | null = null;
constructor(
protected readonly _context: IRenderContext<DocumentDataModel>,
@@ -633,6 +634,7 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
this._pendingWorkerEditBatch = null;
this._pendingChangesetLayoutRequest = null;
this._latestLayoutRestart = null;
+ this._fontInitialization = null;
this._pendingImeLayoutRestart = null;
this._pendingMaterializedPageRange = null;
this._recoveryViewportAnchor = null;
@@ -678,7 +680,7 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
this._cancelWorkerHandoff();
const isInitialLayout = options.reason === 'initial';
const docsComponent = this._context.mainComponent;
- if (!(docsComponent instanceof Documents)) {
+ if (!(docsComponent instanceof Documents) || this._waitForConfiguredFonts(layoutRequestId)) {
return;
}
this._prepareReservedLayoutExtent(skeleton, docsComponent);
@@ -734,6 +736,22 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
);
}
+ private _waitForConfiguredFonts(layoutRequestId: number): boolean {
+ const initialization = this._docLayoutExecutorService.getExecutor()?.renderingFontsReady;
+ if (initialization == null || this._fontInitialization === initialization) {
+ return false;
+ }
+ // Do not publish fallback-font geometry that becomes stale as web fonts finish loading.
+ initialization.then(() => {
+ if (this._disposed || layoutRequestId !== this._layoutRequestId) {
+ return;
+ }
+ this._fontInitialization = initialization;
+ this._latestLayoutRestart?.();
+ }, (error) => this._logService.error('[DocRenderController]: configured document fonts failed to initialize.', error));
+ return true;
+ }
+
private _scheduleInitialInteractionWindow(
layoutRequestId: number,
unitId: string,
diff --git a/packages/docs-ui/src/facade/__tests__/f-document.spec.ts b/packages/docs-ui/src/facade/__tests__/f-document.spec.ts
index 4b3c128043..3640fdac0a 100644
--- a/packages/docs-ui/src/facade/__tests__/f-document.spec.ts
+++ b/packages/docs-ui/src/facade/__tests__/f-document.spec.ts
@@ -97,7 +97,7 @@ function createEditor() {
const skeleton = render.with(DocSkeletonManagerService).getSkeleton();
const pages = skeleton.getSkeletonData()!.pages;
const page = pages[6];
- expect(page).toBeDefined();
+ expect(page, `Offscreen target requires seven pages; layout produced ${pages.length}`).toBeDefined();
return {
doc: FUniver.newAPI(injector).getActiveDocument()!,
model,
@@ -125,13 +125,19 @@ describe('docs-ui document facade', () => {
const context = new Proxy({
font: '',
webkitBackingStorePixelRatio: 1,
- measureText: (text: string) => ({
- width: text.length * 8,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
- fontBoundingBoxAscent: 8,
- fontBoundingBoxDescent: 2,
- }),
+ measureText(this: CanvasRenderingContext2D, text: string) {
+ // Font shaping measures a large reference size, then scales it down.
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
+ const scale = points / 11;
+ return {
+ width: text.length * 8 * scale,
+ actualBoundingBoxAscent: 8 * scale,
+ actualBoundingBoxDescent: 2 * scale,
+ fontBoundingBoxAscent: 8 * scale,
+ fontBoundingBoxDescent: 2 * scale,
+ };
+ },
}, { get: (target, key) => key in target ? Reflect.get(target, key) : () => {} });
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context as never);
});
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index 1111e3426b..492082f834 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -179,6 +179,7 @@ export {
BackgroundColorSelectorMenuItemFactory,
BoldMenuItemFactory,
disableMenuWhenHeaderFooterEditing,
+ disableMenuWithoutDocumentUnitPermission,
FLOAT_TEXT_STYLE_MENU_ID,
FLOAT_TOOLBAR_MENU_POSITION,
FloatTextStyleMenuItemFactory,
@@ -236,6 +237,7 @@ export { convertBodyToHtml } from './services/clipboard/udm-to-html/convertor';
export { DocHtmlExportService } from './services/clipboard/udm-to-html/doc-html-export.service';
export type { DocHtmlExportTransformer } from './services/clipboard/udm-to-html/doc-html-export.service';
export { DocAutoFormatService } from './services/doc-auto-format.service';
+export { DocContextualRibbonService } from './services/doc-contextual-ribbon.service';
export {
DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE,
IDocEmbedInteractionBoundaryService,
@@ -268,6 +270,7 @@ export {
isValidRectRange,
NodePositionConvertToRectRange,
} from './services/selection/convert-rect-range';
+export { findDocRangeNodePositions } from './services/selection/convert-text-range';
export { NodePositionConvertToCursor } from './services/selection/convert-text-range';
export { getOneTextSelectionRange } from './services/selection/convert-text-range';
export type { IEditorInputConfig } from './services/selection/doc-selection-render.service';
diff --git a/packages/docs-ui/src/locale/ar-SA.ts b/packages/docs-ui/src/locale/ar-SA.ts
index bc473f3182..72e4694c8f 100644
--- a/packages/docs-ui/src/locale/ar-SA.ts
+++ b/packages/docs-ui/src/locale/ar-SA.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: 'التحديد الحالي',
wordCount: '{0} كلمة',
selectedWords: '{0} من {1} كلمة',
+ currentPage: 'الصفحة {0}',
+ currentPageOfTotal: 'الصفحة {0} من {1}',
pages: 'الصفحات',
words: 'الكلمات',
charactersWithoutSpaces: 'الأحرف (بدون مسافات)',
diff --git a/packages/docs-ui/src/locale/ca-ES.ts b/packages/docs-ui/src/locale/ca-ES.ts
index a32f9069a3..cacc75aa1a 100644
--- a/packages/docs-ui/src/locale/ca-ES.ts
+++ b/packages/docs-ui/src/locale/ca-ES.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: 'Selecció actual',
wordCount: '{0} paraules',
selectedWords: '{0} de {1} paraules',
+ currentPage: 'Pàgina {0}',
+ currentPageOfTotal: 'Pàgina {0} de {1}',
pages: 'Pàgines',
words: 'Paraules',
charactersWithoutSpaces: 'Caràcters (sense espais)',
diff --git a/packages/docs-ui/src/locale/de-DE.ts b/packages/docs-ui/src/locale/de-DE.ts
index f5b9ce3e63..4ff4204049 100644
--- a/packages/docs-ui/src/locale/de-DE.ts
+++ b/packages/docs-ui/src/locale/de-DE.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: 'Aktuelle Auswahl',
wordCount: '{0} Wörter',
selectedWords: '{0} von {1} Wörtern',
+ currentPage: 'Seite {0}',
+ currentPageOfTotal: 'Seite {0} von {1}',
pages: 'Seiten',
words: 'Wörter',
charactersWithoutSpaces: 'Zeichen (ohne Leerzeichen)',
diff --git a/packages/docs-ui/src/locale/en-US.ts b/packages/docs-ui/src/locale/en-US.ts
index bc7d77555b..befc44215c 100644
--- a/packages/docs-ui/src/locale/en-US.ts
+++ b/packages/docs-ui/src/locale/en-US.ts
@@ -124,6 +124,8 @@ const locale = {
selection: 'Current selection',
wordCount: '{0} words',
selectedWords: '{0} of {1} words',
+ currentPage: 'Page {0}',
+ currentPageOfTotal: 'Page {0} of {1}',
pages: 'Pages',
words: 'Words',
charactersWithoutSpaces: 'Characters (no spaces)',
diff --git a/packages/docs-ui/src/locale/es-ES.ts b/packages/docs-ui/src/locale/es-ES.ts
index 3736ad9b45..df7dd4f9ce 100644
--- a/packages/docs-ui/src/locale/es-ES.ts
+++ b/packages/docs-ui/src/locale/es-ES.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: 'Selección actual',
wordCount: '{0} palabras',
selectedWords: '{0} de {1} palabras',
+ currentPage: 'Página {0}',
+ currentPageOfTotal: 'Página {0} de {1}',
pages: 'Páginas',
words: 'Palabras',
charactersWithoutSpaces: 'Caracteres (sin espacios)',
diff --git a/packages/docs-ui/src/locale/fa-IR.ts b/packages/docs-ui/src/locale/fa-IR.ts
index 53e7018839..852cfeece3 100644
--- a/packages/docs-ui/src/locale/fa-IR.ts
+++ b/packages/docs-ui/src/locale/fa-IR.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: 'انتخاب فعلی',
wordCount: '{0} واژه',
selectedWords: '{0} از {1} واژه',
+ currentPage: 'صفحه {0}',
+ currentPageOfTotal: 'صفحه {0} از {1}',
pages: 'صفحه‌ها',
words: 'واژه‌ها',
charactersWithoutSpaces: 'نویسه‌ها (بدون فاصله)',
diff --git a/packages/docs-ui/src/locale/fr-FR.ts b/packages/docs-ui/src/locale/fr-FR.ts
index 3abda4d1f8..ecf922bab8 100644
--- a/packages/docs-ui/src/locale/fr-FR.ts
+++ b/packages/docs-ui/src/locale/fr-FR.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: 'Sélection actuelle',
wordCount: '{0} mots',
selectedWords: '{0} mots sur {1}',
+ currentPage: 'Page {0}',
+ currentPageOfTotal: 'Page {0} sur {1}',
pages: 'Pages',
words: 'Mots',
charactersWithoutSpaces: 'Caractères (sans espaces)',
diff --git a/packages/docs-ui/src/locale/id-ID.ts b/packages/docs-ui/src/locale/id-ID.ts
index a61db2d96e..42e3092388 100644
--- a/packages/docs-ui/src/locale/id-ID.ts
+++ b/packages/docs-ui/src/locale/id-ID.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: 'Pilihan saat ini',
wordCount: '{0} kata',
selectedWords: '{0} dari {1} kata',
+ currentPage: 'Halaman {0}',
+ currentPageOfTotal: 'Halaman {0} dari {1}',
pages: 'Halaman',
words: 'Kata',
charactersWithoutSpaces: 'Karakter (tanpa spasi)',
diff --git a/packages/docs-ui/src/locale/it-IT.ts b/packages/docs-ui/src/locale/it-IT.ts
index 6296474f3a..279d66bb7a 100644
--- a/packages/docs-ui/src/locale/it-IT.ts
+++ b/packages/docs-ui/src/locale/it-IT.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: 'Selezione corrente',
wordCount: '{0} parole',
selectedWords: '{0} di {1} parole',
+ currentPage: 'Pagina {0}',
+ currentPageOfTotal: 'Pagina {0} di {1}',
pages: 'Pagine',
words: 'Parole',
charactersWithoutSpaces: 'Caratteri (spazi esclusi)',
diff --git a/packages/docs-ui/src/locale/ja-JP.ts b/packages/docs-ui/src/locale/ja-JP.ts
index 5e678b4dbe..7629faa22d 100644
--- a/packages/docs-ui/src/locale/ja-JP.ts
+++ b/packages/docs-ui/src/locale/ja-JP.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: '現在の選択範囲',
wordCount: '{0} 語',
selectedWords: '{1} 語中 {0} 語',
+ currentPage: '{0} ページ',
+ currentPageOfTotal: '{1} ページ中 {0} ページ',
pages: 'ページ数',
words: '単語数',
charactersWithoutSpaces: '文字数(スペースを含めない)',
diff --git a/packages/docs-ui/src/locale/ko-KR.ts b/packages/docs-ui/src/locale/ko-KR.ts
index 39d1449a72..5a68a17715 100644
--- a/packages/docs-ui/src/locale/ko-KR.ts
+++ b/packages/docs-ui/src/locale/ko-KR.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: '현재 선택 영역',
wordCount: '{0}개 단어',
selectedWords: '{1}개 중 {0}개 단어',
+ currentPage: '{0}페이지',
+ currentPageOfTotal: '{1}페이지 중 {0}페이지',
pages: '페이지',
words: '단어',
charactersWithoutSpaces: '문자 수(공백 제외)',
diff --git a/packages/docs-ui/src/locale/pl-PL.ts b/packages/docs-ui/src/locale/pl-PL.ts
index 225ea25d47..c4342b328b 100644
--- a/packages/docs-ui/src/locale/pl-PL.ts
+++ b/packages/docs-ui/src/locale/pl-PL.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: 'Bieżące zaznaczenie',
wordCount: 'Liczba wyrazów: {0}',
selectedWords: 'Liczba wyrazów: {0} z {1}',
+ currentPage: 'Strona {0}',
+ currentPageOfTotal: 'Strona {0} z {1}',
pages: 'Strony',
words: 'Wyrazy',
charactersWithoutSpaces: 'Znaki (bez spacji)',
diff --git a/packages/docs-ui/src/locale/pt-BR.ts b/packages/docs-ui/src/locale/pt-BR.ts
index 856c9911a7..66716e4cc2 100644
--- a/packages/docs-ui/src/locale/pt-BR.ts
+++ b/packages/docs-ui/src/locale/pt-BR.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: 'Seleção atual',
wordCount: '{0} palavras',
selectedWords: '{0} de {1} palavras',
+ currentPage: 'Página {0}',
+ currentPageOfTotal: 'Página {0} de {1}',
pages: 'Páginas',
words: 'Palavras',
charactersWithoutSpaces: 'Caracteres (sem espaços)',
diff --git a/packages/docs-ui/src/locale/ru-RU.ts b/packages/docs-ui/src/locale/ru-RU.ts
index a160a08561..78a17bd088 100644
--- a/packages/docs-ui/src/locale/ru-RU.ts
+++ b/packages/docs-ui/src/locale/ru-RU.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: 'Текущее выделение',
wordCount: 'Слов: {0}',
selectedWords: 'Слов: {0} из {1}',
+ currentPage: 'Страница {0}',
+ currentPageOfTotal: 'Страница {0} из {1}',
pages: 'Страницы',
words: 'Слова',
charactersWithoutSpaces: 'Знаки (без пробелов)',
diff --git a/packages/docs-ui/src/locale/sk-SK.ts b/packages/docs-ui/src/locale/sk-SK.ts
index 4ee1b1945d..ba134c202a 100644
--- a/packages/docs-ui/src/locale/sk-SK.ts
+++ b/packages/docs-ui/src/locale/sk-SK.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: 'Aktuálny výber',
wordCount: 'Počet slov: {0}',
selectedWords: 'Počet slov: {0} z {1}',
+ currentPage: 'Strana {0}',
+ currentPageOfTotal: 'Strana {0} z {1}',
pages: 'Strany',
words: 'Slová',
charactersWithoutSpaces: 'Znaky (bez medzier)',
diff --git a/packages/docs-ui/src/locale/vi-VN.ts b/packages/docs-ui/src/locale/vi-VN.ts
index 7a4b782f44..cbe32d0142 100644
--- a/packages/docs-ui/src/locale/vi-VN.ts
+++ b/packages/docs-ui/src/locale/vi-VN.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: 'Vùng chọn hiện tại',
wordCount: '{0} từ',
selectedWords: '{0} trên {1} từ',
+ currentPage: 'Trang {0}',
+ currentPageOfTotal: 'Trang {0} trên {1}',
pages: 'Trang',
words: 'Từ',
charactersWithoutSpaces: 'Ký tự (không có dấu cách)',
diff --git a/packages/docs-ui/src/locale/zh-CN.ts b/packages/docs-ui/src/locale/zh-CN.ts
index e17ca6b1e2..0db8c055db 100644
--- a/packages/docs-ui/src/locale/zh-CN.ts
+++ b/packages/docs-ui/src/locale/zh-CN.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: '当前选区',
wordCount: '字数 {0}',
selectedWords: '字数 {0} / {1}',
+ currentPage: '第 {0} 页',
+ currentPageOfTotal: '第 {0} 页,共 {1} 页',
pages: '页数',
words: '字数',
charactersWithoutSpaces: '字符数(不计空格)',
diff --git a/packages/docs-ui/src/locale/zh-HK.ts b/packages/docs-ui/src/locale/zh-HK.ts
index 3ec179da39..d9543e7b11 100644
--- a/packages/docs-ui/src/locale/zh-HK.ts
+++ b/packages/docs-ui/src/locale/zh-HK.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: '目前選取範圍',
wordCount: '字數 {0}',
selectedWords: '字數 {0} / {1}',
+ currentPage: '第 {0} 頁',
+ currentPageOfTotal: '第 {0} 頁,共 {1} 頁',
pages: '頁數',
words: '字數',
charactersWithoutSpaces: '字元數(不計空格)',
diff --git a/packages/docs-ui/src/locale/zh-TW.ts b/packages/docs-ui/src/locale/zh-TW.ts
index e3bee68cc3..f854fc1dd5 100644
--- a/packages/docs-ui/src/locale/zh-TW.ts
+++ b/packages/docs-ui/src/locale/zh-TW.ts
@@ -126,6 +126,8 @@ const locale: typeof enUS = {
selection: '目前選取範圍',
wordCount: '字數 {0}',
selectedWords: '字數 {0} / {1}',
+ currentPage: '第 {0} 頁',
+ currentPageOfTotal: '第 {0} 頁,共 {1} 頁',
pages: '頁數',
words: '字數',
charactersWithoutSpaces: '字元數(不計空格)',
diff --git a/packages/docs-ui/src/menu/schema.ts b/packages/docs-ui/src/menu/schema.ts
index 8c23821ed1..c387657494 100644
--- a/packages/docs-ui/src/menu/schema.ts
+++ b/packages/docs-ui/src/menu/schema.ts
@@ -335,7 +335,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonInsertGroup.MEDIA]: {
[TABLE_MENU_ID]: {
order: 2,
- gridLayout: { row: 1, column: 1, rowSpan: 2, showLabel: true },
+ gridLayout: { row: 1, column: 2 },
menuItemFactory: TableMenuFactory,
[DocCreateTableOperation.id]: {
order: 0,
@@ -343,13 +343,13 @@ export const menuSchema: MenuSchemaType = {
},
},
[HorizontalLineCommand.id]: {
- order: 3,
- gridLayout: { row: 1, column: 2, rowSpan: 2, showLabel: true },
+ order: 4,
+ gridLayout: { row: 2, column: 5 },
menuItemFactory: HorizontalLineFactory,
},
[DOC_BREAKS_MENU_ID]: {
order: 4,
- gridLayout: { row: 1, column: 3, rowSpan: 2, showLabel: true },
+ gridLayout: { row: 1, column: 1, rowSpan: 2, showLabel: true },
menuItemFactory: BreaksMenuFactory,
[InsertDocumentColumnBreakOperation.id]: {
order: 0,
@@ -378,12 +378,12 @@ export const menuSchema: MenuSchemaType = {
},
[DOC_INSERT_EMOJI_MENU_ID]: {
order: 5,
- gridLayout: { row: 1, column: 4 },
+ gridLayout: { row: 1, column: 3 },
menuItemFactory: EmojiPickerMenuItemFactory,
},
[DOC_INSERT_SYMBOL_MENU_ID]: {
order: 6,
- gridLayout: { row: 2, column: 4 },
+ gridLayout: { row: 2, column: 3 },
menuItemFactory: SymbolPickerMenuItemFactory,
},
},
diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.ts
index bc1c409c83..d3e8bd4e32 100644
--- a/packages/docs-ui/src/plugin.ts
+++ b/packages/docs-ui/src/plugin.ts
@@ -178,6 +178,7 @@ import {
} from './services/clipboard/doc-paste-mutation-adapter.service';
import { DocHtmlExportService } from './services/clipboard/udm-to-html/doc-html-export.service';
import { DocAutoFormatService } from './services/doc-auto-format.service';
+import { DocContextualRibbonService } from './services/doc-contextual-ribbon.service';
import { DocEventManagerService } from './services/doc-event-manager.service';
import { DocIMEInputManagerService } from './services/doc-ime-input-manager.service';
import { DocIMEStateChangeInterceptorService } from './services/doc-ime-state-change-interceptor.service';
@@ -464,6 +465,7 @@ export class UniverDocsUIPlugin extends Plugin {
[IDocStateChangeInterceptorService, { useClass: DocIMEStateChangeInterceptorService }],
[DocAutoFormatService],
[DocMenuStyleService],
+ [DocContextualRibbonService],
], this._config.override);
dependencies.forEach((d) => injector.add(d));
diff --git a/packages/docs-ui/src/services/__tests__/doc-contextual-ribbon.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-contextual-ribbon.service.spec.ts
new file mode 100644
index 0000000000..4f695c758e
--- /dev/null
+++ b/packages/docs-ui/src/services/__tests__/doc-contextual-ribbon.service.spec.ts
@@ -0,0 +1,146 @@
+/**
+ * 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 { MenuSchemaType } from '@univerjs/ui';
+import {
+ ConfigService,
+ ContextService,
+ DesktopLogService,
+ IConfigService,
+ IContextService,
+ ILogService,
+ Injector,
+ IUniverInstanceService,
+ UniverInstanceService,
+} from '@univerjs/core';
+import {
+ DesktopRibbonService,
+ IMenuManagerService,
+ IRibbonService,
+ MenuManagerPosition,
+ MenuManagerService,
+ RibbonPosition,
+} from '@univerjs/ui';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { DocContextualRibbonService } from '../doc-contextual-ribbon.service';
+
+describe('DocContextualRibbonService', () => {
+ let injector: Injector;
+ let service: DocContextualRibbonService;
+ let ribbon: IRibbonService;
+ let active: string;
+ let visible: string[];
+
+ beforeEach(() => {
+ injector = new Injector([
+ [IConfigService, { useClass: ConfigService }],
+ [IContextService, { useClass: ContextService }],
+ [ILogService, { useClass: DesktopLogService }],
+ [IUniverInstanceService, { useClass: UniverInstanceService }],
+ [IMenuManagerService, { useClass: MenuManagerService }],
+ [IRibbonService, { useClass: DesktopRibbonService }],
+ [DocContextualRibbonService],
+ ]);
+ for (const [order, tab] of [RibbonPosition.START, RibbonPosition.INSERT, 'table', 'sdt', 'shape'].entries()) {
+ injector.get(IMenuManagerService).appendRootMenu({
+ [MenuManagerPosition.RIBBON]: {
+ [tab]: {
+ order,
+ contextual: order > 1,
+ group: { order: 0, command: { order: 0, menuItemFactory: () => ({ id: `${tab}-command` }) } },
+ },
+ },
+ } as MenuSchemaType);
+ }
+ ribbon = injector.get(IRibbonService);
+ ribbon.activatedTab$.subscribe((tab) => active = tab);
+ ribbon.ribbon$.subscribe((tabs) => visible = tabs.map((tab) => tab.key));
+ service = injector.get(DocContextualRibbonService);
+ ribbon.setActivatedTab(RibbonPosition.INSERT);
+ });
+
+ afterEach(() => injector.dispose());
+
+ it.each([true, false])('keeps SDT active regardless of selection notification order (table first: %s)', (tableFirst) => {
+ if (tableFirst) {
+ service.setTableTab('table', true);
+ }
+ service.setContentControlTab('sdt', true);
+ service.setTableTab('table', true);
+ expect(active).toBe('sdt');
+ expect(visible).toEqual(expect.arrayContaining(['table', 'sdt']));
+
+ service.setContentControlTab('sdt', false);
+ expect(active).toBe('table');
+ service.setTableTab('table', false);
+ expect(active).toBe(RibbonPosition.INSERT);
+ expect(visible).not.toContain('sdt');
+ expect(visible).not.toContain('table');
+ });
+
+ it.each([RibbonPosition.START, RibbonPosition.INSERT, 'table'])('preserves manual choice %s while leaving a control', (tab) => {
+ service.setTableTab('table', true);
+ service.setContentControlTab('sdt', true);
+ ribbon.setActivatedTab(tab);
+ service.setTableTab('table', true);
+ service.setContentControlTab('sdt', true);
+ expect(active).toBe(tab);
+ service.setContentControlTab('sdt', false);
+ expect(active).toBe(tab);
+ });
+
+ it('does not steal a manual tab when the containing table reports its selection later', () => {
+ service.setContentControlTab('sdt', true);
+ ribbon.setActivatedTab(RibbonPosition.START);
+ service.setTableTab('table', true);
+ expect(active).toBe(RibbonPosition.START);
+ service.setTableTab('table', false);
+ expect(active).toBe(RibbonPosition.START);
+ });
+
+ it('keeps a standalone control active after leaving its containing table', () => {
+ service.setTableTab('table', true);
+ service.setContentControlTab('sdt', true);
+ service.setTableTab('table', false);
+ expect(active).toBe('sdt');
+ service.setContentControlTab('sdt', false);
+ expect(active).toBe(RibbonPosition.INSERT);
+ service.setTableTab('table', true);
+ expect(active).toBe('table');
+ });
+
+ it('does not change other products contextual activation or fallback', () => {
+ service.setContentControlTab('sdt', true);
+ ribbon.showContextualTab('shape', { activate: true });
+ expect(active).toBe('shape');
+ service.setContentControlTab('sdt', false);
+ expect(active).toBe('shape');
+ ribbon.hideContextualTab('shape');
+ expect(active).toBe(RibbonPosition.INSERT);
+ });
+
+ it('hides its own tabs on disposal without hiding another contextual tab', () => {
+ service.setTableTab('table', true);
+ service.setContentControlTab('sdt', true);
+ ribbon.showContextualTab('shape', { activate: true });
+ service.dispose();
+ service.dispose();
+ expect(active).toBe('shape');
+ expect(visible).toContain('shape');
+ expect(visible).not.toContain('table');
+ expect(visible).not.toContain('sdt');
+ });
+});
diff --git a/packages/docs-ui/src/services/__tests__/doc-event-manager.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-event-manager.service.spec.ts
index 3537b19755..e098db3ce9 100644
--- a/packages/docs-ui/src/services/__tests__/doc-event-manager.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-event-manager.service.spec.ts
@@ -16,9 +16,27 @@
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
import type { IPointerEvent, RenderUnit } from '@univerjs/engine-render';
-import { BooleanNumber, CustomRangeType, DocumentFlavor, EventState, EventSubject, Injector, PresetListType, Univer, UniverInstanceType } from '@univerjs/core';
+import {
+ BooleanNumber,
+ CustomRangeType,
+ DocumentFlavor,
+ EventState,
+ EventSubject,
+ Injector,
+ PresetListType,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
import { DocLayoutExecutorService, DocSkeletonManagerService } from '@univerjs/docs';
-import { CanvasColorService, Documents, ICanvasColorService, IRenderManagerService, RenderManagerService, setDocsTableRenderViewportProvider, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';
+import {
+ CanvasColorService,
+ Documents,
+ ICanvasColorService,
+ IRenderManagerService,
+ RenderManagerService,
+ setDocsTableRenderViewportProvider,
+ TRANSFORM_CHANGE_OBSERVABLE_TYPE,
+} from '@univerjs/engine-render';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
calcDocGlyphPosition,
@@ -50,7 +68,15 @@ describe('custom-range hit testing with real document layout', () => {
afterEach(() => vi.restoreAllMocks());
- it.each([1, 3])('includes the final glyph of a %i-character link without hitting adjacent text', (length) => {
+ it.each([
+ { length: 1, nested: false },
+ { length: 3, nested: false },
+ { length: 1, nested: true },
+ { length: 3, nested: true },
+ ...['checkbox', 'date', 'dropDownList', 'comboBox', 'text', 'richText', 'picture', 'group', 'repeatingSection'].map((kind) => ({ length: 1, nested: false, kind })),
+ ])('hits the innermost range including its final glyph: %j', (testCase) => {
+ const { length, nested } = testCase;
+ const kind = 'kind' in testCase ? testCase.kind : undefined;
const univer = new Univer();
try {
const injector = univer.__getInjector();
@@ -63,7 +89,12 @@ describe('custom-range hit testing with real document layout', () => {
dataStream: 'A目CDZ\r\n',
paragraphs: [{ startIndex: 5, paragraphId: 'paragraph-1' }],
sectionBreaks: [{ startIndex: 6, sectionId: 'body' }],
- customRanges: [{ startIndex: 1, endIndex: length, rangeId: 'link', rangeType: CustomRangeType.HYPERLINK }],
+ customRanges: nested
+ ? [
+ { startIndex: 1, endIndex: length, rangeId: 'link', rangeType: CustomRangeType.SDT, properties: { kind: 'repeatingSectionItem', placement: 'block' } },
+ { startIndex: 1, endIndex: length, rangeId: 'parent', rangeType: CustomRangeType.SDT, properties: { kind: 'repeatingSection', placement: 'block' } },
+ ]
+ : [{ startIndex: 1, endIndex: length, rangeId: 'link', rangeType: kind ? CustomRangeType.SDT : CustomRangeType.HYPERLINK, ...(kind ? { properties: { kind } } : {}) }],
},
documentStyle: {
documentFlavor: DocumentFlavor.TRADITIONAL,
@@ -89,6 +120,11 @@ describe('custom-range hit testing with real document layout', () => {
const glyph = skeleton.findNodeByCharIndex(length)!;
const bounds = calcDocGlyphPosition(glyph, documents, skeleton)!;
expect(bounds.right - bounds.left).toBeGreaterThan(0);
+ expect(service.isPointerOnInteractiveRange(
+ bounds.left + (bounds.right - bounds.left) * 0.75,
+ (bounds.top + bounds.bottom) / 2
+ )).toBe(!nested && kind !== 'group' && kind !== 'repeatingSection');
+ expect(service.isPointerOnInteractiveRange(bounds.right + 1, (bounds.top + bounds.bottom) / 2)).toBe(false);
const click = (x: number): void => {
const event = {
button: 0,
@@ -685,6 +721,15 @@ describe('DocEventManagerService list marker helpers', () => {
};
internalService._customRangeDirty = false;
internalService._customRangeBounds = [{
+ customRange: {
+ rangeId: 'outer-field',
+ startIndex: 0,
+ endIndex: 30,
+ rangeType: CustomRangeType.FIELD,
+ },
+ rects: [{ top: 40, bottom: 60, left: 20, right: 80 }],
+ segmentPageIndex: -1,
+ }, {
customRange: {
rangeId: 'link-1',
startIndex: 12,
@@ -708,6 +753,7 @@ describe('DocEventManagerService list marker helpers', () => {
});
expect(pointerDowns).toEqual([[
+ expect.objectContaining({ range: expect.objectContaining({ rangeId: 'outer-field' }) }),
expect.objectContaining({ range: expect.objectContaining({ rangeId: 'link-1' }) }),
]]);
expect(clicks).toEqual([]);
diff --git a/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts
index 6e3d063c21..80809f01c4 100644
--- a/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts
@@ -156,6 +156,26 @@ describe('popup anchors with real document layout', () => {
render.mainComponent = documents;
render.scene.addObject(documents);
const bounds = calcDocRangePositions({ startOffset: 1, endOffset: 1 + length, collapsed: length === 0 }, render)!;
+ injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
+ injector.add([DocCanvasPopManagerService]);
+ const pendingRange = { startOffset: 1000, endOffset: 1001, collapsed: false };
+ const pendingPopup = injector.get(DocCanvasPopManagerService).attachPopupToRange(pendingRange, {
+ componentKey: 'pending-selection-toolbar',
+ rangeAnchor: 'selection-end',
+ requiresStableLayout: false,
+ }, model.getUnitId());
+ const popupService = injector.get(ICanvasPopupService);
+ expect(popupService.popups).toHaveLength(0);
+ pendingRange.startOffset = 1;
+ pendingRange.endOffset = 2;
+ skeleton.calculate();
+ expect(popupService.popups).toHaveLength(1);
+ expect(popupService.popups[0][1].anchorRect).toEqual(expect.objectContaining({ right: expect.any(Number) }));
+ pendingRange.startOffset = 1000;
+ pendingRange.endOffset = 1001;
+ skeleton.calculate();
+ expect(popupService.popups).toHaveLength(0);
+ pendingPopup.dispose();
const lastGlyph = skeleton.findNodeByCharIndex(Math.max(1, length))!;
const lastGlyphBounds = calcDocGlyphPosition(lastGlyph, documents, skeleton)!;
expect(bounds).toHaveLength(1);
diff --git a/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts
index 8af97e0dde..209481dd88 100644
--- a/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts
@@ -74,17 +74,19 @@ class RecordingDocCanvasPopManagerService {
readonly directions: string[] = [];
readonly offsets: Array<[number, number] | undefined> = [];
onDismiss?: () => void;
+ onMount?: () => () => void;
disposedCount = 0;
getRangeBounds() {
return [{ left: 100, right: 200, top: 240, bottom: 260 }];
}
- attachPopupToRange(range: { startOffset: number; endOffset: number }, options: { direction: string; offset?: [number, number]; extraProps?: { onDismiss?: () => void } }) {
+ attachPopupToRange(range: { startOffset: number; endOffset: number }, options: { direction: string; offset?: [number, number]; extraProps?: { onDismiss?: () => void; onMount?: () => () => void } }) {
this.ranges.push(`${range.startOffset}:${range.endOffset}`);
this.directions.push(options.direction);
this.offsets.push(options.offset);
this.onDismiss = options.extraProps?.onDismiss;
+ this.onMount = options.extraProps?.onMount;
return {
dispose: () => {
@@ -265,6 +267,8 @@ describe('DocFloatMenuService', () => {
expect(popupService.ranges).toEqual(['0:5']);
expect(popupService.offsets).toEqual([[0, 8]]);
expect(service.floatMenu).toMatchObject({ start: 0, end: 5 });
+ expect(layoutInteractionService.isActive).toBe(false);
+ const unmount = popupService.onMount!();
expect(layoutInteractionService.isActive).toBe(true);
const selectionRenderService = injector.get(DocSelectionRenderService) as unknown as ActiveDocSelectionRenderService;
@@ -272,6 +276,8 @@ describe('DocFloatMenuService', () => {
expect(service.floatMenu).toBeNull();
expect(popupService.disposedCount).toBe(1);
expect(layoutInteractionService.isActive).toBe(false);
+ unmount();
+ expect(layoutInteractionService.isActive).toBe(false);
});
it('opens the mobile context menu above an expanded text selection instead of the desktop float toolbar', () => {
diff --git a/packages/docs-ui/src/services/clipboard/__tests__/html-and-udm-convert.spec.ts b/packages/docs-ui/src/services/clipboard/__tests__/html-and-udm-convert.spec.ts
index abf24d84e3..3ea374683a 100644
--- a/packages/docs-ui/src/services/clipboard/__tests__/html-and-udm-convert.spec.ts
+++ b/packages/docs-ui/src/services/clipboard/__tests__/html-and-udm-convert.spec.ts
@@ -721,6 +721,42 @@ describe('test case in html and udm convert', () => {
expect(html).toContain('src=remote-image-id');
});
+ it('should serialize nested TOC fields as visible linked text without field markers', () => {
+ const doc: IDocumentData = {
+ id: 'copy-toc-html',
+ documentStyle: {},
+ body: {
+ dataStream: '\u001F1 Intro\t\u001F3\u001E\u001E',
+ customRanges: [{
+ startIndex: 0,
+ endIndex: 12,
+ rangeId: 'toc',
+ rangeType: CustomRangeType.FIELD,
+ wholeEntity: false,
+ properties: { fieldType: 'TOC', instruction: 'TOC \\o "1-3"' },
+ }, {
+ startIndex: 1,
+ endIndex: 10,
+ rangeId: 'toc-link',
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: { bookmarkId: '_Toc1' },
+ }, {
+ startIndex: 9,
+ endIndex: 11,
+ rangeId: 'page-ref',
+ rangeType: CustomRangeType.FIELD,
+ wholeEntity: false,
+ properties: { fieldType: 'PAGEREF', instruction: 'PAGEREF _Toc1 \\h' },
+ }],
+ },
+ };
+
+ const html = getBodySliceHtml(doc, 0, doc.body!.dataStream.length);
+
+ expect(html).toBe('<a data-rangeid="toc-link" href="#_Toc1">1 Intro\t3</a>');
+ expect(html).not.toMatch(/[\u001E\u001F]/);
+ });
+
it('should paste docs feature coverage from html with styles, blocks, lists and table dimensions', () => {
const convertor = new HtmlToUDMService();
const pasted = convertor.convert(`
diff --git a/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts b/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts
index ba02be134e..c7c6a29da0 100644
--- a/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts
+++ b/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts
@@ -36,6 +36,9 @@ import {
import { parseDataStreamToTree } from '@univerjs/engine-render';
const DEFAULT_CLIPBOARD_FONT_FAMILY = 'Arial';
+function stripFieldBoundaryMarkers(value: string): string {
+ return value.replaceAll('\u001E', '').replaceAll('\u001F', '');
+}
function covertImageToHtml(item: IDocImage) {
const transformObjectToString = (obj: Record<string, string | number | undefined>) => {
@@ -63,7 +66,7 @@ export function covertTextRunToHtml(dataStream: string, textRun: ITextRun): stri
const { st: start, ed, ts = {} } = textRun;
const { ff, fs, it, bl, ul, st, ol, bg, cl, va } = ts;
- let html = escapeInlineText(dataStream.slice(start, ed));
+ let html = escapeInlineText(stripFieldBoundaryMarkers(dataStream.slice(start, ed)));
const style: string[] = [];
// italic
@@ -131,7 +134,7 @@ function getBodyInlineSlice(body: IDocumentBody, startIndex: number, endIndex: n
const { st, ed } = textRun;
if (Tools.hasIntersectionBetweenTwoRanges(startIndex, endIndex, st, ed)) {
if (st > cursorIndex) {
- spanList.push(escapeInlineText(dataStream.slice(cursorIndex, st)));
+ spanList.push(escapeInlineText(stripFieldBoundaryMarkers(dataStream.slice(cursorIndex, st))));
spanList.push(covertTextRunToHtml(dataStream, {
...textRun,
@@ -150,7 +153,7 @@ function getBodyInlineSlice(body: IDocumentBody, startIndex: number, endIndex: n
}
if (cursorIndex !== endIndex) {
- spanList.push(escapeInlineText(dataStream.slice(cursorIndex, endIndex)));
+ spanList.push(escapeInlineText(stripFieldBoundaryMarkers(dataStream.slice(cursorIndex, endIndex))));
}
return spanList.join('');
@@ -161,7 +164,11 @@ export function getBodySliceHtml(doc: IDocumentData, startIndex: number, endInde
const drawings = doc.drawings || {};
const { customRanges = [], customBlocks = [] } = body || {};
const cloneCustomBlocks = [...customBlocks];
- const customRangesInRange = customRanges.filter((range) => range.startIndex >= startIndex && range.endIndex <= endIndex);
+ const customRangesInRange = customRanges.filter((range) =>
+ range.rangeType === CustomRangeType.HYPERLINK &&
+ range.startIndex >= startIndex &&
+ range.endIndex <= endIndex
+ );
let cursorIndex = startIndex;
let html = '';
const handleCustomBlock = (startIndex: number, endIndex: number) => {
@@ -203,7 +210,8 @@ export function getBodySliceHtml(doc: IDocumentData, startIndex: number, endInde
const sliceHtml = handleCustomBlock(startIndex, endIndex + 1);
switch (rangeType) {
case CustomRangeType.HYPERLINK: {
- html += `<a data-rangeid="${rangeId}" href="${range.properties?.url ?? ''}">${sliceHtml.sliceHtml}</a>`;
+ const href = range.properties?.url ?? (range.properties?.bookmarkId ? `#${range.properties.bookmarkId}` : '');
+ html += `<a data-rangeid="${rangeId}" href="${href}">${sliceHtml.sliceHtml}</a>`;
break;
}
default: {
diff --git a/packages/docs-ui/src/services/doc-contextual-ribbon.service.ts b/packages/docs-ui/src/services/doc-contextual-ribbon.service.ts
new file mode 100644
index 0000000000..50f9619880
--- /dev/null
+++ b/packages/docs-ui/src/services/doc-contextual-ribbon.service.ts
@@ -0,0 +1,78 @@
+/**
+ * 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 { Disposable } from '@univerjs/core';
+import { IRibbonService } from '@univerjs/ui';
+
+/** Coordinates the document's containing table and selected content control, not global ribbon priority. */
+export class DocContextualRibbonService extends Disposable {
+ private _tableTab: string | null = null;
+ private _contentControlTab: string | null = null;
+ private _activeTab = '';
+
+ constructor(@IRibbonService private readonly _ribbonService: IRibbonService) {
+ super();
+ this.disposeWithMe(this._ribbonService.activatedTab$.subscribe((tab) => this._activeTab = tab));
+ }
+
+ setTableTab(tab: string, visible: boolean): void {
+ this._setTab('table', tab, visible);
+ }
+
+ setContentControlTab(tab: string, visible: boolean): void {
+ this._setTab('contentControl', tab, visible);
+ }
+
+ private _setTab(context: 'table' | 'contentControl', tab: string, visible: boolean): void {
+ const previousTab = context === 'table' ? this._tableTab : this._contentControlTab;
+ const nextTab = visible ? tab : null;
+ if (previousTab === nextTab) {
+ return;
+ }
+
+ const previousContext = this._contentControlTab ?? this._tableTab;
+ const activeTab = this._activeTab;
+ if (context === 'table') {
+ this._tableTab = nextTab;
+ } else {
+ this._contentControlTab = nextTab;
+ }
+
+ if (previousTab) {
+ this._ribbonService.hideContextualTab(previousTab);
+ }
+ if (nextTab) {
+ this._ribbonService.showContextualTab(nextTab);
+ }
+
+ const nextContext = this._contentControlTab ?? this._tableTab;
+ // Entering a control activates its tools. Leaving it must respect a manually chosen tab.
+ if (nextContext && nextContext !== previousContext
+ && (visible || !previousContext || activeTab === previousContext)) {
+ this._ribbonService.setActivatedTab(nextContext);
+ }
+ }
+
+ override dispose(): void {
+ if (this._contentControlTab) {
+ this.setContentControlTab(this._contentControlTab, false);
+ }
+ if (this._tableTab) {
+ this.setTableTab(this._tableTab, false);
+ }
+ super.dispose();
+ }
+}
diff --git a/packages/docs-ui/src/services/doc-event-manager.service.ts b/packages/docs-ui/src/services/doc-event-manager.service.ts
index 37b00c90d2..fc8d0bf28f 100644
--- a/packages/docs-ui/src/services/doc-event-manager.service.ts
+++ b/packages/docs-ui/src/services/doc-event-manager.service.ts
@@ -28,7 +28,7 @@ import type {
IRenderContext,
IRenderModule,
} from '@univerjs/engine-render';
-import { Disposable, fromEventSubject, Inject, PresetListType } from '@univerjs/core';
+import { CustomRangeType, Disposable, fromEventSubject, Inject, PresetListType } from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
import {
CURSOR_TYPE,
@@ -36,12 +36,13 @@ import {
documentSkeletonTableIterator,
getDocsTableRenderViewport,
getTableIdAndSliceIndex,
+ getTopmostDocsTableHit,
TRANSFORM_CHANGE_OBSERVABLE_TYPE,
} from '@univerjs/engine-render';
import { BehaviorSubject, distinctUntilChanged, filter, map, Subject, switchMap, take, tap, throttleTime } from 'rxjs';
import { DOC_VERTICAL_PADDING } from '../types/const/padding';
import { transformOffset2Bound } from './doc-popup-manager.service';
-import { NodePositionConvertToCursor } from './selection/convert-text-range';
+import { findDocRangeNodePositions, NodePositionConvertToCursor } from './selection/convert-text-range';
import { getLineBounding } from './selection/text-range';
export interface ICustomRangeBound {
@@ -59,7 +60,6 @@ export interface IBulletBound {
}
const calcDocRangePositions = (range: ITextRangeParam, documents: Documents, skeleton: DocumentSkeleton, pageIndex: number): IBoundRectNoAngle[] | undefined => {
- const startPosition = skeleton.findNodePositionByCharIndex(range.startOffset, true, range.segmentId, pageIndex);
const skeletonData = skeleton.getSkeletonData();
let end = range.collapsed ? range.startOffset : range.endOffset - 1;
if (range.segmentId) {
@@ -68,16 +68,16 @@ const calcDocRangePositions = (range: ITextRangeParam, documents: Documents, ske
end = Math.min(root.ed, end);
}
}
- // `end` is inclusive: a non-collapsed range covers the final glyph,
- // not just its leading caret edge (which gives single-glyph links no area).
- const endPosition = skeleton.findNodePositionByCharIndex(end, range.collapsed === true, range.segmentId, pageIndex);
- if (!endPosition || !startPosition) {
+ // SDTs may wrap a cell, row, table, or block. Their structural sentinels do not
+ // have glyphs, so resolve the first and last visible positions inside the range.
+ const positions = findDocRangeNodePositions(skeleton, range.startOffset, end, range.segmentId, pageIndex);
+ if (!positions) {
return;
}
const documentOffsetConfig = documents.getOffsetConfig();
const convertor = new NodePositionConvertToCursor(documentOffsetConfig, skeleton);
- const { borderBoxPointGroup } = convertor.getRangePointData(startPosition, endPosition);
+ const { borderBoxPointGroup } = convertor.getRangePointData(positions.startPosition, positions.endPosition);
const bounds = getLineBounding(borderBoxPointGroup);
return bounds.map((rect) => ({
@@ -455,6 +455,8 @@ export class DocEventManagerService extends Disposable implements IRenderModule
readonly hoverTableRealTime$ = this._hoverTable$.asObservable();
private _customRangeDirty = true;
+ private _customRangeCount = -1;
+ private _customRangeSkeletonSignature = '';
private _bulletDirty = true;
private _paragraphDirty = true;
private _tableBoundsDirty = true;
@@ -617,8 +619,12 @@ export class DocEventManagerService extends Disposable implements IRenderModule
const ranges = this._calcActiveRanges(point);
if (ranges.length) {
+ const hyperlink = ranges.filter(({ range }) => range.rangeType === CustomRangeType.HYPERLINK).pop();
+ const sdt = ranges.filter(({ range }) => range.rangeType === CustomRangeType.SDT)
+ .sort((left, right) => left.range.endIndex - left.range.startIndex -
+ (right.range.endIndex - right.range.startIndex))[0];
this._clickCustomRanges$.next({
- ...ranges.pop()!,
+ ...(hyperlink ?? sdt ?? ranges.pop()!),
ctrlKey: !!down.ctrlKey,
metaKey: !!down.metaKey,
});
@@ -635,6 +641,16 @@ export class DocEventManagerService extends Disposable implements IRenderModule
return Boolean(this._calcActiveBullet(transformOffset2Bound(offsetX, offsetY, this._context.scene)));
}
+ isPointerOnInteractiveRange(offsetX: number, offsetY: number): boolean {
+ return this._calcActiveRanges(transformOffset2Bound(offsetX, offsetY, this._context.scene)).some(({ range }) => {
+ if (range.rangeType === CustomRangeType.HYPERLINK) {
+ return true;
+ }
+ return range.rangeType === CustomRangeType.SDT &&
+ ['checkbox', 'date', 'dropDownList', 'comboBox', 'text', 'richText', 'picture'].includes(range.properties?.kind);
+ });
+ }
+
isPointerOnNonChecklistBullet(offsetX: number, offsetY: number): boolean {
const bullet = this._calcActiveBullet(transformOffset2Bound(offsetX, offsetY, this._context.scene));
@@ -664,9 +680,17 @@ export class DocEventManagerService extends Disposable implements IRenderModule
segmentId,
};
- const rects = calcDocRangePositions(textRange, this._documents, this._skeleton, segmentPage);
+ let rects: IBoundRectNoAngle[] | undefined;
+ try {
+ rects = calcDocRangePositions(textRange, this._documents, this._skeleton, segmentPage);
+ } catch {
+ // A structural wrapper can span incompatible nested page paths. It is
+ // not a text hit target and must not prevent later, inner controls
+ // from receiving hover and click events.
+ return;
+ }
if (!rects) {
- return null;
+ return;
}
layouts.push({
@@ -676,15 +700,21 @@ export class DocEventManagerService extends Disposable implements IRenderModule
segmentPageIndex: segmentPage,
});
});
-
return layouts;
}
private _buildCustomRangeBounds() {
- if (!this._customRangeDirty) {
+ const currentRangeCount = this._context.unit.getBody?.()?.customRanges?.length ?? 0;
+ const pages = this._skeleton.getSkeletonData()?.pages ?? [];
+ const currentSkeletonSignature = `${pages.length}:${pages[pages.length - 1]?.ed ?? -1}`;
+ const cacheMatchesDocument = this._customRangeCount === -1 || this._customRangeCount === currentRangeCount;
+ const cacheMatchesSkeleton = this._customRangeSkeletonSignature === '' || this._customRangeSkeletonSignature === currentSkeletonSignature;
+ if (!this._customRangeDirty && cacheMatchesDocument && cacheMatchesSkeleton && (currentRangeCount === 0 || this._customRangeBounds.length > 0)) {
return;
}
this._customRangeDirty = false;
+ this._customRangeCount = currentRangeCount;
+ this._customRangeSkeletonSignature = currentSkeletonSignature;
const customRangeBounds: ICustomRangeBound[] = [];
customRangeBounds.push(...this._buildCustomRangeBoundsBySegment());
@@ -1129,7 +1159,12 @@ export class DocEventManagerService extends Disposable implements IRenderModule
const { x, y } = evt;
this._buildTableBounds();
- const table = Array.from(this._tableBounds.values()).find((bound) => isPointInRect(x, y, getTableBlockMenuHoverRect(bound.rect)));
+ const table = getTopmostDocsTableHit(
+ Array.from(this._tableBounds.values()),
+ (bound) => isPointInRect(x, y, bound.rect),
+ (bound) => isPointInRect(x, y, getTableBlockMenuHoverRect(bound.rect)),
+ (outer, inner) => getRectArea(inner.rect) < getRectArea(outer.rect) && isRectContainingRect(outer.rect, inner.rect)
+ );
this._hoverTable$.next(table);
if (table) {
diff --git a/packages/docs-ui/src/services/doc-layout-coordinator.service.ts b/packages/docs-ui/src/services/doc-layout-coordinator.service.ts
index bf3b1c19cd..70094e0cdd 100644
--- a/packages/docs-ui/src/services/doc-layout-coordinator.service.ts
+++ b/packages/docs-ui/src/services/doc-layout-coordinator.service.ts
@@ -859,7 +859,7 @@ export class DocLayoutCoordinatorService extends Disposable {
return true;
}
if (!backlogResult.progress.complete) {
- // Match the Main path: one visible page publication per task.
+ // Yield after each bounded publication before requesting more pages.
this._scheduleBackground();
}
return true;
diff --git a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
index a0ac6f4673..881b1e81a0 100644
--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
@@ -532,6 +532,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
getFirstLine,
{
componentKey: DOC_PARAGRAPH_MENU_COMPONENT_KEY,
+ constrainToCanvas: true,
// Hovering is passive; opened menus and drags hold their own interaction lease.
requiresStableLayout: false,
direction: 'left-center',
@@ -621,6 +622,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
getFirstLine,
{
componentKey: DOC_TABLE_BLOCK_MENU_COMPONENT_KEY,
+ constrainToCanvas: true,
requiresStableLayout: false,
direction: 'top-right',
onClickOutside: () => {
diff --git a/packages/docs-ui/src/services/doc-popup-manager.service.ts b/packages/docs-ui/src/services/doc-popup-manager.service.ts
index 4eab5d0a02..198bf8c5b0 100644
--- a/packages/docs-ui/src/services/doc-popup-manager.service.ts
+++ b/packages/docs-ui/src/services/doc-popup-manager.service.ts
@@ -22,10 +22,10 @@ import { Disposable, DisposableCollection, ICommandService, Inject, IUniverInsta
import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { IRenderManagerService, pxToNum } from '@univerjs/engine-render';
import { ICanvasPopupService } from '@univerjs/ui';
-import { BehaviorSubject, map } from 'rxjs';
+import { BehaviorSubject, filter, map } from 'rxjs';
import { VIEWPORT_KEY } from '../basics/docs-view-key';
import { SetDocZoomRatioOperation } from '../commands/operations/set-doc-zoom-ratio.operation';
-import { NodePositionConvertToCursor } from './selection/convert-text-range';
+import { findDocRangeNodePositions, NodePositionConvertToCursor } from './selection/convert-text-range';
import { getLineBounding } from './selection/text-range';
export function transformBound2OffsetBound(originBound: IBoundRectNoAngle, scene: Scene): IBoundRectNoAngle {
@@ -97,13 +97,11 @@ export interface IDocCanvasPopup extends Omit<IPopup, 'anchorRect$' | 'children'
export const calcDocRangePositions = (range: ITextRangeParam, currentRender: IRender): IBoundRectNoAngle[] | undefined => {
const { scene, mainComponent, engine } = currentRender;
const skeleton = currentRender.with(DocSkeletonManagerService).getSkeleton();
- const startPosition = skeleton.findNodePositionByCharIndex(range.startOffset, true, range.segmentId, range.segmentPage);
const endIndex = range.collapsed ? range.startOffset : range.endOffset - 1;
- // Include the last glyph in the anchor and its outside-click exclusion.
- const endPosition = skeleton.findNodePositionByCharIndex(endIndex, range.collapsed === true, range.segmentId, range.segmentPage);
+ const positions = findDocRangeNodePositions(skeleton, range.startOffset, endIndex, range.segmentId, range.segmentPage);
const document = mainComponent as Documents;
- if (!endPosition || !startPosition) {
+ if (!positions) {
return;
}
@@ -121,7 +119,10 @@ export const calcDocRangePositions = (range: ITextRangeParam, currentRender: IRe
const { scaleX, scaleY } = scene.getAncestorScale();
const convertor = new NodePositionConvertToCursor(documentOffsetConfig, skeleton);
- const { borderBoxPointGroup } = convertor.getRangePointData(startPosition, endPosition);
+ const { borderBoxPointGroup } = convertor.getRangePointData(
+ positions.startPosition,
+ range.collapsed ? positions.startPosition : positions.endPosition
+ );
const bounds = getLineBounding(borderBoxPointGroup);
const res = bounds.map((bound) => transformBound2OffsetBound(bound, scene)).map((i) => ({
left: (i.left + docsLeft * scaleX) * scaleAdjust + left,
@@ -290,16 +291,17 @@ export class DocCanvasPopManagerService extends Disposable {
const disposable = new DisposableCollection();
const updatePositions = () => {
try {
- const position = calcDocRangePositions(range, currentRender);
- if (position) {
- positions$.next(position);
- }
+ positions$.next(calcDocRangePositions(range, currentRender) ?? []);
} catch {
// The popup may outlive an embedded render while its host switches tabs.
// Keep the last anchor until the popup is disposed.
}
};
+ const layoutSubscription = currentRender.with(DocSkeletonManagerService).getSkeleton().dirty$?.subscribe(updatePositions);
+ if (layoutSubscription) {
+ disposable.add(layoutSubscription);
+ }
disposable.add(this._commandService.onCommandExecuted((commandInfo) => {
if (this._shouldUpdateForCommand(commandInfo, currentRender.unitId)) {
updatePositions();
@@ -415,7 +417,7 @@ export class DocCanvasPopManagerService extends Disposable {
const popupInjector = this._resolveEmbeddedPopupInjector(unitId, currentRender);
const popupManagerService = this._resolvePopupManagerService(popupInjector);
- const { positions: bounds, positions$: bounds$, disposable } = this._createRangePositionObserver(range, currentRender);
+ const { positions$: bounds$, disposable } = this._createRangePositionObserver(range, currentRender);
const getAnchor = (bounds: IBoundRectNoAngle[]) => {
if (popup.rangeAnchor === 'selection-end') {
const backward = range.direction === 'backward';
@@ -425,34 +427,52 @@ export class DocCanvasPopManagerService extends Disposable {
}
return direction.includes('top') ? bounds[0] : bounds[bounds.length - 1];
};
- const position$ = bounds$.pipe(map(getAnchor));
+ const position$ = bounds$.pipe(filter((bounds) => bounds.length > 0), map(getAnchor));
+ let id: string | undefined;
+ let popupActivity: IDisposable | null = null;
+ const removePopup = () => {
+ if (id != null) {
+ popupManagerService.removePopup(id);
+ id = undefined;
+ }
+ popupActivity?.dispose();
+ popupActivity = null;
+ };
- const id = popupManagerService.addPopup({
- ...popup,
- unitId,
- subUnitId: 'default',
- connectorInjector: popupInjector,
- anchorRect: getAnchor(bounds),
- anchorRect$: position$,
- excludeRects: bounds,
- excludeRects$: bounds$,
- direction: (['top', 'bottom', 'horizontal'].some((i) => direction.includes(i)))
- ? bounds.length > 1
- ? multipleDirection ?? direction
- : direction
- : direction,
- canvasElement: currentRender.engine.getCanvasElement(),
- });
- const popupActivity = popup.requiresStableLayout === false ? null : this._beginPopupActivity(unitId);
+ disposable.add(bounds$.subscribe((bounds) => {
+ if (bounds.length === 0) {
+ removePopup();
+ return;
+ }
+ if (id != null) {
+ return;
+ }
+ id = popupManagerService.addPopup({
+ ...popup,
+ unitId,
+ subUnitId: 'default',
+ connectorInjector: popupInjector,
+ anchorRect: getAnchor(bounds),
+ anchorRect$: position$,
+ excludeRects: bounds,
+ excludeRects$: bounds$,
+ direction: (['top', 'bottom', 'horizontal'].some((i) => direction.includes(i)))
+ ? bounds.length > 1
+ ? multipleDirection ?? direction
+ : direction
+ : direction,
+ canvasElement: currentRender.engine.getCanvasElement(),
+ });
+ popupActivity = popup.requiresStableLayout === false ? null : this._beginPopupActivity(unitId);
+ }));
return {
dispose: () => {
- popupManagerService.removePopup(id);
+ removePopup();
bounds$.complete();
disposable.dispose();
- popupActivity?.dispose();
},
- canDispose: () => popupManagerService.activePopupId !== id,
+ canDispose: () => id == null || popupManagerService.activePopupId !== id,
};
}
// #endregion
diff --git a/packages/docs-ui/src/services/float-menu.service.ts b/packages/docs-ui/src/services/float-menu.service.ts
index e09b3f8ea3..a44329e0fe 100644
--- a/packages/docs-ui/src/services/float-menu.service.ts
+++ b/packages/docs-ui/src/services/float-menu.service.ts
@@ -233,14 +233,23 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {
protected _openSelectionMenu(unitId: string, range: ITextRangeParam): IDisposable | undefined {
const segmentId = range.segmentId ?? '';
+ let layoutInteraction: IDisposable | undefined;
const popup = this._docCanvasPopManagerService.attachPopupToRange(
range,
{
componentKey: FLOAT_MENU_COMPONENT_KEY,
direction: 'top-left',
rangeAnchor: 'selection-end',
+ requiresStableLayout: false,
offset: [0, 8],
extraProps: {
+ // Offscreen popups are not mounted. They must not hold the
+ // layout needed to bring a restored selection into view.
+ onMount: () => {
+ const interaction = this._docLayoutInteractionService.beginInteraction();
+ layoutInteraction = interaction;
+ return () => interaction.dispose();
+ },
onDismiss: () => {
this._invalidatedSelection = this._getSelectionKey(range);
this._hideFloatMenu();
@@ -249,11 +258,10 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {
},
unitId
);
- const layoutInteraction = this._docLayoutInteractionService.beginInteraction();
this._floatMenu = {
disposable: toDisposable(() => {
popup.dispose();
- layoutInteraction.dispose();
+ layoutInteraction?.dispose();
}),
start: range.startOffset,
end: range.endOffset,
diff --git a/packages/docs-ui/src/services/selection/__tests__/convert-rect-range.spec.ts b/packages/docs-ui/src/services/selection/__tests__/convert-rect-range.spec.ts
index 50dfc362c4..9c40b906b4 100644
--- a/packages/docs-ui/src/services/selection/__tests__/convert-rect-range.spec.ts
+++ b/packages/docs-ui/src/services/selection/__tests__/convert-rect-range.spec.ts
@@ -52,6 +52,30 @@ describe('selection rect range helpers', () => {
expect(isInSameTableCell(sameCell, otherCell)).toBe(false);
});
+ it('uses the innermost table path for nested cell selections', () => {
+ const innerCell = (tableId: string, cell: number) => createNodePosition([
+ 'pages',
+ 0,
+ 'skeTables',
+ 'outer',
+ 'rows',
+ 0,
+ 'cells',
+ 0,
+ 'skeTables',
+ tableId,
+ 'rows',
+ 0,
+ 'cells',
+ cell,
+ ]);
+
+ expect(isValidRectRange(innerCell('inner', 0), innerCell('inner', 1))).toBe(true);
+ expect(isValidRectRange(innerCell('inner', 0), innerCell('other-inner', 1))).toBe(false);
+ expect(isInSameTableCell(innerCell('inner', 0), innerCell('inner', 0))).toBe(true);
+ expect(isInSameTableCell(innerCell('inner', 0), innerCell('inner', 1))).toBe(false);
+ });
+
it('ignores column page paths when converting rect ranges', () => {
const columnPosition = createNodePosition(['pages', 0, 'skeColumnGroups', 'cg-1', 'columns', 0, 'page']);
const columnPage = { parent: { parent: { columnGroupId: 'cg-1' } } };
diff --git a/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts b/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts
index 05058bf7b0..f519a739a9 100644
--- a/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts
+++ b/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts
@@ -26,6 +26,7 @@ import { afterEach, describe, expect, it } from 'vitest';
import {
compareNodePosition,
compareNodePositionLogic,
+ findDocRangeNodePositions,
getOneTextSelectionRange,
NodePositionConvertToCursor,
pushToPoints,
@@ -129,7 +130,7 @@ describe('selection convert text range helpers', () => {
]);
});
- it('projects cell cursors through the table horizontal viewport', () => {
+ it.each([false, true])('projects cell cursors through the table viewport (vertical: %s)', (vertical) => {
setDocsTableRenderViewportProvider((unitId, tableId) => {
if (unitId !== 'unit-1' || tableId !== 'table-1') {
return null;
@@ -151,6 +152,8 @@ describe('selection convert text range helpers', () => {
};
const cell = {
left: 100,
+ pageWidth: 40,
+ cellTextDirection: vertical ? 'tbRlV' : undefined,
marginLeft: 0,
marginTop: 0,
sections: [{
@@ -231,7 +234,130 @@ describe('selection convert text range helpers', () => {
const result = convertor.getRangePointData(position, position);
- expect(getAnchorBounding(result.contentBoxPointGroup).left).toBe(70);
+ const bounds = getAnchorBounding(result.contentBoxPointGroup);
+ if (vertical) {
+ expect(bounds).toMatchObject({ left: 78, top: 20, width: 10, height: 10 });
+ } else {
+ expect(bounds.left).toBe(70);
+ }
+ });
+
+ it('does not pass a cross-cell structural range to the text selection converter', () => {
+ const first = {
+ pageType: DocumentSkeletonPageType.CELL,
+ path: ['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 0],
+ } as never;
+ const second = {
+ pageType: DocumentSkeletonPageType.CELL,
+ path: ['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 1],
+ } as never;
+ const skeleton = {
+ findNodePositionByCharIndex: (index: number) => index === 1 ? first : second,
+ } as never;
+
+ expect(findDocRangeNodePositions(skeleton, 1, 2)).toBeUndefined();
+ });
+
+ it('resolves visible positions inside structural range sentinels', () => {
+ const start = { glyph: 1, isBack: true } as never;
+ const end = { glyph: 8, isBack: false } as never;
+ const skeleton = {
+ findNodePositionByCharIndex: (index: number, isBack: boolean) => index === 12
+ ? start
+ : index === 18 && !isBack
+ ? end
+ : undefined,
+ } as unknown as DocumentSkeleton;
+
+ expect(findDocRangeNodePositions(skeleton, 10, 20)).toEqual({ startPosition: start, endPosition: end });
+ });
+
+ it('includes ancestor table and cell offsets for a nested vertical cell selection', () => {
+ const glyph = {
+ bBox: { ba: 8, bd: 2 },
+ count: 1,
+ glyphType: 'LETTER',
+ left: 20,
+ width: 10,
+ };
+ const innerCell = {
+ cellTextDirection: 'tbRlV',
+ left: 19,
+ marginLeft: 3,
+ marginTop: 4,
+ pageWidth: 40,
+ sections: [{
+ columns: [{
+ left: 0,
+ lines: [{
+ asc: 10,
+ divides: [{ glyphGroup: [glyph], left: 0, paddingLeft: 0 }],
+ lineHeight: 20,
+ marginBottom: 0,
+ marginTop: 0,
+ paddingTop: 0,
+ top: 0,
+ }],
+ }],
+ top: 0,
+ }],
+ };
+ const innerRow = { cells: [innerCell], height: 20, index: 0, top: 17 };
+ const innerTable = { left: 11, rows: [innerRow], tableId: 'inner', top: 13 };
+ const outerCell = {
+ left: 30,
+ marginLeft: 5,
+ marginTop: 7,
+ sections: [],
+ skeTables: new Map([['inner', innerTable]]),
+ };
+ const outerRow = { cells: [outerCell], height: 100, index: 0, top: 0 };
+ const outerTable = { left: 100, rows: [outerRow], tableId: 'outer', top: 200 };
+ const page = {
+ marginLeft: 10,
+ marginTop: 20,
+ pageHeight: 500,
+ pageWidth: 500,
+ skeTables: new Map([['outer', outerTable]]),
+ };
+
+ (innerCell as { parent?: unknown }).parent = innerRow;
+ (innerRow as { parent?: unknown }).parent = innerTable;
+ (innerTable as { parent?: unknown }).parent = outerCell;
+ (outerCell as { parent?: unknown }).parent = outerRow;
+ (outerRow as { parent?: unknown }).parent = outerTable;
+ (outerTable as { parent?: unknown }).parent = page;
+
+ const skeleton = {
+ getSkeletonData: () => ({ pages: [page], skeFooters: new Map(), skeHeaders: new Map() }),
+ getViewModel: () => ({ getDataModel: () => ({ getUnitId: () => 'unit-1' }) }),
+ };
+ const position = {
+ column: 0,
+ divide: 0,
+ glyph: 0,
+ isBack: false,
+ line: 0,
+ page: 0,
+ pageType: DocumentSkeletonPageType.CELL,
+ path: ['pages', 0, 'skeTables', 'outer', 'rows', 0, 'cells', 0, 'skeTables', 'inner', 'rows', 0, 'cells', 0],
+ section: 0,
+ segmentPage: 0,
+ };
+ const convertor = new NodePositionConvertToCursor({
+ docsLeft: 0,
+ docsTop: 0,
+ pageLayoutType: 0,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ } as never, skeleton as never);
+
+ expect(getAnchorBounding(convertor.getRangePointData(position, position).contentBoxPointGroup)).toMatchObject({
+ left: 199,
+ top: 280,
+ width: 10,
+ height: 10,
+ });
});
it('projects header table cell cursors from the segment page without requiring a body page index', () => {
diff --git a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts
index 68554d3c5d..bae9bfe62e 100644
--- a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts
+++ b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts
@@ -1409,6 +1409,26 @@ describe('DocSelectionRenderService', () => {
expect(document.activeElement).toBe(input);
});
+ it('preserves the sibling editor focus during passive updates inside the same embed', () => {
+ const { input, renderUnit, service, univer } = createRealSelectionRenderService();
+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());
+ TestLayoutService.root.setAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, 'embed-1');
+ const formulaInput = document.createElement('div');
+ formulaInput.dataset.uComp = input.dataset.uComp;
+ formulaInput.tabIndex = -1;
+ TestLayoutService.root.appendChild(formulaInput);
+ formulaInput.focus();
+
+ service.activate(12, 34);
+
+ expect(document.activeElement).toBe(formulaInput);
+ expect(service.canFocusing).toBe(false);
+
+ // An explicit pointer selection can still move focus between the editors.
+ service.activate(12, 34, true);
+ expect(document.activeElement).toBe(input);
+ });
+
it('publishes hidden editor input, paste, focus, and blur events with the typed content', () => {
const { input, renderUnit, service, univer } = createRealSelectionRenderService();
cleanup.push(() => renderUnit.dispose(), () => univer.dispose());
diff --git a/packages/docs-ui/src/services/selection/convert-rect-range.ts b/packages/docs-ui/src/services/selection/convert-rect-range.ts
index e5a764c328..ef81b128f0 100644
--- a/packages/docs-ui/src/services/selection/convert-rect-range.ts
+++ b/packages/docs-ui/src/services/selection/convert-rect-range.ts
@@ -34,9 +34,9 @@ export function isValidRectRange(anchorNodePosition: INodePosition, focusNodePos
return false;
}
- const tableIdIndex = anchorPath.indexOf('skeTables') + 1;
- const rowIndex = anchorPath.indexOf('rows') + 1;
- const cellIndex = anchorPath.indexOf('cells') + 1;
+ const tableIdIndex = anchorPath.lastIndexOf('skeTables') + 1;
+ const rowIndex = anchorPath.lastIndexOf('rows') + 1;
+ const cellIndex = anchorPath.lastIndexOf('cells') + 1;
const { tableId: anchorTableId, sliceIndex: anchorSliceIndex } = getTableIdAndSliceIndex(anchorPath[tableIdIndex] as string);
const { tableId: focusTableId, sliceIndex: focusSliceIndex } = getTableIdAndSliceIndex(focusPath[tableIdIndex] as string);
@@ -66,12 +66,12 @@ export function isInSameTableCell(anchorNodePosition: INodePosition, focusNodePo
return false;
}
- const anchorTableIdIndex = anchorPath.indexOf('skeTables') + 1;
- const anchorRowIndex = anchorPath.indexOf('rows') + 1;
- const anchorCellIndex = anchorPath.indexOf('cells') + 1;
- const focusTableIdIndex = focusPath.indexOf('skeTables') + 1;
- const focusRowIndex = focusPath.indexOf('rows') + 1;
- const focusCellIndex = focusPath.indexOf('cells') + 1;
+ const anchorTableIdIndex = anchorPath.lastIndexOf('skeTables') + 1;
+ const anchorRowIndex = anchorPath.lastIndexOf('rows') + 1;
+ const anchorCellIndex = anchorPath.lastIndexOf('cells') + 1;
+ const focusTableIdIndex = focusPath.lastIndexOf('skeTables') + 1;
+ const focusRowIndex = focusPath.lastIndexOf('rows') + 1;
+ const focusCellIndex = focusPath.lastIndexOf('cells') + 1;
if (
anchorTableIdIndex === 0 ||
@@ -152,8 +152,8 @@ export function compareNodePositionInTable(a: INodePosition, b: INodePosition):
return aCellCount <= bCellCount;
}
-function isEmptyCellPage(cell: IDocumentSkeletonPage) {
- return cell.sections[0].columns[0].lines.length === 0;
+function isEmptyCellPage(cell: Nullable<IDocumentSkeletonPage>) {
+ return !cell?.sections[0]?.columns[0]?.lines.length;
}
function findNonEmptyCellPages(
@@ -328,7 +328,7 @@ export class NodePositionConvertToRectRange {
if (table == null) {
const nestedTableContext = nestedTableContexts.find((context) => (
context.pageIndex === p &&
- (context.source === 'column' || context.source === 'header' || context.source === 'footer') &&
+ (context.source === 'table-cell' || context.source === 'column' || context.source === 'header' || context.source === 'footer') &&
context.tableId.startsWith(tableId)
));
if (nestedTableContext) {
diff --git a/packages/docs-ui/src/services/selection/convert-text-range.ts b/packages/docs-ui/src/services/selection/convert-text-range.ts
index 9dd465d92c..c281906a96 100644
--- a/packages/docs-ui/src/services/selection/convert-text-range.ts
+++ b/packages/docs-ui/src/services/selection/convert-text-range.ts
@@ -26,6 +26,7 @@ import type {
IDocumentSkeletonPage,
IDocumentSkeletonRow,
IDocumentSkeletonSection,
+ IDocumentSkeletonTable,
INodePosition,
IPoint,
} from '@univerjs/engine-render';
@@ -42,6 +43,53 @@ import {
Liquid,
} from '@univerjs/engine-render';
+export function findDocRangeNodePositions(
+ skeleton: DocumentSkeleton,
+ startIndex: number,
+ endIndex: number,
+ segmentId = '',
+ pageIndex = -1
+): { startPosition: INodePosition; endPosition: INodePosition } | undefined {
+ const dataStream = skeleton.getViewModel?.().getDataModel?.().getSelfOrHeaderFooterModel?.(segmentId)?.getBody?.()?.dataStream as string | undefined;
+ let startPosition: Nullable<INodePosition>;
+ for (let index = startIndex; index <= endIndex && !startPosition; index++) {
+ if (dataStream && isStructuralControl(dataStream.charCodeAt(index))) continue;
+ startPosition = skeleton.findNodePositionByCharIndex(index, true, segmentId, pageIndex);
+ }
+
+ let endPosition: Nullable<INodePosition>;
+ for (let index = endIndex; index >= startIndex && !endPosition; index--) {
+ if (dataStream && isStructuralControl(dataStream.charCodeAt(index))) continue;
+ endPosition = skeleton.findNodePositionByCharIndex(index, false, segmentId, pageIndex);
+ }
+
+ if (!startPosition || !endPosition) return;
+
+ // NodePositionConvertToCursor traverses a cell selection through one nested
+ // page path. A row/table wrapper can start and end in different cells, so
+ // feeding both positions to it indexes the first cell with the second cell's
+ // line coordinates. Structural table SDTs are not text hit targets; their
+ // inner controls are, and are resolved independently.
+ if (startPosition.pageType !== endPosition.pageType) return;
+ if (
+ startPosition.pageType === DocumentSkeletonPageType.CELL &&
+ endPosition.pageType === DocumentSkeletonPageType.CELL &&
+ !sameNodePath(startPosition.path, endPosition.path)
+ ) {
+ return;
+ }
+
+ return { startPosition, endPosition };
+}
+
+function isStructuralControl(code: number): boolean {
+ return code < 0x20 && code !== 0x09;
+}
+
+function sameNodePath(left: Array<string | number>, right: Array<string | number>): boolean {
+ return left.length === right.length && left.every((part, index) => part === right[index]);
+}
+
export enum NodePositionStateType {
NORMAL,
START,
@@ -230,6 +278,7 @@ export function pushToPoints(position: IPosition) {
export class NodePositionConvertToCursor {
private _liquid = new Liquid();
private _horizontalClip: Nullable<{ left: number; right: number }> = null;
+ private _verticalCellOrigin: Nullable<{ x: number; y: number; width: number }> = null;
private _currentStartState: ICurrentNodePositionState = {
page: NodePositionStateType.NORMAL,
@@ -357,8 +406,8 @@ export class NodePositionConvertToCursor {
};
}
- const clippedBorderBoxPosition = clipPositionToHorizontalRange(borderBoxPosition, this._horizontalClip);
- const clippedContentBoxPosition = clipPositionToHorizontalRange(contentBoxPosition, this._horizontalClip);
+ const clippedBorderBoxPosition = clipPositionToHorizontalRange(this._toPhysicalPosition(borderBoxPosition), this._horizontalClip);
+ const clippedContentBoxPosition = clipPositionToHorizontalRange(this._toPhysicalPosition(contentBoxPosition), this._horizontalClip);
if (clippedBorderBoxPosition && !isSelectionOnlyNonInlineDrawing) {
borderBoxPointGroup.push(pushToPoints(clippedBorderBoxPosition));
@@ -381,6 +430,19 @@ export class NodePositionConvertToCursor {
};
}
+ private _toPhysicalPosition(position: IPosition): IPosition {
+ const origin = this._verticalCellOrigin;
+ if (!origin) {
+ return position;
+ }
+ return {
+ startX: origin.x + origin.width - (position.endY - origin.y),
+ endX: origin.x + origin.width - (position.startY - origin.y),
+ startY: origin.y + position.startX - origin.x,
+ endY: origin.y + position.endX - origin.x,
+ };
+ }
+
private _getCaretGlyph(
glyph: IDocumentSkeletonGlyph | undefined,
glyphGroup: IDocumentSkeletonGlyph[],
@@ -639,7 +701,9 @@ export class NodePositionConvertToCursor {
);
this._liquid.translateSave();
const previousHorizontalClip = this._horizontalClip;
+ const previousVerticalCellOrigin = this._verticalCellOrigin;
this._horizontalClip = null;
+ this._verticalCellOrigin = null;
switch (pageType) {
case DocumentSkeletonPageType.NOTE: {
@@ -659,56 +723,7 @@ export class NodePositionConvertToCursor {
break;
}
case DocumentSkeletonPageType.CELL: {
- const nestedPageOffset = getDocumentSkeletonNestedPageOffset(segmentPage);
- if (nestedPageOffset) {
- this._liquid.translatePagePadding(page);
- this._liquid.translate(nestedPageOffset.left, nestedPageOffset.top);
- this._liquid.translatePagePadding(segmentPage);
- break;
- }
-
- const rowSke = segmentPage.parent as IDocumentSkeletonRow;
- const tableSke = rowSke.parent!;
- const tablePage = tableSke.parent as IDocumentSkeletonPage | undefined;
- const tablePageNestedOffset = tablePage ? getDocumentSkeletonNestedPageOffset(tablePage) : undefined;
- const { left: cellLeft } = segmentPage;
- const { top: tableTop, left: tableLeft } = tableSke;
- const { top: rowTop } = rowSke;
- const sourceTableId = getTableIdAndSliceIndex(tableSke.tableId).tableId;
- const viewport = getDocsTableRenderViewport(getDocumentUnitId(skeleton), sourceTableId);
- const hasHorizontalViewport = hasHorizontalTableViewport(viewport);
- const scrollLeft = hasHorizontalViewport ? viewport.scrollLeft : 0;
-
- if (tablePage?.type === DocumentSkeletonPageType.HEADER) {
- this._liquid.translatePagePadding({
- ...tablePage,
- marginLeft: page.marginLeft,
- });
- } else if (tablePage?.type === DocumentSkeletonPageType.FOOTER) {
- const footerTop = page.pageHeight - tablePage.height - tablePage.marginBottom;
- this._liquid.translate(page.marginLeft, footerTop);
- } else if (tablePage?.type === DocumentSkeletonPageType.NOTE) {
- const note = page.notes?.find((fragment) => fragment.page === tablePage);
- this._liquid.translate(note?.left ?? page.marginLeft, note?.top ?? page.marginTop);
- } else {
- this._liquid.translatePagePadding(page);
- }
-
- if (tablePageNestedOffset) {
- this._liquid.translate(tablePageNestedOffset.left, tablePageNestedOffset.top);
- this._liquid.translatePagePadding(tablePage!);
- }
-
- if (hasHorizontalViewport) {
- const visibleLeft = this._liquid.x + tableLeft - (viewport.leadingInsetLeft ?? 0);
- this._horizontalClip = {
- left: visibleLeft,
- right: visibleLeft + viewport.viewportWidth,
- };
- }
-
- this._liquid.translate(tableLeft + cellLeft - scrollLeft, tableTop + rowTop);
- this._liquid.translatePagePadding(segmentPage);
+ this._translateToCellPage(page, segmentPage, skeleton);
break;
}
default:
@@ -716,6 +731,14 @@ export class NodePositionConvertToCursor {
break;
}
+ if (segmentPage.cellTextDirection === 'tbRlV') {
+ this._verticalCellOrigin = {
+ x: this._liquid.x - segmentPage.marginLeft,
+ y: this._liquid.y - segmentPage.marginTop,
+ width: segmentPage.pageWidth,
+ };
+ }
+
for (let s = start_s; s <= end_s; s++) {
const section = sections[s];
const columns = section.columns;
@@ -799,10 +822,77 @@ export class NodePositionConvertToCursor {
}
this._liquid.translateRestore();
this._horizontalClip = previousHorizontalClip;
+ this._verticalCellOrigin = previousVerticalCellOrigin;
this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
}
}
+
+ private _translateToCellPage(
+ rootPage: IDocumentSkeletonPage,
+ segmentPage: IDocumentSkeletonPage,
+ skeleton: DocumentSkeleton
+ ): void {
+ const ancestors: Array<{
+ cell: IDocumentSkeletonPage;
+ row: IDocumentSkeletonRow;
+ table: IDocumentSkeletonTable;
+ }> = [];
+ let hostPage = segmentPage;
+
+ while (hostPage.parent) {
+ const row = hostPage.parent as IDocumentSkeletonRow;
+ const table = row.parent;
+ if (!row.cells?.includes(hostPage) || !table?.rows?.includes(row) || !table.tableId) {
+ break;
+ }
+
+ ancestors.unshift({ cell: hostPage, row, table });
+ if (!table.parent) {
+ hostPage = rootPage;
+ break;
+ }
+ hostPage = table.parent;
+ }
+
+ const nestedPageOffset = getDocumentSkeletonNestedPageOffset(hostPage);
+ if (hostPage.type === DocumentSkeletonPageType.HEADER) {
+ this._liquid.translatePagePadding({ ...hostPage, marginLeft: rootPage.marginLeft });
+ } else if (hostPage.type === DocumentSkeletonPageType.FOOTER) {
+ const footerTop = rootPage.pageHeight - hostPage.height - hostPage.marginBottom;
+ this._liquid.translate(rootPage.marginLeft, footerTop);
+ } else if (hostPage.type === DocumentSkeletonPageType.NOTE) {
+ const note = rootPage.notes?.find((fragment) => fragment.page === hostPage);
+ this._liquid.translate(note?.left ?? rootPage.marginLeft, note?.top ?? rootPage.marginTop);
+ } else {
+ this._liquid.translatePagePadding(rootPage);
+ if (nestedPageOffset) {
+ this._liquid.translate(nestedPageOffset.left, nestedPageOffset.top);
+ this._liquid.translatePagePadding(hostPage);
+ }
+ }
+
+ for (const { cell, row, table } of ancestors) {
+ const sourceTableId = getTableIdAndSliceIndex(table.tableId).tableId;
+ const viewport = getDocsTableRenderViewport(getDocumentUnitId(skeleton), sourceTableId);
+ const hasHorizontalViewport = hasHorizontalTableViewport(viewport);
+ const scrollLeft = hasHorizontalViewport ? viewport.scrollLeft : 0;
+
+ if (hasHorizontalViewport) {
+ const left = this._liquid.x + table.left - (viewport.leadingInsetLeft ?? 0);
+ const clip = { left, right: left + viewport.viewportWidth };
+ this._horizontalClip = this._horizontalClip
+ ? {
+ left: Math.max(this._horizontalClip.left, clip.left),
+ right: Math.min(this._horizontalClip.right, clip.right),
+ }
+ : clip;
+ }
+
+ this._liquid.translate(table.left + cell.left - scrollLeft, table.top + row.top);
+ this._liquid.translatePagePadding(cell);
+ }
+ }
}
function hasHorizontalTableViewport(viewport: Nullable<IDocsTableRenderViewport>): viewport is IDocsTableRenderViewport {
diff --git a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts b/packages/docs-ui/src/services/selection/doc-selection-render.service.ts
index f7b7b99ac8..afa14bd68e 100644
--- a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts
+++ b/packages/docs-ui/src/services/selection/doc-selection-render.service.ts
@@ -178,7 +178,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
get canFocusing() {
const ownerDocument = this._getOwnerDocument();
const activeElement = ownerDocument.activeElement;
- return !this._shouldPreserveExternalFocus() && (
+ return !this._shouldPreserveExternalFocus() && !this._isAnotherEditorFocused() && (
this.isFocusing ||
activeElement === ownerDocument.body ||
activeElement === null ||
diff --git a/packages/docs-ui/src/views/ParagraphMenu.tsx b/packages/docs-ui/src/views/ParagraphMenu.tsx
index 0839786cb5..4ffad2e66a 100644
--- a/packages/docs-ui/src/views/ParagraphMenu.tsx
+++ b/packages/docs-ui/src/views/ParagraphMenu.tsx
@@ -1478,6 +1478,7 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
const latestTarget = docParagraphMenuService?.activeTarget ?? activeTarget;
if (latestTarget?.kind === 'table' && commandId && targetRange) {
+ univerInstanceService.focusUnit(popup.unitId);
const tableRange = {
...targetRange,
segmentId: targetRange.segmentId ?? '',
@@ -1510,12 +1511,19 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
}
if (commandService && commandId) {
- commandService.executeCommand(commandId, commandId === DocTableDeleteTableCommand.id
- ? { ...commandParams, targetRange: tableRange }
- : commandParams);
+ const isOverriddenTableDelete = params.id === DocTableDeleteTableCommand.id;
+ await commandService.executeCommand(commandId, commandId === DocTableDeleteTableCommand.id
+ ? { ...commandParams, targetRange: tableRange, unitId: popup.unitId }
+ : isOverriddenTableDelete
+ ? {
+ ...commandParams,
+ tableId: (commandParams as { tableId?: string } | undefined)?.tableId ?? latestTarget.table?.tableId,
+ }
+ : commandParams);
}
finishParagraphMenuCommand(docParagraphMenuService, layoutService, handleHideMenu);
+ univerInstanceService.focusUnit(popup.unitId);
return;
}
diff --git a/packages/docs-ui/src/views/doc-statistics/DocPageStatus.tsx b/packages/docs-ui/src/views/doc-statistics/DocPageStatus.tsx
new file mode 100644
index 0000000000..b05de17f77
--- /dev/null
+++ b/packages/docs-ui/src/views/doc-statistics/DocPageStatus.tsx
@@ -0,0 +1,277 @@
+/**
+ * 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 type { IDocumentLayoutProgress, IDocumentSkeletonPage, IScrollObserverParam } from '@univerjs/engine-render';
+import type { LocaleKey } from '../../locale/types';
+import {
+ DisposableCollection,
+ DocumentFlavor,
+ fromEventSubject,
+ IUniverInstanceService,
+ LocaleService,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { Popup } from '@univerjs/design';
+import { DocSkeletonManagerService } from '@univerjs/docs';
+import { Documents, IRenderManagerService, PageLayoutType } from '@univerjs/engine-render';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { VIEWPORT_KEY } from '../../basics/docs-view-key';
+
+const SCROLL_SETTLE_DELAY = 120;
+const DRAG_TOOLTIP_HIDE_DELAY = 500;
+
+type PageGeometry = Pick<
+ IDocumentSkeletonPage,
+ 'isLayoutPlaceholder' | 'isMaterializationPlaceholder' | 'pageHeight' | 'pageWidth'
+>;
+
+type LayoutProgress = Pick<IDocumentLayoutProgress, 'complete' | 'publishedPageCount'>;
+
+interface IDocPageStatus {
+ currentPage: number | null;
+ totalPages: number | null;
+ dragTooltip: {
+ left: number;
+ page: number;
+ top: number;
+ } | null;
+}
+
+const EMPTY_DOC_PAGE_STATUS: IDocPageStatus = {
+ currentPage: null,
+ totalPages: null,
+ dragTooltip: null,
+};
+
+export function resolveDocPageStatus(
+ pages: Readonly<PageGeometry[]>,
+ viewportCenter: number,
+ pageGap: number,
+ vertical: boolean,
+ progress?: LayoutProgress | null
+): Pick<IDocPageStatus, 'currentPage' | 'totalPages'> {
+ const totalPages = progress == null || progress.complete ? pages.length : null;
+ const accuratePageCount = progress == null || progress.complete
+ ? pages.length
+ : Math.min(progress.publishedPageCount, pages.length);
+
+ let pageStart = 0;
+ for (let pageIndex = 0; pageIndex < accuratePageCount; pageIndex++) {
+ const page = pages[pageIndex];
+ const pageExtent = vertical ? page.pageHeight : page.pageWidth;
+ if (viewportCenter <= pageStart + pageExtent) {
+ const accurate = !page.isLayoutPlaceholder && !page.isMaterializationPlaceholder;
+ return {
+ currentPage: accurate ? pageIndex + 1 : null,
+ totalPages,
+ };
+ }
+ pageStart += pageExtent + pageGap;
+ }
+
+ return { currentPage: null, totalPages };
+}
+
+export function DocPageStatus() {
+ const instanceService = useDependency(IUniverInstanceService);
+ const localeService = useDependency(LocaleService);
+ const renderManagerService = useDependency(IRenderManagerService);
+ const currentDoc = useObservable(useMemo(
+ () => instanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC),
+ [instanceService]
+ ));
+ const renderer = currentDoc ? renderManagerService.getRenderUnitById(currentDoc.getUnitId()) : null;
+ const skeletonManager = renderer?.with(DocSkeletonManagerService);
+ const skeleton = useObservable(
+ skeletonManager?.currentSkeleton$ ?? null,
+ skeletonManager?.getSkeleton() ?? null,
+ false,
+ [skeletonManager]
+ );
+ const isTraditional = currentDoc?.getDocumentStyle().documentFlavor === DocumentFlavor.TRADITIONAL;
+ const canShowPageStatus = isTraditional && renderer != null && skeleton != null && renderer.mainComponent instanceof Documents;
+ const [state, setState] = useState<IDocPageStatus>(EMPTY_DOC_PAGE_STATUS);
+ const scrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const tooltipHideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(() => {
+ const viewport = renderer?.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+ const docsComponent = renderer?.mainComponent;
+ if (
+ !canShowPageStatus ||
+ renderer == null ||
+ skeleton == null ||
+ viewport == null ||
+ !(docsComponent instanceof Documents)
+ ) {
+ return;
+ }
+
+ const readPageStatus = () => {
+ const pages = skeleton.getSkeletonData()?.pages ?? [];
+ const viewBound = viewport.calcViewportInfo().viewBound;
+ const {
+ docsLeft,
+ docsTop,
+ pageLayoutType = PageLayoutType.VERTICAL,
+ pageMarginLeft,
+ pageMarginTop,
+ } = docsComponent.getOffsetConfig();
+ const vertical = pageLayoutType !== PageLayoutType.HORIZONTAL;
+ const viewportCenter = vertical
+ ? (viewBound.top + viewBound.bottom) / 2 - docsTop
+ : (viewBound.left + viewBound.right) / 2 - docsLeft;
+
+ return resolveDocPageStatus(
+ pages,
+ viewportCenter,
+ vertical ? pageMarginTop : pageMarginLeft,
+ vertical,
+ skeleton.getLayoutProgress() ?? null
+ );
+ };
+
+ const updateFooter = () => {
+ const pageStatus = readPageStatus();
+ setState((current) => {
+ if (
+ current.currentPage === pageStatus.currentPage &&
+ current.totalPages === pageStatus.totalPages
+ ) {
+ return current;
+ }
+ return { ...current, ...pageStatus };
+ });
+ };
+ const scheduleFooterUpdate = () => {
+ if (scrollSettleTimerRef.current != null) {
+ clearTimeout(scrollSettleTimerRef.current);
+ }
+ scrollSettleTimerRef.current = setTimeout(updateFooter, SCROLL_SETTLE_DELAY);
+ };
+ const readTooltipPosition = (page: number, scrollY: number) => {
+ const scrollBar = viewport.getScrollBar();
+ const thumb = scrollBar?.verticalThumbRect;
+ const canvas = renderer.engine.getCanvasElement();
+ if (!scrollBar?.hasVerticalThumb() || thumb == null || canvas == null) {
+ return null;
+ }
+ const canvasRect = canvas.getBoundingClientRect();
+ const scaleX = renderer.engine.width > 0 ? canvasRect.width / renderer.engine.width : 1;
+ const scaleY = renderer.engine.height > 0 ? canvasRect.height / renderer.engine.height : 1;
+ return {
+ page,
+ left: canvasRect.left + (viewport.left + thumb.left) * scaleX - 8,
+ top: canvasRect.top + (viewport.top + scrollY + scrollBar.verticalThumbSize / 2) * scaleY,
+ };
+ };
+ const updateDragTooltip = (param: IScrollObserverParam) => {
+ const page = readPageStatus().currentPage;
+ const dragTooltip = page == null ? null : readTooltipPosition(page, param.scrollY);
+ setState((current) => ({ ...current, dragTooltip }));
+ };
+ const hideDragTooltipLater = () => {
+ if (tooltipHideTimerRef.current != null) {
+ clearTimeout(tooltipHideTimerRef.current);
+ }
+ tooltipHideTimerRef.current = setTimeout(() => {
+ setState((current) => current.dragTooltip == null ? current : { ...current, dragTooltip: null });
+ }, DRAG_TOOLTIP_HIDE_DELAY);
+ };
+
+ const subscriptions = new DisposableCollection();
+ const cleanup = () => {
+ subscriptions.dispose();
+ if (scrollSettleTimerRef.current != null) {
+ clearTimeout(scrollSettleTimerRef.current);
+ scrollSettleTimerRef.current = null;
+ }
+ if (tooltipHideTimerRef.current != null) {
+ clearTimeout(tooltipHideTimerRef.current);
+ tooltipHideTimerRef.current = null;
+ }
+ };
+ // Render disposal is synchronous; React effect cleanup can run after layout publications.
+ subscriptions.add(fromEventSubject(docsComponent.onDispose$).subscribe(() => {
+ cleanup();
+ setState(EMPTY_DOC_PAGE_STATUS);
+ }));
+ scheduleFooterUpdate();
+ subscriptions.add(fromEventSubject(viewport.onScrollAfter$).subscribe((param) => {
+ if (param.isBarDragging || param.isBarDragEnd) {
+ if (tooltipHideTimerRef.current != null) {
+ clearTimeout(tooltipHideTimerRef.current);
+ tooltipHideTimerRef.current = null;
+ }
+ updateDragTooltip(param);
+ if (param.isBarDragEnd) {
+ hideDragTooltipLater();
+ scheduleFooterUpdate();
+ }
+ return;
+ }
+ scheduleFooterUpdate();
+ }));
+ subscriptions.add(skeleton.layoutProgress$.subscribe(updateFooter));
+ subscriptions.add(skeleton.layoutPageMaterialized$.subscribe(updateFooter));
+
+ return cleanup;
+ }, [canShowPageStatus, renderer, skeleton]);
+
+ if (!canShowPageStatus) {
+ return null;
+ }
+
+ let pageLabel: string | null = null;
+ if (state.currentPage != null) {
+ if (state.totalPages == null) {
+ pageLabel = localeService.t<LocaleKey>('docs-ui.statistics.currentPage', String(state.currentPage));
+ } else {
+ pageLabel = localeService.t<LocaleKey>(
+ 'docs-ui.statistics.currentPageOfTotal',
+ String(state.currentPage),
+ String(state.totalPages)
+ );
+ }
+ }
+
+ return (
+ <>
+ {pageLabel && <span className="univer-tabular-nums">{pageLabel}</span>}
+ {state.dragTooltip && (
+ <Popup visible overflowVisible offset={[state.dragTooltip.left, state.dragTooltip.top]}>
+ <div
+ data-testid="doc-scroll-page-tooltip"
+ className={`
+ univer-pointer-events-none univer-absolute univer-whitespace-nowrap univer-rounded
+ univer-border univer-border-gray-300 univer-bg-white univer-px-2 univer-py-1 univer-text-xs
+ univer-font-medium univer-tabular-nums univer-text-gray-700 univer-shadow-md
+ dark:!univer-border-gray-600 dark:!univer-bg-gray-800 dark:!univer-text-gray-200
+ `}
+ style={{ transform: 'translate(-100%, -50%)' }}
+ >
+ {localeService.t<LocaleKey>(
+ 'docs-ui.statistics.currentPage',
+ String(state.dragTooltip.page)
+ )}
+ </div>
+ </Popup>
+ )}
+ </>
+ );
+}
diff --git a/packages/docs-ui/src/views/doc-statistics/DocStatistics.tsx b/packages/docs-ui/src/views/doc-statistics/DocStatistics.tsx
index 94dcb61135..b95b3ef10a 100644
--- a/packages/docs-ui/src/views/doc-statistics/DocStatistics.tsx
+++ b/packages/docs-ui/src/views/doc-statistics/DocStatistics.tsx
@@ -21,6 +21,7 @@ import { Dropdown, Separator } from '@univerjs/design';
import { LoadingMultiIcon, StatisticalFunctionIcon } from '@univerjs/icons';
import { ToolbarButton, useDependency, useObservable } from '@univerjs/ui';
import { useState } from 'react';
+import { DocPageStatus } from './DocPageStatus';
import { useDocStatistics } from './use-doc-statistics';
type DisplayStatistics = IDocumentStatistics & { pages: number; lines: number };
@@ -185,6 +186,7 @@ export function DocStatistics() {
>
<span className="univer-flex univer-items-center univer-gap-1.5">
<StatisticalFunctionIcon className="univer-size-4" />
+ <DocPageStatus />
<span>{label}</span>
{loading && <LoadingMultiIcon className="univer-size-3.5 univer-animate-spin" />}
</span>
diff --git a/packages/docs-ui/src/views/doc-statistics/__tests__/DocPageStatus.spec.tsx b/packages/docs-ui/src/views/doc-statistics/__tests__/DocPageStatus.spec.tsx
new file mode 100644
index 0000000000..4190bb498e
--- /dev/null
+++ b/packages/docs-ui/src/views/doc-statistics/__tests__/DocPageStatus.spec.tsx
@@ -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 { IDocumentSkeletonPage } from '@univerjs/engine-render';
+import { describe, expect, it } from 'vitest';
+import { resolveDocPageStatus } from '../DocPageStatus';
+
+type PageGeometry = Pick<
+ IDocumentSkeletonPage,
+ 'isLayoutPlaceholder' | 'isMaterializationPlaceholder' | 'pageHeight' | 'pageWidth'
+>;
+
+function createPages(count: number): PageGeometry[] {
+ return Array.from({ length: count }, () => ({ pageHeight: 100, pageWidth: 80 }));
+}
+
+describe('resolveDocPageStatus', () => {
+ it('resolves the page at the viewport center after layout completes', () => {
+ expect(resolveDocPageStatus(createPages(5), 230, 10, true, {
+ complete: true,
+ publishedPageCount: 5,
+ })).toEqual({ currentPage: 3, totalPages: 5 });
+ });
+
+ it('does not expose an unfinished total or a page beyond the published prefix', () => {
+ const pages = createPages(5);
+ const progress = { complete: false, publishedPageCount: 2 };
+
+ expect(resolveDocPageStatus(pages, 150, 10, true, progress)).toEqual({
+ currentPage: 2,
+ totalPages: null,
+ });
+ expect(resolveDocPageStatus(pages, 260, 10, true, progress)).toEqual({
+ currentPage: null,
+ totalPages: null,
+ });
+ });
+
+ it('does not expose a placeholder page as accurate', () => {
+ const pages = createPages(3);
+ pages[1].isMaterializationPlaceholder = true;
+
+ expect(resolveDocPageStatus(pages, 150, 10, true, {
+ complete: false,
+ publishedPageCount: 2,
+ })).toEqual({ currentPage: null, totalPages: null });
+ });
+
+ it('supports horizontal page layout', () => {
+ expect(resolveDocPageStatus(createPages(3), 95, 10, false)).toEqual({
+ currentPage: 2,
+ totalPages: 3,
+ });
+ });
+});
diff --git a/packages/docs-ui/src/views/doc-statistics/__tests__/DocStatistics.spec.tsx b/packages/docs-ui/src/views/doc-statistics/__tests__/DocStatistics.spec.tsx
index 7e16fe963f..f92365cc1c 100644
--- a/packages/docs-ui/src/views/doc-statistics/__tests__/DocStatistics.spec.tsx
+++ b/packages/docs-ui/src/views/doc-statistics/__tests__/DocStatistics.spec.tsx
@@ -29,6 +29,7 @@ import enUS from '../../../locale/en-US';
import { DocStatistics } from '../DocStatistics';
import { useDocStatistics } from '../use-doc-statistics';
+vi.mock('../DocPageStatus', () => ({ DocPageStatus: () => null }));
vi.mock('../use-doc-statistics');
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
diff --git a/packages/docs-ui/src/views/float-toolbar/FloatToolbar.tsx b/packages/docs-ui/src/views/float-toolbar/FloatToolbar.tsx
index c664b927e0..b696df8a90 100644
--- a/packages/docs-ui/src/views/float-toolbar/FloatToolbar.tsx
+++ b/packages/docs-ui/src/views/float-toolbar/FloatToolbar.tsx
@@ -39,7 +39,7 @@ import { FLOAT_TEXT_STYLE_MENU_ID, FLOAT_TOOLBAR_MENU_POSITION } from '../../men
interface IFloatToolbarProps {
avaliableMenus?: Array<string | IFloatToolbarMenuConfig>;
- popup?: { extraProps?: { onDismiss?: () => void } };
+ popup?: { extraProps?: { onDismiss?: () => void; onMount?: () => () => void } };
}
interface IFloatToolbarMenuConfig {
@@ -98,6 +98,9 @@ export function resolveFloatToolbarMenus(
export function FloatToolbar(props: IFloatToolbarProps) {
const { avaliableMenus = DEFAULT_AVALIABLE_MENUS } = props;
const onDismiss = props.popup?.extraProps?.onDismiss;
+ const onMount = props.popup?.extraProps?.onMount;
+
+ useEffect(() => onMount?.(), [onMount]);
const menuManagerService = useDependency(IMenuManagerService);
const toolbarRef = useRef<HTMLDivElement>(null);
diff --git a/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsx b/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsx
index 6e441b9e32..95675b1148 100644
--- a/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsx
+++ b/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsx
@@ -35,6 +35,7 @@ import {
IShortcutService,
MenuItemType,
MenuManagerPosition,
+ MenuManagerService,
RediContext,
} from '@univerjs/ui';
import { act } from 'react';
@@ -46,6 +47,7 @@ import {
SetInlineFormatTextBackgroundColorCommand,
} from '../../../commands/commands/inline-format.command';
import { FLOAT_TEXT_STYLE_MENU_ID, FLOAT_TOOLBAR_MENU_POSITION } from '../../../menu/menu';
+import { DocLayoutInteractionService } from '../../../services/doc-layout-interaction.service';
import { FloatToolbar, resolveFloatToolbarMenus } from '../FloatToolbar';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -183,7 +185,7 @@ function createToolbarTestBed() {
};
}
-function renderToolbar(injector: Injector, avaliableMenus: string[], onDismiss?: () => void) {
+function renderToolbar(injector: Injector, avaliableMenus: string[], onDismiss?: () => void, onMount?: () => () => void) {
const container = document.createElement('div');
document.body.appendChild(container);
const root = createRoot(container);
@@ -191,7 +193,7 @@ function renderToolbar(injector: Injector, avaliableMenus: string[], onDismiss?:
act(() => {
root.render(
<RediContext.Provider value={{ injector }}>
- <FloatToolbar avaliableMenus={avaliableMenus} popup={{ extraProps: { onDismiss } }} />
+ <FloatToolbar avaliableMenus={avaliableMenus} popup={{ extraProps: { onDismiss, onMount } }} />
</RediContext.Provider>
);
});
@@ -224,6 +226,31 @@ describe('FloatToolbar', () => {
container = undefined;
});
+ it('holds layout only during the mounted toolbar lifetime', () => {
+ const injector = new Injector();
+ injector.add([IConfigService, { useClass: ConfigService }]);
+ injector.add([IMenuManagerService, { useClass: MenuManagerService }]);
+ injector.add([DocLayoutInteractionService]);
+ const interaction = injector.get(DocLayoutInteractionService);
+ try {
+ expect(interaction.isActive).toBe(false);
+ ({ root, container } = renderToolbar(injector, [], undefined, () => {
+ const lock = interaction.beginInteraction();
+ return () => lock.dispose();
+ }));
+ expect(interaction.isActive).toBe(true);
+ act(() => root!.unmount());
+ root = undefined;
+ expect(interaction.isActive).toBe(false);
+ } finally {
+ if (root) {
+ act(() => root!.unmount());
+ root = undefined;
+ }
+ injector.dispose();
+ }
+ });
+
it('fades outside the safe area and dismisses only once without prior hover', () => {
const testBed = createToolbarTestBed();
const onDismiss = vi.fn();
diff --git a/packages/docs-ui/src/views/header-footer/content-cover.ts b/packages/docs-ui/src/views/header-footer/content-cover.ts
new file mode 100644
index 0000000000..800551a863
--- /dev/null
+++ b/packages/docs-ui/src/views/header-footer/content-cover.ts
@@ -0,0 +1,187 @@
+/**
+ * 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 type {
+ Documents,
+ IBoundRectNoAngle,
+ IDocumentSkeletonCached,
+ IDocumentSkeletonPage,
+ IViewportInfo,
+ Scene,
+ UniverRenderingContext,
+} from '@univerjs/engine-render';
+import { BooleanNumber, DocumentFlavor } from '@univerjs/core';
+import { getDrawingShapeKeyByDrawingSearch } from '@univerjs/drawing';
+import { BaseObject, DocumentEditArea, PageLayoutType, RENDER_CLASS_TYPE, Vector2 } from '@univerjs/engine-render';
+
+/** A paint-only overlay. It never participates in hit testing or selection. */
+export class HeaderFooterContentCover extends BaseObject {
+ color = '';
+
+ constructor(key: string, private readonly _documents: Documents, private readonly _scene: Scene) {
+ super(key);
+ this.evented = false;
+ }
+
+ override render(ctx: UniverRenderingContext, viewport?: IViewportInfo): void {
+ const skeleton = this._documents.getSkeleton();
+ const viewModel = skeleton?.getViewModel();
+ const data = skeleton?.getSkeletonData();
+ if (!data || !viewModel || !this.color || viewModel.getEditArea() !== DocumentEditArea.BODY
+ || viewModel.getDataModel().documentStyle.documentFlavor !== DocumentFlavor.TRADITIONAL) {
+ return;
+ }
+
+ const content: IBoundRectNoAngle[] = [];
+ this._collectStoryBounds(data, content, viewport);
+ this._collectDrawingBounds(viewModel.getSnapshot(), content, viewport?.viewBound);
+ if (content.length === 0) {
+ return;
+ }
+ ctx.save();
+ ctx.fillStyle = this.color;
+ ctx.beginPath();
+ for (const rect of content) {
+ ctx.rect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
+ }
+ // One nonzero fill forms the union, so overlapping blocks are not faded twice.
+ ctx.fill();
+ ctx.restore();
+ this.makeDirty(false);
+ }
+
+ private _collectStoryBounds(data: IDocumentSkeletonCached, content: IBoundRectNoAngle[], viewport?: IViewportInfo): void {
+ const { pageLayoutType, pageMarginTop, pageMarginLeft } = this._documents.getOffsetConfig();
+ let pageLeft = 0;
+ let pageTop = 0;
+ for (const page of data.pages) {
+ if (!page.isLayoutPlaceholder && !page.isMaterializationPlaceholder
+ && !this._documents.isSkipByDiffBounds(page, pageTop, pageLeft, viewport)) {
+ const pageBounds = this._transformBounds({ left: pageLeft, top: pageTop, right: pageLeft + page.pageWidth, bottom: pageTop + page.pageHeight });
+ const header = data.skeHeaders.get(page.headerId)?.get(page.pageWidth);
+ const footer = data.skeFooters.get(page.footerId)?.get(page.pageWidth);
+ const local: IBoundRectNoAngle[] = [];
+ if (header) {
+ this._collectTextAndTables(header, pageLeft + page.marginLeft, pageTop + header.marginTop, local);
+ }
+ if (footer) {
+ this._collectTextAndTables(footer, pageLeft + page.marginLeft, pageTop + page.pageHeight - footer.height - footer.marginBottom, local);
+ }
+ for (const rect of local) {
+ this._appendClipped(content, this._transformBounds(rect), pageBounds);
+ }
+ }
+ if (pageLayoutType === PageLayoutType.HORIZONTAL) {
+ pageLeft += page.pageWidth + pageMarginLeft;
+ } else {
+ pageTop += page.pageHeight + pageMarginTop;
+ }
+ }
+ }
+
+ private _collectDrawingBounds(snapshot: IDocumentData, content: IBoundRectNoAngle[], viewport?: IBoundRectNoAngle): void {
+ // Drawing render objects already contain page-relative anchoring, grouping,
+ // crop and repeated-page transforms. Do not calculate a second placement.
+ const unitId = snapshot.id;
+ const prefix = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId: unitId, drawingId: '' });
+ for (const object of this._scene.getAllObjects()) {
+ if (!object.visible || object.classType === RENDER_CLASS_TYPE.GROUP || !object.oKey.startsWith(prefix)) {
+ continue;
+ }
+ const drawingId = object.oKey.slice(prefix.length).split('#-#', 1)[0];
+ const drawing = snapshot.drawings?.[drawingId];
+ if (drawing?.isMultiTransform !== BooleanNumber.TRUE) {
+ continue;
+ }
+ const effect = drawing.effectExtent;
+ const rect = this._transformBounds({
+ left: -(effect?.left ?? 0),
+ top: -(effect?.top ?? 0),
+ right: object.width + (effect?.right ?? 0),
+ bottom: object.height + (effect?.bottom ?? 0),
+ }, object.ancestorTransform);
+ const clip = (object as { clipBounds?: { left: number; top: number; width: number; height: number } }).clipBounds;
+ const clipped: IBoundRectNoAngle[] = [];
+ this._appendClipped(clipped, rect, clip
+ ? { left: clip.left, top: clip.top, right: clip.left + clip.width, bottom: clip.top + clip.height }
+ : undefined);
+ for (const bounds of clipped) {
+ this._appendClipped(content, bounds, viewport);
+ }
+ }
+ }
+
+ private _transformBounds(rect: IBoundRectNoAngle, transform = this._documents.getOffsetConfig().documentTransform): IBoundRectNoAngle {
+ const points = [
+ [rect.left, rect.top],
+ [rect.right, rect.top],
+ [rect.right, rect.bottom],
+ [rect.left, rect.bottom],
+ ].map(([x, y]) => transform.applyPoint(new Vector2(x, y)));
+ return {
+ left: Math.min(...points.map((point) => point.x)),
+ right: Math.max(...points.map((point) => point.x)),
+ top: Math.min(...points.map((point) => point.y)),
+ bottom: Math.max(...points.map((point) => point.y)),
+ };
+ }
+
+ private _appendClipped(result: IBoundRectNoAngle[], rect: IBoundRectNoAngle, clip?: IBoundRectNoAngle): void {
+ const bounds = clip
+ ? {
+ left: Math.max(rect.left, clip.left),
+ right: Math.min(rect.right, clip.right),
+ top: Math.max(rect.top, clip.top),
+ bottom: Math.min(rect.bottom, clip.bottom),
+ }
+ : rect;
+ if (Object.values(bounds).every(Number.isFinite) && bounds.right > bounds.left && bounds.bottom > bounds.top) {
+ result.push(bounds);
+ }
+ }
+
+ private _collectTextAndTables(page: IDocumentSkeletonPage, left: number, top: number, result: IBoundRectNoAngle[]): void {
+ for (const section of page.sections) {
+ for (const column of section.columns) {
+ for (const line of column.lines) {
+ const lineTop = top + section.top + line.top + line.marginTop + line.paddingTop;
+ for (const divide of line.divides) {
+ for (const glyph of divide.glyphGroup) {
+ if (!Array.from(glyph.content).some((character) => character.charCodeAt(0) > 32 && character.trim()) || glyph.width <= 0) {
+ continue;
+ }
+ const x = left + column.left + divide.left + divide.paddingLeft + glyph.left + glyph.xOffset;
+ const baseline = lineTop + line.asc;
+ result.push({
+ left: x - 1,
+ right: x + Math.max(glyph.width, glyph.bBox.width) + 1,
+ top: Math.min(lineTop, baseline - glyph.bBox.aba) - 1,
+ bottom: Math.max(lineTop + line.lineHeight, baseline + glyph.bBox.abd) + 1,
+ });
+ }
+ }
+ if (line.borderTop || line.borderBottom || line.borderLeft || line.borderRight || line.borderBetween) {
+ result.push({ left: left + column.left, right: left + column.left + column.width, top: lineTop - 2, bottom: lineTop + line.lineHeight + 2 });
+ }
+ }
+ }
+ }
+ for (const table of page.skeTables.values()) {
+ result.push({ left: left + table.left - 1, right: left + table.left + table.width + 1, top: top + table.top - 1, bottom: top + table.top + table.height + 1 });
+ }
+ }
+}
diff --git a/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts b/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts
index ad59317456..4ebddef195 100644
--- a/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts
+++ b/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts
@@ -14,7 +14,18 @@
* limitations under the License.
*/
-import { BlockType, DataStreamTreeTokenType, DeleteDirection, DrawingTypeEnum, getRichTextEditPath, ICommandService, IUndoRedoService, JSONX, PositionedObjectLayoutType, TextXActionType } from '@univerjs/core';
+import {
+ BlockType,
+ DataStreamTreeTokenType,
+ DeleteDirection,
+ DrawingTypeEnum,
+ getRichTextEditPath,
+ ICommandService,
+ IUndoRedoService,
+ JSONX,
+ PositionedObjectLayoutType,
+ TextXActionType,
+} from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { createTestBed } from '../../../facade/__tests__/create-test-bed';
import { RichTextEditingMutation } from '../../mutations/core-editing.mutation';
@@ -33,6 +44,40 @@ describe('core editing commands', () => {
testBed.univer.dispose();
});
+ it.each([{}, { lang: 'ja-JP', altLang: 'zh-CN' }, { eastAsiaFontFamily: 'Meiryo' }, { kerning: 0 }, { kerning: 12.5 }, { caps: false }, { caps: true }, { smallCaps: false }, { smallCaps: true }])('preserves text styles through text replacement, undo, redo and save (%j)', (style) => {
+ testBed.univer.dispose();
+ const ts = { fs: 14, ...style };
+ testBed = createTestBed({
+ id: 'test',
+ body: {
+ dataStream: 'Av\r\n',
+ paragraphs: [{ startIndex: 2, paragraphId: 'kerning-paragraph' }],
+ textRuns: [{ st: 0, ed: 2, ts }],
+ },
+ documentStyle: { textStyle: { kerning: 10, caps: true } },
+ });
+ commandService = testBed.get(ICommandService);
+ testBed.get(IUndoRedoService);
+ const document = testBed.univerAPI.getActiveDocument()!;
+ const before = document.save();
+
+ expect(commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: 'test',
+ body: { dataStream: 'To', textRuns: [{ st: 0, ed: 2, ts }] },
+ range: { startOffset: 0, endOffset: 2, collapsed: false },
+ debounce: false,
+ })).toBe(true);
+ const edited = document.save();
+ expect(edited.body?.dataStream).toBe('To\r\n');
+ expect(edited.body?.textRuns).toEqual([{ st: 0, ed: 2, ts }]);
+ expect(edited.documentStyle.textStyle?.kerning).toBe(10);
+ expect(edited.documentStyle.textStyle?.caps).toBe(true);
+ expect(document.undo()).toBe(true);
+ expect(document.save().body).toMatchObject(before.body!);
+ expect(document.redo()).toBe(true);
+ expect(document.save().body).toEqual(edited.body);
+ });
+
it('deletes text to the left of the collapsed range in the active document', () => {
const result = commandService.syncExecuteCommand(DeleteTextCommand.id, {
unitId: 'test',
@@ -309,6 +354,34 @@ describe('core editing commands', () => {
expect(testBed.doc.getBody()?.dataStream).toBe('AX\b\r\n');
});
+ it('allows a valid paragraph replacement that does not add to legacy structure defects', () => {
+ testBed.univer.dispose();
+ testBed = createTestBed({
+ id: 'test',
+ body: {
+ dataStream: 'A\b\r\n',
+ paragraphs: [{ startIndex: 2, paragraphId: 'body' }],
+ sectionBreaks: [{ sectionId: 'section_fixture_legacy', startIndex: 3 }],
+ },
+ documentStyle: {},
+ });
+ commandService = testBed.get(ICommandService);
+
+ expect(commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: 'test',
+ body: {
+ dataStream: '\r',
+ paragraphs: [{ startIndex: 0, paragraphId: 'inserted' }],
+ },
+ range: {
+ startOffset: 1,
+ endOffset: 1,
+ collapsed: true,
+ },
+ })).toBe(true);
+ expect(testBed.doc.getBody()?.dataStream).toBe('A\r\b\r\n');
+ });
+
it('inserts a paragraph around imported DOCX raw custom blocks without rolling back Enter', () => {
testBed.univer.dispose();
testBed = createTestBed({
diff --git a/packages/docs/src/commands/mutations/__tests__/core-editing.mutation.spec.ts b/packages/docs/src/commands/mutations/__tests__/core-editing.mutation.spec.ts
index 49fea856e0..fa355e47c1 100644
--- a/packages/docs/src/commands/mutations/__tests__/core-editing.mutation.spec.ts
+++ b/packages/docs/src/commands/mutations/__tests__/core-editing.mutation.spec.ts
@@ -79,6 +79,34 @@ describe('transformDocumentTextRanges', () => {
});
describe('RichTextEditingMutation selection scheduling', () => {
+ it('rejects a locked keystroke without normalizing or modifying the imported snapshot', () => {
+ const snapshot = createDocumentData('locked-input', {
+ dataStream: 'ABCD\r\n',
+ paragraphs: [{ paragraphId: 'p', startIndex: 4 }],
+ sectionBreaks: [{ sectionId: 's', startIndex: 5 }],
+ textRuns: [
+ { st: 0, ed: 2, ts: { ff: 'Arial' } },
+ { st: 2, ed: 4, ts: { ff: 'Arial' } },
+ ],
+ customRanges: [{ rangeId: 'locked', rangeType: CustomRangeType.SDT, startIndex: 0, endIndex: 3, properties: { kind: 'text', placement: 'inline', lock: 'contentLocked' } }],
+ });
+ const bed = createTestBed(snapshot);
+ try {
+ const before = structuredClone(bed.doc.getSnapshot());
+ const params = {
+ unitId: snapshot.id,
+ textRanges: null,
+ actions: JSONX.getInstance().editOp(new TextX().retain(1).insert(1, { dataStream: 'X' }).serialize(), ['body']),
+ };
+ expect(bed.get(ICommandService).syncExecuteCommand(RichTextEditingMutation.id, params))
+ .toEqual({ unitId: snapshot.id, actions: [], textRanges: [] });
+ expect(params.actions).toEqual([]);
+ expect(bed.doc.getSnapshot()).toEqual(before);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
it('rejects a remote footnote whose segment identity belongs to a header', () => {
const snapshot = createDocumentData('note-collision', {
dataStream: 'Body\r\n',
diff --git a/packages/docs/src/commands/mutations/__tests__/doc-structure-mutation-validation.spec.ts b/packages/docs/src/commands/mutations/__tests__/doc-structure-mutation-validation.spec.ts
index 117545f9f9..39b4c2f5a3 100644
--- a/packages/docs/src/commands/mutations/__tests__/doc-structure-mutation-validation.spec.ts
+++ b/packages/docs/src/commands/mutations/__tests__/doc-structure-mutation-validation.spec.ts
@@ -14,12 +14,129 @@
* limitations under the License.
*/
-import type { DocumentDataModel } from '@univerjs/core';
-import { JSONX } from '@univerjs/core';
+import { BuildTextUtils, CustomRangeType, DocumentDataModel, getRichTextEditPath, JSONX, TextX } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
-import { validateDocStructureMutation } from '../doc-structure-mutation-validation';
+import { isDocSdtMutationAllowed, validateDocStructureMutation } from '../doc-structure-mutation-validation';
describe('validateDocStructureMutation', () => {
+ it('does not treat an SDT identity edit as a footnote structure replacement', () => {
+ const model = new DocumentDataModel({ id: 'legacy-table', body: {
+ dataStream: '\x1AValue\r\n',
+ customRanges: [{ startIndex: 1, endIndex: 5, rangeId: 'control', rangeType: CustomRangeType.SDT, properties: { kind: 'text', placement: 'inline' } }],
+ } });
+ const before = structuredClone(model.getSnapshot());
+ const actions = JSONX.getInstance().editOp(new TextX().updateCustomRanges([{ rangeId: 'control', range: null }]).serialize());
+ const undo = JSONX.invertWithDoc(actions, model.getSnapshot());
+ model.apply(actions);
+ expect(validateDocStructureMutation(model, '', actions, undo)).toBe(true);
+ expect(model.getBody()!.dataStream).toBe(before.body!.dataStream);
+ expect(model.getBody()!.customRanges).toEqual([]);
+ model.apply(undo);
+ expect(model.getBody()!.customRanges).toEqual(before.body!.customRanges);
+ });
+
+ it('still rejects a missing footnote introduced by an identity edit', () => {
+ const model = new DocumentDataModel({ id: 'invalid-note', body: { dataStream: 'X\r\n' } });
+ const actions = JSONX.getInstance().editOp(new TextX().updateCustomRanges([{
+ rangeId: 'ref',
+ range: { startIndex: 0, endIndex: 0, rangeId: 'ref', rangeType: CustomRangeType.FOOTNOTE, properties: { noteId: 'missing' } },
+ }]).serialize());
+ const undo = JSONX.invertWithDoc(actions, model.getSnapshot());
+ model.apply(actions);
+ expect(() => validateDocStructureMutation(model, '', actions, undo)).toThrow('[DocStructure]');
+ });
+
+ it.each([
+ { editSource: false, sameStore: true, sourceLocked: false, allowed: false },
+ { editSource: true, sameStore: true, sourceLocked: false, allowed: true },
+ { editSource: true, sameStore: false, sourceLocked: false, allowed: false },
+ { editSource: true, sameStore: true, sourceLocked: true, allowed: false },
+ ])('validates a locked XML-bound mirror: %j', ({ editSource, sameStore, sourceLocked, allowed }) => {
+ const controls = [0, 1].map((index) => ({
+ startIndex: index * 4,
+ endIndex: index * 4 + 2,
+ rangeId: `bound-${index}`,
+ rangeType: CustomRangeType.SDT,
+ properties: {
+ kind: 'text',
+ placement: 'inline',
+ lock: index === 1 || sourceLocked ? 'contentLocked' : 'unlocked',
+ dataBinding: { storeItemID: index === 1 && !sameStore ? 'other' : 'store', xpath: '/value' },
+ },
+ }));
+ const model = new DocumentDataModel({ id: 'locked-mirror', body: { dataStream: 'Old Old\r\n', customRanges: controls } });
+ const edit = new TextX();
+ if (editSource) {
+ edit.delete(3).insert(3, { dataStream: 'New', customRanges: [controls[0]] }).retain(1);
+ } else {
+ edit.retain(4);
+ }
+ edit.delete(3).insert(3, { dataStream: 'New', customRanges: [{ ...controls[1], startIndex: 0, endIndex: 2 }] });
+ const actions = JSONX.getInstance().editOp(edit.serialize());
+ expect(isDocSdtMutationAllowed(model, '', actions)).toBe(allowed);
+ expect(model.getBody()?.dataStream).toBe('Old Old\r\n');
+ });
+
+ it.each([
+ { rangeIndex: 0, allowed: true },
+ { rangeIndex: 2, allowed: false },
+ ])('keeps nested repeating-section policies independent when removing range $rangeIndex', ({ rangeIndex, allowed }) => {
+ const item = { startIndex: 0, endIndex: 0, rangeId: 'inner-item', rangeType: CustomRangeType.SDT, properties: { kind: 'repeatingSectionItem', placement: 'block' } };
+ const model = new DocumentDataModel({
+ id: 'nested-repeat-policy',
+ body: { dataStream: 'A\r\n', customRanges: [
+ item,
+ { ...item, rangeId: 'inner', properties: { kind: 'repeatingSection', placement: 'block' } },
+ { ...item, rangeId: 'outer-item' },
+ { ...item, rangeId: 'outer', properties: { kind: 'repeatingSection', placement: 'block', repeatingSection: { doNotAllowInsertDelete: true } } },
+ ] },
+ });
+ const before = structuredClone(model.getSnapshot());
+ const actions = JSONX.getInstance().removeOp(['body', 'customRanges', rangeIndex], before.body!.customRanges![rangeIndex]);
+ expect(isDocSdtMutationAllowed(model, '', actions)).toBe(allowed);
+ expect(model.getSnapshot()).toEqual(before);
+ });
+
+ it.each([
+ { action: 'remove-item', allowed: false },
+ { action: 'add-item', allowed: false },
+ { action: 'edit-content', allowed: true },
+ { action: 'unlock', allowed: true },
+ ])('enforces repeating-section insertion/deletion policy for $action', ({ action, allowed }) => {
+ const section = {
+ startIndex: 0,
+ endIndex: 2,
+ rangeId: 'repeat',
+ rangeType: CustomRangeType.SDT,
+ properties: { kind: 'repeatingSection', placement: 'block', repeatingSection: { doNotAllowInsertDelete: true } },
+ };
+ const first = {
+ startIndex: 0,
+ endIndex: 0,
+ rangeId: 'first',
+ rangeType: CustomRangeType.SDT,
+ properties: { kind: 'repeatingSectionItem', placement: 'block' },
+ };
+ const model = new DocumentDataModel({
+ id: 'repeat-policy',
+ body: { dataStream: 'A\rB\r\n', customRanges: [first, section, { ...first, rangeId: 'second', startIndex: 2, endIndex: 2 }] },
+ });
+ const jsonX = JSONX.getInstance();
+ let actions;
+ if (action === 'remove-item') {
+ actions = jsonX.editOp(new TextX().delete(2).serialize(), getRichTextEditPath(model));
+ } else if (action === 'add-item') {
+ actions = jsonX.editOp(new TextX().retain(2).insert(2, { dataStream: 'C\r', customRanges: [{ ...first, rangeId: 'third' }] }).serialize(), getRichTextEditPath(model));
+ } else if (action === 'unlock') {
+ actions = jsonX.replaceOp(['body', 'customRanges', 1, 'properties', 'repeatingSection', 'doNotAllowInsertDelete'], true, false);
+ } else {
+ actions = jsonX.editOp(new TextX().retain(1).insert(1, { dataStream: 'X' }).serialize(), getRichTextEditPath(model));
+ }
+ const before = structuredClone(model.getSnapshot());
+ expect(isDocSdtMutationAllowed(model, '', actions)).toBe(allowed);
+ expect(model.getSnapshot()).toEqual(before);
+ });
+
it('skips body structure scans for table metadata updates', () => {
const getSelfOrHeaderFooterModel = vi.fn(() => {
throw new Error('body structure should not be scanned');
@@ -67,4 +184,133 @@ describe('validateDocStructureMutation', () => {
expect(validateDocStructureMutation(model, '', actions, undoActions)).toBe(true);
expect(getSelfOrHeaderFooterModel).not.toHaveBeenCalled();
});
+
+ it('allows a history replay to restore structural content from a legacy document', () => {
+ const getSelfOrHeaderFooterModel = vi.fn(() => {
+ throw new Error('history replay should not reject restored baseline issues');
+ });
+ const model = {
+ getSnapshot: () => ({}),
+ getSelfOrHeaderFooterModel,
+ } as unknown as DocumentDataModel;
+ const actions = JSONX.getInstance().insertOp(['body', 'tables', 0], { tableId: 'legacy-table' });
+ const undoActions = JSONX.getInstance().removeOp(['body', 'tables', 0], { tableId: 'legacy-table' });
+
+ expect(validateDocStructureMutation(model, '', actions, undoActions, true)).toBe(false);
+ expect(getSelfOrHeaderFooterModel).not.toHaveBeenCalled();
+ });
+
+ it('rejects typing inside a content-locked SDT', () => {
+ const model = new DocumentDataModel({
+ id: 'locked-sdt-doc',
+ body: {
+ dataStream: 'ABC\r',
+ customRanges: [{
+ startIndex: 0,
+ endIndex: 2,
+ rangeId: 'locked-sdt',
+ rangeType: CustomRangeType.SDT,
+ properties: { kind: 'text', placement: 'inline', lock: 'contentLocked' },
+ }],
+ },
+ });
+ const edit = new TextX().retain(1).insert(1, { dataStream: 'X' }).serialize();
+ const actions = JSONX.getInstance().editOp(edit, getRichTextEditPath(model));
+ const before = structuredClone(model.getSnapshot());
+ expect(isDocSdtMutationAllowed(model, '', actions)).toBe(false);
+ expect(model.getSnapshot()).toEqual(before);
+ });
+
+ it('allows a content-locked SDT to be unlocked through its properties', () => {
+ const range = {
+ startIndex: 0,
+ endIndex: 2,
+ rangeId: 'locked-sdt',
+ rangeType: CustomRangeType.SDT,
+ properties: { kind: 'text' as const, placement: 'inline' as const, lock: 'contentLocked' as const },
+ };
+ const model = new DocumentDataModel({
+ id: 'unlock-sdt-doc',
+ body: { dataStream: 'ABC\r', customRanges: [range] },
+ });
+ const edit = new TextX().retain(3, {
+ dataStream: '',
+ customRanges: [{ ...range, properties: { ...range.properties, lock: 'unlocked' as const } }],
+ }).serialize();
+ const actions = JSONX.getInstance().editOp(edit, getRichTextEditPath(model));
+ const undoActions = JSONX.invertWithDoc(actions, model.getSnapshot());
+ expect(isDocSdtMutationAllowed(model, '', actions)).toBe(true);
+ model.apply(actions);
+
+ expect(() => validateDocStructureMutation(model, '', actions, undoActions)).not.toThrow();
+ expect(model.getBody()?.customRanges?.[0].properties?.lock).toBe('unlocked');
+ });
+
+ it('allows an sdtLocked control to update its value while preserving the wrapper', () => {
+ const model = new DocumentDataModel({
+ id: 'wrapper-locked-sdt-doc',
+ body: {
+ dataStream: 'X\x1Cdd mmm yyyy\r\n\x1D',
+ customRanges: [{
+ startIndex: 1,
+ endIndex: 15,
+ rangeId: 'date-cell',
+ rangeType: CustomRangeType.SDT,
+ wholeEntity: false,
+ properties: { kind: 'date', placement: 'cell', lock: 'sdtLocked', showingPlaceholder: true },
+ }],
+ },
+ });
+ const body = model.getBody()!;
+ const replacement = BuildTextUtils.selection.delete([{
+ startOffset: 2,
+ endOffset: 13,
+ collapsed: false,
+ }], body, 0, { dataStream: '06 Sep 2026' });
+ const metadata = new TextX().retain(1).retain(15, {
+ dataStream: '',
+ customRanges: [{
+ ...body.customRanges![0],
+ startIndex: 0,
+ endIndex: 14,
+ properties: { kind: 'date', placement: 'cell', lock: 'sdtLocked', showingPlaceholder: false },
+ }],
+ }).serialize();
+ const actions = JSONX.getInstance().editOp(TextX.compose(replacement, metadata), getRichTextEditPath(model));
+ const undoActions = JSONX.invertWithDoc(actions, model.getSnapshot());
+ expect(isDocSdtMutationAllowed(model, '', actions)).toBe(true);
+ model.apply(actions);
+
+ expect(() => validateDocStructureMutation(model, '', actions, undoActions)).not.toThrow();
+ expect(model.getBody()?.customRanges).toEqual([expect.objectContaining({
+ rangeId: 'date-cell',
+ startIndex: 1,
+ endIndex: 15,
+ properties: expect.objectContaining({ showingPlaceholder: false }),
+ })]);
+ });
+
+ it.each([
+ { offset: 5, childLock: 'sdtLocked' as const, allowed: true },
+ { offset: 1, childLock: 'sdtLocked' as const, allowed: false },
+ { offset: 9, childLock: 'sdtLocked' as const, allowed: false },
+ { offset: 5, childLock: 'sdtContentLocked' as const, allowed: false },
+ ])('preserves Word group boundaries at $offset with child lock $childLock', ({ offset, childLock, allowed }) => {
+ const model = new DocumentDataModel({
+ id: 'group-lock',
+ body: {
+ dataStream: 'leftABCright\r',
+ customRanges: [
+ { startIndex: 0, endIndex: 11, rangeId: 'group', rangeType: CustomRangeType.SDT, properties: { kind: 'group', placement: 'block', lock: 'contentLocked' } },
+ { startIndex: 4, endIndex: 6, rangeId: 'child', rangeType: CustomRangeType.SDT, properties: { kind: 'richText', placement: 'inline', lock: childLock } },
+ ],
+ },
+ });
+ const before = structuredClone(model.getSnapshot());
+ const actions = JSONX.getInstance().editOp(new TextX().retain(offset).insert(1, { dataStream: 'X' }).serialize(), getRichTextEditPath(model));
+ expect(isDocSdtMutationAllowed(model, '', actions)).toBe(allowed);
+ expect(model.getSnapshot()).toEqual(before);
+ const removeChild = JSONX.getInstance().removeOp(['body', 'customRanges', 1], before.body!.customRanges![1]);
+ expect(isDocSdtMutationAllowed(model, '', removeChild)).toBe(false);
+ });
});
diff --git a/packages/docs/src/commands/mutations/core-editing.mutation.ts b/packages/docs/src/commands/mutations/core-editing.mutation.ts
index 9ebf3d96b2..1511147bb5 100644
--- a/packages/docs/src/commands/mutations/core-editing.mutation.ts
+++ b/packages/docs/src/commands/mutations/core-editing.mutation.ts
@@ -34,9 +34,11 @@ import {
IUniverInstanceService,
JSON1,
JSONX,
+ RedoCommandId,
TextX,
TextXActionType,
Tools,
+ UndoCommandId,
UniverInstanceType,
} from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
@@ -44,7 +46,7 @@ import { DocSelectionManagerService } from '../../services/doc-selection-manager
import { DocSkeletonManagerService } from '../../services/doc-skeleton-manager.service';
import { DocStateEmitService } from '../../services/doc-state-emit.service';
import { RICH_TEXT_EDITING_MUTATION_ID } from './core-editing.mutation-id';
-import { validateDocStructureMutation } from './doc-structure-mutation-validation';
+import { isDocSdtMutationAllowed, validateDocStructureMutation } from './doc-structure-mutation-validation';
export enum DocHistoryAction {
DeleteChart = 'delete-chart',
@@ -150,7 +152,8 @@ function canRemoveFootnoteReference(actions: JSONXActions, references: ICustomRa
canRemove = true;
return;
}
- if (action.t === TextXActionType.RETAIN && action.body?.customRanges != null) {
+ if (action.t === TextXActionType.RETAIN && (action.body?.customRanges != null ||
+ action.rangeUpdates?.some((update) => references.some((reference) => reference.rangeId === update.rangeId)))) {
canRemove = true;
return;
}
@@ -191,7 +194,8 @@ function includeFootnoteCleanup(before: IDocumentData, actions: JSONXActions): J
function applyValidatedDocumentActions(
documentDataModel: DocumentDataModel,
segmentId: string,
- actions: JSONXActions
+ actions: JSONXActions,
+ isHistoryReplay = false
): { actions: JSONXActions; undoActions: JSONXActions; preservesStructure: boolean } {
const before = documentDataModel.getSnapshot();
const appliedActions = includeFootnoteCleanup(before, actions);
@@ -201,7 +205,7 @@ function applyValidatedDocumentActions(
return {
actions: appliedActions,
undoActions,
- preservesStructure: validateDocStructureMutation(documentDataModel, segmentId, appliedActions, undoActions),
+ preservesStructure: validateDocStructureMutation(documentDataModel, segmentId, appliedActions, undoActions, isHistoryReplay),
};
} catch (error) {
documentDataModel.apply(undoActions);
@@ -323,10 +327,17 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
};
}
+ const isHistoryReplay = trigger === UndoCommandId || trigger === RedoCommandId;
+ if (!isHistoryReplay && !isDocSdtMutationAllowed(documentDataModel, segmentId, actions)) {
+ params.actions = [];
+ return { unitId, actions: [], textRanges: docRanges };
+ }
+
const { actions: appliedActions, undoActions, preservesStructure } = applyValidatedDocumentActions(
documentDataModel,
segmentId,
- actions
+ actions,
+ isHistoryReplay
);
// Publish reference deletion and note cleanup in the same deterministic mutation.
diff --git a/packages/docs/src/commands/mutations/doc-structure-mutation-validation.ts b/packages/docs/src/commands/mutations/doc-structure-mutation-validation.ts
index 651bd6c62a..a365ecc64c 100644
--- a/packages/docs/src/commands/mutations/doc-structure-mutation-validation.ts
+++ b/packages/docs/src/commands/mutations/doc-structure-mutation-validation.ts
@@ -14,17 +14,27 @@
* limitations under the License.
*/
-import type { DocumentDataModel, IDocumentBody, JSONXActions, JSONXPath } from '@univerjs/core';
+import type {
+ DocumentDataModel,
+ ICustomRange,
+ IDocStructureIssue,
+ IDocumentBody,
+ IDocumentData,
+ ISdtCustomRange,
+ JSONXActions,
+ JSONXPath,
+} from '@univerjs/core';
import {
CustomRangeType,
DataStreamTreeTokenType,
-
getRichTextEditPath,
-
+ getSdtBindingKey,
+ getSdtBindingValue,
JSON1,
-
+ JSONX,
TextX,
TextXActionType,
+ Tools,
validateDocBodyStructure,
validateDocumentStructure,
} from '@univerjs/core';
@@ -178,7 +188,36 @@ function getSegmentType(documentDataModel: DocumentDataModel, segmentId: string)
return 'body';
}
-function assertValidDocBodyStructure(documentDataModel: DocumentDataModel, segmentId: string): void {
+function getSnapshotBody(snapshot: IDocumentData, segmentId: string): IDocumentBody | undefined {
+ if (!segmentId) {
+ return snapshot.body;
+ }
+ return snapshot.headers?.[segmentId]?.body ?? snapshot.footers?.[segmentId]?.body ?? snapshot.notes?.[segmentId]?.body;
+}
+
+function containsTextXEdit(actions: JSONXActions): boolean {
+ const cursor = JSON1.type.readCursor(actions);
+ let found = false;
+ cursor.traverse(null, (component) => {
+ if (component.et === TextX.id) found = true;
+ });
+ return found;
+}
+
+function subtractBaselineIssues(issues: IDocStructureIssue[], baseline: IDocStructureIssue[]): IDocStructureIssue[] {
+ const counts = new Map<string, number>();
+ baseline.forEach((issue) => counts.set(issue.code, (counts.get(issue.code) ?? 0) + 1));
+ return issues.filter((issue) => {
+ const count = counts.get(issue.code) ?? 0;
+ if (count === 0) {
+ return true;
+ }
+ counts.set(issue.code, count - 1);
+ return false;
+ });
+}
+
+function assertValidDocBodyStructure(documentDataModel: DocumentDataModel, segmentId: string, undoActions: JSONXActions): void {
const segmentModel = documentDataModel.getSelfOrHeaderFooterModel(segmentId);
const body = segmentModel?.getBody();
if (!body) {
@@ -186,6 +225,7 @@ function assertValidDocBodyStructure(documentDataModel: DocumentDataModel, segme
}
const segmentType = getSegmentType(documentDataModel, segmentId);
+ const context = { segmentType, segmentId: segmentId || undefined };
const note = documentDataModel.getSnapshot().notes?.[segmentId];
const issues = note
? validateDocumentStructure({ notes: { [segmentId]: note } })
@@ -194,16 +234,158 @@ function assertValidDocBodyStructure(documentDataModel: DocumentDataModel, segme
return;
}
- const detail = issues.map((issue) => `${issue.code}${issue.index == null ? '' : `@${issue.index}`}`).join(', ');
+ const snapshot = Tools.deepClone(documentDataModel.getSnapshot());
+ const restoredSnapshot = JSONX.apply(snapshot, undoActions) as unknown as IDocumentData;
+ const baselineBody = getSnapshotBody(restoredSnapshot, segmentId);
+ // ponytail: issue counts preserve editability for legacy imports; add offset-aware mapping if two
+ // defects of the same kind can be exchanged by one mutation in production.
+ const newIssues = baselineBody
+ ? subtractBaselineIssues(issues, validateDocBodyStructure(baselineBody, context))
+ : issues;
+ if (!newIssues.length) {
+ return;
+ }
+
+ const detail = newIssues.map((issue) => `${issue.code}${issue.index == null ? '' : `@${issue.index}`}`).join(', ');
const segmentLabel = segmentId ? `${segmentType} ${segmentId}` : segmentType;
throw new Error(`[DocStructure] ${segmentLabel}: ${detail}`);
}
+function getLockedSdtContent(body: IDocumentBody, range: ICustomRange): string {
+ if (range.properties?.kind !== 'group') {
+ return body.dataStream.slice(range.startIndex, range.endIndex + 1);
+ }
+ // A Word group protects text outside its child controls. Each child retains
+ // its own lock policy; keep its identity here so deleting it is not an edit.
+ const children = (body.customRanges ?? []).filter((child) =>
+ child.rangeType === CustomRangeType.SDT && child.rangeId !== range.rangeId &&
+ child.startIndex >= range.startIndex && child.endIndex <= range.endIndex
+ ).sort((left, right) => {
+ const position = left.startIndex - right.startIndex || right.endIndex - left.endIndex;
+ if (position || left.rangeId === right.rangeId) {
+ return position;
+ }
+ return left.rangeId < right.rangeId ? -1 : 1;
+ });
+ const protectedContent: string[] = [];
+ let offset = range.startIndex;
+ for (const child of children) {
+ if (child.startIndex < offset) {
+ continue;
+ }
+ protectedContent.push(body.dataStream.slice(offset, child.startIndex), child.rangeId);
+ offset = child.endIndex + 1;
+ }
+ protectedContent.push(body.dataStream.slice(offset, range.endIndex + 1));
+ return JSON.stringify(protectedContent);
+}
+
+function getRepeatingItemIds(body: IDocumentBody, section: ICustomRange): string[] {
+ const ranges = body.customRanges ?? [];
+ const sectionIndex = ranges.indexOf(section);
+ const nestedSections = ranges.filter((range, index) => range.rangeType === CustomRangeType.SDT &&
+ range.properties?.kind === 'repeatingSection' && range.rangeId !== section.rangeId &&
+ range.startIndex >= section.startIndex && range.endIndex <= section.endIndex &&
+ (range.startIndex > section.startIndex || range.endIndex < section.endIndex || index < sectionIndex));
+ return ranges.filter((range, index) => range.rangeType === CustomRangeType.SDT &&
+ range.properties?.kind === 'repeatingSectionItem' &&
+ range.startIndex >= section.startIndex && range.endIndex <= section.endIndex &&
+ !nestedSections.some((nested) => nested.startIndex <= range.startIndex && range.endIndex <= nested.endIndex &&
+ (nested.startIndex < range.startIndex || range.endIndex < nested.endIndex || index < ranges.indexOf(nested))))
+ .map((range) => range.rangeId)
+ .sort();
+}
+
+export function isDocSdtMutationAllowed(documentDataModel: DocumentDataModel, segmentId: string, actions: JSONXActions): boolean {
+ if (!containsTextXEdit(actions) && isStructurePreservingJSONXEdit(actions, getRichTextEditPath(documentDataModel, segmentId))) {
+ return true;
+ }
+ const snapshot = documentDataModel.getSnapshot();
+ const previousBody = getSnapshotBody(snapshot, segmentId);
+ const lockedRanges = previousBody?.customRanges?.filter((range) =>
+ range.rangeType === CustomRangeType.SDT && (
+ (range.properties?.lock && range.properties.lock !== 'unlocked') ||
+ (range.properties?.kind === 'repeatingSection' && range.properties.repeatingSection?.doNotAllowInsertDelete)
+ )
+ );
+ if (!previousBody || !lockedRanges?.length) {
+ return true;
+ }
+ // Preview before applying: an inverse TextX edit can merge imported runs,
+ // so rolling back a rejected keystroke is not an exact no-op.
+ const candidate = JSONX.apply(Tools.deepClone(snapshot), actions) as unknown as IDocumentData;
+ const currentBody = getSnapshotBody(candidate, segmentId);
+
+ for (const previous of lockedRanges) {
+ const lock = previous.properties?.lock;
+ const current = currentBody?.customRanges?.find((range) => range.rangeId === previous.rangeId && range.rangeType === CustomRangeType.SDT);
+ const wrapperLocked = lock === 'sdtLocked' || lock === 'sdtContentLocked';
+ const contentLocked = lock === 'contentLocked' || lock === 'sdtContentLocked';
+ if (wrapperLocked && !current) {
+ return false;
+ }
+ if (previous.properties?.kind === 'repeatingSection' && previous.properties.repeatingSection?.doNotAllowInsertDelete &&
+ current && currentBody) {
+ const before = getRepeatingItemIds(previousBody, previous);
+ const after = getRepeatingItemIds(currentBody, current);
+ if (before.length !== after.length || before.some((id, index) => id !== after[index])) {
+ return false;
+ }
+ }
+ // Word allows deleting a contentLocked control as a whole, but not changing its contents.
+ if (contentLocked && current && currentBody) {
+ const before = getLockedSdtContent(previousBody, previous);
+ const after = getLockedSdtContent(currentBody, current);
+ // Content locking protects the value, not the control's developer properties.
+ // Word still lets the author change or clear the lock from Content Control Properties.
+ if (before !== after && !isBoundSdtValueUpdate(snapshot, candidate, previous as ISdtCustomRange, current as ISdtCustomRange, currentBody)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+function isBoundSdtValueUpdate(
+ before: IDocumentData,
+ after: IDocumentData,
+ previous: ISdtCustomRange,
+ current: ISdtCustomRange,
+ currentBody: IDocumentBody
+): boolean {
+ const key = getSdtBindingKey(previous);
+ const value = getSdtBindingValue(currentBody, current);
+ if (!key || key !== getSdtBindingKey(current) || value === undefined) {
+ return false;
+ }
+ const segments = ['', ...Object.keys(before.headers ?? {}), ...Object.keys(before.footers ?? {}), ...Object.keys(before.notes ?? {})];
+ return segments.some((segmentId) => {
+ const previousBody = getSnapshotBody(before, segmentId);
+ const nextBody = getSnapshotBody(after, segmentId);
+ if (!previousBody || !nextBody) {
+ return false;
+ }
+ return previousBody.customRanges?.some((range) => {
+ if (range.rangeType !== CustomRangeType.SDT || range.properties?.lock === 'contentLocked' ||
+ range.properties?.lock === 'sdtContentLocked' || getSdtBindingKey(range as ISdtCustomRange) !== key) {
+ return false;
+ }
+ const next = nextBody.customRanges?.find((item) => item.rangeType === CustomRangeType.SDT && item.rangeId === range.rangeId);
+ // Word updates locked mirrors through the shared XML node, but a direct
+ // edit of the locked control alone must still be rejected.
+ return next != null && getSdtBindingKey(next as ISdtCustomRange) === key &&
+ getSdtBindingValue(previousBody, range as ISdtCustomRange) !== value &&
+ getSdtBindingValue(nextBody, next as ISdtCustomRange) === value;
+ }) ?? false;
+ });
+}
+
export function validateDocStructureMutation(
documentDataModel: DocumentDataModel,
segmentId: string,
actions: JSONXActions,
- undoActions: JSONXActions
+ undoActions: JSONXActions,
+ isHistoryReplay = false
): boolean {
const editPath = getRichTextEditPath(documentDataModel, segmentId);
const preservesStructure =
@@ -219,6 +401,11 @@ export function validateDocStructureMutation(
}
if (component.et === TextX.id && Array.isArray(component.e)) {
for (const action of component.e) {
+ if (isRecord(action) && Array.isArray(action.rangeUpdates) && action.rangeUpdates.some((update) =>
+ isRecord(update) && isRecord(update.range) &&
+ (update.range.rangeType === CustomRangeType.FOOTNOTE || update.range.rangeType === CustomRangeType.ENDNOTE))) {
+ changesFootnoteStructure = true;
+ }
const ranges: unknown = isRecord(action) && isRecord(action.body) ? action.body.customRanges : undefined;
if (Array.isArray(ranges) && ranges.some((range) => isRecord(range) && (range.rangeType === CustomRangeType.FOOTNOTE || range.rangeType === CustomRangeType.ENDNOTE))) {
changesFootnoteStructure = true;
@@ -231,8 +418,8 @@ export function validateDocStructureMutation(
if (issues.length > 0) {
throw new Error(`[DocStructure] ${issues.map((issue) => `${issue.code}@${issue.index ?? issue.segmentId ?? ''}`).join(', ')}`);
}
- } else if (!preservesStructure) {
- assertValidDocBodyStructure(documentDataModel, segmentId);
+ } else if (!preservesStructure && !isHistoryReplay) {
+ assertValidDocBodyStructure(documentDataModel, segmentId, undoActions);
}
return preservesStructure && !changesFootnoteStructure;
}
diff --git a/packages/docs/src/facade/__tests__/f-document.spec.ts b/packages/docs/src/facade/__tests__/f-document.spec.ts
index 59ada7a319..0dd6c544de 100644
--- a/packages/docs/src/facade/__tests__/f-document.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document.spec.ts
@@ -30,8 +30,9 @@ import {
SectionType,
UniverInstanceType,
} from '@univerjs/core';
-import { DocSelectionManagerService, InsertTextCommand } from '@univerjs/docs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { InsertTextCommand } from '../../commands/commands/core-editing.command';
+import { DocSelectionManagerService } from '../../services/doc-selection-manager.service';
import { createDocumentData, createSimpleDocument, createTestBed } from './create-test-bed';
describe('FDocument', () => {
@@ -100,6 +101,24 @@ describe('FDocument', () => {
expect(document.save().body?.dataStream).toBe('Hello,\rLine 1\rLine 2\r\n');
});
+ it.each(['DOC_WORD_STYLES_PLUGIN', 'DOC_NOTE_PLUGIN'])('preserves %s through editing, save and reopening', (name) => {
+ univer.dispose();
+ const data = createSimpleDocument('word-metadata');
+ const resource = {
+ name,
+ data: JSON.stringify({ stylesXml: '<styles/>', coreProperties: { xml: '<core/>', sourceName: 'Imported' } }),
+ };
+ data.resources = [resource];
+ createDocumentFacade(data);
+ expect(document.insertText(0, 'Edited ')).toBe(true);
+ const saved = document.save();
+ expect(saved.resources?.find((item) => item.name === resource.name)).toEqual(resource);
+ expect(saved.body?.dataStream).toContain('Edited ');
+ univer.dispose();
+ createDocumentFacade(saved);
+ expect(document.save().resources?.find((item) => item.name === resource.name)).toEqual(resource);
+ });
+
it('includes current document resources in saved snapshots', () => {
const resourceManagerService = get(IResourceManagerService);
diff --git a/packages/docs/src/layout-worker/__tests__/document-font-metrics.spec.ts b/packages/docs/src/layout-worker/__tests__/document-font-metrics.spec.ts
index f9c55f81f1..d353bb0db2 100644
--- a/packages/docs/src/layout-worker/__tests__/document-font-metrics.spec.ts
+++ b/packages/docs/src/layout-worker/__tests__/document-font-metrics.spec.ts
@@ -14,11 +14,38 @@
* limitations under the License.
*/
-import { JSONX } from '@univerjs/core';
-import { describe, expect, it } from 'vitest';
-import { collectDocumentFontFamilies } from '../document-font-metrics';
+import { BooleanNumber, DEFAULT_STYLES, JSONX } from '@univerjs/core';
+import { FontCache, getFontStyleString } from '@univerjs/engine-render';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { collectDocumentFontFamilies, measureDocumentFontFamilies } from '../document-font-metrics';
describe('document font metrics', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ FontCache.invalidateMetrics(() => true);
+ });
+
+ it.each(['Latin Font', undefined])('transfers the composite East Asian font key used in document layout (%s)', (ff) => {
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({ height: 3000 } as DOMRect);
+ const families = new Set<string>();
+ collectDocumentFontFamilies({ ts: { ff, eastAsiaFontFamily: 'East Asian Font' } }, families);
+ const transferred = measureDocumentFontFamilies(families);
+ const primary = ff || DEFAULT_STYLES.ff;
+ const fontStyles = [
+ `${primary}, East Asian Font`,
+ `East Asian Font, ${primary}, East Asian Font`,
+ ].flatMap((family) => [BooleanNumber.FALSE, BooleanNumber.TRUE].flatMap((bl) =>
+ [BooleanNumber.FALSE, BooleanNumber.TRUE].map((it) => getFontStyleString({ ff: family, fs: 12, bl, it }))));
+
+ FontCache.invalidateMetrics(() => true);
+ vi.stubGlobal('document', undefined);
+ FontCache.setNormalLineHeightCache(transferred);
+ for (const fontStyle of fontStyles) {
+ expect(FontCache.getNormalLineHeight(fontStyle), fontStyle.fontString).toBe(18);
+ }
+ });
+
it('collects inherited, header and footnote families and font changes without inspecting text content', () => {
const families = new Set<string>();
collectDocumentFontFamilies({
diff --git a/packages/docs/src/layout-worker/__tests__/font-loader.spec.ts b/packages/docs/src/layout-worker/__tests__/font-loader.spec.ts
new file mode 100644
index 0000000000..192d5b9279
--- /dev/null
+++ b/packages/docs/src/layout-worker/__tests__/font-loader.spec.ts
@@ -0,0 +1,128 @@
+/**
+ * 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 { FontCache } from '@univerjs/engine-render';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { DocsLayoutFontLoader } from '../font-loader';
+
+function stubFontPlatform(worker = false, loading: Promise<void> = Promise.resolve()) {
+ const faces = new Set<FontFace>();
+ class PlatformFontFace {
+ constructor(readonly family: string, readonly source: string | ArrayBuffer, readonly descriptors?: FontFaceDescriptors) {}
+
+ async load() {
+ await loading;
+ return this;
+ }
+ }
+ vi.stubGlobal('FontFace', PlatformFontFace);
+ if (worker) {
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('fonts', faces);
+ } else {
+ vi.stubGlobal('document', { fonts: faces });
+ }
+ return faces;
+}
+
+describe('DocsLayoutFontLoader', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ FontCache.invalidateMetrics(() => true);
+ });
+
+ it.each([false, true])('loads identical bytes and descriptors in the %s worker realm and drops stale fallback metrics', async (worker) => {
+ const faces = stubFontPlatform(worker);
+ const loader = new DocsLayoutFontLoader();
+ const source = new Uint8Array([1, 2, 3]).buffer;
+ FontCache.setFontMeasureCache('11pt MissingFace', 'A', {
+ width: 7,
+ fontBoundingBoxAscent: 8,
+ fontBoundingBoxDescent: 2,
+ actualBoundingBoxAscent: 7,
+ actualBoundingBoxDescent: 1,
+ });
+ await loader.load([{ family: 'Document Face', source, descriptors: { weight: '700', style: 'italic' } }]);
+ expect([...faces]).toMatchObject([{ family: 'Document Face', source, descriptors: { weight: '700', style: 'italic' } }]);
+ expect(FontCache.getFontMeasureCache('11pt MissingFace', 'A')).toBeUndefined();
+ loader.dispose();
+ expect(faces.size).toBe(0);
+ });
+
+ it('waits for all faces before publishing them and removes only the faces it owns', async () => {
+ let finish!: () => void;
+ const pending = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const faces = stubFontPlatform(false, pending);
+ const externalFace = new FontFace('Existing Face', 'url(existing.woff2)');
+ faces.add(externalFace);
+ const loader = new DocsLayoutFontLoader();
+ const loading = loader.load([{ family: 'New Face', source: 'url(new.woff2)' }]);
+ expect([...faces]).toEqual([externalFace]);
+ finish();
+ await loading;
+ expect(faces.size).toBe(2);
+ loader.dispose();
+ loader.dispose();
+ expect([...faces]).toEqual([externalFace]);
+ });
+
+ it('does not publish a font after its owner is disposed during loading', async () => {
+ let finish!: () => void;
+ const pending = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const faces = stubFontPlatform(false, pending);
+ const loader = new DocsLayoutFontLoader();
+ const loading = loader.load([{ family: 'Pending Face', source: 'url(pending.woff2)' }]);
+ loader.dispose();
+ finish();
+ await expect(loading).rejects.toThrow('disposed');
+ expect(faces.size).toBe(0);
+ });
+
+ it('does not silently render with fallback metrics after a configured face fails to load', async () => {
+ const faces = stubFontPlatform(false, Promise.reject(new Error('Font request failed')));
+ const loader = new DocsLayoutFontLoader();
+ await expect(loader.load([{ family: 'Missing Face', source: 'url(missing.woff2)' }])).rejects.toThrow('Font request failed');
+ expect(faces.size).toBe(0);
+ });
+
+ it('requires the platform only when explicit font faces are configured', async () => {
+ vi.stubGlobal('FontFace', undefined);
+ const emptyLoader = new DocsLayoutFontLoader();
+ await expect(emptyLoader.load([])).resolves.toBeUndefined();
+ emptyLoader.dispose();
+ const loader = new DocsLayoutFontLoader();
+ await expect(loader.load([{ family: 'Font', source: 'url(font.woff2)' }])).rejects.toThrow('FontFace support');
+ loader.dispose();
+ });
+
+ it('rejects empty configured font names and sources', async () => {
+ const faces = stubFontPlatform();
+ for (const definition of [
+ { family: '', source: 'url(font.woff2)' },
+ { family: 'Font', source: '' },
+ { family: 'Font', source: new ArrayBuffer(0) },
+ ]) {
+ const loader = new DocsLayoutFontLoader();
+ await expect(loader.load([definition])).rejects.toThrow('must not be empty');
+ loader.dispose();
+ }
+ expect(faces.size).toBe(0);
+ });
+});
diff --git a/packages/docs/src/layout-worker/config/config.ts b/packages/docs/src/layout-worker/config/config.ts
index e0db36230d..f49ac8ec89 100644
--- a/packages/docs/src/layout-worker/config/config.ts
+++ b/packages/docs/src/layout-worker/config/config.ts
@@ -20,8 +20,17 @@ export const configSymbol = Symbol(DOCS_LAYOUT_WORKER_PLUGIN_CONFIG_KEY);
export const DEFAULT_DOCS_LAYOUT_WORKER_REQUEST_TIMEOUT_MS = 15_000;
+export interface IDocsLayoutFontFace {
+ family: string;
+ /** Font bytes or a CSS FontFace source, such as url("https://example.test/font.woff2"). */
+ source: string | ArrayBuffer;
+ descriptors?: FontFaceDescriptors;
+}
+
export interface IUniverDocsLayoutWorkerConfig {
workerFactory?: () => Worker;
+ /** Licensed web fonts to load in both the rendering context and the layout Worker before layout. */
+ fontFaces?: IDocsLayoutFontFace[];
/** Maximum time allowed for one Worker RPC request before recovery starts. */
requestTimeoutMs?: number;
}
diff --git a/packages/docs/src/layout-worker/document-font-metrics.ts b/packages/docs/src/layout-worker/document-font-metrics.ts
index 54e5c60d18..d60a2b6abd 100644
--- a/packages/docs/src/layout-worker/document-font-metrics.ts
+++ b/packages/docs/src/layout-worker/document-font-metrics.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { BooleanNumber } from '@univerjs/core';
+import { BooleanNumber, DEFAULT_STYLES } from '@univerjs/core';
import { FontCache, getFontStyleString } from '@univerjs/engine-render';
/** Collect once from the snapshot, then only from mutation payloads (including JSON1 font replacements). */
@@ -32,6 +32,14 @@ export function collectDocumentFontFamilies(value: unknown, families: Set<string
}
return;
}
+ const textStyle = value as { ff?: unknown; eastAsiaFontFamily?: unknown };
+ if (typeof textStyle.eastAsiaFontFamily === 'string' && textStyle.eastAsiaFontFamily.trim()) {
+ // Shaping appends the fallback for Latin text and prepends it for East Asian glyphs.
+ // Transfer both keys so Worker leading does not depend on prior UI shaping.
+ const primary = typeof textStyle.ff === 'string' && textStyle.ff.trim() ? textStyle.ff : DEFAULT_STYLES.ff;
+ families.add(`${primary}, ${textStyle.eastAsiaFontFamily.trim()}`);
+ families.add(`${textStyle.eastAsiaFontFamily.trim()}, ${primary}, ${textStyle.eastAsiaFontFamily.trim()}`);
+ }
for (const [key, item] of Object.entries(value)) {
if (key === 'ff' && typeof item === 'string') {
families.add(item);
diff --git a/packages/docs/src/layout-worker/font-loader.ts b/packages/docs/src/layout-worker/font-loader.ts
new file mode 100644
index 0000000000..58ab7cbaf2
--- /dev/null
+++ b/packages/docs/src/layout-worker/font-loader.ts
@@ -0,0 +1,77 @@
+/**
+ * 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 { IDocsLayoutFontFace } from './config/config';
+import { Disposable } from '@univerjs/core';
+import { FontCache } from '@univerjs/engine-render';
+
+/** Owns the same explicitly supplied font faces in the rendering and layout realms. */
+export class DocsLayoutFontLoader extends Disposable {
+ private _loading: Promise<void> | null = null;
+ private _fontSet: FontFaceSet | undefined;
+ private _faces: FontFace[] = [];
+
+ load(fonts: readonly IDocsLayoutFontFace[]): Promise<void> {
+ this._loading ??= this._load(fonts);
+ return this._loading;
+ }
+
+ override dispose(): void {
+ for (const face of this._faces) {
+ this._fontSet?.delete(face);
+ }
+ if (this._faces.length > 0) {
+ // A face can replace the fallback of any cached font stack.
+ FontCache.invalidateMetrics(() => true);
+ }
+ this._faces = [];
+ this._fontSet = undefined;
+ super.dispose();
+ }
+
+ private async _load(fonts: readonly IDocsLayoutFontFace[]): Promise<void> {
+ this.ensureNotDisposed();
+ if (fonts.length === 0) {
+ return;
+ }
+ const fontSet = typeof document === 'undefined'
+ ? (globalThis as { fonts?: FontFaceSet }).fonts
+ : document.fonts;
+ if (typeof FontFace === 'undefined' || fontSet == null) {
+ throw new Error('Document layout requires FontFace support to load the configured fonts.');
+ }
+
+ try {
+ const faces = fonts.map(({ family, source, descriptors }) => {
+ if (!family.trim() || (typeof source === 'string' ? !source.trim() : source.byteLength === 0)) {
+ throw new TypeError('Document layout font family and source must not be empty.');
+ }
+ return new FontFace(family, source, descriptors);
+ });
+ await Promise.all(faces.map((face) => face.load()));
+ this.ensureNotDisposed();
+ this._fontSet = fontSet;
+ this._faces = faces;
+ for (const face of faces) {
+ fontSet.add(face);
+ }
+ FontCache.invalidateMetrics(() => true);
+ } catch (error) {
+ this.dispose();
+ throw error;
+ }
+ }
+}
diff --git a/packages/docs/src/layout-worker/index.ts b/packages/docs/src/layout-worker/index.ts
index 5bf95dfcc2..ca38450007 100644
--- a/packages/docs/src/layout-worker/index.ts
+++ b/packages/docs/src/layout-worker/index.ts
@@ -16,7 +16,7 @@
import type { IMessageProtocol } from '@univerjs/rpc';
import type { IDocLayoutCancelRequest, IDocLayoutCreateSessionRequest, IDocLayoutDisposeMountRequest, IDocLayoutDisposeSessionRequest, IDocLayoutExecutor, IDocLayoutPageRequest, IDocLayoutPageResult, IDocLayoutPerformanceMetrics, IDocLayoutStartRequest, IDocLayoutStartResult, IDocLayoutStepRequest, IDocLayoutStepResult } from '../services/doc-layout-executor.service';
-import type { IUniverDocsLayoutWorkerConfig } from './config/config';
+import type { IDocsLayoutFontFace, IUniverDocsLayoutWorkerConfig } from './config/config';
import type { IDocsLayoutWorkerCapabilities, IDocsLayoutWorkerRuntime } from './protocol';
import { DependentOn, Disposable, IConfigService, Inject, Injector, merge, Plugin, Tools } from '@univerjs/core';
import { FontCache } from '@univerjs/engine-render';
@@ -27,6 +27,7 @@ import { UniverDocsPlugin } from '../plugin';
import { DocLayoutExecutorService, DocLayoutExecutorType } from '../services/doc-layout-executor.service';
import { DEFAULT_DOCS_LAYOUT_WORKER_REQUEST_TIMEOUT_MS, defaultPluginDocsLayoutWorkerConfig, DOCS_LAYOUT_WORKER_PLUGIN_CONFIG_KEY } from './config/config';
import { collectDocumentFontFamilies, measureDocumentFontFamilies } from './document-font-metrics';
+import { DocsLayoutFontLoader } from './font-loader';
import { DocsLayoutWorkerPerformanceTracker } from './performance-tracker';
import { DOCS_LAYOUT_WORKER_CHANNEL, DOCS_LAYOUT_WORKER_PROTOCOL_VERSION } from './protocol';
import { startDocsLayoutWorker } from './worker';
@@ -67,12 +68,15 @@ export class DocsLayoutWorkerClientService extends Disposable implements IDocLay
private _initialized = false;
private readonly _performanceTracker = new DocsLayoutWorkerPerformanceTracker();
private readonly _fontFamilies = new Map<string, Set<string>>();
+ private readonly _fontLoader = new DocsLayoutFontLoader();
constructor(
private readonly _workerFactory: () => Worker,
- private readonly _requestTimeoutMs = DEFAULT_DOCS_LAYOUT_WORKER_REQUEST_TIMEOUT_MS
+ private readonly _requestTimeoutMs = DEFAULT_DOCS_LAYOUT_WORKER_REQUEST_TIMEOUT_MS,
+ private readonly _fontFaces: IDocsLayoutFontFace[] = []
) {
super();
+ this.disposeWithMe(this._fontLoader);
this._initialization = this._replaceRuntime();
}
@@ -80,7 +84,12 @@ export class DocsLayoutWorkerClientService extends Disposable implements IDocLay
return this._initialization;
}
- getCapabilities(): Promise<IDocsLayoutWorkerCapabilities> {
+ get renderingFontsReady(): Promise<void> | undefined {
+ return this._fontFaces.length > 0 ? this._initialization : undefined;
+ }
+
+ async getCapabilities(): Promise<IDocsLayoutWorkerCapabilities> {
+ await this._initialization;
return this._getRuntime().getCapabilities();
}
@@ -180,6 +189,8 @@ export class DocsLayoutWorkerClientService extends Disposable implements IDocLay
private async _replaceRuntime(): Promise<void> {
this._initialized = false;
this._disposeRuntime();
+ await this._withTimeout(this._fontLoader.load(this._fontFaces), 'load rendering fonts');
+ this.ensureNotDisposed();
const worker = this._workerFactory();
const channelService = new ChannelService(createDocsLayoutWorkerMessageProtocol(worker, this._performanceTracker));
this._worker = worker;
@@ -187,8 +198,17 @@ export class DocsLayoutWorkerClientService extends Disposable implements IDocLay
this._runtime = toModule<IDocsLayoutWorkerRuntime>(
channelService.requestChannel(DOCS_LAYOUT_WORKER_CHANNEL)
);
- await this._withTimeout(this._verifyCapabilities(), 'verify capabilities');
- this._initialized = true;
+ try {
+ await this._withTimeout(this._runtime.initialize(this._fontFaces), 'load Worker fonts');
+ await this._withTimeout(this._verifyCapabilities(), 'verify capabilities');
+ this.ensureNotDisposed();
+ this._initialized = true;
+ } catch (error) {
+ if (this._worker === worker) {
+ this._disposeRuntime();
+ }
+ throw error;
+ }
}
private _disposeRuntime(): void {
@@ -224,7 +244,7 @@ export class DocsLayoutWorkerClientService extends Disposable implements IDocLay
}
private async _verifyCapabilities(): Promise<void> {
- const capabilities = await this.getCapabilities();
+ const capabilities = await this._getRuntime().getCapabilities();
if (capabilities.protocolVersion !== DOCS_LAYOUT_WORKER_PROTOCOL_VERSION) {
throw new DocsLayoutWorkerCapabilityError('Document layout Worker protocol version mismatch.');
}
@@ -286,7 +306,7 @@ export class UniverDocsLayoutWorkerPlugin extends Plugin {
throw new RangeError('[UniverDocsLayoutWorkerPlugin]: requestTimeoutMs must be a positive finite number.');
}
- const client = new DocsLayoutWorkerClientService(this._config.workerFactory, requestTimeoutMs);
+ const client = new DocsLayoutWorkerClientService(this._config.workerFactory, requestTimeoutMs, this._config.fontFaces);
this._injector.add([DocsLayoutWorkerClientService, { useValue: client }]);
this.disposeWithMe(client);
this.disposeWithMe(this._layoutExecutorService.register(client));
diff --git a/packages/docs/src/layout-worker/protocol.ts b/packages/docs/src/layout-worker/protocol.ts
index 4c0e11aabc..1bf4813364 100644
--- a/packages/docs/src/layout-worker/protocol.ts
+++ b/packages/docs/src/layout-worker/protocol.ts
@@ -15,6 +15,7 @@
*/
import type { DocLayoutExecutorType, IDocLayoutExecutor } from '../services/doc-layout-executor.service';
+import type { IDocsLayoutFontFace } from './config/config';
export const DOCS_LAYOUT_WORKER_CHANNEL = 'univer.docs-layout-worker';
export const DOCS_LAYOUT_WORKER_PROTOCOL_VERSION = 5;
@@ -36,5 +37,6 @@ export interface IDocsLayoutWorkerCapabilities {
}
export interface IDocsLayoutWorkerRuntime extends IDocLayoutExecutor {
+ initialize(fontFaces?: IDocsLayoutFontFace[]): Promise<void>;
getCapabilities(): Promise<IDocsLayoutWorkerCapabilities>;
}
diff --git a/packages/docs/src/layout-worker/worker.ts b/packages/docs/src/layout-worker/worker.ts
index 98ef2cd301..b46dcdcba0 100644
--- a/packages/docs/src/layout-worker/worker.ts
+++ b/packages/docs/src/layout-worker/worker.ts
@@ -18,12 +18,14 @@ import type { ICustomRangeForInterceptor } from '@univerjs/core';
import type { IDocsCustomBlockRenderViewport } from '@univerjs/engine-render';
import type { IMessageProtocol } from '@univerjs/rpc';
import type { IDocLayoutCancelRequest, IDocLayoutCreateSessionRequest, IDocLayoutCustomRangePresentationEntry, IDocLayoutDisposeMountRequest, IDocLayoutDisposeSessionRequest, IDocLayoutMountIdentity, IDocLayoutPageRequest, IDocLayoutPageResult, IDocLayoutPerformanceMetrics, IDocLayoutStartRequest, IDocLayoutStartResult, IDocLayoutStepRequest, IDocLayoutStepResult } from '../services/doc-layout-executor.service';
+import type { IDocsLayoutFontFace } from './config/config';
import type { IDocsLayoutWorkerCapabilities, IDocsLayoutWorkerRuntime } from './protocol';
import { DocumentDataModel, LocaleService, requestImmediateMacroTask, Tools } from '@univerjs/core';
import { DocumentLayoutSession, FontCache, setDocsCustomBlockRenderViewportProvider } from '@univerjs/engine-render';
import { ChannelService, fromModule } from '@univerjs/rpc';
import { Observable, shareReplay } from 'rxjs';
import { DocLayoutExecutorType, DocLayoutSessionStatus } from '../services/doc-layout-executor.service';
+import { DocsLayoutFontLoader } from './font-loader';
import { DocsLayoutWorkerPerformanceTracker } from './performance-tracker';
import { DOCS_LAYOUT_WORKER_CHANNEL, DOCS_LAYOUT_WORKER_PROTOCOL_VERSION } from './protocol';
@@ -95,14 +97,15 @@ function applyRecordPatch<T>(
export class DocsLayoutWorkerRuntime implements IDocsLayoutWorkerRuntime {
private readonly _sessions = new Map<string, IDocsLayoutWorkerSession>();
+ private readonly _fontLoader = new DocsLayoutFontLoader();
readonly type = DocLayoutExecutorType.WORKER;
constructor(
private readonly _performanceTracker = new DocsLayoutWorkerPerformanceTracker()
) {}
- initialize(): Promise<void> {
- return Promise.resolve();
+ initialize(fontFaces: IDocsLayoutFontFace[] = []): Promise<void> {
+ return this._fontLoader.load(fontFaces);
}
async getCapabilities(): Promise<IDocsLayoutWorkerCapabilities> {
@@ -402,6 +405,7 @@ export class DocsLayoutWorkerRuntime implements IDocsLayoutWorkerRuntime {
}
dispose(): void {
+ this._fontLoader.dispose();
for (const unitId of this._sessions.keys()) {
this._disposeSession(unitId);
}
@@ -499,12 +503,24 @@ export class DocsLayoutWorkerRuntime implements IDocsLayoutWorkerRuntime {
}
}
+class DocsLayoutWorkerChannelService extends ChannelService {
+ constructor(protocol: IMessageProtocol, private readonly _runtime: DocsLayoutWorkerRuntime) {
+ super(protocol);
+ }
+
+ override dispose(): void {
+ this._runtime.dispose();
+ super.dispose();
+ }
+}
+
export function startDocsLayoutWorker(): ChannelService {
const performanceTracker = new DocsLayoutWorkerPerformanceTracker();
- const channelService = new ChannelService(createDocsLayoutWorkerMessageProtocol(performanceTracker));
+ const runtime = new DocsLayoutWorkerRuntime(performanceTracker);
+ const channelService = new DocsLayoutWorkerChannelService(createDocsLayoutWorkerMessageProtocol(performanceTracker), runtime);
channelService.registerChannel(
DOCS_LAYOUT_WORKER_CHANNEL,
- fromModule(new DocsLayoutWorkerRuntime(performanceTracker))
+ fromModule(runtime)
);
return channelService;
}
diff --git a/packages/docs/src/plugin.ts b/packages/docs/src/plugin.ts
index d8ede39f14..d9e20ff361 100644
--- a/packages/docs/src/plugin.ts
+++ b/packages/docs/src/plugin.ts
@@ -21,9 +21,11 @@ import {
IConfigService,
Inject,
Injector,
+ IResourceManagerService,
merge,
ObjectPermissionService,
Plugin,
+ UniverInstanceType,
} from '@univerjs/core';
import { UnitObject } from '@univerjs/protocol';
import pkg from '../package.json';
@@ -94,6 +96,23 @@ export class UniverDocsPlugin extends Plugin {
));
this._initializeDependencies();
this._initializeCommands();
+ this._initializeWordResources();
+ }
+
+ private _initializeWordResources(): void {
+ // Imported Word package metadata is opaque to editing but must survive save().
+ for (const pluginName of ['DOC_WORD_STYLES_PLUGIN', 'DOC_NOTE_PLUGIN'] as const) {
+ const resources = new Map<string, string>();
+ this.disposeWithMe({ dispose: () => resources.clear() });
+ this.disposeWithMe(this._injector.get(IResourceManagerService).registerPluginResource({
+ pluginName,
+ businesses: [UniverInstanceType.UNIVER_DOC],
+ parseJson: (data: string) => data,
+ onLoad: (unitId, data) => { resources.set(unitId, data); },
+ onUnLoad: (unitId) => { resources.delete(unitId); },
+ toJson: (unitId) => resources.get(unitId) ?? '',
+ }));
+ }
}
private _initializeCommands(): void {
diff --git a/packages/docs/src/services/__tests__/doc-layout-executor.service.spec.ts b/packages/docs/src/services/__tests__/doc-layout-executor.service.spec.ts
index 6e190157d4..e9e55cfdc6 100644
--- a/packages/docs/src/services/__tests__/doc-layout-executor.service.spec.ts
+++ b/packages/docs/src/services/__tests__/doc-layout-executor.service.spec.ts
@@ -606,7 +606,7 @@ describe('DocLayoutExecutorService', () => {
]);
});
- it('serializes main-thread custom block viewport measurements with a layout start', async () => {
+ it.each(['body', 'header', 'footer'] as const)('serializes main-thread custom block viewport measurements from the %s with a layout start', async (story) => {
const injector = univer.__getInjector();
const service = injector.get(DocLayoutExecutorService);
const executor = createExecutor();
@@ -648,6 +648,17 @@ describe('DocLayoutExecutorService', () => {
},
},
};
+ if (story !== 'body') {
+ const body = documentData.body;
+ documentData.body = createDocumentData('traditional-doc', DocumentFlavor.TRADITIONAL).body;
+ if (story === 'header') {
+ documentData.headers = { header: { headerId: 'header', body } };
+ documentData.documentStyle.defaultHeaderId = 'header';
+ } else {
+ documentData.footers = { footer: { footerId: 'footer', body } };
+ documentData.documentStyle.defaultFooterId = 'footer';
+ }
+ }
univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, documentData);
await Promise.resolve();
diff --git a/packages/docs/src/services/__tests__/doc-state-change-manager.service.spec.ts b/packages/docs/src/services/__tests__/doc-state-change-manager.service.spec.ts
index 146dd69260..0e92e55e48 100644
--- a/packages/docs/src/services/__tests__/doc-state-change-manager.service.spec.ts
+++ b/packages/docs/src/services/__tests__/doc-state-change-manager.service.spec.ts
@@ -77,6 +77,25 @@ describe('DocStateChangeManagerService', () => {
};
}
+ it('cancels pending history and collaboration callbacks when disposed', () => {
+ vi.useFakeTimers();
+ const { service, emitter, undoRedoService } = createService();
+ const changes: unknown[] = [];
+ const completed = vi.fn();
+ service.docStateChange$.subscribe({ next: (value) => changes.push(value), complete: completed });
+ emitter.emitStateChangeInfo(createChange({ debounce: true }));
+ expect(vi.getTimerCount()).toBe(2);
+
+ service.dispose();
+
+ expect(vi.getTimerCount()).toBe(0);
+ expect(service.getStateCache('doc-1')).toEqual({ history: [], collaboration: [] });
+ vi.advanceTimersByTime(300);
+ expect(undoRedoService.pitchTopUndoElement()).toBeNull();
+ expect(changes).toEqual([null]);
+ expect(completed).toHaveBeenCalledOnce();
+ });
+
it('turns emitted document edits into history items and collaboration change events', () => {
const { service, emitter, undoRedoService, univerInstanceService } = createService();
const changes: unknown[] = [];
@@ -89,8 +108,8 @@ describe('DocStateChangeManagerService', () => {
expect(undoRedoService.pitchTopUndoElement()).toMatchObject({
unitID: 'doc-1',
- undoMutations: [{ id: 'doc.rich-text-editing' }],
- redoMutations: [{ id: 'doc.rich-text-editing' }],
+ undoMutations: [{ id: 'doc.rich-text-editing', params: { trigger: 'univer.command.undo' } }],
+ redoMutations: [{ id: 'doc.rich-text-editing', params: { trigger: 'univer.command.redo' } }],
});
expect(changes.at(-1)).toMatchObject({
commandId: 'doc.rich-text-editing',
diff --git a/packages/docs/src/services/__tests__/document-layout-snapshot.spec.ts b/packages/docs/src/services/__tests__/document-layout-snapshot.spec.ts
index 07bf0e3244..5478a5c10c 100644
--- a/packages/docs/src/services/__tests__/document-layout-snapshot.spec.ts
+++ b/packages/docs/src/services/__tests__/document-layout-snapshot.spec.ts
@@ -19,6 +19,47 @@ import { describe, expect, it } from 'vitest';
import { createDocumentLayoutSnapshot } from '../document-layout-snapshot';
describe('createDocumentLayoutSnapshot', () => {
+ it('transfers note stories and their table geometry without raw exchange payloads', () => {
+ const snapshot: IDocumentData = {
+ id: 'note-layout',
+ documentStyle: {},
+ footnotes: {
+ 7: {
+ noteId: '7',
+ type: 'normal',
+ tableSource: {},
+ body: {
+ dataStream: '\bNote\r\n',
+ textRuns: [{ st: 0, ed: 1, ts: { fs: 9 } }],
+ customBlocks: [{ startIndex: 0, blockId: 'footnote-7', noteType: 'footnote', noteId: '7' }],
+ docxRawBlocks: [{ startIndex: 0, xml: '<w:footnote />' }],
+ },
+ },
+ '-1': {
+ noteId: '-1',
+ type: 'separator',
+ body: { dataStream: '\b\r\n' },
+ },
+ },
+ endnotes: {
+ 7: { noteId: '7', type: 'normal', body: { dataStream: 'Endnote\r\n', payloads: { raw: 'excluded' } } },
+ },
+ };
+
+ const projected = createDocumentLayoutSnapshot(snapshot);
+
+ expect(projected.footnotes?.['7'].body).toEqual({
+ dataStream: '\bNote\r\n',
+ textRuns: [{ st: 0, ed: 1, ts: { fs: 9 } }],
+ customBlocks: [{ startIndex: 0, blockId: 'footnote-7', noteType: 'footnote', noteId: '7' }],
+ });
+ expect(projected.footnotes?.['7'].tableSource).toEqual({});
+ expect(projected.footnotes?.['-1'].type).toBe('separator');
+ expect(projected.endnotes?.['7'].body).toEqual({ dataStream: 'Endnote\r\n' });
+ expect(snapshot.footnotes?.['7'].body.docxRawBlocks).toHaveLength(1);
+ expect(snapshot.endnotes?.['7'].body.payloads).toEqual({ raw: 'excluded' });
+ });
+
it('excludes exchange-only resources while preserving layout metadata', () => {
const snapshot: IDocumentData = {
id: 'layout-snapshot',
diff --git a/packages/docs/src/services/doc-layout-executor.service.ts b/packages/docs/src/services/doc-layout-executor.service.ts
index 81482a8c42..f1917a6c95 100644
--- a/packages/docs/src/services/doc-layout-executor.service.ts
+++ b/packages/docs/src/services/doc-layout-executor.service.ts
@@ -206,6 +206,8 @@ export interface IDocLayoutStepResult extends IDocumentLayoutStepResult, IDocLay
export interface IDocLayoutExecutor {
readonly type: DocLayoutExecutorType;
+ /** When present, foreground layout must wait for the configured rendering and Worker fonts. */
+ readonly renderingFontsReady?: Promise<void>;
initialize(): Promise<void>;
recover(): Promise<void>;
/**
@@ -331,7 +333,12 @@ function collectCustomBlockViewports(dataModel: DocumentDataModel): Record<strin
const documentStyle = snapshot.documentStyle;
const viewports: Record<string, IDocsCustomBlockRenderViewport> = {};
- for (const customBlock of snapshot.body?.customBlocks ?? []) {
+ const bodies = [
+ snapshot.body,
+ ...Object.values(snapshot.headers ?? {}).map((header) => header.body),
+ ...Object.values(snapshot.footers ?? {}).map((footer) => footer.body),
+ ];
+ for (const customBlock of bodies.flatMap((body) => body?.customBlocks ?? [])) {
const drawing = snapshot.drawings?.[customBlock.blockId];
if (drawing == null) {
continue;
diff --git a/packages/docs/src/services/doc-state-change-manager.service.ts b/packages/docs/src/services/doc-state-change-manager.service.ts
index f8990b0c35..13958e202f 100644
--- a/packages/docs/src/services/doc-state-change-manager.service.ts
+++ b/packages/docs/src/services/doc-state-change-manager.service.ts
@@ -61,6 +61,21 @@ export class DocStateChangeManagerService extends RxDisposable {
this._listenDocStateChange();
}
+ override dispose(): void {
+ if (this._historyTimer != null) {
+ clearTimeout(this._historyTimer);
+ this._historyTimer = null;
+ }
+ if (this._changeStateCacheTimer != null) {
+ clearTimeout(this._changeStateCacheTimer);
+ this._changeStateCacheTimer = null;
+ }
+ this._historyStateCache.clear();
+ this._changeStateCache.clear();
+ this._docStateChange$.complete();
+ super.dispose();
+ }
+
getStateCache(unitId: string) {
return {
history: this._historyStateCache.get(unitId) ?? [],
@@ -77,6 +92,11 @@ export class DocStateChangeManagerService extends RxDisposable {
this._historyStateCache.delete(unitId);
}
+ flushPendingChanges(unitId: string): void {
+ this._pushHistory(unitId);
+ this._emitChangeState(unitId);
+ }
+
private _setChangeState(changeState: IDocStateChangeParams) {
this._cacheChangeState(changeState, 'history');
// Mutations by user or historyService need collaboration.
@@ -124,7 +144,6 @@ export class DocStateChangeManagerService extends RxDisposable {
private _cacheChangeState(changeState: IDocStateChangeParams, type: ChangeStateCacheType = 'history') {
const { trigger, unitId, noHistory, debounce = false } = changeState;
-
if (noHistory || (type === 'history' && trigger == null)) {
return;
}
@@ -195,6 +214,7 @@ export class DocStateChangeManagerService extends RxDisposable {
const redoParams: IRichTextEditingMutationParams = {
unitId,
+ trigger: RedoCommandId,
actions: cacheStates.reduce((acc, cur) => JSONX.compose(acc, cur.redoState.actions), null as JSONXActions),
textRanges: lastState.redoState.textRanges,
segmentId: lastState.segmentId,
@@ -204,6 +224,7 @@ export class DocStateChangeManagerService extends RxDisposable {
const undoParams: IRichTextEditingMutationParams = {
unitId,
+ trigger: UndoCommandId,
// Always need to put undoParams after redoParams, because `reverse` will change the `cacheStates` order.
actions: cacheStates.reverse().reduce((acc, cur) => JSONX.compose(acc, cur.undoState.actions), null as JSONXActions),
textRanges: firstState.undoState.textRanges,
diff --git a/packages/docs/src/services/document-layout-snapshot.ts b/packages/docs/src/services/document-layout-snapshot.ts
index 7684e88cf2..daa4f2bb5c 100644
--- a/packages/docs/src/services/document-layout-snapshot.ts
+++ b/packages/docs/src/services/document-layout-snapshot.ts
@@ -60,9 +60,25 @@ function projectFooter(footer: IFooterData): IFooterData {
* the structured-clone boundary because they do not affect document geometry.
*/
export function createDocumentLayoutSnapshot(snapshot: IDocumentData): IDocumentData {
- const { resources: _resources, body, headers, footers, ...layoutSnapshot } = snapshot;
+ const { resources: _resources, body, headers, footers, footnotes, endnotes, ...layoutSnapshot } = snapshot;
return {
...layoutSnapshot,
+ ...(footnotes == null
+ ? {}
+ : {
+ footnotes: Object.fromEntries(Object.entries(footnotes).map(([id, note]) => [
+ id,
+ { ...note, body: projectDocumentBody(note.body) },
+ ])),
+ }),
+ ...(endnotes == null
+ ? {}
+ : {
+ endnotes: Object.fromEntries(Object.entries(endnotes).map(([id, note]) => [
+ id,
+ { ...note, body: projectDocumentBody(note.body) },
+ ])),
+ }),
...(body == null ? {} : { body: projectDocumentBody(body) }),
...(headers == null
? {}
diff --git a/packages/drawing-ui/src/controllers/__tests__/utils.spec.ts b/packages/drawing-ui/src/controllers/__tests__/utils.spec.ts
index b40b9fbfb3..fa69c181f9 100644
--- a/packages/drawing-ui/src/controllers/__tests__/utils.spec.ts
+++ b/packages/drawing-ui/src/controllers/__tests__/utils.spec.ts
@@ -298,6 +298,23 @@ describe('drawing controller utils', () => {
expect(scene.getObject).not.toHaveBeenCalled();
});
+ it('disposes every repeated drawing instance including hidden ones', () => {
+ const prefix = getDrawingShapeKeyByDrawingSearch({ unitId: 'unit-1', subUnitId: 'doc-1', drawingId: 'footer' });
+ const hidden = { oKey: `${prefix}#-#0`, visible: false, dispose: vi.fn() };
+ const visible = { oKey: `${prefix}#-#1`, visible: true, dispose: vi.fn() };
+ const unrelated = { oKey: `${prefix}-other#-#0`, visible: true, dispose: vi.fn() };
+ const scene = { getAllObjects: () => [hidden, visible, unrelated] };
+ expect(disposeDrawingRenderObject(scene as never, {
+ unitId: 'unit-1',
+ subUnitId: 'doc-1',
+ drawingId: 'footer',
+ isMultiTransform: 1,
+ })).toBe(true);
+ expect(hidden.dispose).toHaveBeenCalledOnce();
+ expect(visible.dispose).toHaveBeenCalledOnce();
+ expect(unrelated.dispose).not.toHaveBeenCalled();
+ });
+
it('does not fall back to top-level scene lookup when grouped lookup misses', () => {
const scene = {
getObject: vi.fn(() => ({ oKey: 'top-level-child', dispose: vi.fn() })),
diff --git a/packages/drawing-ui/src/controllers/drawing-update.controller.ts b/packages/drawing-ui/src/controllers/drawing-update.controller.ts
index 121fac31dc..3fa1d8f610 100644
--- a/packages/drawing-ui/src/controllers/drawing-update.controller.ts
+++ b/packages/drawing-ui/src/controllers/drawing-update.controller.ts
@@ -699,7 +699,7 @@ export class DrawingUpdateController extends Disposable {
this.disposeWithMe(
this._drawingManagerService.remove$.subscribe((params) => {
(params).forEach((param) => {
- const { unitId, subUnitId, drawingId } = param;
+ const { unitId } = param;
const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
@@ -708,7 +708,7 @@ export class DrawingUpdateController extends Disposable {
}
const { scene } = renderObject;
- if (disposeDrawingRenderObject(scene, { unitId, subUnitId, drawingId })) {
+ if (disposeDrawingRenderObject(scene, param)) {
scene.getTransformer()?.clearSelectedObjects();
}
});
diff --git a/packages/drawing-ui/src/controllers/utils.ts b/packages/drawing-ui/src/controllers/utils.ts
index c976fb67aa..c86b05cf0e 100644
--- a/packages/drawing-ui/src/controllers/utils.ts
+++ b/packages/drawing-ui/src/controllers/utils.ts
@@ -17,7 +17,7 @@
import type { IDrawingParam, IDrawingSearch, IUniverInstanceService, Nullable, Workbook } from '@univerjs/core';
import type { IDrawingManagerService } from '@univerjs/drawing';
import type { BaseObject, Scene } from '@univerjs/engine-render';
-import { UniverInstanceType } from '@univerjs/core';
+import { BooleanNumber, UniverInstanceType } from '@univerjs/core';
import { getDrawingShapeKeyByDrawingSearch } from '@univerjs/drawing';
import { DRAWING_OBJECT_LAYER_INDEX, DrawingGroupObject, Group } from '@univerjs/engine-render';
import { resolveDrawingUIRotateEnabled } from '../utils/rotate-enabled';
@@ -27,7 +27,15 @@ export function getDrawingRenderObject(scene: Scene, drawingSearch: IDrawingSear
return scene.getObjectIncludeInGroup(key) ?? null;
}
-export function disposeDrawingRenderObject(scene: Scene, drawingSearch: IDrawingSearch): boolean {
+export function disposeDrawingRenderObject(scene: Scene, drawingSearch: IDrawingSearch & { isMultiTransform?: BooleanNumber }): boolean {
+ if (drawingSearch.isMultiTransform === BooleanNumber.TRUE) {
+ const key = getDrawingShapeKeyByDrawingSearch(drawingSearch);
+ const prefix = `${key}#-#`;
+ // Repeated header/footer instances have indexed keys and may still be hidden.
+ const instances = scene.getAllObjects().filter((object) => object.oKey === key || object.oKey.startsWith(prefix));
+ instances.forEach((object) => object.dispose());
+ return instances.length > 0;
+ }
const object = getDrawingRenderObject(scene, drawingSearch);
if (object == null) {
diff --git a/packages/engine-render/src/__tests__/scene.input-manager.spec.ts b/packages/engine-render/src/__tests__/scene.input-manager.spec.ts
index 5ccda86ef9..6532b95a72 100644
--- a/packages/engine-render/src/__tests__/scene.input-manager.spec.ts
+++ b/packages/engine-render/src/__tests__/scene.input-manager.spec.ts
@@ -169,4 +169,15 @@ describe('InputManager click gestures', () => {
expect(doubleClick).toHaveBeenCalledTimes(deviceType === DeviceType.Touch ? 1 : 0);
});
+
+ it('uses event timestamps even when the double-click expiry callback is delayed', () => {
+ const timeStamp = vi.spyOn(Event.prototype, 'timeStamp', 'get').mockReturnValue(100);
+ click();
+ timeStamp.mockReturnValue(601);
+ click();
+ expect(doubleClick).not.toHaveBeenCalled();
+ timeStamp.mockReturnValue(700);
+ click();
+ expect(doubleClick).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/packages/engine-render/src/__tests__/worker-layout.spec.ts b/packages/engine-render/src/__tests__/worker-layout.spec.ts
index c59c78e672..8c5fe1d736 100644
--- a/packages/engine-render/src/__tests__/worker-layout.spec.ts
+++ b/packages/engine-render/src/__tests__/worker-layout.spec.ts
@@ -15,8 +15,9 @@
*/
import type { IDocumentSkeletonPage } from '../basics/i-document-skeleton-cached';
-import { cpuUsage } from 'node:process';
+import { cpuUsage, memoryUsage, stdout } from 'node:process';
import {
+ BooleanNumber,
ColumnLayoutType,
ColumnResponsiveType,
createDocumentModelWithStyle,
@@ -26,6 +27,7 @@ import {
DrawingTypeEnum,
JSONX,
LocaleService,
+ LocaleType,
ObjectRelativeFromH,
ObjectRelativeFromV,
PositionedObjectLayoutType,
@@ -36,6 +38,7 @@ import {
TableTextWrapType,
TextX,
TextXActionType,
+ Univer,
VerticalAlignmentType,
} from '@univerjs/core';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -124,6 +127,167 @@ describe('worker document layout session', () => {
vi.unstubAllGlobals();
});
+ it('paginates and resolves a 1000-page TOC target incrementally', () => {
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText(this: { font: string }, content: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
+ return {
+ width: content.length * 7 * points / 11,
+ fontBoundingBoxAscent: 9 * points / 11,
+ fontBoundingBoxDescent: 3 * points / 11,
+ actualBoundingBoxAscent: 8 * points / 11,
+ actualBoundingBoxDescent: 2 * points / 11,
+ };
+ },
+ };
+ }
+ });
+ const paragraphs = [];
+ const pageStarts = [];
+ let dataStream = '';
+ for (let pageIndex = 0; pageIndex < 1_000; pageIndex++) {
+ pageStarts.push(dataStream.length);
+ dataStream += `Page ${pageIndex + 1}\r`;
+ paragraphs.push({
+ startIndex: dataStream.length - 1,
+ paragraphId: `page-${pageIndex + 1}`,
+ paragraphStyle: pageIndex === 0 ? undefined : { pageBreakBefore: BooleanNumber.TRUE },
+ });
+ }
+ dataStream += '\n';
+ const dataModel = new DocumentDataModel({
+ id: 'toc-1000-page-benchmark',
+ body: {
+ dataStream,
+ paragraphs,
+ sectionBreaks: [{ startIndex: dataStream.length - 1, sectionId: 'section' }],
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 240, height: 180 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ });
+ const session = new DocumentLayoutSession(dataModel, new LocaleService());
+ const heapStart = memoryUsage().heapUsed;
+ const startedAt = performance.now();
+ const generation = session.start({ reason: 'initial' });
+ let result = session.step(generation, 8);
+ let stepCount = 1;
+ const publishedPages: number[] = [];
+ const publicationSizes: number[] = [];
+ const collectPages = () => {
+ if (result.publication?.kind === 'page') {
+ publishedPages.push(...result.publication.pages.map((page) => page.pageIndex));
+ publicationSizes.push(result.publication.pages.length);
+ }
+ };
+ collectPages();
+ while (!result.progress.complete && stepCount < 20_000) {
+ result = session.step(generation, 8);
+ collectPages();
+ stepCount++;
+ }
+ const benchmark = {
+ elapsedMs: Math.round(performance.now() - startedAt),
+ heapDeltaMb: Math.round((memoryUsage().heapUsed - heapStart) / 1024 / 1024),
+ maxBlockMs: Math.round(result.progress.maxBlockDuration),
+ stepCount,
+ };
+ if (process.env.DOC_BENCHMARK_LOG === '1') {
+ stdout.write(`1000-page-layout ${JSON.stringify(benchmark)}\n`);
+ }
+
+ expect(result.progress.complete).toBe(true);
+ expect(result.progress.pageCount).toBe(1_000);
+ expect(publishedPages).toEqual(Array.from({ length: 1_000 }, (_, index) => index));
+ expect(Math.max(...publicationSizes)).toBeGreaterThan(1);
+ expect(Math.max(...publicationSizes)).toBeLessThanOrEqual(4);
+ expect(session.resolvePageByOffset(pageStarts[999])).toMatchObject({
+ pageIndex: 999,
+ pageNumber: 1_000,
+ });
+ expect(session.getPage(999)?.pageIndex).toBe(999);
+ expect(benchmark.maxBlockMs).toBeLessThan(50);
+ session.dispose();
+ dataModel.dispose();
+ }, 60_000);
+
+ it.each(['initial', 'edit'] as const)('finishes a late anchor page before publishing a fresh %s session', (reason) => {
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText(this: { font: string }, content: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
+ return {
+ width: content.length * 7 * points / 11,
+ fontBoundingBoxAscent: 9 * points / 11,
+ fontBoundingBoxDescent: 3 * points / 11,
+ actualBoundingBoxAscent: 8 * points / 11,
+ actualBoundingBoxDescent: 2 * points / 11,
+ };
+ },
+ };
+ }
+ });
+ const univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: {} } });
+ const localeService = univer.__getInjector().get(LocaleService);
+ localeService.setDirection('ltr');
+ const dataModel = new DocumentDataModel({
+ id: 'fresh-late-anchor',
+ body: {
+ dataStream: 'Cover\rHeading\rFollowing\rTail\r\n',
+ paragraphs: [
+ { startIndex: 5, paragraphId: 'cover' },
+ { startIndex: 13, paragraphId: 'heading', paragraphStyle: { pageBreakBefore: BooleanNumber.TRUE } },
+ { startIndex: 23, paragraphId: 'following' },
+ { startIndex: 28, paragraphId: 'tail' },
+ ],
+ sectionBreaks: [{ startIndex: 29, sectionId: 'section' }],
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 240, height: 180 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ });
+ const session = new DocumentLayoutSession(dataModel, localeService);
+ try {
+ // A recreated Worker mount has no previous page boundary, even for an edit.
+ const generation = session.start({ reason, anchor: 8 });
+ let result = session.step(generation, 0);
+ for (let step = 0; step < 100 && !result.progress.complete; step++) {
+ if (result.progress.didPublishAnchor) {
+ expect(result.progress.laidOutThrough).toBeGreaterThanOrEqual(28);
+ }
+ result = session.step(generation, 0);
+ }
+ expect(result.progress.complete).toBe(true);
+ expect(result.progress.pageCount).toBe(2);
+ expect(session.getPage(1)?.page.ed).toBe(29);
+ } finally {
+ session.dispose();
+ dataModel.dispose();
+ univer.dispose();
+ }
+ });
+
it('publishes list nesting jumps and tolerates legacy sparse list caches', () => {
vi.stubGlobal('document', undefined);
vi.stubGlobal('OffscreenCanvas', class {
@@ -131,13 +295,15 @@ describe('worker document layout session', () => {
return {
font: '',
textBaseline: 'alphabetic',
- measureText(content: string) {
+ measureText(this: { font: string }, content: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
return {
- width: content.length * 7,
- fontBoundingBoxAscent: 9,
- fontBoundingBoxDescent: 3,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
+ width: content.length * 7 * points / 11,
+ fontBoundingBoxAscent: 9 * points / 11,
+ fontBoundingBoxDescent: 3 * points / 11,
+ actualBoundingBoxAscent: 8 * points / 11,
+ actualBoundingBoxDescent: 2 * points / 11,
};
},
};
@@ -256,13 +422,15 @@ describe('worker document layout session', () => {
return {
font: '',
textBaseline: 'alphabetic',
- measureText(content: string) {
+ measureText(this: { font: string }, content: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
return {
- width: content.length * 7,
- fontBoundingBoxAscent: 9,
- fontBoundingBoxDescent: 3,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
+ width: content.length * 7 * points / 11,
+ fontBoundingBoxAscent: 9 * points / 11,
+ fontBoundingBoxDescent: 3 * points / 11,
+ actualBoundingBoxAscent: 8 * points / 11,
+ actualBoundingBoxDescent: 2 * points / 11,
};
},
};
@@ -398,13 +566,15 @@ describe('worker document layout session', () => {
return {
font: '',
textBaseline: 'alphabetic',
- measureText(content: string) {
+ measureText(this: { font: string }, content: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
return {
- width: content.length * 7,
- fontBoundingBoxAscent: 9,
- fontBoundingBoxDescent: 3,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
+ width: content.length * 7 * points / 11,
+ fontBoundingBoxAscent: 9 * points / 11,
+ fontBoundingBoxDescent: 3 * points / 11,
+ actualBoundingBoxAscent: 8 * points / 11,
+ actualBoundingBoxDescent: 2 * points / 11,
};
},
};
@@ -456,6 +626,10 @@ describe('worker document layout session', () => {
const distantPageIndex = 10;
const distantWindow = { startPageIndex: 8, endPageIndex: 12 };
+ const materializedPageListener = vi.fn();
+ const layoutProgressListener = vi.fn();
+ mainSkeleton.layoutPageMaterialized$.subscribe(materializedPageListener);
+ mainSkeleton.layoutProgress$.subscribe(layoutProgressListener);
for (
let pageIndex = distantWindow.startPageIndex;
pageIndex <= distantWindow.endPageIndex;
@@ -475,6 +649,8 @@ describe('worker document layout session', () => {
!page.isLayoutPlaceholder && !page.isMaterializationPlaceholder
) ?? [];
expect(materializedPages).toHaveLength(5);
+ expect(materializedPageListener).toHaveBeenCalledTimes(5);
+ expect(layoutProgressListener).not.toHaveBeenCalled();
expect(mainSkeleton.getSkeletonData()?.pages[0].isMaterializationPlaceholder).toBe(true);
const distantPublication = session.getPage(distantPageIndex);
if (distantPublication == null) {
@@ -488,6 +664,10 @@ describe('worker document layout session', () => {
if (editAnchor == null || editAnchor < 0) {
throw new Error('Expected the distant Main page to expose a logical edit anchor.');
}
+ expect(session.resolvePageByOffset(editAnchor)).toMatchObject({
+ pageIndex: distantPageIndex,
+ startOffset: editAnchor,
+ });
const textX = new TextX();
textX.push({ t: TextXActionType.RETAIN, len: editAnchor });
textX.push({ t: TextXActionType.INSERT, len: 1, body: { dataStream: 'X' } });
@@ -523,13 +703,15 @@ describe('worker document layout session', () => {
return {
font: '',
textBaseline: 'alphabetic',
- measureText(content: string) {
+ measureText(this: { font: string }, content: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
return {
- width: content.length * 7,
- fontBoundingBoxAscent: 9,
- fontBoundingBoxDescent: 3,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
+ width: content.length * 7 * points / 11,
+ fontBoundingBoxAscent: 9 * points / 11,
+ fontBoundingBoxDescent: 3 * points / 11,
+ actualBoundingBoxAscent: 8 * points / 11,
+ actualBoundingBoxDescent: 2 * points / 11,
};
},
};
@@ -608,9 +790,18 @@ describe('worker document layout session', () => {
}
expect(result.progress).toMatchObject({ complete: true, cancelled: false });
expect(layoutStepCount).toBeLessThan(200);
+ const firstPublication = pagePublications[0];
+ expect(firstPublication?.kind === 'page' && firstPublication.pages.length).toBe(1);
expect(pagePublications.every((publication) =>
- publication?.kind !== 'page' || publication.pages.length <= 1
+ publication?.kind !== 'page' || publication.pages.length <= 4
)).toBe(true);
+ const publishedIndexes = pagePublications.flatMap((publication) =>
+ publication?.kind === 'page' ? publication.pages.map((page) => page.pageIndex) : []
+ );
+ expect(publishedIndexes).toEqual(Array.from(
+ { length: result.progress.pageCount - publishedIndexes[0] },
+ (_, index) => publishedIndexes[0] + index
+ ));
session.dispose();
initialSkeleton.dispose();
@@ -625,13 +816,15 @@ describe('worker document layout session', () => {
return {
font: '',
textBaseline: 'alphabetic',
- measureText(content: string) {
+ measureText(this: { font: string }, content: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
return {
- width: content.length * 7,
- fontBoundingBoxAscent: 9,
- fontBoundingBoxDescent: 3,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
+ width: content.length * 7 * points / 11,
+ fontBoundingBoxAscent: 9 * points / 11,
+ fontBoundingBoxDescent: 3 * points / 11,
+ actualBoundingBoxAscent: 8 * points / 11,
+ actualBoundingBoxDescent: 2 * points / 11,
};
},
};
@@ -698,13 +891,15 @@ describe('worker document layout session', () => {
return {
font: '',
textBaseline: 'alphabetic',
- measureText(content: string) {
+ measureText(this: { font: string }, content: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
return {
- width: content.length * 7,
- fontBoundingBoxAscent: 9,
- fontBoundingBoxDescent: 3,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
+ width: content.length * 7 * points / 11,
+ fontBoundingBoxAscent: 9 * points / 11,
+ fontBoundingBoxDescent: 3 * points / 11,
+ actualBoundingBoxAscent: 8 * points / 11,
+ actualBoundingBoxDescent: 2 * points / 11,
};
},
};
@@ -788,13 +983,15 @@ describe('worker document layout session', () => {
return {
font: '',
textBaseline: 'alphabetic',
- measureText(content: string) {
+ measureText(this: { font: string }, content: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
return {
- width: content.length * 7,
- fontBoundingBoxAscent: 9,
- fontBoundingBoxDescent: 3,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
+ width: content.length * 7 * points / 11,
+ fontBoundingBoxAscent: 9 * points / 11,
+ fontBoundingBoxDescent: 3 * points / 11,
+ actualBoundingBoxAscent: 8 * points / 11,
+ actualBoundingBoxDescent: 2 * points / 11,
};
},
};
@@ -943,13 +1140,15 @@ describe('worker document layout session', () => {
return {
font: '',
textBaseline: 'alphabetic',
- measureText(content: string) {
+ measureText(this: { font: string }, content: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
return {
- width: content.length * 7,
- fontBoundingBoxAscent: 9,
- fontBoundingBoxDescent: 3,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
+ width: content.length * 7 * points / 11,
+ fontBoundingBoxAscent: 9 * points / 11,
+ fontBoundingBoxDescent: 3 * points / 11,
+ actualBoundingBoxAscent: 8 * points / 11,
+ actualBoundingBoxDescent: 2 * points / 11,
};
},
};
@@ -1027,13 +1226,15 @@ describe('worker document layout session', () => {
return {
font: '',
textBaseline: 'alphabetic',
- measureText(content: string) {
+ measureText(this: { font: string }, content: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
return {
- width: content.length * 7,
- fontBoundingBoxAscent: 9,
- fontBoundingBoxDescent: 3,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
+ width: content.length * 7 * points / 11,
+ fontBoundingBoxAscent: 9 * points / 11,
+ fontBoundingBoxDescent: 3 * points / 11,
+ actualBoundingBoxAscent: 8 * points / 11,
+ actualBoundingBoxDescent: 2 * points / 11,
};
},
};
@@ -1120,13 +1321,15 @@ describe('worker document layout session', () => {
return {
font: '',
textBaseline: 'alphabetic',
- measureText(content: string) {
+ measureText(this: { font: string }, content: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
return {
- width: content.length * 7,
- fontBoundingBoxAscent: 9,
- fontBoundingBoxDescent: 3,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
+ width: content.length * 7 * points / 11,
+ fontBoundingBoxAscent: 9 * points / 11,
+ fontBoundingBoxDescent: 3 * points / 11,
+ actualBoundingBoxAscent: 8 * points / 11,
+ actualBoundingBoxDescent: 2 * points / 11,
};
},
};
@@ -1557,13 +1760,15 @@ describe('worker document layout session', () => {
return {
font: '',
textBaseline: 'alphabetic',
- measureText(content: string) {
+ measureText(this: { font: string }, content: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
return {
- width: content.length * 7,
- fontBoundingBoxAscent: 9,
- fontBoundingBoxDescent: 3,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
+ width: content.length * 7 * points / 11,
+ fontBoundingBoxAscent: 9 * points / 11,
+ fontBoundingBoxDescent: 3 * points / 11,
+ actualBoundingBoxAscent: 8 * points / 11,
+ actualBoundingBoxDescent: 2 * points / 11,
};
},
};
diff --git a/packages/engine-render/src/basics/__tests__/tools.spec.ts b/packages/engine-render/src/basics/__tests__/tools.spec.ts
index 7ae1d29e62..cac12b57da 100644
--- a/packages/engine-render/src/basics/__tests__/tools.spec.ts
+++ b/packages/engine-render/src/basics/__tests__/tools.spec.ts
@@ -174,6 +174,24 @@ describe('tools extra', () => {
expect(isObject({ a: 1 })).toBe(true);
});
+ it.each([
+ [undefined, undefined],
+ [Number.NaN, undefined],
+ [Number.POSITIVE_INFINITY, undefined],
+ [-1, undefined],
+ [0, 'none'],
+ [12, 'normal'],
+ [12.5, 'normal'],
+ [13, 'none'],
+ ] as const)('resolves kerning threshold %s against the authored font size', (kerning, expected) => {
+ vi.spyOn(FontCache, 'getBaselineOffsetInfo').mockReturnValue({ sbr: 0.5, sbo: 0, spr: 0.6, spo: 0 });
+ const textStyle = { ff: 'Arial', fs: 12.5, kerning };
+ for (const va of [undefined, BaselineOffset.SUBSCRIPT, BaselineOffset.SUPERSCRIPT]) {
+ expect(getFontStyleString({ ...textStyle, va }).fontKerning).toBe(expected);
+ }
+ expect(textStyle).toEqual({ ff: 'Arial', fs: 12.5, kerning });
+ });
+
it('builds font styles and language detectors', () => {
const baselineSpy = vi.spyOn(FontCache, 'getBaselineOffsetInfo').mockReturnValue({ sbr: 0.5, spr: 0.6 } as any);
diff --git a/packages/engine-render/src/basics/i-document-skeleton-cached.ts b/packages/engine-render/src/basics/i-document-skeleton-cached.ts
index d746884811..e1c6300877 100644
--- a/packages/engine-render/src/basics/i-document-skeleton-cached.ts
+++ b/packages/engine-render/src/basics/i-document-skeleton-cached.ts
@@ -113,6 +113,8 @@ export interface IDocumentSkeletonPage {
marginBottom: number;
left: number; // Only use for cell.
+ /** Cell lines use logical axes; the page bounds remain physical after layout. */
+ cellTextDirection?: 'tbRlV';
pageNumber: number; // page number
pageNumberStart: number; // start page number
@@ -254,6 +256,8 @@ export interface IDocumentSkeletonLine {
top: number; // top paragraph(spaceAbove, spaceBelow, lineSpacing*PreLineHeight)
asc: number; // =max(glyph.textMetrics.ba) alphabet alignment, needs calibration
dsc: number; // =max(glyph.textMetrics.bd) alphabet alignment, needs calibration
+ drawingMLBaselineHeight?: number; // Recomputed as the final glyph metrics grow.
+ drawingMLNormalLineHeight?: number; // Minimum terminal extent for expanded automatic line spacing.
paddingTop: number; // paddingTop distance from content to top
paddingBottom: number; // paddingBottom distance from content to bottom
marginTop: number; // marginTop paragraph spaceAbove
@@ -274,6 +278,8 @@ export interface IDocumentSkeletonLine {
paragraphBorders?: IDocumentSkeletonParagraphBorders;
paragraphPaddingLeft?: number;
paragraphPaddingRight?: number;
+ borderTopSpace?: number;
+ borderBottomSpace?: number;
backgroundColor?: IColorStyle; // backgroundColor
bullet?: IDocumentSkeletonBullet; // unordered and ordered list bullet
width?: number; // the actual width of a line
@@ -311,6 +317,10 @@ export interface IDocumentSkeletonGlyph {
width: number; // cum width
bBox: IDocumentSkeletonBoundingBox; // bBox: size of glyph
xOffset: number; // xOffset, adjust text align in glyph
+ /** Automatic CJK/Latin gaps on the left and right; omitted at a wrapped line edge. */
+ autoSpacing?: [number, number];
+ /** Left-side punctuation space removed during shaping, restorable at a new line boundary. */
+ leadingPunctuationCompression?: number;
left: number; // left
count: number; // count, content length,default 1
content: string; // content
@@ -326,7 +336,12 @@ export interface IDocumentSkeletonGlyph {
noteId?: string;
noteSeparator?: boolean;
fauxBoldStrokeWidth?: number;
+ /** Runtime-only advance adjustment, recomputed when a shaped word is split across lines. */
+ kerningAdjustment?: number;
tabLeader?: TabStopLeader;
+ tabAlignedTextWidth?: number;
+ /** Runtime-only positions for tracked text that shares one shaping glyph. */
+ textSpacing?: { content: string; segments: Array<{ content: string; left: number }> };
}
export interface IDocumentSkeletonBullet {
@@ -376,6 +391,7 @@ export interface IDocumentSkeletonDrawing {
}
export interface IDocumentSkeletonFontStyle {
+ fontKerning?: CanvasFontKerning;
fontString: string;
fontSize: number;
originFontSize: number;
diff --git a/packages/engine-render/src/basics/interfaces.ts b/packages/engine-render/src/basics/interfaces.ts
index 40908e9ec5..2a0e66acae 100644
--- a/packages/engine-render/src/basics/interfaces.ts
+++ b/packages/engine-render/src/basics/interfaces.ts
@@ -115,7 +115,10 @@ export interface ISectionBreakConfig extends IDocStyleBase, ISectionBreakBase, I
sectionId: string;
/** Cell continuation pages retain their segment and physical row-slice budgets. */
cellTableId?: string;
+ /** Absolute final paragraph mark excluded by this cell's w:hideMark property. */
+ cellHiddenEndMarkIndex?: number;
cellPageHeights?: readonly number[];
+ fontFamilyFallbacks?: Record<string, string>;
headerIds?: IHeaderIds;
footerIds?: IFooterIds;
useFirstPageHeaderFooter?: BooleanNumber;
@@ -154,6 +157,8 @@ export interface IParagraphConfig {
// pageContentWidth: number;
// pageContentHeight: number;
paragraphStyle?: IParagraphStyle;
+ borderTopSpace?: number;
+ borderBottomSpace?: number;
skeHeaders: Map<string, Map<number, IDocumentSkeletonHeaderFooter>>;
skeFooters: Map<string, Map<number, IDocumentSkeletonHeaderFooter>>;
pDrawingAnchor?: Map<number, IDocumentSkeletonDrawingAnchor>;
@@ -167,6 +172,8 @@ export interface IFontCreateConfig {
snapToGrid: BooleanNumber;
documentCompatibilityPolicy?: IDocumentCompatibilityPolicy;
gridType?: GridType;
+ balanceSingleByteDoubleByteWidth?: BooleanNumber;
+ balanceSpaceWidth?: boolean;
pageWidth?: number;
}
diff --git a/packages/engine-render/src/basics/tools.ts b/packages/engine-render/src/basics/tools.ts
index f46a30c9f8..d2ce7651d5 100644
--- a/packages/engine-render/src/basics/tools.ts
+++ b/packages/engine-render/src/basics/tools.ts
@@ -19,7 +19,7 @@ import type {
IRange,
IRangeWithCoord,
IScale,
- IStyleBase,
+ ITextStyle,
Nullable,
} from '@univerjs/core';
import type { IDocumentSkeletonFontStyle } from './i-document-skeleton-cached';
@@ -257,7 +257,8 @@ export function fixLineWidthByScale(num: number, scale: number) {
}
export function getFontStyleString(
- textStyle?: Nullable<IStyleBase>
+ textStyle?: Nullable<ITextStyle>,
+ fontFamilyFallbacks?: Record<string, string>
): IDocumentSkeletonFontStyle {
const defaultFont = DEFAULT_STYLES.ff;
@@ -297,7 +298,19 @@ export function getFontStyleString(
}
let fontSize = originFontSize;
- const fontFamilyResult = normalizeFontFamily(textStyle.ff, defaultFont);
+ let fontFamilyResult = normalizeFontFamily(textStyle.ff, defaultFont);
+ if (fontFamilyFallbacks) {
+ const families = fontFamilyResult.split(',').map((family) => family.trim().replace(/^['"]|['"]$/g, ''));
+ const expanded: string[] = [];
+ for (const family of families) {
+ let current: string | undefined = family;
+ while (typeof current === 'string' && current && !expanded.includes(current)) {
+ expanded.push(current);
+ current = fontFamilyFallbacks[current];
+ }
+ }
+ fontFamilyResult = normalizeFontFamily(expanded.join(', '), defaultFont);
+ }
const { va: baselineOffset } = textStyle;
@@ -316,6 +329,9 @@ export function getFontStyleString(
const fontString = `${fontStringPure}, ${DEFAULT_FONTFACE_PLANE} `;
return {
+ ...(textStyle.kerning != null && Number.isFinite(textStyle.kerning) && textStyle.kerning >= 0
+ ? { fontKerning: textStyle.kerning > 0 && originFontSize >= textStyle.kerning ? 'normal' as const : 'none' as const }
+ : {}),
fontCache: fontStringPure,
fontString,
fontSize,
@@ -324,6 +340,17 @@ export function getFontStyleString(
};
}
+/** Office display casing preserves one source character instead of expanding forms such as ß to SS. */
+export function getTextWithCaps(content: string, caps?: boolean): string {
+ if (!caps) {
+ return content;
+ }
+ return Array.from(content, (char) => {
+ const upper = char.toUpperCase();
+ return Array.from(upper).length === 1 ? upper : char;
+ }).join('');
+}
+
function normalizeFontFamily(fontFamily: Nullable<string>, defaultFont: string): string {
if (!fontFamily?.trim()) {
return defaultFont;
diff --git a/packages/engine-render/src/components/docs/__tests__/document-compatibility.spec.ts b/packages/engine-render/src/components/docs/__tests__/document-compatibility.spec.ts
index 64ecbcf463..710a5659b9 100644
--- a/packages/engine-render/src/components/docs/__tests__/document-compatibility.spec.ts
+++ b/packages/engine-render/src/components/docs/__tests__/document-compatibility.spec.ts
@@ -41,6 +41,74 @@ const bBox = {
} as IDocumentSkeletonBoundingBox;
describe('document compatibility policy', () => {
+ it.each([7.5, 12])('matches native Word YaHei single spacing at %s pt without changing ink metrics', (fontSize) => {
+ const em = fontSize / 0.75;
+ const measured = { ...bBox, ba: em * 2167 / 2048, bd: em * 536 / 2048, normalLineHeight: em * 2703 / 2048 };
+ const traditional = getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL);
+ for (const fontFamily of ['Microsoft YaHei', '"微软雅黑", Arial, 微软雅黑']) {
+ const style = { ...fontStyle, fontSize, originFontSize: fontSize, fontFamily };
+ for (const content of ['中', 'H']) {
+ const actual = applyFontMetricCompatibility(content, style, measured, traditional);
+ // Native PDF coordinates at 96 DPI; tolerate Word's sub-point rounding.
+ expect(Math.abs(actual.normalLineHeight! - (fontSize === 7.5 ? 17.12 : 27.52))).toBeLessThan(0.1);
+ expect({ ...actual, normalLineHeight: measured.normalLineHeight }).toEqual(measured);
+ expect(applyFontMetricCompatibility(content, style, measured, getDocumentCompatibilityPolicy(DocumentFlavor.MODERN))).toBe(measured);
+ }
+ const larger = { ...measured, normalLineHeight: 60 };
+ expect(applyFontMetricCompatibility('H', style, larger, traditional)).toBe(larger);
+ const substituted = { ...measured, ba: em, bd: 0 };
+ expect(applyFontMetricCompatibility('H', style, substituted, traditional)).toBe(substituted);
+ expect(applyFontMetricCompatibility('H', { ...style, fontFamily: 'Arial, Microsoft YaHei' }, measured, traditional)).toBe(measured);
+ expect(applyFontMetricCompatibility('H', { ...style, fontFamily: 'Microsoft YaHei UI' }, measured, traditional)).toBe(measured);
+ }
+ });
+
+ it.each([11, 16])('retains Word MS Gothic auto-leading at %s pt without enlarging the ink box', (fontSize) => {
+ const em = fontSize / 0.75;
+ const style = { ...fontStyle, fontSize, originFontSize: fontSize, fontFamily: '"MS Gothic", Arial' };
+ const measured = { ...bBox, ba: em * 220 / 256, bd: em * 36 / 256, normalLineHeight: em };
+ for (const content of ['☐', 'M']) {
+ const actual = applyFontMetricCompatibility(content, style, measured, getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL));
+ // Native Word PDF row heights, excluding the 0.5pt table border, at 96 DPI.
+ expect(actual.normalLineHeight).toBeCloseTo(fontSize === 11 ? 19.01334 : 27.65334, 1);
+ expect({ ...actual, normalLineHeight: em }).toEqual(measured);
+ expect(applyFontMetricCompatibility(content, style, measured, getDocumentCompatibilityPolicy(DocumentFlavor.MODERN))).toBe(measured);
+ }
+ expect(applyFontMetricCompatibility(
+ 'M',
+ { ...style, fontFamily: 'Arial, "MS Gothic"' },
+ measured,
+ getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL)
+ )).toBe(measured);
+ });
+
+ it.each([
+ { content: '中', measured: 13.329986572265623, expected: 40 / 3 },
+ { content: '(', measured: 13.329986572265623, expected: 40 / 3 },
+ { content: '𠀀', measured: 13.329986572265623, expected: 40 / 3 },
+ { content: 'カ', measured: 20 / 3, expected: 20 / 3 },
+ { content: '中', measured: 12.5, expected: 12.5 },
+ { content: 'A', measured: 13.33, expected: 13.33 },
+ { content: '中文', measured: 13.33, expected: 13.33 },
+ ])('recovers fractional-em CJK advances without changing proportional glyphs: $content/$measured', ({ content, measured, expected }) => {
+ const measuredBox = { ...bBox, width: measured };
+ const style = { ...fontStyle, fontSize: 10, originFontSize: 10, fontFamily: 'Microsoft YaHei' };
+ const traditional = applyFontMetricCompatibility(content, style, measuredBox, getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL));
+ expect(traditional.width).toBeCloseTo(expected, 10);
+ expect({ ...traditional, width: measured }).toEqual(measuredBox);
+ expect(measuredBox.width).toBe(measured);
+ expect(applyFontMetricCompatibility(content, style, measuredBox, getDocumentCompatibilityPolicy(DocumentFlavor.MODERN)))
+ .toBe(measuredBox);
+ });
+
+ it('selects DrawingML font metrics without changing existing document flavors', () => {
+ const policy = getDocumentCompatibilityPolicy(DocumentFlavor.DRAWINGML);
+ expect(policy.mode).toBe('drawingml');
+ expect(applyFontMetricCompatibility('5', fontStyle, bBox, policy)).toEqual(bBox);
+ for (const flavor of [undefined, DocumentFlavor.UNSPECIFIED, DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL]) {
+ expect(getDocumentCompatibilityPolicy(flavor).mode).not.toBe('drawingml');
+ }
+ });
it('applies traditional Word font metric width rules without changing modern documents', () => {
const traditional = getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL);
const modern = getDocumentCompatibilityPolicy(DocumentFlavor.MODERN);
@@ -49,7 +117,7 @@ describe('document compatibility policy', () => {
expect(applyFontMetricCompatibility('5', fontStyle, bBox, modern).width).toBe(16);
});
- it('scales only non-bold primary Arial Latin glyphs in traditional documents', () => {
+ it('preserves measured Arial advances instead of narrowing Latin text in traditional documents', () => {
const normalArial = {
...fontStyle,
fontString: 'normal normal 11.5pt Arial',
@@ -67,7 +135,9 @@ describe('document compatibility policy', () => {
const traditional = getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL);
const modern = getDocumentCompatibilityPolicy(DocumentFlavor.MODERN);
- expect(applyFontMetricCompatibility('A', normalArial, browserMeasuredGlyph, traditional).width).toBeCloseTo(9.8);
+ for (const content of ['A', '0', '1', '8', ' ', '“']) {
+ expect(applyFontMetricCompatibility(content, normalArial, browserMeasuredGlyph, traditional)).toBe(browserMeasuredGlyph);
+ }
expect(applyFontMetricCompatibility('A', boldArial, browserMeasuredGlyph, traditional).width).toBe(10);
expect(applyFontMetricCompatibility('A', normalArial, browserMeasuredGlyph, modern).width).toBe(10);
expect(applyFontMetricCompatibility('中', normalArial, browserMeasuredGlyph, traditional).width).toBe(10);
diff --git a/packages/engine-render/src/components/docs/__tests__/document.spec.ts b/packages/engine-render/src/components/docs/__tests__/document.spec.ts
index 06c90546ec..a804cbadd1 100644
--- a/packages/engine-render/src/components/docs/__tests__/document.spec.ts
+++ b/packages/engine-render/src/components/docs/__tests__/document.spec.ts
@@ -14,9 +14,31 @@
* limitations under the License.
*/
-import { ColumnSeparatorType, CustomRangeType, DashStyleType, DocumentFlavor } from '@univerjs/core';
+import type { IDocumentBody, IParagraphStyle, IScale, ITable } from '@univerjs/core';
+import type { IDocumentSkeletonGlyph } from '../../../basics/i-document-skeleton-cached';
+import type { IExtensionConfig } from '../../extension';
+import {
+ ColumnSeparatorType,
+ CustomRangeType,
+ DashStyleType,
+ DataStreamTreeTokenType,
+ DocumentDataModel,
+ DocumentFlavor,
+ HorizontalAlign,
+ LocaleService,
+ ObjectRelativeFromH,
+ ObjectRelativeFromV,
+ TableAlignmentType,
+ TableRowHeightRule,
+ TableSizeType,
+ TableTextWrapType,
+ TabStopAlignment,
+ Univer,
+ WrapStrategy,
+} from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { setupRenderTestEnv } from '../../../__tests__/render-test-utils';
+import { BORDER_TYPE } from '../../../basics/const';
import {
DocumentSkeletonPageType,
GlyphType,
@@ -33,10 +55,10 @@ import { Viewport } from '../../../viewport';
import { DocBackground } from '../doc-background';
import { DOCS_EXTENSION_TYPE } from '../doc-extension';
import { Documents, drawSectionColumnSeparators, resolveHeaderFooterFieldGlyph } from '../document';
-import { getDocumentCompatibilityPolicy } from '../document-compatibility';
import { createParagraphLayoutTestBed } from '../layout/block/paragraph/__tests__/create-paragraph-layout-test-bed';
import { DocumentSkeleton } from '../layout/doc-skeleton';
import { setDocsTableRenderViewportProvider } from '../table-render-viewport';
+import { DocumentEditArea, DocumentViewModel } from '../view-model/document-view-model';
function createGlyph(content: string, left: number, width = 16, backgroundColor?: string) {
return {
@@ -316,12 +338,12 @@ function attachColumnGroup(page: any) {
describe('documents render', () => {
it('resolves PAGE and NUMPAGES fields without mutating the model glyph', () => {
- const glyph = { st: 0, ed: 0, content: '1' } as any;
- const pageRange = { startIndex: 0, endIndex: 0, properties: { fieldType: 'PAGE' } } as any;
- const pageCountRange = { startIndex: 0, endIndex: 0, properties: { fieldType: 'NUMPAGES' } } as any;
+ const glyph = { st: 1, ed: 1, content: '1' } as any;
+ const pageRange = { startIndex: 0, endIndex: 2, properties: { fieldType: 'PAGE' } } as any;
+ const pageCountRange = { startIndex: 0, endIndex: 2, properties: { fieldType: 'NUMPAGES' } } as any;
- expect(resolveHeaderFooterFieldGlyph(glyph, 0, 0, [pageRange], 15, 16).content).toBe('15');
- expect(resolveHeaderFooterFieldGlyph(glyph, 0, 0, [pageCountRange], 15, 16).content).toBe('16');
+ expect(resolveHeaderFooterFieldGlyph(glyph, 1, 1, [pageRange], 15, 16).content).toBe('15');
+ expect(resolveHeaderFooterFieldGlyph(glyph, 1, 1, [pageCountRange], 15, 16).content).toBe('16');
expect(glyph.content).toBe('1');
});
let restoreEnv: () => void;
@@ -554,6 +576,89 @@ describe('documents render', () => {
documents.dispose();
});
+ it.each([
+ { a: 1, d: 1, e: 0, f: 0 },
+ { a: 1.25, d: 1.25, e: 0.35, f: 0.7 },
+ { a: 2, d: 2, e: 1.1, f: 2.3 },
+ { a: 1.5, d: 2, e: -0.7, f: -1.3 },
+ ])('paints traditional table borders on whole device pixels at $a/$d scale', ({ a, d, e, f }) => {
+ const bed = createParagraphLayoutTestBed('Table', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);
+ const documents = new Documents('pixel-table-border', skeleton);
+ const ctx = canvas.getContext();
+ ctx.setTransform(a, 0, 0, d, e, f);
+ const move = vi.spyOn(ctx, 'moveTo');
+ const line = vi.spyOn(ctx, 'lineTo');
+ const widths: number[] = [];
+ vi.spyOn(ctx, 'stroke').mockImplementation(() => {
+ widths.push(ctx.lineWidth);
+ });
+ const position = { startX: 10.99, startY: 20.99, endX: 110.1, endY: 80.4 };
+ const savedPosition = { ...position };
+ try {
+ for (const width of [2 / 3, 1, 2]) {
+ const border = { color: { rgb: '#000000' }, width: { v: width } };
+ for (const side of [BORDER_TYPE.TOP, BORDER_TYPE.RIGHT, BORDER_TYPE.BOTTOM, BORDER_TYPE.LEFT]) {
+ (documents as any)._drawTableCellBorder(ctx, border, side, position);
+ const horizontal = side === BORDER_TYPE.TOP || side === BORDER_TYPE.BOTTOM;
+ const scale = horizontal ? d : a;
+ const paintedWidth = widths[widths.length - 1] * scale;
+ const start = move.mock.calls[move.mock.calls.length - 1];
+ const end = line.mock.calls[line.mock.calls.length - 1];
+ const center = horizontal ? start[1] * d + f : start[0] * a + e;
+ expect(paintedWidth).toBeGreaterThanOrEqual(1);
+ expect(Math.abs(paintedWidth - width * scale)).toBeLessThanOrEqual(0.5);
+ expect(center - paintedWidth / 2).toBeCloseTo(Math.round(center - paintedWidth / 2), 10);
+ expect(center + paintedWidth / 2).toBeCloseTo(Math.round(center + paintedWidth / 2), 10);
+ expect(horizontal ? end[1] : end[0]).toBe(horizontal ? start[1] : start[0]);
+ const modelX = side === BORDER_TYPE.LEFT ? position.startX : position.endX;
+ const modelY = side === BORDER_TYPE.TOP ? position.startY : position.endY;
+ const modelCenter = horizontal ? modelY * d + f : modelX * a + e;
+ const originalInkEdge = modelCenter - width * scale / 2;
+ expect(Math.abs(center - paintedWidth / 2 - originalInkEdge)).toBeLessThanOrEqual(0.5);
+ expect(border.width.v).toBe(width);
+ }
+ }
+ expect(position).toEqual(savedPosition);
+ expect(ctx.getTransform()).toMatchObject({ a, b: 0, c: 0, d, e, f });
+ } finally {
+ documents.dispose();
+ skeleton.dispose();
+ bed.viewModel.dispose();
+ }
+ });
+
+ it.each([
+ { flavor: DocumentFlavor.MODERN, rotated: false },
+ { flavor: DocumentFlavor.TRADITIONAL, rotated: true },
+ ])('retains the existing stroke path for $flavor with rotation=$rotated', ({ flavor, rotated }) => {
+ const bed = createParagraphLayoutTestBed('Table', { documentStyle: { documentFlavor: flavor } });
+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);
+ const documents = new Documents('unsnapped-table-border', skeleton);
+ const ctx = canvas.getContext();
+ if (rotated) {
+ ctx.rotate(Math.PI / 4);
+ }
+ const move = vi.spyOn(ctx, 'moveToByPrecision');
+ const width = vi.spyOn(ctx, 'setLineWidthByPrecision');
+ try {
+ (documents as any)._drawTableCellBorder(
+ ctx,
+ { width: { v: 2 / 3 } },
+ BORDER_TYPE.TOP,
+ { startX: 10, startY: 20, endX: 100, endY: 80 }
+ );
+ expect(move).toHaveBeenCalledWith(10, 20);
+ expect(width).toHaveBeenCalledWith(2 / 3);
+ } finally {
+ documents.dispose();
+ skeleton.dispose();
+ bed.viewModel.dispose();
+ }
+ });
+
it('draws section column separators between columns', () => {
const nativeContext = document.createElement('canvas').getContext('2d');
if (!nativeContext) {
@@ -910,13 +1015,21 @@ describe('documents render', () => {
documents.dispose();
});
- it('draws all paragraph borders with their own style, padding, and paragraph indentation', () => {
+ it.each([
+ { traditional: false, cleared: false },
+ { traditional: false, cleared: true },
+ { traditional: true, cleared: false },
+ { traditional: true, cleared: true },
+ ])('draws paragraph borders with mode-specific clearance: %s', ({ traditional, cleared }) => {
const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;
const documents = new Documents('docs-paragraph-border', skeleton, {
pageLayoutType: PageLayoutType.VERTICAL,
pageMarginLeft: 0,
pageMarginTop: 0,
});
+ vi.spyOn(documents as any, '_getDocumentFlavor').mockReturnValue(
+ traditional ? DocumentFlavor.TRADITIONAL : DocumentFlavor.MODERN
+ );
const page = createPage(DocumentSkeletonPageType.BODY, '');
const line = page.sections[0].columns[0].lines[1];
line.paragraphPaddingLeft = 8;
@@ -945,6 +1058,11 @@ describe('documents render', () => {
padding: 5,
dashStyle: DashStyleType.DASH,
};
+ if (cleared) {
+ for (const border of [line.borderTop, line.borderBottom, line.borderLeft, line.borderRight]) {
+ border.width = 0;
+ }
+ }
(documents as any)._drawLiquid = { x: 0, y: 0 };
const strokeStyles: string[] = [];
@@ -965,13 +1083,20 @@ describe('documents render', () => {
(documents as any)._drawParagraphBorders(ctx, page, line, 72);
+ if (cleared) {
+ expect(ctx.stroke).not.toHaveBeenCalled();
+ expect(ctx.setLineWidthByPrecision).not.toHaveBeenCalled();
+ documents.dispose();
+ return;
+ }
+
expect(ctx.setLineWidthByPrecision.mock.calls).toEqual([[1], [4], [2], [3]]);
expect(ctx.setLineDash.mock.calls).toEqual([[[2]], [[6]], [[0]], [[6]]]);
expect(ctx.lineToByPrecision.mock.calls).toEqual([
- [75, 7],
- [75, 35],
- [14, 35],
- [75, 35],
+ [traditional ? 78.5 : 75, 7],
+ [traditional ? 78.5 : 75, 35],
+ [traditional ? 11 : 14, 35],
+ [traditional ? 78.5 : 75, 35],
]);
expect(strokeStyles).toEqual(['rgb(0,0,0)', '#444444', '#222222', '#333333']);
expect(ctx.stroke).toHaveBeenCalledTimes(4);
@@ -979,6 +1104,39 @@ describe('documents render', () => {
documents.dispose();
});
+ it.each([
+ { sideWidth: null, left: 8, right: 84 },
+ { sideWidth: undefined, left: 7.5, right: 84.5 },
+ { sideWidth: 0, left: 8, right: 84 },
+ { sideWidth: 8, left: 4, right: 88 },
+ ])('keeps Word paragraph clearance independent of the side stroke: %s', ({ sideWidth, left, right }) => {
+ const documents = new Documents('docs-paragraph-clearance', { getSkeletonData: () => ({ pages: [] }) } as any);
+ vi.spyOn(documents as any, '_getDocumentFlavor').mockReturnValue(DocumentFlavor.TRADITIONAL);
+ const page = createPage(DocumentSkeletonPageType.BODY, '');
+ const line = page.sections[0].columns[0].lines[1];
+ line.borderTop = { color: { rgb: '#000000' }, width: 1 };
+ if (sideWidth !== null) {
+ line.borderLeft = { color: { rgb: '#000000' }, width: sideWidth };
+ line.borderRight = { color: { rgb: '#000000' }, width: sideWidth };
+ }
+ (documents as any)._drawLiquid = { x: 0, y: 0 };
+ const ctx = {
+ save: vi.fn(),
+ restore: vi.fn(),
+ setLineWidthByPrecision: vi.fn(),
+ beginPath: vi.fn(),
+ moveToByPrecision: vi.fn(),
+ lineToByPrecision: vi.fn(),
+ setLineDash: vi.fn(),
+ stroke: vi.fn(),
+ closePathByEnv: vi.fn(),
+ } as any;
+ (documents as any)._drawParagraphBorders(ctx, page, line, 72);
+ expect(ctx.moveToByPrecision.mock.calls[0][0]).toBe(left);
+ expect(ctx.lineToByPrecision.mock.calls[0][0]).toBe(right);
+ documents.dispose();
+ });
+
it('limits paragraph backgrounds to the current column width', () => {
const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;
const documents = new Documents('docs-paragraph-background', skeleton, {
@@ -1076,6 +1234,54 @@ describe('documents render', () => {
documents.dispose();
});
+ it('closes the exposed top of a wider row without redrawing its shared edge', () => {
+ const documents = new Documents('docs-omitted-grid', {
+ getSkeletonData: () => ({ pages: [] }),
+ } as any);
+ const none = { color: { rgb: 'transparent' }, width: { v: 0 } };
+ const top = { color: { rgb: '#000000' }, width: { v: 1 } };
+ const rows = [0, 1].map((index) => {
+ const cell = createPage(DocumentSkeletonPageType.CELL, `omitted-${index}`);
+ cell.left = index === 0 ? 10 : 0;
+ cell.pageWidth = index === 0 ? 80 : 100;
+ cell.pageHeight = 30;
+ const row = {
+ index,
+ cells: [cell],
+ rowSource: { tableCells: [{
+ borderTop: index === 0 ? none : top,
+ borderBottom: none,
+ borderLeft: none,
+ borderRight: none,
+ }] },
+ } as any;
+ cell.parent = row;
+ return row;
+ });
+ const table = { rows };
+ rows.forEach((row) => {
+ row.parent = table;
+ });
+ const ctx = {
+ save: vi.fn(),
+ restore: vi.fn(),
+ setLineWidthByPrecision: vi.fn(),
+ setLineDash: vi.fn(),
+ beginPath: vi.fn(),
+ closePathByEnv: vi.fn(),
+ stroke: vi.fn(),
+ moveToByPrecision: vi.fn(),
+ lineToByPrecision: vi.fn(),
+ } as any;
+ for (const row of rows) {
+ (documents as any)._drawLiquid = { x: row.cells[0].left, y: row.index * 30 };
+ (documents as any)._drawTableCellBordersAndBg(ctx, { marginLeft: 0, marginTop: 0 }, row.cells[0]);
+ }
+ expect(ctx.moveToByPrecision.mock.calls).toEqual([[10, 30], [0, 30], [90, 30]]);
+ expect(ctx.lineToByPrecision.mock.calls).toEqual([[90, 30], [10, 30], [100, 30]]);
+ documents.dispose();
+ });
+
it('uses neighboring table cell borders for internal canonical edges', () => {
const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;
const documents = new Documents('docs-border-neighbor', skeleton, {
@@ -1425,9 +1631,7 @@ describe('documents render', () => {
} as any;
vi.spyOn(documents as any, '_drawTableCell').mockImplementation(() => {});
- vi.spyOn(documents as any, '_getDocumentCompatibilityPolicy').mockReturnValue(
- getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL)
- );
+ vi.spyOn(documents as any, '_getDocumentFlavor').mockReturnValue(DocumentFlavor.TRADITIONAL);
(documents as any)._drawTable(
ctx,
@@ -1449,7 +1653,16 @@ describe('documents render', () => {
documents.dispose();
});
- it('uses explicit table cell border width and skips no-border markers', () => {
+ it.each([
+ { inheritedTopWidth: undefined, traditional: true, expectedWidth: 5 },
+ { inheritedTopWidth: 0, traditional: true, expectedWidth: 0 },
+ { inheritedTopWidth: 2, traditional: true, expectedWidth: 2 },
+ { inheritedTopWidth: 0, traditional: false, expectedWidth: 5 },
+ ].flatMap((testCase) => [
+ { ...testCase, edge: 'top', boundary: true },
+ { ...testCase, edge: 'bottom', boundary: true },
+ { ...testCase, edge: 'bottom', boundary: false, expectedWidth: 5 },
+ ]))('resolves fragment edges without hiding explicit cell borders: %j', ({ inheritedTopWidth, traditional, expectedWidth, edge, boundary }) => {
const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;
const documents = new Documents('docs-border', skeleton, {
pageLayoutType: PageLayoutType.VERTICAL,
@@ -1465,19 +1678,37 @@ describe('documents render', () => {
cells: [cell],
rowSource: {
tableCells: [{
- borderTop: { color: { rgb: '#ff0000' }, width: { v: 5 } },
+ borderTop: { color: { rgb: 'transparent' }, width: { v: 0 } },
borderBottom: { color: { rgb: 'transparent' }, width: { v: 0 } },
+ [edge === 'top' ? 'borderTop' : 'borderBottom']: {
+ color: { rgb: '#ff0000' },
+ width: { v: 5 },
+ ...(inheritedTopWidth == null
+ ? {}
+ : {
+ [edge === 'top' ? 'tableTopBorder' : 'tableBottomBorder']: { color: { rgb: '#ff0000' }, width: { v: inheritedTopWidth } },
+ }),
+ },
borderLeft: { color: { rgb: 'transparent' }, width: { v: 0 } },
borderRight: { color: { rgb: 'transparent' }, width: { v: 0 } },
}],
},
} as any;
cell.parent = row;
+ if (!boundary) {
+ row.parent = { rows: [row, { rowSource: { tableCells: [] } }] };
+ }
(documents as any)._drawLiquid = { x: 0, y: 0 };
+ vi.spyOn(documents as any, '_getDocumentFlavor').mockReturnValue(
+ traditional ? DocumentFlavor.TRADITIONAL : DocumentFlavor.MODERN
+ );
const lineWidths: number[] = [];
const strokeStyles: string[] = [];
const ctx = {
+ getTransform: () => ({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
save: vi.fn(),
restore: vi.fn(),
fillRectByPrecision: vi.fn(),
@@ -1495,9 +1726,9 @@ describe('documents render', () => {
(documents as any)._drawTableCellBordersAndBg(ctx, { marginLeft: 0, marginTop: 0 }, cell);
- expect(lineWidths).toEqual([5]);
- expect(strokeStyles).toEqual(['#ff0000']);
- expect(ctx.stroke).toHaveBeenCalledTimes(1);
+ expect(lineWidths).toEqual(expectedWidth > 0 ? [expectedWidth] : []);
+ expect(strokeStyles).toEqual(expectedWidth > 0 ? ['#ff0000'] : []);
+ expect(ctx.stroke).toHaveBeenCalledTimes(expectedWidth > 0 ? 1 : 0);
documents.dispose();
});
@@ -1612,6 +1843,137 @@ describe('documents render', () => {
documents.dispose();
});
+ it('clips nested table cells at the accumulated content origin', () => {
+ const parent = createPage(DocumentSkeletonPageType.CELL, 'outer-cell');
+ parent.marginLeft = 4;
+ parent.marginTop = 6;
+ const cell = createPage(DocumentSkeletonPageType.CELL, 'inner-cell');
+ cell.pageWidth = 120;
+ cell.pageHeight = 60;
+ cell.sections[0].columns[0].lines = [];
+ const documents = new Documents('docs-nested-table-cell-clip');
+ (documents as any)._drawLiquid.translate(12, 20);
+ const ctx = {
+ beginPath: vi.fn(),
+ clip: vi.fn(),
+ closePath: vi.fn(),
+ rectByPrecision: vi.fn(),
+ restore: vi.fn(),
+ save: vi.fn(),
+ };
+
+ (documents as any)._drawNestedPageContent(
+ ctx,
+ parent,
+ cell,
+ [],
+ null,
+ [],
+ [],
+ Vector2.create(30, 40),
+ 0,
+ 0,
+ {},
+ { scaleX: 1, scaleY: 1 }
+ );
+
+ expect(ctx.rectByPrecision).toHaveBeenCalledWith(42, 60, 120, 60);
+ expect((documents as any)._drawLiquid).toMatchObject({ x: 12, y: 20 });
+ documents.dispose();
+ });
+
+ it.each([TableTextWrapType.NONE, TableTextWrapType.WRAP])('clips flow tables but preserves floating table overflow beyond the anchor cell: %s', (textWrap) => {
+ const parent = createPage(DocumentSkeletonPageType.BODY, '');
+ const cell = createPage(DocumentSkeletonPageType.CELL, 'anchor');
+ cell.pageWidth = 50;
+ cell.sections[0].columns[0].lines = [];
+ attachTable(cell);
+ const table = cell.skeTables.get('table-1');
+ table.tableSource.textWrap = textWrap;
+ table.tableSource.size = { width: { v: 120 } };
+ table.tableSource.tableColumns = [{ size: { width: { v: 120 } } }];
+ table.rows[0].cells[0].sections[0].columns[0].lines = [];
+ const univer = new Univer();
+ const model = new DocumentDataModel({
+ id: 'floating-table-cell-overflow',
+ body: { dataStream: '\r\n' },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));
+ const documents = new Documents(model.getUnitId(), skeleton);
+ const ctx = canvas.getContext();
+ const clip = vi.spyOn(ctx, 'clip');
+ const fill = vi.spyOn(ctx, 'fill');
+
+ (documents as any)._drawNestedPageContent(
+ ctx,
+ parent,
+ cell,
+ [],
+ null,
+ [],
+ [],
+ Vector2.create(10, 12),
+ 0,
+ 0,
+ {},
+ { scaleX: 1, scaleY: 1 }
+ );
+
+ expect(fill).toHaveBeenCalled();
+ expect(clip).toHaveBeenCalled();
+ expect(fill.mock.invocationCallOrder[0] < clip.mock.invocationCallOrder[0])
+ .toBe(textWrap === TableTextWrapType.WRAP);
+ expect((documents as any)._drawLiquid).toMatchObject({ x: 0, y: 0 });
+ documents.dispose();
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it('draws vertical cell glyphs down the physical cell and restores its parent origin', () => {
+ const parent = createPage(DocumentSkeletonPageType.CELL, 'outer');
+ const cell = createPage(DocumentSkeletonPageType.CELL, 'vertical');
+ cell.cellTextDirection = 'tbRlV';
+ cell.pageWidth = 40;
+ cell.pageHeight = 120;
+ cell.marginLeft = 5;
+ cell.marginTop = 4;
+ const line = createLine(LineType.PARAGRAPH, 0);
+ line.paddingTop = 0;
+ line.marginTop = 0;
+ const column = cell.sections[0].columns[0];
+ column.lines = [line];
+ line.parent = column;
+ const documents = new Documents('vertical-cell-render');
+ (documents as any)._drawLiquid.translate(12, 20);
+ const positions: { x: number; y: number }[] = [];
+ const extension = {
+ extensionOffset: {} as any,
+ draw() {
+ expect(this.extensionOffset.renderConfig).toMatchObject({ centerAngle: 90, vertexAngle: 90 });
+ const { spanStartPoint, centerPoint } = this.extensionOffset;
+ positions.push({ x: spanStartPoint.x + centerPoint.x, y: spanStartPoint.y + centerPoint.y });
+ },
+ };
+ const ctx = {
+ beginPath: vi.fn(),
+ clip: vi.fn(),
+ closePath: vi.fn(),
+ rectByPrecision: vi.fn(),
+ restore: vi.fn(),
+ save: vi.fn(),
+ };
+ (documents as any)._drawNestedPageContent(ctx, parent, cell, [], null, [], [extension], Vector2.create(30, 40), 0, 0, {}, { scaleX: 1, scaleY: 1 });
+ expect(ctx.rectByPrecision).toHaveBeenCalledWith(42, 60, 40, 120);
+ expect(positions).toHaveLength(2);
+ expect(positions[0].x).toBeCloseTo(68);
+ expect(positions[1].x).toBeCloseTo(68);
+ expect(positions[0].y).toBeCloseTo(73);
+ expect(positions[1].y).toBeCloseTo(91);
+ expect((documents as any)._drawLiquid).toMatchObject({ x: 12, y: 20 });
+ documents.dispose();
+ });
+
it('offsets table cell paragraph backgrounds by parent page margins', () => {
const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');
bodyPage.marginLeft = 30;
@@ -1773,7 +2135,8 @@ describe('documents render', () => {
0,
0,
{},
- { scaleX: 1, scaleY: 1 }
+ { scaleX: 1, scaleY: 1 },
+ undefined
);
expect(translate).toHaveBeenCalledWith(4, 6);
@@ -1839,6 +2202,422 @@ describe('documents render', () => {
documents.dispose();
});
+ it.each([
+ { documentFlavor: DocumentFlavor.TRADITIONAL, zOrder: 'front' as const },
+ { documentFlavor: DocumentFlavor.TRADITIONAL, zOrder: 'back' as const },
+ { documentFlavor: DocumentFlavor.MODERN, zOrder: 'front' as const },
+ ])('renders section borders only in paginated documents, with $zOrder ordering: $documentFlavor', ({ documentFlavor, zOrder }) => {
+ const univer = new Univer();
+ const model = new DocumentDataModel({
+ id: 'section-page-borders',
+ body: {
+ dataStream: 'A\r\n',
+ paragraphs: [{ startIndex: 1, paragraphId: 'p' }],
+ sectionBreaks: [{ startIndex: 2, sectionId: 'section', pageBorders: {
+ offsetFrom: 'page',
+ zOrder,
+ top: { width: 2, padding: 24, color: { rgb: '#123456' } },
+ } }],
+ },
+ documentStyle: { documentFlavor, pageSize: { width: 320, height: 400 } },
+ });
+ const viewModel = new DocumentViewModel(model);
+ const skeleton = DocumentSkeleton.create(viewModel, univer.__getInjector().get(LocaleService));
+ skeleton.calculate();
+ const documents = new Documents(model.getUnitId(), skeleton);
+ scene.addObject(documents, 1);
+ const ctx = canvas.getContext();
+ const paints: string[] = [];
+ const rectangles: number[][] = [];
+ vi.spyOn(ctx, 'fillRect').mockImplementation((...rect) => {
+ if (ctx.fillStyle === '#123456') {
+ paints.push('border');
+ rectangles.push(rect);
+ }
+ });
+ vi.spyOn(ctx, 'fillText').mockImplementation(() => {
+ paints.push('text');
+ });
+ documents.draw(ctx);
+ if (documentFlavor === DocumentFlavor.MODERN) {
+ expect(rectangles).toEqual([]);
+ } else {
+ expect(rectangles).toEqual([[0, 24, 320, 2]]);
+ expect(paints).toContain('text');
+ expect(paints.indexOf('border') < paints.indexOf('text')).toBe(zOrder === 'back');
+ }
+ documents.dispose();
+ skeleton.dispose();
+ viewModel.dispose();
+ univer.dispose();
+ });
+
+ it.each(['PAGE', 'NUMPAGES'])('renders %s once, excluding sentinels and subsequent cached digit runs', (fieldType) => {
+ const univer = new Univer();
+ const model = new DocumentDataModel({
+ id: 'footer-field-once',
+ body: {
+ dataStream: 'A\r\n',
+ paragraphs: [{ startIndex: 1, paragraphId: 'p' }],
+ sectionBreaks: [{ startIndex: 2, sectionId: 's', defaultFooterId: 'footer' }],
+ },
+ footers: { footer: { footerId: 'footer', body: {
+ dataStream: `${DataStreamTreeTokenType.CUSTOM_RANGE_START}67${DataStreamTreeTokenType.CUSTOM_RANGE_END}\r\n`,
+ paragraphs: [{ startIndex: 4, paragraphId: 'footer-p' }],
+ textRuns: [{ st: 1, ed: 2, ts: { fs: 11 } }, { st: 2, ed: 3, ts: { fs: 12 } }],
+ customRanges: [{ startIndex: 0, endIndex: 3, rangeId: 'f', rangeType: 1, properties: { fieldType } }],
+ } } },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 320, height: 400 } },
+ });
+ const viewModel = new DocumentViewModel(model);
+ const skeleton = DocumentSkeleton.create(viewModel, univer.__getInjector().get(LocaleService));
+ skeleton.calculate();
+ const documents = new Documents(model.getUnitId(), skeleton);
+ scene.addObject(documents, 1);
+ const ctx = canvas.getContext();
+ const text = vi.spyOn(ctx, 'fillText');
+ documents.draw(ctx);
+ expect(text.mock.calls.map(([value]) => value).filter((value) => /\d/.test(String(value)))).toEqual(['1']);
+ expect(model.getSnapshot().footers!.footer.body.dataStream).toContain('67');
+ documents.dispose();
+ skeleton.dispose();
+ viewModel.dispose();
+ univer.dispose();
+ });
+
+ it.each([
+ { horizontalAlign: HorizontalAlign.LEFT },
+ { horizontalAlign: HorizontalAlign.CENTER },
+ { horizontalAlign: HorizontalAlign.RIGHT },
+ { tabStops: [{ offset: 150, alignment: TabStopAlignment.START }] },
+ { tabStops: [{ offset: 150, alignment: TabStopAlignment.CENTER }] },
+ { tabStops: [{ offset: 150, alignment: TabStopAlignment.END }] },
+ ].flatMap((paragraphStyle) => [80, 100].map((scale) => ({ paragraphStyle, scale }))))(
+ 'positions live multi-digit page fields independently of cached digit widths: %j',
+ ({ paragraphStyle, scale }: { paragraphStyle: IParagraphStyle; scale: number }) => {
+ const render = (cached: string) => {
+ const univer = new Univer();
+ const T = DataStreamTreeTokenType;
+ const prefix = paragraphStyle.tabStops ? 'X\t' : 'X';
+ const fieldStart = prefix.length;
+ const suffix = paragraphStyle.tabStops ? 'Y\tZ' : 'Y Z';
+ const dataStream = `${prefix}${T.CUSTOM_RANGE_START}${cached}${T.CUSTOM_RANGE_END}${suffix}\r\n`;
+ const bodyStream = `${new Array(18).fill('A').join(T.PAGE_BREAK)}\r\n`;
+ const model = new DocumentDataModel({
+ id: `field-advance-${cached}`,
+ body: {
+ dataStream: bodyStream,
+ paragraphs: [{ startIndex: bodyStream.length - 2, paragraphId: 'body' }],
+ sectionBreaks: [{ startIndex: bodyStream.length - 1, sectionId: 's', defaultFooterId: 'footer' }],
+ },
+ footers: { footer: { footerId: 'footer', body: {
+ dataStream,
+ paragraphs: [{ startIndex: dataStream.length - 2, paragraphId: 'f', paragraphStyle }],
+ textRuns: [{ st: 0, ed: dataStream.length - 1, ts: { fs: 11, sa: scale } }],
+ customRanges: [{ startIndex: fieldStart, endIndex: fieldStart + cached.length + 1, rangeId: 'field', rangeType: CustomRangeType.FIELD, properties: { fieldType: 'NUMPAGES' } }],
+ } } },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 320, height: 400 } },
+ });
+ const viewModel = new DocumentViewModel(model);
+ const skeleton = DocumentSkeleton.create(viewModel, univer.__getInjector().get(LocaleService));
+ const documents = new Documents(model.getUnitId(), skeleton);
+ try {
+ skeleton.calculate();
+ expect(skeleton.getSkeletonData()!.pages).toHaveLength(18);
+ scene.addObject(documents, 1);
+ const text = vi.spyOn(canvas.getContext(), 'fillText');
+ text.mockClear();
+ documents.draw(canvas.getContext());
+ const positions = text.mock.calls.filter(([value]) => ['X', '18', 'Y', 'Z'].includes(String(value)))
+ .map(([value, x, y]) => [value, x, y]);
+ expect(positions).toHaveLength(18 * 4);
+ expect(model.getSnapshot().footers!.footer.body.dataStream).toBe(dataStream);
+ return positions;
+ } finally {
+ documents.dispose();
+ skeleton.dispose();
+ viewModel.dispose();
+ model.dispose();
+ univer.dispose();
+ }
+ };
+ const expected = render('18');
+ for (const cached of ['1', '123']) {
+ const actual = render(cached);
+ actual.forEach(([value, x, y], i) => {
+ expect(value).toBe(expected[i][0]);
+ expect(x).toBeCloseTo(expected[i][1] as number, 4);
+ expect(y).toBeCloseTo(expected[i][2] as number, 4);
+ });
+ }
+ }
+ );
+
+ it.each(['header', 'footer'] as const)('renders live page fields inside nested %s tables without changing cached results', (story) => {
+ const univer = new Univer();
+ const T = DataStreamTreeTokenType;
+ const fields = `${T.CUSTOM_RANGE_START}67${T.CUSTOM_RANGE_END} / ${T.CUSTOM_RANGE_START}89${T.CUSTOM_RANGE_END}\r`;
+ const wrap = (content: string) => `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${content}\n${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const inner = wrap(fields);
+ const outer = wrap(`${inner}\r`);
+ const dataStream = `${outer}\r\n`;
+ const fieldStart = dataStream.indexOf(T.CUSTOM_RANGE_START);
+ const countStart = dataStream.indexOf(T.CUSTOM_RANGE_START, fieldStart + 1);
+ const body: IDocumentBody = {
+ dataStream,
+ paragraphs: [...dataStream.matchAll(/\r/g)].map((match, index) => ({ startIndex: match.index!, paragraphId: `p-${index}` })),
+ sectionBreaks: [...dataStream.matchAll(/\n/g)].map((match, index) => ({ startIndex: match.index!, sectionId: `s-${index}` })),
+ tables: [
+ { tableId: 'outer', startIndex: 0, endIndex: outer.length },
+ { tableId: 'inner', startIndex: 3, endIndex: 3 + inner.length },
+ ],
+ customRanges: [fieldStart, countStart].map((startIndex, index) => ({
+ startIndex,
+ endIndex: startIndex + 3,
+ rangeId: `f-${index}`,
+ rangeType: CustomRangeType.FIELD,
+ properties: { fieldType: index === 0 ? 'PAGE' : 'NUMPAGES' },
+ })),
+ textRuns: [fieldStart, countStart].flatMap((st) => [
+ { st: st + 1, ed: st + 2, ts: { fs: 11 } },
+ { st: st + 2, ed: st + 3, ts: { fs: 12 } },
+ ]),
+ };
+ const tableSource = Object.fromEntries(['outer', 'inner'].map((tableId): [string, ITable] => [tableId, {
+ tableId,
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ size: { type: TableSizeType.SPECIFIED, width: { v: 200 } },
+ position: { positionH: { relativeFrom: ObjectRelativeFromH.PAGE }, positionV: { relativeFrom: ObjectRelativeFromV.PAGE } },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ cellMargin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 200 } } }],
+ tableRows: [{ trHeight: { hRule: TableRowHeightRule.AUTO, val: { v: 0 } }, tableCells: [{}] }],
+ }]));
+ const model = new DocumentDataModel({
+ id: `nested-${story}-fields`,
+ body: {
+ dataStream: `A${T.PAGE_BREAK}B${T.PAGE_BREAK}C\r\n`,
+ paragraphs: [{ startIndex: 5, paragraphId: 'body' }],
+ sectionBreaks: [{ startIndex: 6, sectionId: 'section', defaultHeaderId: 'header', defaultFooterId: 'footer' }],
+ },
+ headers: story === 'header' ? { header: { headerId: 'header', body } } : {},
+ footers: story === 'footer' ? { footer: { footerId: 'footer', body } } : {},
+ tableSource,
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 320, height: 400 } },
+ });
+ const viewModel = new DocumentViewModel(model);
+ const skeleton = DocumentSkeleton.create(viewModel, univer.__getInjector().get(LocaleService));
+ const documents = new Documents(model.getUnitId(), skeleton);
+ try {
+ skeleton.calculate();
+ expect(skeleton.getSkeletonData()!.pages).toHaveLength(3);
+ scene.addObject(documents, 1);
+ const text = vi.spyOn(canvas.getContext(), 'fillText');
+ documents.draw(canvas.getContext());
+ expect(text.mock.calls.map(([value]) => String(value)).filter((value) => /\d/.test(value)))
+ .toEqual(['1', '3', '2', '3', '3', '3']);
+ expect((story === 'header' ? model.getSnapshot().headers!.header : model.getSnapshot().footers!.footer).body.dataStream)
+ .toBe(dataStream);
+ } finally {
+ documents.dispose();
+ skeleton.dispose();
+ viewModel.dispose();
+ model.dispose();
+ univer.dispose();
+ }
+ });
+
+ it('does not treat the first visible continuation page as the first page of its section', () => {
+ const univer = new Univer();
+ const pageBorders = {
+ display: 'firstPage' as const,
+ offsetFrom: 'page' as const,
+ top: { width: 2, padding: 24, color: { rgb: '#123456' } },
+ };
+ const model = new DocumentDataModel({
+ id: 'section-border-scroll',
+ body: {
+ dataStream: `A${DataStreamTreeTokenType.PAGE_BREAK}B\r\nC\r\n`,
+ paragraphs: [{ startIndex: 3, paragraphId: 'ab' }, { startIndex: 6, paragraphId: 'c' }],
+ sectionBreaks: [
+ { startIndex: 4, sectionId: 'ab', pageBorders },
+ { startIndex: 7, sectionId: 'c', pageBorders },
+ ],
+ },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 320, height: 400 } },
+ });
+ const viewModel = new DocumentViewModel(model);
+ const skeleton = DocumentSkeleton.create(viewModel, univer.__getInjector().get(LocaleService));
+ skeleton.calculate();
+ const pages = skeleton.getSkeletonData()!.pages;
+ expect(pages.map((page) => page.sectionId)).toEqual(['ab', 'ab', 'c']);
+ const documents = new Documents(model.getUnitId(), skeleton);
+ scene.addObject(documents, 1);
+ const ctx = canvas.getContext();
+ const rectangles: number[][] = [];
+ vi.spyOn(ctx, 'fillRect').mockImplementation((...rect) => {
+ if (ctx.fillStyle === '#123456') {
+ rectangles.push(rect);
+ }
+ });
+ documents.draw(ctx, { viewBound: { left: 0, right: 500, top: 700, bottom: 1500 } } as any);
+ expect(rectangles).toEqual([[0, 2 * (400 + documents.pageMarginTop) + 24, 320, 2]]);
+ documents.dispose();
+ skeleton.dispose();
+ viewModel.dispose();
+ univer.dispose();
+ });
+
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('retains the physical page boundary only in paginated rendering: %s', (documentFlavor) => {
+ const univer = new Univer();
+ const model = new DocumentDataModel({
+ id: 'physical-page-clip',
+ body: { dataStream: 'A\r\n', paragraphs: [{ startIndex: 1, paragraphId: 'p' }] },
+ documentStyle: { documentFlavor, pageSize: { width: 320, height: 400 } },
+ });
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));
+ skeleton.calculate();
+ const documents = new Documents(model.getUnitId(), skeleton);
+ scene.addObject(documents, 1);
+ const ctx = canvas.getContext();
+ const rect = vi.spyOn(ctx, 'rect');
+ const clip = vi.spyOn(ctx, 'clip');
+
+ documents.draw(ctx);
+
+ if (documentFlavor === DocumentFlavor.TRADITIONAL) {
+ expect(rect).toHaveBeenCalledWith(0, 0, 320, 400);
+ expect(clip).toHaveBeenCalled();
+ } else {
+ expect(clip).not.toHaveBeenCalled();
+ }
+ documents.dispose();
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it.each([
+ { documentFlavor: DocumentFlavor.TRADITIONAL, enabled: true },
+ { documentFlavor: DocumentFlavor.TRADITIONAL, enabled: false },
+ { documentFlavor: DocumentFlavor.MODERN, enabled: true },
+ ])('dims body content but leaves header/footer intact for the content cover: $documentFlavor, editor=$enabled', ({ documentFlavor, enabled }) => {
+ const univer = new Univer();
+ const model = new DocumentDataModel({
+ id: 'edit-area-colors',
+ body: {
+ dataStream: 'D\r\n',
+ paragraphs: [{ startIndex: 1, paragraphId: 'body-p' }],
+ sectionBreaks: [{ startIndex: 2, sectionId: 'section', defaultHeaderId: 'header', defaultFooterId: 'footer' }],
+ },
+ headers: { header: { headerId: 'header', body: { dataStream: 'H\r\n', paragraphs: [{ startIndex: 1, paragraphId: 'header-p' }] } } },
+ footers: { footer: { footerId: 'footer', body: { dataStream: 'F\r\n', paragraphs: [{ startIndex: 1, paragraphId: 'footer-p' }] } } },
+ documentStyle: {
+ documentFlavor,
+ pageSize: { width: 320, height: 400 },
+ marginTop: 50,
+ marginBottom: 50,
+ marginHeader: 10,
+ marginFooter: 10,
+ },
+ });
+ const viewModel = new DocumentViewModel(model);
+ const skeleton = DocumentSkeleton.create(viewModel, univer.__getInjector().get(LocaleService));
+ skeleton.calculate();
+ const bodyPage = skeleton.getSkeletonData()!.pages[0];
+ attachTable(bodyPage);
+ bodyPage.skeTables.get('table-1')!.top = -bodyPage.marginTop;
+ const documents = new Documents(model.getUnitId(), skeleton);
+ scene.addObject(documents, 1);
+ if (enabled) {
+ documents.setInactiveAreaOpacity(0.5);
+ }
+ const ctx = canvas.getContext();
+ const textPaints: Array<{ text: string; alpha: number }> = [];
+ const tablePaints: number[] = [];
+ vi.spyOn(ctx, 'fillText').mockImplementation((text) => {
+ textPaints.push({ text: String(text), alpha: ctx.globalAlpha });
+ });
+ vi.spyOn(ctx, 'fill').mockImplementation(() => {
+ if (ctx.fillStyle === '#ffeecc') {
+ tablePaints.push(ctx.globalAlpha);
+ }
+ });
+
+ for (const editArea of [DocumentEditArea.BODY, DocumentEditArea.HEADER, DocumentEditArea.FOOTER]) {
+ viewModel.setEditArea(editArea);
+ textPaints.length = 0;
+ tablePaints.length = 0;
+ ctx.globalAlpha = 0.8;
+ documents.draw(ctx);
+
+ const dims = enabled && documentFlavor === DocumentFlavor.TRADITIONAL;
+ const bodyAlpha = dims && editArea !== DocumentEditArea.BODY ? 0.4 : 0.8;
+ expect(textPaints.filter(({ text }) => text === 'D').map(({ alpha }) => alpha)).toEqual([bodyAlpha]);
+ expect(tablePaints).toEqual([bodyAlpha]);
+ if (documentFlavor === DocumentFlavor.TRADITIONAL) {
+ expect(textPaints.filter(({ text }) => text === 'H' || text === 'F').map(({ alpha }) => alpha))
+ .toEqual([0.8, 0.8]);
+ }
+ expect(ctx.globalAlpha).toBe(0.8);
+ }
+ documents.dispose();
+ skeleton.dispose();
+ viewModel.dispose();
+ univer.dispose();
+ });
+
+ it.each([
+ { centerAngle: 0, vertexAngle: 0 },
+ { centerAngle: 0, vertexAngle: -45 },
+ { centerAngle: 0, vertexAngle: 45 },
+ { centerAngle: 90, vertexAngle: 90 },
+ ].flatMap((angles) => [WrapStrategy.WRAP, WrapStrategy.OVERFLOW, WrapStrategy.CLIP]
+ .map((wrapStrategy) => ({ ...angles, wrapStrategy }))))(
+ 'keeps glyph ink offsets independent of column layout at $centerAngle/$vertexAngle with wrap=$wrapStrategy',
+ ({ centerAngle, vertexAngle, wrapStrategy }) => {
+ const page = createPage(DocumentSkeletonPageType.BODY, '');
+ page.renderConfig = { ...page.renderConfig, centerAngle, vertexAngle, wrapStrategy };
+ const glyph = page.sections[0].columns[0].lines[1].divides[0].glyphGroup[0];
+ const skeletonData = { pages: [page], skeHeaders: new Map(), skeFooters: new Map() };
+ const documents = new Documents('ink-offset', { getSkeletonData: () => skeletonData } as never);
+ documents.resize(260, 40);
+ scene.addObject(documents, 1);
+ const paints: Array<{ start: Vector2; baseline: Vector2; origin: Vector2 }> = [];
+ const extension = {
+ uKey: 'InkOffset',
+ type: DOCS_EXTENSION_TYPE.SPAN,
+ extensionOffset: {} as IExtensionConfig,
+ clearCache() {},
+ draw(_ctx: UniverRenderingContext, _scale: IScale, paintedGlyph: IDocumentSkeletonGlyph) {
+ if (paintedGlyph === glyph) {
+ const { spanStartPoint, spanPointWithFont, originTranslate } = this.extensionOffset;
+ if (!spanStartPoint || !spanPointWithFont || !originTranslate) {
+ throw new Error('A painted glyph must have complete placement coordinates');
+ }
+ paints.push({ start: spanStartPoint.clone(), baseline: spanPointWithFont.clone(), origin: originTranslate.clone() });
+ }
+ },
+ };
+ vi.spyOn(documents, 'getExtensionsByOrder').mockReturnValue([extension] as never);
+ try {
+ documents.draw(canvas.getContext());
+ glyph.xOffset = 6;
+ documents.draw(canvas.getContext());
+ expect(paints).toHaveLength(2);
+ expect(paints[1].origin).toEqual(paints[0].origin);
+ const angle = centerAngle * Math.PI / 180;
+ for (const key of ['start', 'baseline'] as const) {
+ expect(paints[1][key].x - paints[0][key].x).toBeCloseTo(6 * Math.cos(angle));
+ expect(paints[1][key].y - paints[0][key].y).toBeCloseTo(6 * Math.sin(angle));
+ }
+ } finally {
+ documents.dispose();
+ }
+ }
+ );
+
it('draws body/header/footer/table flows with extension dispatch and page events', () => {
const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');
const headerPage = createPage(DocumentSkeletonPageType.HEADER, 'header-main');
diff --git a/packages/engine-render/src/components/docs/__tests__/page-borders.spec.ts b/packages/engine-render/src/components/docs/__tests__/page-borders.spec.ts
new file mode 100644
index 0000000000..2cf2a2d116
--- /dev/null
+++ b/packages/engine-render/src/components/docs/__tests__/page-borders.spec.ts
@@ -0,0 +1,105 @@
+/**
+ * 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 { IPageBorders } from '@univerjs/core';
+import type { IDocumentSkeletonPage } from '../../../basics/i-document-skeleton-cached';
+import type { UniverRenderingContext } from '../../../context';
+import { describe, expect, it, vi } from 'vitest';
+import { drawPageBorders } from '../page-borders';
+
+function createContext(): UniverRenderingContext {
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ beginPath: vi.fn(),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ closePath: vi.fn(),
+ clip: vi.fn(),
+ fillRect: vi.fn(),
+ setLineDash: vi.fn(),
+ stroke: vi.fn(),
+ } as unknown as UniverRenderingContext;
+}
+
+const page = {
+ pageWidth: 800,
+ pageHeight: 1120,
+ marginLeft: 80,
+ marginRight: 80,
+ originMarginTop: 96,
+ originMarginBottom: 96,
+} as IDocumentSkeletonPage;
+
+describe('section page borders', () => {
+ it('keeps thin outer and thick inner lines on all four edges of the Word compound frame', () => {
+ const ctx = createContext();
+ const start = { style: 'thickThinSmallGap', width: 4, padding: 32 };
+ const end = { ...start, style: 'thinThickSmallGap' };
+ drawPageBorders(ctx, page, { offsetFrom: 'page', top: start, left: start, bottom: end, right: end }, 10, 20, true);
+ expect(vi.mocked(ctx.fillRect).mock.calls).toEqual([
+ [42, 52, 736, 1],
+ [42, 54, 736, 4],
+ [777, 52, 1, 1056],
+ [772, 52, 4, 1056],
+ [42, 1107, 736, 1],
+ [42, 1102, 736, 4],
+ [42, 52, 1, 1056],
+ [44, 52, 4, 1056],
+ ]);
+ expect(ctx.save).toHaveBeenCalledTimes(4);
+ expect(ctx.restore).toHaveBeenCalledTimes(4);
+ });
+
+ it('positions text-relative borders outside the text margins, not inside them', () => {
+ const ctx = createContext();
+ const edge = { width: 2, padding: 8 };
+ drawPageBorders(ctx, page, { offsetFrom: 'text', top: edge, left: edge, right: edge, bottom: edge }, 0, 0, true);
+ expect(vi.mocked(ctx.fillRect).mock.calls).toEqual([
+ [70, 86, 660, 2],
+ [728, 86, 2, 948],
+ [70, 1032, 660, 2],
+ [70, 86, 2, 948],
+ ]);
+ });
+
+ it.each([
+ ['firstPage', true, true],
+ ['firstPage', false, false],
+ ['notFirstPage', true, false],
+ ['notFirstPage', false, true],
+ ['allPages', true, true],
+ ['allPages', false, true],
+ ] as const)('honors %s on a section first page=%s', (display, first, visible) => {
+ const ctx = createContext();
+ drawPageBorders(ctx, page, { display, top: { width: 1 } }, 0, 0, first);
+ expect(vi.mocked(ctx.fillRect).mock.calls.length > 0).toBe(visible);
+ });
+
+ it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])('ignores invalid border width %s', (width) => {
+ const ctx = createContext();
+ drawPageBorders(ctx, page, { top: { width } }, 0, 0, true);
+ expect(ctx.fillRect).not.toHaveBeenCalled();
+ });
+
+ it('does not replace disabled or unsupported art borders with solid lines', () => {
+ const ctx = createContext();
+ const borders: IPageBorders = { top: { style: 'nil' }, right: { style: 'apples' }, left: { style: 'none' } };
+ drawPageBorders(ctx, page, borders, 0, 0, true);
+ expect(ctx.fillRect).not.toHaveBeenCalled();
+ expect(ctx.stroke).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/engine-render/src/components/docs/__tests__/table-hit-test.spec.ts b/packages/engine-render/src/components/docs/__tests__/table-hit-test.spec.ts
new file mode 100644
index 0000000000..8644963b2e
--- /dev/null
+++ b/packages/engine-render/src/components/docs/__tests__/table-hit-test.spec.ts
@@ -0,0 +1,83 @@
+/**
+ * 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 { describe, expect, it } from 'vitest';
+import { getTopmostDocsTableHit } from '../table-hit-test';
+
+describe('getTopmostDocsTableHit', () => {
+ const bottom = { id: 'bottom', top: 100, bottom: 200 };
+ const top = { id: 'top', top: 150, bottom: 250 };
+ const hit = (y: number) => getTopmostDocsTableHit(
+ [bottom, top],
+ (table) => y >= table.top && y <= table.bottom,
+ (table) => y >= table.top - 30 && y <= table.bottom
+ );
+
+ it('chooses the last-painted table in an overlap', () => {
+ expect(hit(175)).toBe(top);
+ });
+
+ it('does not let the top table header gutter intercept the lower table body', () => {
+ expect(hit(130)).toBe(bottom);
+ });
+
+ it('keeps controls reachable outside content and clears the hit outside both', () => {
+ expect(hit(80)).toBe(bottom);
+ expect(hit(60)).toBeUndefined();
+ });
+
+ it('prefers a nested table header over its parent table body', () => {
+ const outer = { id: 'outer', top: 0, bottom: 300 };
+ const inner = { id: 'inner', top: 100, bottom: 200 };
+ const result = getTopmostDocsTableHit(
+ [outer, inner],
+ (table) => table.top <= 90 && table.bottom >= 90,
+ (table) => table.top - 30 <= 90 && table.bottom >= 90,
+ (parent, child) => parent.top < child.top && parent.bottom > child.bottom
+ );
+
+ expect(result).toBe(inner);
+ });
+
+ it('keeps a nested table header reachable when its gutter overlaps a sibling table body', () => {
+ const outer = { id: 'outer', start: 0, end: 400 };
+ const sibling = { id: 'sibling', start: 1, end: 100 };
+ const middle = { id: 'middle', start: 101, end: 399 };
+ const inner = { id: 'inner', start: 150, end: 300 };
+ const result = getTopmostDocsTableHit(
+ [outer, sibling, middle, inner],
+ (table) => table === outer || table === sibling,
+ (table) => table === inner,
+ (parent, child) => parent.start < child.start && parent.end > child.end
+ );
+
+ expect(result).toBe(inner);
+ });
+
+ it('keeps the deepest table body active over ancestor controls', () => {
+ const outer = { id: 'outer', start: 0, end: 300 };
+ const middle = { id: 'middle', start: 50, end: 250 };
+ const inner = { id: 'inner', start: 100, end: 200 };
+ const result = getTopmostDocsTableHit(
+ [outer, middle, inner],
+ () => true,
+ () => true,
+ (parent, child) => parent.start < child.start && parent.end > child.end
+ );
+
+ expect(result).toBe(inner);
+ });
+});
diff --git a/packages/engine-render/src/components/docs/__tests__/table-render-viewport.spec.ts b/packages/engine-render/src/components/docs/__tests__/table-render-viewport.spec.ts
new file mode 100644
index 0000000000..d6de8eddda
--- /dev/null
+++ b/packages/engine-render/src/components/docs/__tests__/table-render-viewport.spec.ts
@@ -0,0 +1,58 @@
+/**
+ * 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 { DocumentFlavor, TableTextWrapType } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { DocumentSkeletonPageType } from '../../../basics/i-document-skeleton-cached';
+import { getDocsTableLayoutViewportWidth } from '../table-render-viewport';
+
+describe('table layout viewport width', () => {
+ const page = { pageWidth: 794, marginLeft: 53, marginRight: 60 };
+ const importedTable = { size: { width: { v: 788 } } };
+
+ it('keeps a page-anchored imported cover table visible across both margins', () => {
+ expect(getDocsTableLayoutViewportWidth(page, -53, importedTable, DocumentFlavor.TRADITIONAL)).toBe(794);
+ });
+
+ it('allows a traditional model-width table to extend into the right margin', () => {
+ expect(getDocsTableLayoutViewportWidth(page, 0, importedTable, DocumentFlavor.TRADITIONAL)).toBe(741);
+ });
+
+ it.each([DocumentFlavor.MODERN, undefined])('keeps ordinary content bounds for flavor %s', (flavor) => {
+ expect(getDocsTableLayoutViewportWidth(page, 0, importedTable, flavor)).toBe(681);
+ });
+
+ it('does not infer margin overflow for tables without a model width', () => {
+ expect(getDocsTableLayoutViewportWidth(page, 0, {}, DocumentFlavor.TRADITIONAL)).toBe(681);
+ });
+
+ it('never returns a negative visible width', () => {
+ expect(getDocsTableLayoutViewportWidth(page, 800, importedTable, DocumentFlavor.TRADITIONAL)).toBe(0);
+ });
+
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN].flatMap((flavor) =>
+ [TableTextWrapType.NONE, TableTextWrapType.WRAP].map((textWrap) => ({ flavor, textWrap }))
+ ))('keeps a floating nested grid wider than its anchor cell without changing flow bounds: %j', ({ flavor, textWrap }) => {
+ const cell = { pageWidth: 51.4, marginLeft: 0, marginRight: 0, type: DocumentSkeletonPageType.CELL };
+ const table = {
+ size: { width: { v: 57.6 } },
+ tableColumns: [{ size: { width: { v: 57.6 } } }],
+ textWrap,
+ };
+ const actual = getDocsTableLayoutViewportWidth(cell, 0, table, flavor);
+ expect(actual).toBe(flavor === DocumentFlavor.TRADITIONAL && textWrap === TableTextWrapType.WRAP ? 57.6 : 51.4);
+ });
+});
diff --git a/packages/engine-render/src/components/docs/document-compatibility.ts b/packages/engine-render/src/components/docs/document-compatibility.ts
index f242349afa..6027785f64 100644
--- a/packages/engine-render/src/components/docs/document-compatibility.ts
+++ b/packages/engine-render/src/components/docs/document-compatibility.ts
@@ -14,12 +14,14 @@
* limitations under the License.
*/
-import type { ITable } from '@univerjs/core';
+import type { ITable, ITextStyle } from '@univerjs/core';
import type {
IDocumentSkeletonBoundingBox,
IDocumentSkeletonFontStyle,
} from '../../basics/i-document-skeleton-cached';
import { DocumentFlavor } from '@univerjs/core';
+import { cjk } from '../../basics/cjk-regexp';
+import { getFontStyleString } from '../../basics/tools';
interface IFontMetricScaleRule {
fontFamily: RegExp;
@@ -30,7 +32,7 @@ interface IFontMetricScaleRule {
}
export interface IDocumentCompatibilityPolicy {
- mode: 'modern' | 'traditional' | 'unspecified';
+ mode: 'modern' | 'traditional' | 'unspecified' | 'drawingml';
applyDocumentDefaultParagraphStyle: boolean;
useWordStyleLineHeight: boolean;
font: {
@@ -63,12 +65,6 @@ const TRADITIONAL_DOCUMENT_COMPATIBILITY_POLICY: IDocumentCompatibilityPolicy =
useWordStyleLineHeight: true,
font: {
metricScaleRules: [
- {
- fontFamily: /^arial$/i,
- fontString: /^\S+\s+normal\s+\d+(?:\.\d+)?pt\s+["']?Arial["']?(?:,|$)/i,
- content: /^[\u0000-\u024F\u2000-\u206F]$/u,
- widthScale: 0.98,
- },
{
fontFamily: /^calibri$/i,
minFontSize: 20,
@@ -104,7 +100,15 @@ const UNSPECIFIED_DOCUMENT_COMPATIBILITY_POLICY: IDocumentCompatibilityPolicy =
},
};
+const DRAWINGML_COMPATIBILITY_POLICY: IDocumentCompatibilityPolicy = {
+ ...UNSPECIFIED_DOCUMENT_COMPATIBILITY_POLICY,
+ mode: 'drawingml',
+};
+
export function getDocumentCompatibilityPolicy(documentFlavor?: DocumentFlavor): IDocumentCompatibilityPolicy {
+ if (documentFlavor === DocumentFlavor.DRAWINGML) {
+ return DRAWINGML_COMPATIBILITY_POLICY;
+ }
if (documentFlavor === DocumentFlavor.MODERN) {
return MODERN_DOCUMENT_COMPATIBILITY_POLICY;
}
@@ -122,6 +126,18 @@ export function applyFontMetricCompatibility(
bBox: IDocumentSkeletonBoundingBox,
policy: IDocumentCompatibilityPolicy
): IDocumentSkeletonBoundingBox {
+ if (policy.mode === 'drawingml') {
+ // PowerPoint's measured advances use eighths of a slide-layout unit.
+ return { ...bBox, width: Math.round(bBox.width * 8) / 8 };
+ }
+ // Canvas quantizes fractional font sizes (10pt Han advances can become 13.330px).
+ // Recover the nominal em only for already full-width CJK glyphs; leave proportional
+ // glyphs, explicit half-width forms, and their actual ink/vertical metrics unchanged.
+ const em = fontStyle.fontSize / 0.75;
+ const width = policy.mode === 'traditional' && Array.from(content).length === 1 && cjk.hasCJK(content)
+ && Math.abs(bBox.width - em) < 0.01
+ ? em
+ : bBox.width;
const fontFamilies = fontStyle.fontFamily
.split(',')
.map((item) => item.trim().replace(/^['"]|['"]$/g, ''));
@@ -133,16 +149,60 @@ export function applyFontMetricCompatibility(
fontFamilies.some((family) => rule.fontFamily.test(family))
);
- if (rule?.widthScale == null) {
+ const adjustedWidth = width * (rule?.widthScale ?? 1);
+ let normalLineHeight = bBox.normalLineHeight;
+ if (policy.mode === 'traditional' && /^(?:Microsoft YaHei|微软雅黑)$/i.test(fontFamilies[0])
+ && Math.abs((bBox.ba + bBox.bd) / (fontStyle.originFontSize / 0.75) - 2703 / 2048) < 0.001) {
+ // Word's single spacing adds leading to YaHei's font box. Isolated native
+ // Word probes at 7.5pt and 12pt measure 17.12px and 27.52px baseline advances.
+ // Guard the actual font metrics so a missing/substituted font is not inflated.
+ // AUTO and AT_LEAST consume this value; keep ink and exact line metrics.
+ normalLineHeight = Math.max(normalLineHeight ?? 0, (bBox.ba + bBox.bd) * 1.3);
+ }
+ if (policy.mode === 'traditional' && /^(?:MS Gothic|MS ゴシック)$/i.test(fontFamilies[0])
+ && Math.abs(bBox.ba + bBox.bd - fontStyle.originFontSize / 0.75) < 0.01) {
+ // Word adds auto-leading beyond MS Gothic's one-em font box, for Latin
+ // text as well as symbols. Native Word probes at 11pt and 16pt confirm
+ // this ratio; leave ink metrics and fixed/minimum line spacing intact.
+ normalLineHeight = Math.max(normalLineHeight ?? 0, fontStyle.originFontSize / 0.75 * 83 / 64);
+ }
+ if (adjustedWidth === bBox.width && normalLineHeight === bBox.normalLineHeight) {
return bBox;
}
return {
...bBox,
- width: bBox.width * rule.widthScale,
+ width: adjustedWidth,
+ ...(normalLineHeight != null ? { normalLineHeight } : {}),
};
}
+export function getSmallCapsFontStyle(
+ raw: string,
+ textStyle: ITextStyle | undefined,
+ fontStyle: IDocumentSkeletonFontStyle,
+ policy: IDocumentCompatibilityPolicy
+): IDocumentSkeletonFontStyle {
+ if (!textStyle?.smallCaps || textStyle.caps || raw === raw.toUpperCase()) {
+ return fontStyle;
+ }
+ // Native Office uses synthetic 80% capitals; Word rounds the size to half-points.
+ // Keep the authored size for line metrics and kerning-threshold decisions.
+ const size = fontStyle.originFontSize * 0.8;
+ const fs = policy.mode === 'drawingml' ? size : Math.max(0.5, Math.round(size * 2) / 2);
+ return {
+ ...getFontStyleString({ ...textStyle, fs }),
+ originFontSize: fontStyle.originFontSize,
+ fontKerning: fontStyle.fontKerning,
+ };
+}
+
+export function getNominalFontLineHeight(fontSize: number, policy?: IDocumentCompatibilityPolicy): number | undefined {
+ // Office renderer compatibility, not an OOXML-specified font metric.
+ // Font sizes are points; the layout engine uses 96-DPI pixels.
+ return policy?.mode === 'drawingml' && fontSize > 0 ? fontSize * 1.2 * (96 / 72) : undefined;
+}
+
export function isTraditionalDocumentCompatibility(policy?: IDocumentCompatibilityPolicy): boolean {
return policy?.mode === 'traditional';
}
diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.ts
index 991a4b4807..58d222e61c 100644
--- a/packages/engine-render/src/components/docs/document.ts
+++ b/packages/engine-render/src/components/docs/document.ts
@@ -24,8 +24,10 @@ import type {
Nullable,
} from '@univerjs/core';
import type {
+ IDocumentSkeletonColumn,
IDocumentSkeletonColumnGroup,
IDocumentSkeletonColumnGroupColumn,
+ IDocumentSkeletonDivide,
IDocumentSkeletonGlyph,
IDocumentSkeletonLine,
IDocumentSkeletonPage,
@@ -41,36 +43,44 @@ import type { ComponentExtension, IDrawInfo, IExtensionConfig } from '../extensi
import type { IDocumentsConfig, IPageMarginLayout } from './doc-component';
import type { DocumentSkeleton } from './layout/doc-skeleton';
import type { IDocsTableRenderViewport } from './table-render-viewport';
+import type { DocumentViewModel } from './view-model/document-view-model';
import {
CellValueType,
ColumnSeparatorType,
DashStyleType,
+ DataStreamTreeTokenType,
DocumentFlavor,
HorizontalAlign,
+ TableTextWrapType,
+ TabStopAlignment,
VerticalAlign,
WrapStrategy,
} from '@univerjs/core';
import { Subject } from 'rxjs';
-import { BORDER_TYPE, COLOR_BLACK_RGB, drawLineByBorderType } from '../../basics';
-import { calculateRectRotate, getRotateOffsetAndFarthestHypotenuse } from '../../basics/draw';
-import { DocumentSkeletonPageType, LineType } from '../../basics/i-document-skeleton-cached';
+import { BORDER_TYPE, COLOR_BLACK_RGB } from '../../basics/const';
+import { calculateRectRotate, drawLineByBorderType, getRotateOffsetAndFarthestHypotenuse } from '../../basics/draw';
+import { DocumentSkeletonPageType, GlyphType, LineType } from '../../basics/i-document-skeleton-cached';
import { VERTICAL_ROTATE_ANGLE } from '../../basics/text-rotation';
import { degToRad, fixLineWidthByScale } from '../../basics/tools';
import { Vector2 } from '../../basics/vector2';
import { DocumentsSpanAndLineExtensionRegistry } from '../extension';
import { DocComponent } from './doc-component';
import { DOCS_EXTENSION_TYPE } from './doc-extension';
-import { getDocumentCompatibilityPolicy, shouldAllowImportedTableMarginOverflow } from './document-compatibility';
import { collectBackgroundGlyphRuns } from './extensions/background-runs';
import { getTableIdAndSliceIndex } from './layout/block/table';
+import { getTextHorizontalScale } from './layout/model/glyph';
+import { FontCache } from './layout/shaping-engine/font-cache';
import { getColorStyleForCanvas } from './layout/style/color';
import { documentSkeletonTableIterator } from './layout/tools';
import { Liquid } from './liquid';
+import { drawPageBorders } from './page-borders';
import {
+ getDocsTableLayoutViewportWidth,
getDocsTableRenderViewport,
getDocsTableViewportLeft,
hasDocsTableHorizontalViewport,
} from './table-render-viewport';
+import { DocumentEditArea } from './view-model/document-view-model';
import './extensions';
const DEFAULT_BORDER_COLOR: ITableCellBorder = {
@@ -129,19 +139,27 @@ export function resolveHeaderFooterFieldGlyph(
pageNumber: number,
pageCount: number
): IDocumentSkeletonGlyph {
+ if (!glyph.content || glyph.raw === DataStreamTreeTokenType.CUSTOM_RANGE_START ||
+ glyph.raw === DataStreamTreeTokenType.CUSTOM_RANGE_END) {
+ return glyph;
+ }
const fieldRange = customRanges.find((customRange) =>
customRange.startIndex <= startIndex &&
customRange.endIndex >= endIndex &&
typeof customRange.properties?.fieldType === 'string'
);
const fieldType = fieldRange?.properties?.fieldType?.toUpperCase();
- const content = fieldType === 'PAGE'
- ? String(pageNumber)
- : fieldType === 'NUMPAGES'
- ? String(pageCount)
- : undefined;
+ if (!fieldRange || (fieldType !== 'PAGE' && fieldType !== 'NUMPAGES')) {
+ return glyph;
+ }
+ // FIELD endpoints are invisible sentinels. Paint the value once even when
+ // the cached digits were split into several differently formatted runs.
+ let content = '';
+ if (startIndex === fieldRange.startIndex + 1) {
+ content = String(fieldType === 'PAGE' ? pageNumber : pageCount);
+ }
- return content == null || content === glyph.content ? glyph : { ...glyph, content };
+ return content === glyph.content ? glyph : { ...glyph, content };
}
export interface IPageRenderConfig {
@@ -151,6 +169,97 @@ export interface IPageRenderConfig {
ctx: UniverRenderingContext;
}
+interface IHeaderFooterFieldContext {
+ customRanges: ICustomRange[];
+ pageNumber: number;
+ pageCount: number;
+ viewModel?: DocumentViewModel;
+}
+
+function resolveHeaderFooterFieldGlyphGroup(
+ divide: IDocumentSkeletonDivide,
+ context: IHeaderFooterFieldContext
+): IDocumentSkeletonGlyph[] {
+ // Header/footer skeletons are shared between body pages; keep cached advances immutable.
+ // ponytail: Preserve cached line breaks; overflowing fields need per-page header/footer layout.
+ const { glyphGroup } = divide;
+ let index = divide.st;
+ const resolved = glyphGroup.map((glyph) => {
+ const result = resolveHeaderFooterFieldGlyph(
+ glyph,
+ index,
+ index + glyph.count - 1,
+ context.customRanges,
+ context.pageNumber,
+ context.pageCount
+ );
+ index += glyph.count;
+ if (result === glyph) {
+ return glyph;
+ }
+ const font = glyph.fontStyle?.fontString;
+ let widthDelta = -glyph.width;
+ if (result.content) {
+ widthDelta = font
+ ? (FontCache.getMeasureText(result.content, font).width - FontCache.getMeasureText(glyph.content, font).width)
+ * getTextHorizontalScale(glyph.ts?.sa)
+ : 0;
+ }
+ const width = Math.max(0, glyph.width + widthDelta);
+ return { ...result, width, bBox: { ...glyph.bBox, width: Math.max(0, glyph.bBox.width + widthDelta) } };
+ });
+ if (resolved.every((glyph, i) => glyph === glyphGroup[i])) {
+ return glyphGroup;
+ }
+
+ const style = divide.parent && context.viewModel?.getParagraph(divide.parent.paragraphIndex)?.paragraphStyle;
+ // A tab absorbs changes before its fixed stop; right/center tabs also account for the following field.
+ const followingDeltas: number[] = [];
+ let followingDelta = 0;
+ for (let i = resolved.length - 1; i >= 0; i--) {
+ followingDeltas[i] = followingDelta;
+ if (resolved[i].glyphType === GlyphType.TAB) {
+ followingDelta = 0;
+ } else {
+ followingDelta += resolved[i].width - glyphGroup[i].width;
+ }
+ }
+ let offset = 0;
+ const positioned = resolved.map((glyph, i) => {
+ const original = glyphGroup[i];
+ let width = glyph.width;
+ if (glyph.glyphType === GlyphType.TAB) {
+ const tabLeft = divide.left + divide.paddingLeft + original.left;
+ const stop = style?.tabStops?.filter((tab) => !tab.clear && tab.offset > tabLeft)
+ .sort((a, b) => a.offset - b.offset)[0];
+ const alignment = glyph.ts?.positionedTab?.alignment ?? stop?.alignment;
+ let alignedDelta = 0;
+ if (alignment === TabStopAlignment.END) {
+ alignedDelta = followingDeltas[i];
+ } else if (alignment === TabStopAlignment.CENTER) {
+ alignedDelta = followingDeltas[i] / 2;
+ }
+ width = Math.max(0, original.width - offset - alignedDelta);
+ }
+ const result = { ...glyph, left: original.left + offset, width, bBox: { ...glyph.bBox } };
+ if (glyph.glyphType === GlyphType.TAB) {
+ result.bBox.width = width;
+ }
+ offset += width - original.width;
+ return result;
+ });
+ let alignmentOffset = 0;
+ if (style?.horizontalAlign === HorizontalAlign.RIGHT) {
+ alignmentOffset = offset;
+ } else if (style?.horizontalAlign === HorizontalAlign.CENTER) {
+ alignmentOffset = offset / 2;
+ }
+ for (const glyph of positioned) {
+ glyph.left -= alignmentOffset;
+ }
+ return positioned;
+}
+
export interface IDocumentOffsetConfig extends IPageMarginLayout {
docsLeft: number;
docsTop: number;
@@ -195,6 +304,8 @@ export class Documents extends DocComponent {
private _drawLiquid: Nullable<Liquid> = new Liquid();
+ private _inactiveAreaOpacity = 1;
+
constructor(oKey: string, documentSkeleton?: DocumentSkeleton, config?: IDocumentsConfig) {
super(oKey, documentSkeleton, config);
@@ -286,6 +397,14 @@ export class Documents extends DocComponent {
return this;
}
+ /** Editor-only emphasis; standalone and export renderers retain full document colors. */
+ setInactiveAreaOpacity(opacity: number): void {
+ if (this._inactiveAreaOpacity !== opacity) {
+ this._inactiveAreaOpacity = opacity;
+ this.makeDirty(true);
+ }
+ }
+
protected override _draw(ctx: UniverRenderingContext, bounds?: IViewportInfo) {
this.draw(ctx, bounds);
}
@@ -301,8 +420,18 @@ export class Documents extends DocComponent {
const { pages, skeHeaders, skeFooters } = skeletonData;
const isContinuousLayout = this.getSkeleton()?.getViewModel?.().getDataModel().documentStyle.documentFlavor === DocumentFlavor.MODERN;
+ const isTraditionalLayout = this._getDocumentFlavor() === DocumentFlavor.TRADITIONAL;
+ const dataModel = this.getSkeleton()?.getViewModel?.().getDataModel();
+ const sectionBorders = new Map((dataModel?.getBody?.()?.sectionBreaks ?? [])
+ .map((section) => [section.sectionId, section.pageBorders]));
+ const renderedSections = new Set<string | undefined>();
+ const inactiveAreaOpacity = isTraditionalLayout ? this._inactiveAreaOpacity : 1;
+ const isEditBody = inactiveAreaOpacity === 1 || this.getSkeleton()?.getViewModel().getEditArea() === DocumentEditArea.BODY;
+ const bodyOpacity = isEditBody ? 1 : inactiveAreaOpacity;
+ // Header/footer emphasis is painted over the completed content, so
+ // overlapping opaque objects retain their original occlusion.
+ const headerFooterOpacity = 1;
const parentScale = this.getParentScale();
- // const scale = getScale(parentScale);
const extensions = this.getExtensionsByOrder();
for (const extension of extensions) {
@@ -320,8 +449,10 @@ export class Documents extends DocComponent {
for (let i = 0, len = pages.length; i < len; i++) {
const page = pages[i];
+ const firstPageInSection = !renderedSections.has(page.sectionId);
+ renderedSections.add(page.sectionId);
+ const pageBorders = (page.sectionId == null ? undefined : sectionBorders.get(page.sectionId)) ?? dataModel?.documentStyle.pageBorders;
const {
- sections,
marginTop: pagePaddingTop = 0,
marginBottom: pagePaddingBottom = 0,
marginLeft: pagePaddingLeft = 0,
@@ -340,11 +471,8 @@ export class Documents extends DocComponent {
horizontalAlign = HorizontalAlign.LEFT, // Do not make changes, otherwise the document will not render.
centerAngle: centerAngleDeg = 0,
vertexAngle: vertexAngleDeg = 0,
- wrapStrategy = WrapStrategy.UNSPECIFIED,
cellValueType,
- // isRotateNonEastAsian = BooleanNumber.FALSE,
} = renderConfig;
- const isVertical = vertexAngleDeg === VERTICAL_ROTATE_ANGLE && centerAngleDeg === VERTICAL_ROTATE_ANGLE;
const horizontalOffsetNoAngle = this._horizontalHandler(
actualWidth,
pagePaddingLeft,
@@ -379,7 +507,21 @@ export class Documents extends DocComponent {
continue;
}
+ const clipsToPhysicalPage = isTraditionalLayout && Number.isFinite(pageWidth) && Number.isFinite(page.pageHeight);
+ if (clipsToPhysicalPage) {
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(this._drawLiquid.x, this._drawLiquid.y, pageWidth, page.pageHeight);
+ ctx.clip();
+ }
+
+ if (clipsToPhysicalPage && pageBorders?.zOrder === 'back') {
+ drawPageBorders(ctx, page, pageBorders, pageLeft, pageTop, firstPageInSection);
+ }
+
if (skeTables.size > 0) {
+ ctx.save();
+ ctx.globalAlpha *= bodyOpacity;
this._drawTable(
ctx,
page,
@@ -394,6 +536,7 @@ export class Documents extends DocComponent {
renderConfig,
parentScale
);
+ ctx.restore();
}
const headerSkeletonPage = skeHeaders.get(headerId)?.get(pageWidth);
@@ -418,251 +561,32 @@ export class Documents extends DocComponent {
parentScale,
page,
true,
- pages.length
+ pages.length,
+ undefined,
+ headerFooterOpacity
);
}
+ ctx.save();
+ ctx.globalAlpha *= bodyOpacity;
this._startRotation(ctx, finalAngle);
- for (const [sectionIndex, section] of sections.entries()) {
- const { columns } = section;
- const nextSectionTop = sections
- .slice(sectionIndex + 1)
- .find((candidate) => candidate.top > section.top)
- ?.top;
- const separatorHeight = Math.max(
- 0,
- (nextSectionTop ?? page.pageHeight - pagePaddingTop - pagePaddingBottom) - section.top
- );
-
- this._drawLiquid.translateSave();
- this._drawLiquid.translateSection(section);
- drawSectionColumnSeparators(
- ctx,
- section,
- separatorHeight,
- alignOffsetNoAngle.x,
- alignOffsetNoAngle.y
- );
-
- for (const column of columns) {
- const { lines, width: columnWidth } = column;
-
- this._drawLiquid.translateSave();
- this._drawLiquid.translateColumn(column);
-
- const linesCount = lines.length;
- const visibleLineRange = isContinuousLayout && bounds != null
- ? getVisibleContinuousLineRange(
- lines,
- bounds.viewBound.top,
- bounds.viewBound.bottom,
- pageTop + pagePaddingTop + section.top
- )
- : { start: 0, end: linesCount };
-
- let alignOffset = alignOffsetNoAngle;
- let rotateTranslateXListApply = null;
-
- let rotatedHeightStore = 0;
-
- if (vertexAngle !== 0) {
- const {
- rotateTranslateXList,
- rotatedHeight,
- rotatedWidth,
- fixOffsetX,
- fixOffsetY,
- rotateTranslateY,
- } = getRotateOffsetAndFarthestHypotenuse(lines, columnWidth, vertexAngle);
-
- rotatedHeightStore = rotatedHeight;
-
- let exceedWidthFix = rotatedWidth;
- if (rotatedHeight > this.height && wrapStrategy !== WrapStrategy.WRAP) {
- if (wrapStrategy === WrapStrategy.OVERFLOW || vertexAngle > 0) {
- exceedWidthFix = this.height / Math.tan(Math.abs(vertexAngle));
- }
- }
-
- const horizontalOffset = this._horizontalHandler(
- exceedWidthFix,
- pagePaddingLeft,
- pagePaddingRight,
- horizontalAlign,
- vertexAngleDeg,
- centerAngleDeg
- );
-
- const verticalOffset = this._verticalHandler(
- rotatedHeight,
- pagePaddingTop,
- pagePaddingBottom,
- verticalAlign
- );
-
- let exceedHeightFix = verticalOffset - fixOffsetY;
- if (rotatedHeight > this.height && !isVertical) {
- if (vertexAngle < 0) {
- exceedHeightFix = this.height - (rotatedHeight + fixOffsetY);
- } else {
- exceedHeightFix = -fixOffsetY;
- }
- }
- alignOffset = Vector2.create(horizontalOffset + fixOffsetX, exceedHeightFix);
-
- this._drawLiquid.translate(0, -rotateTranslateY);
-
- rotateTranslateXListApply = rotateTranslateXList;
- } else if (
- wrapStrategy === WrapStrategy.WRAP
- // Use fix: https://github.com/dream-num/univer-pro/issues/734
- && (horizontalAlign !== HorizontalAlign.UNSPECIFIED || cellValueType !== CellValueType.NUMBER)
- ) {
- // @Jocs, Why reset alignOffset.x? When you know the reason, add a description
- alignOffset.x = pagePaddingLeft;
- }
-
- for (let i = visibleLineRange.start; i < visibleLineRange.end; i++) {
- const line = lines[i];
- const { divides, asc = 0, type, lineHeight = 0 } = line;
-
- if (
- !isContinuousLayout &&
- page.pageHeight === Number.POSITIVE_INFINITY &&
- bounds != null
- ) {
- const lineTop = pageTop + pagePaddingTop + section.top + line.top +
- (line.marginTop ?? 0) + (line.paddingTop ?? 0);
- const lineBottom = lineTop + lineHeight;
- const { top, bottom } = bounds.viewBound;
- if (
- lineBottom < top - CONTINUOUS_LAYOUT_LINE_OVERSCAN ||
- lineTop > bottom + CONTINUOUS_LAYOUT_LINE_OVERSCAN
- ) {
- continue;
- }
- }
-
- const maxLineAsc = asc;
-
- const maxLineAscSin = maxLineAsc * Math.sin(centerAngle);
- const maxLineAscCos = maxLineAsc * Math.cos(centerAngle);
-
- if (type === LineType.BLOCK) {
- for (const extension of extensions) {
- if (extension.type === DOCS_EXTENSION_TYPE.LINE) {
- extension.extensionOffset = {
- alignOffset,
- renderConfig,
- };
- extension.draw(ctx, parentScale, line);
- }
- }
- } else {
- // let { x, y } = this._drawLiquid;
- // x += horizontalOffsetNoAngle;
- // y += verticalOffsetNoAngle + line.top;
- // ctx.save();
- // ctx.strokeStyle = 'rgb(245, 90, 34)';
- // ctx.moveTo(x, y);
- // ctx.lineTo(line.width ?? 0 + x, y);
- // ctx.lineTo(line.width ?? 0 + x, lineHeight + y);
- // ctx.lineTo(x, lineHeight + y);
- // ctx.lineTo(x, y);
- // ctx.stroke();
- // ctx.restore();
-
- this._drawLiquid.translateSave();
- this._drawLiquid.translateLine(line, true, true);
-
- rotateTranslateXListApply && this._drawLiquid.translate(rotateTranslateXListApply[i]); // x axis offset
- this._drawLineBackground(ctx, page, line, column.width);
-
- const divideLength = divides.length;
-
- for (let i = 0; i < divideLength; i++) {
- const divide = divides[i];
- const { glyphGroup } = divide;
-
- this._drawLiquid.translateSave();
- this._drawLiquid.translateDivide(divide, isVertical && wrapStrategy === WrapStrategy.WRAP, verticalAlign, rotatedHeightStore);
-
- this._drawGlyphGroupBackgrounds(
- ctx,
- parentScale,
- glyphGroup,
- lineHeight,
- alignOffset,
- centerAngle,
- vertexAngle,
- backgroundExtension,
- preTextBackgroundExtensions
- );
-
- // Draw text\border\lines etc.
- for (const glyph of glyphGroup) {
- if (!glyph.content || glyph.content.length === 0) {
- continue;
- }
-
- const { width: spanWidth, left: spanLeft, xOffset } = glyph;
-
- const { x: translateX, y: translateY } = this._drawLiquid;
-
- const originTranslate = Vector2.create(translateX, translateY);
-
- const centerPoint = Vector2.create(spanWidth / 2, lineHeight / 2);
-
- const spanStartPoint = calculateRectRotate(
- originTranslate.addByPoint(spanLeft + xOffset, 0),
- centerPoint,
- centerAngle,
- vertexAngle,
- alignOffset
- );
-
- const spanPointWithFont = calculateRectRotate(
- originTranslate.addByPoint(
- spanLeft + maxLineAscSin + xOffset,
- maxLineAscCos
- ),
- centerPoint,
- centerAngle,
- vertexAngle,
- alignOffset
- );
-
- const extensionOffset: IExtensionConfig = {
- originTranslate,
- spanStartPoint,
- spanPointWithFont,
- centerPoint,
- alignOffset,
- renderConfig,
- };
-
- for (const extension of glyphExtensionsExcludeBackground) {
- extension.extensionOffset = extensionOffset;
- extension.draw(ctx, parentScale, glyph, [], {
- viewBound: bounds?.viewBound,
- } as IDrawInfo);
- }
- }
-
- this._drawLiquid.translateRestore();
- }
-
- this._drawParagraphBorders(ctx, page, line, column.width);
- this._drawLiquid.translateRestore();
- }
- }
-
- this._drawLiquid.translateRestore();
- }
-
- this._drawLiquid.translateRestore();
- }
+ this._drawBodySections(
+ ctx,
+ page,
+ extensions,
+ backgroundExtension,
+ preTextBackgroundExtensions,
+ glyphExtensionsExcludeBackground,
+ alignOffsetNoAngle,
+ centerAngle,
+ vertexAngle,
+ renderConfig,
+ parentScale,
+ isContinuousLayout,
+ pageTop,
+ bounds
+ );
if (skeColumnGroups.size > 0) {
this._drawColumnGroups(
@@ -682,6 +606,7 @@ export class Documents extends DocComponent {
}
this._resetRotation(ctx, finalAngle);
+ ctx.restore();
for (const note of [...page.noteDecorations ?? [], ...page.notes ?? []]) {
this._drawHeaderFooter(
@@ -727,10 +652,19 @@ export class Documents extends DocComponent {
parentScale,
page,
false,
- pages.length
+ pages.length,
+ undefined,
+ headerFooterOpacity
);
}
+ if (clipsToPhysicalPage) {
+ if (pageBorders?.zOrder !== 'back') {
+ drawPageBorders(ctx, page, pageBorders, pageLeft, pageTop, firstPageInSection);
+ }
+ ctx.restore();
+ }
+
this._pageRender$.next({
page,
pageLeft,
@@ -749,6 +683,295 @@ export class Documents extends DocComponent {
}
}
+ private _drawBodySections(
+ ctx: UniverRenderingContext,
+ page: IDocumentSkeletonPage,
+ extensions: ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>[],
+ backgroundExtension: Nullable<ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>>,
+ preTextBackgroundExtensions: ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>[],
+ glyphExtensionsExcludeBackground: ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>[],
+ alignOffsetNoAngle: Vector2,
+ centerAngle: number,
+ vertexAngle: number,
+ renderConfig: IDocumentRenderConfig,
+ parentScale: IScale,
+ isContinuousLayout: boolean,
+ pageTop: number,
+ bounds?: IViewportInfo
+ ): void {
+ if (this._drawLiquid == null) {
+ return;
+ }
+ const { sections, marginTop: pagePaddingTop = 0, marginBottom: pagePaddingBottom = 0 } = page;
+ const { verticalAlign = VerticalAlign.TOP, wrapStrategy = WrapStrategy.UNSPECIFIED } = renderConfig;
+ const isVertical = renderConfig.vertexAngle === VERTICAL_ROTATE_ANGLE && renderConfig.centerAngle === VERTICAL_ROTATE_ANGLE;
+
+ for (const [sectionIndex, section] of sections.entries()) {
+ const { columns } = section;
+ const nextSectionTop = sections
+ .slice(sectionIndex + 1)
+ .find((candidate) => candidate.top > section.top)
+ ?.top;
+ const separatorHeight = Math.max(
+ 0,
+ (nextSectionTop ?? page.pageHeight - pagePaddingTop - pagePaddingBottom) - section.top
+ );
+
+ this._drawLiquid.translateSave();
+ this._drawLiquid.translateSection(section);
+ drawSectionColumnSeparators(
+ ctx,
+ section,
+ separatorHeight,
+ alignOffsetNoAngle.x,
+ alignOffsetNoAngle.y
+ );
+
+ for (const column of columns) {
+ const { lines } = column;
+
+ this._drawLiquid.translateSave();
+ this._drawLiquid.translateColumn(column);
+
+ const linesCount = lines.length;
+ const visibleLineRange = isContinuousLayout && bounds != null
+ ? getVisibleContinuousLineRange(
+ lines,
+ bounds.viewBound.top,
+ bounds.viewBound.bottom,
+ pageTop + pagePaddingTop + section.top
+ )
+ : { start: 0, end: linesCount };
+
+ const {
+ alignOffset,
+ rotatedHeight: rotatedHeightStore,
+ rotateTranslateXList: rotateTranslateXListApply,
+ rotateTranslateY,
+ } = this._getColumnDrawLayout(page, column, alignOffsetNoAngle);
+ if (vertexAngle !== 0) {
+ this._drawLiquid.translate(0, -rotateTranslateY);
+ }
+
+ for (let i = visibleLineRange.start; i < visibleLineRange.end; i++) {
+ const line = lines[i];
+ const { divides, type, lineHeight = 0 } = line;
+
+ if (
+ !isContinuousLayout &&
+ page.pageHeight === Number.POSITIVE_INFINITY &&
+ bounds != null
+ ) {
+ const lineTop = pageTop + pagePaddingTop + section.top + line.top +
+ (line.marginTop ?? 0) + (line.paddingTop ?? 0);
+ const lineBottom = lineTop + lineHeight;
+ const { top, bottom } = bounds.viewBound;
+ if (
+ lineBottom < top - CONTINUOUS_LAYOUT_LINE_OVERSCAN ||
+ lineTop > bottom + CONTINUOUS_LAYOUT_LINE_OVERSCAN
+ ) {
+ continue;
+ }
+ }
+
+ if (type === LineType.BLOCK) {
+ for (const extension of extensions) {
+ if (extension.type === DOCS_EXTENSION_TYPE.LINE) {
+ extension.extensionOffset = {
+ alignOffset,
+ renderConfig,
+ };
+ extension.draw(ctx, parentScale, line);
+ }
+ }
+ } else {
+ this._drawLiquid.translateSave();
+ this._drawLiquid.translateLine(line, true, true);
+
+ rotateTranslateXListApply && this._drawLiquid.translate(rotateTranslateXListApply[i]); // x axis offset
+ this._drawLineBackground(ctx, page, line, column.width);
+
+ const divideLength = divides.length;
+
+ for (let i = 0; i < divideLength; i++) {
+ const divide = divides[i];
+ const { glyphGroup } = divide;
+
+ this._drawLiquid.translateSave();
+ this._drawLiquid.translateDivide(divide, isVertical && wrapStrategy === WrapStrategy.WRAP, verticalAlign, rotatedHeightStore);
+
+ this._drawGlyphGroupBackgrounds(
+ ctx,
+ parentScale,
+ glyphGroup,
+ lineHeight,
+ alignOffset,
+ centerAngle,
+ vertexAngle,
+ backgroundExtension,
+ preTextBackgroundExtensions
+ );
+
+ // Draw text\border\lines etc.
+ this._drawGlyphGroup(
+ ctx,
+ parentScale,
+ glyphGroup,
+ line,
+ alignOffset,
+ centerAngle,
+ vertexAngle,
+ renderConfig,
+ glyphExtensionsExcludeBackground,
+ { viewBound: bounds?.viewBound } as IDrawInfo
+ );
+
+ this._drawLiquid.translateRestore();
+ }
+
+ this._drawParagraphBorders(ctx, page, line, column.width);
+ this._drawLiquid.translateRestore();
+ }
+ }
+
+ this._drawLiquid.translateRestore();
+ }
+
+ this._drawLiquid.translateRestore();
+ }
+ }
+
+ private _getColumnDrawLayout(
+ page: IDocumentSkeletonPage,
+ column: IDocumentSkeletonColumn,
+ alignOffset: Vector2
+ ): { alignOffset: Vector2; rotatedHeight: number; rotateTranslateXList: number[] | null; rotateTranslateY: number } {
+ const {
+ marginTop = 0,
+ marginBottom = 0,
+ marginLeft = 0,
+ marginRight = 0,
+ renderConfig = {},
+ } = page;
+ const {
+ verticalAlign = VerticalAlign.TOP,
+ horizontalAlign = HorizontalAlign.LEFT,
+ centerAngle: centerAngleDeg = 0,
+ vertexAngle: vertexAngleDeg = 0,
+ wrapStrategy = WrapStrategy.UNSPECIFIED,
+ cellValueType,
+ } = renderConfig;
+ const vertexAngle = degToRad(vertexAngleDeg);
+ if (vertexAngle === 0) {
+ if (wrapStrategy === WrapStrategy.WRAP &&
+ (horizontalAlign !== HorizontalAlign.UNSPECIFIED || cellValueType !== CellValueType.NUMBER)) {
+ // Wrapped text retains the cell padding rather than block alignment.
+ alignOffset.x = marginLeft;
+ }
+ return { alignOffset, rotatedHeight: 0, rotateTranslateXList: null, rotateTranslateY: 0 };
+ }
+
+ const {
+ rotateTranslateXList,
+ rotatedHeight,
+ rotatedWidth,
+ fixOffsetX,
+ fixOffsetY,
+ rotateTranslateY,
+ } = getRotateOffsetAndFarthestHypotenuse(column.lines, column.width, vertexAngle);
+ let exceedWidthFix = rotatedWidth;
+ if (rotatedHeight > this.height && wrapStrategy !== WrapStrategy.WRAP) {
+ if (wrapStrategy === WrapStrategy.OVERFLOW || vertexAngle > 0) {
+ exceedWidthFix = this.height / Math.tan(Math.abs(vertexAngle));
+ }
+ }
+ const horizontalOffset = this._horizontalHandler(
+ exceedWidthFix,
+ marginLeft,
+ marginRight,
+ horizontalAlign,
+ vertexAngleDeg,
+ centerAngleDeg
+ );
+ const verticalOffset = this._verticalHandler(rotatedHeight, marginTop, marginBottom, verticalAlign);
+ const isVertical = vertexAngleDeg === VERTICAL_ROTATE_ANGLE && centerAngleDeg === VERTICAL_ROTATE_ANGLE;
+ let exceedHeightFix = verticalOffset - fixOffsetY;
+ if (rotatedHeight > this.height && !isVertical) {
+ if (vertexAngle < 0) {
+ exceedHeightFix = this.height - (rotatedHeight + fixOffsetY);
+ } else {
+ exceedHeightFix = -fixOffsetY;
+ }
+ }
+ return {
+ alignOffset: Vector2.create(horizontalOffset + fixOffsetX, exceedHeightFix),
+ rotatedHeight,
+ rotateTranslateXList,
+ rotateTranslateY,
+ };
+ }
+
+ private _drawGlyphGroup(
+ ctx: UniverRenderingContext,
+ parentScale: IScale,
+ glyphGroup: IDocumentSkeletonGlyph[],
+ line: IDocumentSkeletonLine,
+ alignOffset: Vector2,
+ centerAngle: number,
+ vertexAngle: number,
+ renderConfig: IDocumentRenderConfig,
+ extensions: ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>[],
+ drawInfo?: IDrawInfo
+ ): void {
+ if (this._drawLiquid == null) {
+ return;
+ }
+ const { asc = 0, lineHeight = 0 } = line;
+ const maxLineAscSin = asc * Math.sin(centerAngle);
+ const maxLineAscCos = asc * Math.cos(centerAngle);
+
+ for (const glyph of glyphGroup) {
+ if (!glyph.content) {
+ continue;
+ }
+ const { width: spanWidth, left: spanLeft, xOffset } = glyph;
+ const { x, y } = this._drawLiquid;
+ const originTranslate = Vector2.create(x, y);
+ const centerPoint = Vector2.create(spanWidth / 2, lineHeight / 2);
+ const spanStartPoint = calculateRectRotate(
+ originTranslate.addByPoint(spanLeft + xOffset, 0),
+ centerPoint,
+ centerAngle,
+ vertexAngle,
+ alignOffset
+ );
+ const spanPointWithFont = calculateRectRotate(
+ originTranslate.addByPoint(spanLeft + maxLineAscSin + xOffset, maxLineAscCos),
+ centerPoint,
+ centerAngle,
+ vertexAngle,
+ alignOffset
+ );
+ const extensionOffset: IExtensionConfig = {
+ originTranslate,
+ spanStartPoint,
+ spanPointWithFont,
+ centerPoint,
+ alignOffset,
+ renderConfig,
+ };
+
+ for (const extension of extensions) {
+ extension.extensionOffset = extensionOffset;
+ if (drawInfo) {
+ extension.draw(ctx, parentScale, glyph, [], { ...drawInfo });
+ } else {
+ extension.draw(ctx, parentScale, glyph);
+ }
+ }
+ }
+ }
+
private _drawTable(
ctx: UniverRenderingContext,
page: IDocumentSkeletonPage,
@@ -761,7 +984,8 @@ export class Documents extends DocComponent {
centerAngle: number,
vertexAngle: number,
renderConfig: IDocumentRenderConfig,
- parentScale: IScale
+ parentScale: IScale,
+ fieldContext?: IHeaderFooterFieldContext
) {
const drawLiquid = this._drawLiquid;
if (drawLiquid == null) {
@@ -821,7 +1045,8 @@ export class Documents extends DocComponent {
centerAngle,
vertexAngle,
renderConfig,
- parentScale
+ parentScale,
+ fieldContext
);
drawLiquid.translateRestore();
@@ -949,15 +1174,17 @@ export class Documents extends DocComponent {
return viewport;
}
- const { pageWidth, marginLeft = 0, marginRight = 0 } = page;
+ const { pageWidth } = page;
if (!Number.isFinite(pageWidth)) {
return null;
}
- const compatibilityPolicy = this._getDocumentCompatibilityPolicy();
- const viewportWidth = shouldAllowImportedTableMarginOverflow(compatibilityPolicy, tableSkeleton.tableSource)
- ? Math.max(0, pageWidth - Math.max(0, marginLeft + tableSkeleton.left))
- : Math.max(0, pageWidth - marginLeft - marginRight - tableSkeleton.left);
+ const viewportWidth = getDocsTableLayoutViewportWidth(
+ page,
+ tableSkeleton.left,
+ tableSkeleton.tableSource,
+ this._getDocumentFlavor()
+ );
if (viewportWidth <= 0 || tableSkeleton.width <= viewportWidth) {
return null;
}
@@ -983,7 +1210,7 @@ export class Documents extends DocComponent {
return dataModel?.getUnitId?.() ?? this.oKey;
}
- private _getDocumentCompatibilityPolicy() {
+ private _getDocumentFlavor() {
const skeleton = this.getSkeleton() as {
getViewModel?: () => {
getSnapshot?: () => {
@@ -995,7 +1222,7 @@ export class Documents extends DocComponent {
} | undefined;
const documentFlavor = skeleton?.getViewModel?.()?.getSnapshot?.()?.documentStyle?.documentFlavor;
- return getDocumentCompatibilityPolicy(documentFlavor);
+ return documentFlavor;
}
private _drawLineBackground(
@@ -1054,13 +1281,25 @@ export class Documents extends DocComponent {
y -= line.paddingTop;
y += marginTop + top;
- const startX = x + (line.paragraphPaddingLeft ?? 0) - (line.borderLeft?.padding ?? 0);
- const endX = x + width - (line.paragraphPaddingRight ?? 0) + (line.borderRight?.padding ?? 0);
- const startY = y + line.marginTop - (line.borderTop?.padding ?? 0);
- const endY = y + line.lineHeight - line.marginBottom + (bottomBorder?.padding ?? 0);
+ // Word adds 1.5pt of horizontal clearance, even for top/bottom-only paragraph borders.
+ // Border spacing reaches the inner edge; Canvas strokes are centered on their path.
+ const traditional = this._getDocumentFlavor() === DocumentFlavor.TRADITIONAL;
+ const leftWidth = line.borderLeft ? Math.max(0, line.borderLeft.width ?? 1) : 0;
+ const rightWidth = line.borderRight ? Math.max(0, line.borderRight.width ?? 1) : 0;
+ const leftOutset = traditional ? 2 + leftWidth / 2 : 0;
+ const rightOutset = traditional ? 2 + rightWidth / 2 : 0;
+ const startX = x + (line.paragraphPaddingLeft ?? 0) - (line.borderLeft?.padding ?? 0) - leftOutset;
+ const endX = x + width - (line.paragraphPaddingRight ?? 0) + (line.borderRight?.padding ?? 0) + rightOutset;
+ const startY = y + line.marginTop + (line.borderTopSpace ?? 0) - (line.borderTop?.padding ?? 0);
+ const endY = y + line.lineHeight - line.marginBottom - (line.borderBottomSpace ?? 0) + (bottomBorder?.padding ?? 0);
const drawBorder = (border: IParagraphBorder, type: BORDER_TYPE) => {
+ const lineWidth = border.width ?? 1;
+ // Explicit zero widths cancel inherited borders; Canvas ignores a zero lineWidth.
+ if (lineWidth <= 0) {
+ return;
+ }
ctx.save();
- ctx.setLineWidthByPrecision(Math.max(0, border.width ?? 1));
+ ctx.setLineWidthByPrecision(lineWidth);
ctx.strokeStyle = border.color.rgb === 'auto'
? COLOR_BLACK_RGB
: getColorStyleForCanvas(border.color) ?? COLOR_BLACK_RGB;
@@ -1165,7 +1404,8 @@ export class Documents extends DocComponent {
centerAngle: number,
vertexAngle: number,
renderConfig: IDocumentRenderConfig,
- parentScale: IScale
+ parentScale: IScale,
+ fieldContext?: IHeaderFooterFieldContext
) {
if (this._drawLiquid == null) {
return;
@@ -1184,7 +1424,8 @@ export class Documents extends DocComponent {
centerAngle,
vertexAngle,
renderConfig,
- parentScale
+ parentScale,
+ fieldContext
);
}
@@ -1200,62 +1441,80 @@ export class Documents extends DocComponent {
centerAngle: number,
vertexAngle: number,
renderConfig: IDocumentRenderConfig,
- parentScale: IScale
+ parentScale: IScale,
+ fieldContext?: IHeaderFooterFieldContext
) {
if (this._drawLiquid == null) {
return;
}
const { sections, marginLeft, marginTop, skeTables } = nestedPage;
- const alignOffset = Vector2.create(alignOffsetNoAngle.x + marginLeft, alignOffsetNoAngle.y + marginTop);
-
+ let alignOffset = Vector2.create(alignOffsetNoAngle.x + marginLeft, alignOffsetNoAngle.y + marginTop);
ctx.save();
+ const drawLiquid = this._drawLiquid;
const { x, y } = this._drawLiquid;
const { pageWidth, pageHeight } = nestedPage;
- const clipOrigin = getNestedPageClipOrigin(parentPage, nestedPage, { x, y }, alignOffset);
+ let clipOffset = Vector2.create(parentPage.marginLeft, parentPage.marginTop);
+ if (isColumnGroupNestedPage(nestedPage)) {
+ clipOffset = alignOffset;
+ } else if (parentPage.type === DocumentSkeletonPageType.CELL) {
+ clipOffset = alignOffsetNoAngle;
+ }
+ const clipOrigin = { x: x + clipOffset.x, y: y + clipOffset.y };
+ const isVerticalCell = nestedPage.cellTextDirection === 'tbRlV';
+ if (isVerticalCell) {
+ this._drawLiquid.translateSave();
+ this._drawLiquid.translate(-x, -y);
+ alignOffset = Vector2.create(clipOrigin.x + pageWidth - marginTop, clipOrigin.y + marginLeft);
+ centerAngle = Math.PI / 2;
+ vertexAngle = Math.PI / 2;
+ renderConfig = { ...renderConfig, centerAngle: 90, vertexAngle: 90 };
+ }
+
+ const drawNestedTables = (tables: Map<string, IDocumentSkeletonTable>): void => {
+ drawLiquid.translateSave();
+ drawLiquid.translate(alignOffset.x, alignOffset.y);
+ this._drawTable(
+ ctx,
+ {
+ ...nestedPage,
+ marginLeft: 0,
+ marginTop: 0,
+ },
+ tables,
+ extensions,
+ backgroundExtension,
+ preTextBackgroundExtensions,
+ glyphExtensionsExcludeBackground,
+ Vector2.create(0, 0),
+ centerAngle,
+ vertexAngle,
+ renderConfig,
+ parentScale,
+ fieldContext
+ );
+ drawLiquid.translateRestore();
+ };
+ // Floating tables can extend past their anchor cell into a neighbouring
+ // gutter. Preserve ancestor clips without applying that cell's text clip.
+ const floatingTables = new Map([...skeTables].filter(([, table]) =>
+ nestedPage.type === DocumentSkeletonPageType.CELL && !isVerticalCell &&
+ this._getDocumentFlavor() === DocumentFlavor.TRADITIONAL &&
+ table.tableSource.textWrap === TableTextWrapType.WRAP
+ ));
+ if (floatingTables.size > 0) {
+ drawNestedTables(floatingTables);
+ }
+
ctx.beginPath();
ctx.rectByPrecision(clipOrigin.x, clipOrigin.y, pageWidth, pageHeight);
ctx.closePath();
ctx.clip();
- if (skeTables.size > 0) {
- if (isColumnGroupNestedPage(nestedPage)) {
- this._drawLiquid.translateSave();
- this._drawLiquid.translate(alignOffset.x, alignOffset.y);
- this._drawTable(
- ctx,
- {
- ...nestedPage,
- marginLeft: 0,
- marginTop: 0,
- },
- skeTables,
- extensions,
- backgroundExtension,
- preTextBackgroundExtensions,
- glyphExtensionsExcludeBackground,
- Vector2.create(0, 0),
- centerAngle,
- vertexAngle,
- renderConfig,
- parentScale
- );
- this._drawLiquid.translateRestore();
- } else {
- this._drawTable(
- ctx,
- nestedPage,
- skeTables,
- extensions,
- backgroundExtension,
- preTextBackgroundExtensions,
- glyphExtensionsExcludeBackground,
- alignOffset,
- centerAngle,
- vertexAngle,
- renderConfig,
- parentScale
- );
- }
+ const clippedTables = floatingTables.size > 0
+ ? new Map([...skeTables].filter(([id]) => !floatingTables.has(id)))
+ : skeTables;
+ if (clippedTables.size > 0) {
+ drawNestedTables(clippedTables);
}
for (const section of sections) {
@@ -1274,12 +1533,7 @@ export class Documents extends DocComponent {
for (let i = 0; i < linesCount; i++) {
const line = lines[i];
- const { divides, asc = 0, type, lineHeight = 0 } = line;
-
- const maxLineAsc = asc;
-
- const maxLineAscSin = maxLineAsc * Math.sin(centerAngle);
- const maxLineAscCos = maxLineAsc * Math.cos(centerAngle);
+ const { divides, type, lineHeight = 0 } = line;
if (type === LineType.BLOCK) {
for (const extension of extensions) {
@@ -1307,7 +1561,9 @@ export class Documents extends DocComponent {
for (let i = 0; i < divideLength; i++) {
const divide = divides[i];
- const { glyphGroup } = divide;
+ const glyphGroup = fieldContext
+ ? resolveHeaderFooterFieldGlyphGroup(divide, fieldContext)
+ : divide.glyphGroup;
this._drawLiquid.translateSave();
this._drawLiquid.translateDivide(divide);
@@ -1324,53 +1580,17 @@ export class Documents extends DocComponent {
preTextBackgroundExtensions
);
- // Draw text\border\lines etc.
- for (const glyph of glyphGroup) {
- if (!glyph.content || glyph.content.length === 0) {
- continue;
- }
-
- const { width: spanWidth, left: spanLeft, xOffset } = glyph;
-
- const { x: translateX, y: translateY } = this._drawLiquid;
-
- const originTranslate = Vector2.create(translateX, translateY);
-
- const centerPoint = Vector2.create(spanWidth / 2, lineHeight / 2);
-
- const spanStartPoint = calculateRectRotate(
- originTranslate.addByPoint(spanLeft + xOffset, 0),
- centerPoint,
- centerAngle,
- vertexAngle,
- alignOffset
- );
-
- const spanPointWithFont = calculateRectRotate(
- originTranslate.addByPoint(
- spanLeft + maxLineAscSin + xOffset,
- maxLineAscCos
- ),
- centerPoint,
- centerAngle,
- vertexAngle,
- alignOffset
- );
-
- const extensionOffset: IExtensionConfig = {
- originTranslate,
- spanStartPoint,
- spanPointWithFont,
- centerPoint,
- alignOffset,
- renderConfig,
- };
-
- for (const extension of glyphExtensionsExcludeBackground) {
- extension.extensionOffset = extensionOffset;
- extension.draw(ctx, parentScale, glyph);
- }
- }
+ this._drawGlyphGroup(
+ ctx,
+ parentScale,
+ glyphGroup,
+ line,
+ alignOffset,
+ centerAngle,
+ vertexAngle,
+ renderConfig,
+ glyphExtensionsExcludeBackground
+ );
this._drawLiquid.translateRestore();
}
@@ -1394,6 +1614,9 @@ export class Documents extends DocComponent {
this._drawLiquid.translateRestore();
}
+ if (isVerticalCell) {
+ this._drawLiquid.translateRestore();
+ }
ctx.restore();
}
@@ -1446,11 +1669,44 @@ export class Documents extends DocComponent {
const rightCellSource = this._getTableCellSource(rowSke, index + 1);
const bottomCellSource = tableSke ? this._getTableCellSource(tableSke.rows[rowIndex + 1], index) : undefined;
+ const bottom = cellSource.borderBottom;
+ const bottomBorder = this._getDocumentFlavor() === DocumentFlavor.TRADITIONAL && rowIndex === (tableSke?.rows.length ?? 1) - 1
+ ? bottom?.tableBottomBorder ?? bottom
+ : bottom;
this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderRight, rightCellSource?.borderLeft), BORDER_TYPE.RIGHT, position);
- this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderBottom, bottomCellSource?.borderTop), BORDER_TYPE.BOTTOM, position);
+ this._drawTableCellBorder(ctx, this._resolveTableCellBorder(bottomBorder, bottomCellSource?.borderTop), BORDER_TYPE.BOTTOM, position);
if (rowIndex <= 0) {
- this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderTop), BORDER_TYPE.TOP, position);
+ const top = cellSource.borderTop;
+ const border = this._getDocumentFlavor() === DocumentFlavor.TRADITIONAL ? top?.tableTopBorder ?? top : top;
+ this._drawTableCellBorder(ctx, this._resolveTableCellBorder(border), BORDER_TYPE.TOP, position);
+ } else if (tableSke) {
+ // The preceding row owns shared horizontal edges, but omitted grid
+ // columns can leave part of this cell's top without an owner.
+ let left = cell.left;
+ const right = cell.left + pageWidth;
+ const drawExposedTop = (end: number) => {
+ if (end > left) {
+ this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderTop), BORDER_TYPE.TOP, {
+ ...position,
+ startX: x + left - cell.left,
+ endX: x + end - cell.left,
+ });
+ }
+ };
+ const previous = tableSke.rows[rowIndex - 1];
+ for (const [column, above] of previous.cells.entries()) {
+ const source = previous.rowSource.tableCells[column];
+ if (source?.rowSpan === 0 || source?.columnSpan === 0) {
+ continue;
+ }
+ drawExposedTop(Math.min(right, above.left));
+ left = Math.max(left, above.left + above.pageWidth);
+ if (left >= right) {
+ break;
+ }
+ }
+ drawExposedTop(right);
}
if (index <= 0) {
@@ -1508,6 +1764,39 @@ export class Documents extends DocComponent {
ctx.setLineWidthByPrecision(lineWidth);
setDocsBorderDash(ctx, border.dashStyle);
ctx.strokeStyle = color;
+ if (this._getDocumentFlavor() === DocumentFlavor.TRADITIONAL) {
+ const { a, b, c, d, e, f } = ctx.getTransform();
+ if (b === 0 && c === 0 && a > 0 && d > 0) {
+ const horizontal = type === BORDER_TYPE.TOP || type === BORDER_TYPE.BOTTOM;
+ const scale = horizontal ? d : a;
+ const pixels = Math.max(1, Math.round(lineWidth * scale));
+ const offset = (pixels % 2) / 2;
+ // Snap ink edges in device space, including fractional viewport
+ // translation. Keep the document's border width and cell bounds intact.
+ const snapX = (x: number) => {
+ const inkOffset = horizontal ? offset : lineWidth * a / 2;
+ const centerOffset = horizontal ? offset : pixels / 2;
+ return (Math.round(x * a + e - inkOffset) + centerOffset - e) / a;
+ };
+ const snapY = (y: number) => {
+ const inkOffset = horizontal ? lineWidth * d / 2 : offset;
+ const centerOffset = horizontal ? pixels / 2 : offset;
+ return (Math.round(y * d + f - inkOffset) + centerOffset - f) / d;
+ };
+ const startX = snapX(type === BORDER_TYPE.RIGHT ? position.endX : position.startX);
+ const startY = snapY(type === BORDER_TYPE.BOTTOM ? position.endY : position.startY);
+ const endX = horizontal ? snapX(position.endX) : startX;
+ const endY = horizontal ? startY : snapY(position.endY);
+ ctx.lineWidth = pixels / scale;
+ ctx.beginPath();
+ ctx.moveTo(startX, startY);
+ ctx.lineTo(endX, endY);
+ ctx.stroke();
+ ctx.closePathByEnv();
+ ctx.restore();
+ return;
+ }
+ }
drawLineByBorderType(ctx, type, 0, position);
ctx.restore();
}
@@ -1527,7 +1816,8 @@ export class Documents extends DocComponent {
parentPage: IDocumentSkeletonPage,
isHeader = true,
pageCount = 1,
- customRangesOverride?: ICustomRange[]
+ customRangesOverride?: ICustomRange[],
+ opacity = 1
) {
if (this._drawLiquid == null) {
return;
@@ -1535,13 +1825,16 @@ export class Documents extends DocComponent {
const { sections, skeTables } = page;
const { y: originY } = this._drawLiquid;
const skeleton = this.getSkeleton();
- const customRanges = customRangesOverride ?? (typeof skeleton?.getViewModel === 'function'
+ const viewModel = typeof skeleton?.getViewModel === 'function'
? skeleton
.getViewModel()
.getSelfOrHeaderFooterViewModel(page.segmentId)
- .getBody()
- ?.customRanges ?? []
- : []);
+ : undefined;
+ const customRanges = customRangesOverride ?? viewModel?.getBody()?.customRanges ?? [];
+ const fieldContext = { customRanges, pageNumber: parentPage.pageNumber, pageCount, viewModel };
+
+ ctx.save();
+ ctx.globalAlpha *= opacity;
if (skeTables.size > 0) {
const tablePage = {
@@ -1563,7 +1856,8 @@ export class Documents extends DocComponent {
centerAngle,
vertexAngle,
renderConfig,
- parentScale
+ parentScale,
+ fieldContext
);
}
@@ -1585,12 +1879,7 @@ export class Documents extends DocComponent {
for (let i = 0; i < linesCount; i++) {
const line = lines[i];
- const { divides, asc = 0, type, lineHeight = 0 } = line;
-
- const maxLineAsc = asc;
-
- const maxLineAscSin = maxLineAsc * Math.sin(centerAngle);
- const maxLineAscCos = maxLineAsc * Math.cos(centerAngle);
+ const { divides, type, lineHeight = 0 } = line;
if (type === LineType.BLOCK) {
for (const extension of extensions) {
@@ -1619,8 +1908,7 @@ export class Documents extends DocComponent {
for (let i = 0; i < divideLength; i++) {
const divide = divides[i];
- const { glyphGroup } = divide;
- let glyphStartIndex = divide.st;
+ const glyphGroup = resolveHeaderFooterFieldGlyphGroup(divide, fieldContext);
this._drawLiquid.translateSave();
this._drawLiquid.translateDivide(divide);
@@ -1638,61 +1926,17 @@ export class Documents extends DocComponent {
);
// Draw text\border\lines etc.
- for (const glyph of glyphGroup) {
- const renderGlyph = resolveHeaderFooterFieldGlyph(
- glyph,
- glyphStartIndex,
- glyphStartIndex + glyph.count - 1,
- customRanges,
- parentPage.pageNumber,
- pageCount
- );
- glyphStartIndex += glyph.count;
- if (!renderGlyph.content || renderGlyph.content.length === 0) {
- continue;
- }
-
- const { width: spanWidth, left: spanLeft, xOffset } = renderGlyph;
-
- const { x: translateX, y: translateY } = this._drawLiquid;
-
- const originTranslate = Vector2.create(translateX, translateY);
-
- const centerPoint = Vector2.create(spanWidth / 2, lineHeight / 2);
-
- const spanStartPoint = calculateRectRotate(
- originTranslate.addByPoint(spanLeft + xOffset, 0),
- centerPoint,
- centerAngle,
- vertexAngle,
- alignOffset
- );
-
- const spanPointWithFont = calculateRectRotate(
- originTranslate.addByPoint(
- spanLeft + maxLineAscSin + xOffset,
- maxLineAscCos
- ),
- centerPoint,
- centerAngle,
- vertexAngle,
- alignOffset
- );
-
- const extensionOffset: IExtensionConfig = {
- originTranslate,
- spanStartPoint,
- spanPointWithFont,
- centerPoint,
- alignOffset,
- renderConfig,
- };
-
- for (const extension of glyphExtensionsExcludeBackground) {
- extension.extensionOffset = extensionOffset;
- extension.draw(ctx, parentScale, renderGlyph);
- }
- }
+ this._drawGlyphGroup(
+ ctx,
+ parentScale,
+ glyphGroup,
+ line,
+ alignOffset,
+ centerAngle,
+ vertexAngle,
+ renderConfig,
+ glyphExtensionsExcludeBackground
+ );
this._drawLiquid.translateRestore();
}
@@ -1708,6 +1952,7 @@ export class Documents extends DocComponent {
this._drawLiquid.translateRestore();
}
+ ctx.restore();
}
private _horizontalHandler(
@@ -1815,25 +2060,6 @@ function isColumnGroupNestedPage(page: IDocumentSkeletonPage): boolean {
return parent?.columnId != null && parent.parent?.columnGroupId != null;
}
-function getNestedPageClipOrigin(
- parentPage: IDocumentSkeletonPage,
- nestedPage: IDocumentSkeletonPage,
- drawOrigin: { x: number; y: number },
- alignOffset: Vector2
-): { x: number; y: number } {
- if (isColumnGroupNestedPage(nestedPage)) {
- return {
- x: drawOrigin.x + alignOffset.x,
- y: drawOrigin.y + alignOffset.y,
- };
- }
-
- return {
- x: drawOrigin.x + parentPage.marginLeft,
- y: drawOrigin.y + parentPage.marginTop,
- };
-}
-
function fillRectByPrecisionBounds(
ctx: UniverRenderingContext,
x: number,
diff --git a/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts b/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts
index 28411a4d5c..137b3f2775 100644
--- a/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts
+++ b/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts
@@ -22,6 +22,7 @@ import { BaselineOffset } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
import { COLOR_BLACK_RGB } from '../../../../basics/const';
import { GlyphType } from '../../../../basics/i-document-skeleton-cached';
+import { getFontStyleString } from '../../../../basics/tools';
import { Vector2 } from '../../../../basics/vector2';
import { CheckboxShape } from '../../../../shape/checkbox';
import { FontAndBaseLine } from '../font-and-base-line';
@@ -32,6 +33,7 @@ type MockRenderContext = UniverRenderingContext & {
fillText: ReturnType<typeof vi.fn>;
translate: ReturnType<typeof vi.fn>;
rotate: ReturnType<typeof vi.fn>;
+ scale: ReturnType<typeof vi.fn>;
createLinearGradient: ReturnType<typeof vi.fn>;
createRadialGradient: ReturnType<typeof vi.fn>;
createPattern: ReturnType<typeof vi.fn>;
@@ -76,6 +78,7 @@ function createContext(): MockRenderContext {
fillText: vi.fn(),
translate: vi.fn(),
rotate: vi.fn(),
+ scale: vi.fn(),
createLinearGradient: vi.fn(() => gradient),
createRadialGradient: vi.fn(() => gradient),
createPattern: vi.fn(() => ({ setTransform: vi.fn() })),
@@ -131,6 +134,61 @@ function createGlyph(content: string, overrides?: GlyphOverrides): IDocumentSkel
}
describe('docs font and baseline extension', () => {
+ it.each([90, 200])('paints character width scaling at the glyph origin without changing baseline: %s', (sa) => {
+ const extension = new FontAndBaseLine();
+ const context = createContext();
+ extension.extensionOffset = {
+ spanPointWithFont: Vector2.create(12, 20),
+ spanStartPoint: Vector2.create(10, 10),
+ centerPoint: Vector2.create(8, 8),
+ renderConfig: { vertexAngle: 0, centerAngle: 0 },
+ };
+ extension.draw(context, DEFAULT_SCALE, createGlyph('AB', { ts: { fs: 12, sa } }));
+ expect(context.translate).toHaveBeenCalledWith(12, 20);
+ expect(context.scale).toHaveBeenCalledWith(sa / 100, 1);
+ expect(context.fillText).toHaveBeenCalledWith('AB', 0, 0);
+ expect(context.save.mock.calls.length).toBe(context.restore.mock.calls.length);
+ });
+
+ it('uses the measured kerning mode and resets it for legacy text', () => {
+ const extension = new FontAndBaseLine();
+ const context = createContext();
+ context.fontKerning = 'auto';
+ extension.extensionOffset = {
+ spanPointWithFont: Vector2.create(12, 20),
+ spanStartPoint: Vector2.create(10, 10),
+ centerPoint: Vector2.create(8, 8),
+ renderConfig: { vertexAngle: 0, centerAngle: 0 },
+ };
+ for (const fontKerning of ['normal', 'none', undefined] as const) {
+ extension.draw(context, DEFAULT_SCALE, createGlyph('AV', {
+ fontStyle: { ...getFontStyleString({ fs: 12, ff: 'Arial' }), fontKerning },
+ }));
+ expect(context.fontKerning).toBe(fontKerning ?? 'auto');
+ }
+ });
+
+ it.each([0, 90])('paints tracked glyph segments using layout positions at %s degrees without native letterSpacing', (angle) => {
+ const extension = new FontAndBaseLine();
+ const context = createContext();
+ extension.extensionOffset = {
+ spanPointWithFont: Vector2.create(12, 20),
+ spanStartPoint: Vector2.create(10, 10),
+ centerPoint: Vector2.create(8, 8),
+ renderConfig: { vertexAngle: angle, centerAngle: angle },
+ };
+ const glyph = createGlyph('ก้ข', {
+ textSpacing: { content: 'ก้ข', segments: [{ content: 'ก้', left: 0 }, { content: 'ข', left: 7 }] },
+ });
+ extension.draw(context, DEFAULT_SCALE, glyph);
+ const x = angle === 0 ? 12 : 0;
+ const y = angle === 0 ? 20 : 0;
+ expect(context.fillText.mock.calls).toEqual([['ก้', x, y], ['ข', x + 7, y]]);
+ context.fillText.mockClear();
+ extension.draw(context, DEFAULT_SCALE, { ...glyph, content: 'Updated field' });
+ expect(context.fillText).toHaveBeenCalledWith('Updated field', x, y);
+ });
+
it('keeps existing document text colors unchanged', () => {
const screenExtension = new FontAndBaseLine();
const ScreenContext = createContext();
@@ -156,22 +214,40 @@ describe('docs font and baseline extension', () => {
}));
expect(ScreenContext.fillStyle).toBe('#000000');
+
+ for (const rgb of ['auto', '#auto']) {
+ ScreenContext.fillStyle = '#ffffff';
+ screenExtension.draw(ScreenContext, DEFAULT_SCALE, createGlyph('Automatic color', {
+ ts: { fs: 12, cl: { rgb } },
+ }));
+ expect(ScreenContext.fillStyle).toBe(COLOR_BLACK_RGB);
+ }
});
- it('draws footnote separator marks with their measured width and text color', () => {
+ it.each([
+ { fs: 8, rise: 3, thickness: 0.48 },
+ { fs: 11, rise: 3.92, thickness: 0.8 },
+ { fs: 16, rise: 5.84, thickness: 1.12 },
+ { fs: 22, rise: 8.08, thickness: 1.44 },
+ ])('draws a $fs pt footnote separator above the baseline with scalable thickness', ({ fs, rise, thickness }) => {
const extension = new FontAndBaseLine();
const SeparatorContext = Object.assign(createContext(), {
- beginPath: vi.fn(),
- moveToByPrecision: vi.fn(),
- lineToByPrecision: vi.fn(),
- stroke: vi.fn(),
+ fillRect: vi.fn(),
});
extension.extensionOffset = { spanPointWithFont: Vector2.create(12, 20) };
- extension.draw(SeparatorContext, DEFAULT_SCALE, createGlyph(' ', { noteSeparator: true, width: 192 }));
- expect(SeparatorContext.moveToByPrecision).toHaveBeenCalledWith(12, 20);
- expect(SeparatorContext.lineToByPrecision).toHaveBeenCalledWith(204, 20);
- expect(SeparatorContext.strokeStyle).toBe('#223344');
- expect(SeparatorContext.stroke).toHaveBeenCalledOnce();
+ extension.draw(SeparatorContext, DEFAULT_SCALE, createGlyph(' ', {
+ noteSeparator: true,
+ width: 192,
+ fontStyle: getFontStyleString({ ff: 'Univers', fs }),
+ }));
+ expect(SeparatorContext.fillRect).toHaveBeenCalledOnce();
+ const [left, top, width, height] = SeparatorContext.fillRect.mock.calls[0];
+ expect(left).toBe(12);
+ expect(width).toBe(192);
+ // Word's native PDF measurements are quantized to 1/600 inch (0.16 CSS px).
+ expect(Math.abs(20 - top - height / 2 - rise)).toBeLessThan(0.16);
+ expect(Math.abs(height - thickness)).toBeLessThan(0.08);
+ expect(SeparatorContext.fillStyle).toBe('#223344');
expect(SeparatorContext.fillText).not.toHaveBeenCalled();
expect(SeparatorContext.restore).toHaveBeenCalledOnce();
});
diff --git a/packages/engine-render/src/components/docs/extensions/__tests__/line.spec.ts b/packages/engine-render/src/components/docs/extensions/__tests__/line.spec.ts
index cabe739527..5af0c6f749 100644
--- a/packages/engine-render/src/components/docs/extensions/__tests__/line.spec.ts
+++ b/packages/engine-render/src/components/docs/extensions/__tests__/line.spec.ts
@@ -16,6 +16,7 @@
import { BaselineOffset, BooleanNumber, TextDecoration } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
+import { GlyphType } from '../../../../basics/i-document-skeleton-cached';
import { Line } from '../line';
function createCtx() {
@@ -61,6 +62,24 @@ function createGlyph() {
}
describe('docs line extension', () => {
+ it.each([0, -3, -6])('limits explicit marker decorations to aligned ink, not tab advance (%s)', (xOffset) => {
+ const extension = new Line();
+ extension.extensionOffset = {};
+ const ctx = createCtx();
+ const glyph = createGlyph();
+ glyph.glyphType = GlyphType.LIST;
+ glyph.xOffset = xOffset;
+ glyph.width = 24;
+ glyph.bBox.width = 6;
+ glyph.ts = { ul: { s: BooleanNumber.TRUE, t: TextDecoration.SINGLE } };
+ extension.draw(ctx, { scaleX: 1, scaleY: 1 }, glyph);
+ expect(ctx.moveTo.mock.calls[0][0]).toBeCloseTo(10 + xOffset);
+ expect(ctx.moveTo.mock.calls[0][1]).toBeCloseTo(8);
+ expect(ctx.lineTo.mock.calls[0][0]).toBeCloseTo(16 + xOffset);
+ expect(ctx.lineTo.mock.calls[0][1]).toBeCloseTo(8);
+ expect(glyph.width).toBe(24);
+ });
+
it('draws underline/bottom-border/strikethrough/overline', () => {
const line = new Line();
(line as any).extensionOffset = {};
diff --git a/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts b/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts
index b2879ed974..c0a17fc822 100644
--- a/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts
+++ b/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts
@@ -15,19 +15,21 @@
*/
import type { IDocTextFill, IDocTextFillGradientStop, IScale, TabStopLeader } from '@univerjs/core';
-import type { IBoundRectNoAngle } from '../../../basics';
import type { IDocumentSkeletonGlyph } from '../../../basics/i-document-skeleton-cached';
+import type { IBoundRectNoAngle } from '../../../basics/vector2';
import type { UniverRenderingContext } from '../../../context';
import type { IDrawInfo } from '../../extension';
import { BaselineOffset } from '@univerjs/core';
-import { GlyphType } from '../../../basics';
import { cjk } from '../../../basics/cjk-regexp';
import { COLOR_BLACK_RGB } from '../../../basics/const';
import { resolveGlowEffect, resolveOuterShadowEffect } from '../../../basics/drawing-effect';
+import { GlyphType } from '../../../basics/i-document-skeleton-cached';
+import { getFontStyleString } from '../../../basics/tools';
import { Vector2 } from '../../../basics/vector2';
import { CheckboxShape, isCheckboxGlyph } from '../../../shape/checkbox';
import { DocumentsSpanAndLineExtensionRegistry } from '../../extension';
import { docExtension } from '../doc-extension';
+import { getTextHorizontalScale } from '../layout/model/glyph';
import { getColorStyleForCanvas } from '../layout/style/color';
const UNIQUE_KEY = 'DefaultDocsFontAndBaseLineExtension';
@@ -86,6 +88,10 @@ export class FontAndBaseLine extends docExtension {
return;
}
+ if (ctx.fontKerning != null) {
+ ctx.fontKerning = fontStyle?.fontKerning ?? 'auto';
+ }
+
if (!textStyle) {
this._fillText(ctx, glyph, spanPointWithFont);
return;
@@ -109,13 +115,13 @@ export class FontAndBaseLine extends docExtension {
}
if (glyph.noteSeparator) {
+ const em = (fontStyle ?? getFontStyleString(textStyle)).fontSize / 0.75;
+ const thickness = em / 20;
ctx.save();
- ctx.strokeStyle = fontColor;
- ctx.lineWidth = 1;
- ctx.beginPath();
- ctx.moveToByPrecision(spanPointWithFont.x, spanPointWithFont.y);
- ctx.lineToByPrecision(spanPointWithFont.x + glyph.width, spanPointWithFont.y);
- ctx.stroke();
+ ctx.fillStyle = fontColor;
+ // Word places the rule's bottom a quarter em above the baseline.
+ // Preserve fractional geometry instead of snapping a 1 px baseline stroke.
+ ctx.fillRect(spanPointWithFont.x, spanPointWithFont.y - em / 4 - thickness, glyph.width, thickness);
ctx.restore();
return;
}
@@ -432,13 +438,17 @@ export class FontAndBaseLine extends docExtension {
const VERTICAL_DEG = 90;
const isVertical = vertexAngle === VERTICAL_DEG && centerAngle === VERTICAL_DEG;
+ const horizontalScale = getTextHorizontalScale(glyph.ts?.sa);
if (isVertical && !cjk.hasCJK(content)) {
ctx.save();
ctx.translate(spanStartPoint.x + centerPoint.x, spanStartPoint.y + centerPoint.y);
ctx.rotate(Math.PI / 2);
ctx.translate(-width / 2, (aba + abd) / 2 - abd);
- ctx.fillText(content, 0, 0);
+ if (horizontalScale !== 1) {
+ ctx.scale(horizontalScale, 1);
+ }
+ this._paintGlyphText(ctx, glyph, 0, 0);
ctx.restore();
} else {
if (isCheckboxGlyph(content) && glyph.glyphType === GlyphType.LIST) {
@@ -463,11 +473,31 @@ export class FontAndBaseLine extends docExtension {
x_offset = (glyph.width - glyph.bBox.width) / 2;
y_offset = -(glyph.width - fontHeight) / 2;
}
- ctx.fillText(content, spanPointWithFont.x + x_offset, spanPointWithFont.y + y_offset);
+ if (horizontalScale !== 1) {
+ ctx.save();
+ ctx.translate(spanPointWithFont.x + x_offset, spanPointWithFont.y + y_offset);
+ ctx.scale(horizontalScale, 1);
+ this._paintGlyphText(ctx, glyph, 0, 0);
+ ctx.restore();
+ } else {
+ this._paintGlyphText(ctx, glyph, spanPointWithFont.x + x_offset, spanPointWithFont.y + y_offset);
+ }
}
}
}
+ private _paintGlyphText(ctx: UniverRenderingContext, glyph: IDocumentSkeletonGlyph, x: number, y: number): void {
+ const { content, textSpacing } = glyph;
+ // Field resolution can replace content after shaping; never paint offsets belonging to the old text.
+ if (textSpacing?.content === content) {
+ for (const segment of textSpacing.segments) {
+ ctx.fillText(segment.content, x + segment.left / getTextHorizontalScale(glyph.ts?.sa), y);
+ }
+ } else {
+ ctx.fillText(content, x, y);
+ }
+ }
+
private _getTabLeaderCharacter(leader: TabStopLeader): string {
switch (leader) {
case 2:
diff --git a/packages/engine-render/src/components/docs/extensions/line.ts b/packages/engine-render/src/components/docs/extensions/line.ts
index d05003b659..ab7b73be3a 100644
--- a/packages/engine-render/src/components/docs/extensions/line.ts
+++ b/packages/engine-render/src/components/docs/extensions/line.ts
@@ -22,6 +22,7 @@ import type { IDrawInfo } from '../../extension';
import { BaselineOffset, BooleanNumber, TextDecoration } from '@univerjs/core';
import { COLOR_BLACK_RGB, DEFAULT_OFFSET_SPACING } from '../../../basics/const';
import { calculateRectRotate } from '../../../basics/draw';
+import { GlyphType } from '../../../basics/i-document-skeleton-cached';
import { degToRad, getScale } from '../../../basics/tools';
import { Vector2 } from '../../../basics/vector2';
import { DocumentsSpanAndLineExtensionRegistry } from '../../extension';
@@ -124,7 +125,9 @@ export class Line extends docExtension {
renderConfig = {},
} = this.extensionOffset;
- const { left, width } = glyph;
+ const isListMarker = glyph.glyphType === GlyphType.LIST;
+ const left = glyph.left + (isListMarker ? glyph.xOffset : 0);
+ const width = isListMarker ? glyph.bBox.width : glyph.width;
const isAccounting = this._isAccounting(lineType);
if (isAccounting && !this._isFirstAccountingGlyph(glyph)) {
return;
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.ts
index b4b15bfaa0..6876838933 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
@@ -15,7 +15,9 @@
*/
import type { IDocumentData } from '@univerjs/core';
+import { BooleanNumber, DocumentFlavor } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
+import { getFontStyleString } from '../../../../basics/tools';
import {
measureDocumentNoWrapTextRangeWidth,
measureDocumentNoWrapTextWidth,
@@ -41,6 +43,128 @@ function createDocument(dataStream: string): IDocumentData {
}
describe('measureDocumentNoWrapTextWidth', () => {
+ it.each([undefined, DocumentFlavor.UNSPECIFIED, DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN, DocumentFlavor.DRAWINGML])(
+ 'honors the East Asian spacing switch across runs and ranges without changing its default (%s)',
+ (documentFlavor) => {
+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
+ width: Array.from(text).reduce((width, char) => width + (/[中文]/.test(char) ? 16 : 8), 0),
+ }) as never);
+ try {
+ const document = createDocument('A中1文B\r\n');
+ document.documentStyle.documentFlavor = documentFlavor;
+ for (const runs of [[], [{ st: 0, ed: 1, ts: { bl: 1 } }, { st: 1, ed: 2, ts: { bl: 1 } }]]) {
+ document.body!.textRuns = runs;
+ for (const flag of [undefined, BooleanNumber.TRUE, BooleanNumber.FALSE]) {
+ document.documentStyle.spaceWidthEastAsian = flag;
+ expect(measureDocumentNoWrapTextWidth(document)).toBe(flag === BooleanNumber.FALSE ? 56 : 72);
+ expect(measureDocumentNoWrapTextRangeWidth(document, 0, 3)).toBe(flag === BooleanNumber.FALSE ? 32 : 40);
+ }
+ }
+ } finally {
+ measureSpy.mockRestore();
+ }
+ }
+ );
+
+ it.each([DocumentFlavor.MODERN, DocumentFlavor.DRAWINGML])('shares small-cap fonts for inherited styles and source ranges (%s)', (flavor) => {
+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text, font) => ({
+ width: Array.from(text).length * Number(font.match(/([\d.]+)pt/)![1]),
+ }) as never);
+ try {
+ const document = createDocument('Hh x \r\n');
+ document.documentStyle.documentFlavor = flavor;
+ document.documentStyle.textStyle = { fs: 12, smallCaps: true };
+ const small = flavor === DocumentFlavor.DRAWINGML ? 9.6 : 9.5;
+ expect(measureDocumentNoWrapTextWidth(document)).toBeCloseTo(24 + small * 2);
+ expect(measureDocumentNoWrapTextRangeWidth(document, 1, 2)).toBeCloseTo(small);
+ document.body!.textRuns = [{ st: 3, ed: 4, ts: { smallCaps: false } }];
+ expect(measureDocumentNoWrapTextWidth(document)).toBeCloseTo(36 + small);
+ document.body!.textRuns = [{ st: 3, ed: 4, ts: { caps: true } }];
+ expect(measureDocumentNoWrapTextWidth(document)).toBeCloseTo(36 + small);
+ expect(document.body!.dataStream).toBe('Hh x \r\n');
+ } finally {
+ measureSpy.mockRestore();
+ }
+ });
+
+ it('measures inherited display capitals with direct off and unchanged source ranges', () => {
+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
+ width: Array.from(text).reduce((width, char) => width + (/[A-Z]/.test(char) ? 10 : 5), 0),
+ }) as never);
+ try {
+ const document = createDocument('ab cd\r\n');
+ document.documentStyle.textStyle = { caps: true, fs: 12 };
+ document.body!.textRuns = [{ st: 0, ed: 2, ts: { bl: 1 } }, { st: 3, ed: 5, ts: { caps: false } }];
+ expect(measureDocumentNoWrapTextWidth(document)).toBe(35);
+ expect(measureDocumentNoWrapTextRangeWidth(document, 0, 2)).toBe(20);
+ expect(measureDocumentNoWrapTextRangeWidth(document, 3, 5)).toBe(10);
+ expect(document.body!.dataStream).toBe('ab cd\r\n');
+ } finally {
+ measureSpy.mockRestore();
+ }
+ });
+
+ it('preserves space-letter kerning across styled runs but not across line or font changes', () => {
+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text, _font, mode) => ({
+ width: text.length * 10 - (mode === 'normal' ? (text.match(/ V/g)?.length ?? 0) * 2 : 0),
+ }) as never);
+ try {
+ const document = createDocument('A V \r\n');
+ const style = { ff: 'Space kerning regression', fs: 12, kerning: 12 };
+ document.body!.textRuns = [
+ { st: 0, ed: 2, ts: style },
+ { st: 2, ed: 5, ts: { ...style, bl: 0 } },
+ ];
+ expect(measureDocumentNoWrapTextWidth(document)).toBe(28);
+ expect(measureDocumentNoWrapTextRangeWidth(document, 0, 2)).toBe(10);
+ document.body!.textRuns[1].ts!.fs = 13;
+ expect(measureDocumentNoWrapTextWidth(document)).toBe(30);
+ document.body!.textRuns[1].ts!.fs = 12;
+ document.body!.dataStream = 'A\rV \r\n';
+ expect(measureDocumentNoWrapTextWidth(document)).toBe(10);
+ } finally {
+ measureSpy.mockRestore();
+ }
+ });
+
+ it.each([false, true])('measures explicit line separators without reserving an advance (styled: %s)', (styled) => {
+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({ width: text.length * 10 }) as never);
+ try {
+ const document = createDocument('AA \u2028BBBB\r\n');
+ if (styled) {
+ document.body!.textRuns = [{ st: 0, ed: 8, ts: { fs: 12 } }];
+ }
+ expect(measureDocumentNoWrapTextWidth(document)).toBe(40);
+ expect(measureDocumentNoWrapTextRangeWidth(document, 0, 4)).toBe(20);
+ expect(measureDocumentNoWrapTextRangeWidth(document, 0, 8)).toBe(40);
+ expect(measureDocumentUnbreakableTextWidth(document)).toBe(40);
+ } finally {
+ measureSpy.mockRestore();
+ }
+ });
+
+ it('includes run tracking without inflating East Asian automatic spacing or trailing whitespace', () => {
+ const font = getFontStyleString({ fs: 12, ff: 'Tracking no-wrap' }).fontCache;
+ for (const text of ['A', 'B', '中', ' ']) {
+ FontCache.setFontMeasureCache(font, text, {
+ width: text === '中' ? 20 : 10,
+ fontBoundingBoxAscent: 12,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 2,
+ });
+ }
+ try {
+ const document = createDocument('A中B \r\n');
+ document.body!.textRuns = [{ st: 0, ed: 5, ts: { fs: 12, ff: 'Tracking no-wrap', sc: -3 } }];
+ // Three -3 pt tracking intervals become -12 layout pixels; trailing spaces do not count.
+ expect(measureDocumentNoWrapTextWidth(document)).toBe(40 + 10 - 9 / 0.75);
+ expect(measureDocumentNoWrapTextRangeWidth(document, 0, 3)).toBe(40 + 10 - 9 / 0.75);
+ } finally {
+ FontCache.clearFontMeasureCache(font);
+ }
+ });
+
it('uses docs CJK-Latin spacing for mixed no-wrap text', () => {
const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
width: Array.from(text).reduce((total, char) => total + (/[\u2E80-\u9FFF\uF900-\uFAFF]/u.test(char) ? 20 : 10), 0),
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
index 4da1cba73a..b234838d2a 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
@@ -40,11 +40,13 @@ import {
TableRowHeightRule,
TableSizeType,
TableTextWrapType,
+ TabStopAlignment,
+ TabStopLeader,
Univer,
VerticalAlignmentType,
WrapTextType,
} from '@univerjs/core';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import {
DocumentSkeletonPageType,
GlyphType,
@@ -62,6 +64,25 @@ import { PATTERN_LOADERS } from '../hyphenation/pattern-loaders.gen';
import * as CellLayout from '../model/page';
import { FontCache } from '../shaping-engine/font-cache';
+function mockCanvasTextMetrics(baseFontSize = 11, advance = 8) {
+ Reflect.set(FontCache, '_context', null);
+ FontCache.invalidateMetrics(() => true);
+ return vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
+ font: '',
+ measureText(this: CanvasRenderingContext2D, text: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : baseFontSize;
+ return {
+ width: text.length * advance * points / baseFontSize,
+ fontBoundingBoxAscent: 8 * points / baseFontSize,
+ fontBoundingBoxDescent: 2 * points / baseFontSize,
+ actualBoundingBoxAscent: 8 * points / baseFontSize,
+ actualBoundingBoxDescent: 2 * points / baseFontSize,
+ };
+ },
+ } as unknown as CanvasRenderingContext2D);
+}
+
function normalizeSkeleton(value: unknown): unknown {
if (typeof value === 'number' && Object.is(value, -0)) {
return 0;
@@ -221,31 +242,86 @@ function createPage(type: DocumentSkeletonPageType, st: number, tableId = '') {
}
describe('doc skeleton', () => {
- it.each([2, 6].flatMap((paragraphCount) => [TableRowHeightRule.AUTO, TableRowHeightRule.AT_LEAST, TableRowHeightRule.EXACT].map((hRule) => ({ paragraphCount, hRule }))))('sizes vertically merged cells against the whole row span ($paragraphCount paragraphs, rule $hRule)', ({ paragraphCount, hRule }) => {
- const measure = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
- width: text.length * 5,
- fontBoundingBoxAscent: 8,
- fontBoundingBoxDescent: 2,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
- }) as TextMetrics);
+ it('uses the largest DrawingML text size across runs, without changing snapshots or document defaults', () => {
+ const measure = vi.spyOn(FontCache, 'getMeasureText').mockReturnValue({
+ width: 6.1572265625,
+ fontBoundingBoxAscent: 15,
+ fontBoundingBoxDescent: 4,
+ actualBoundingBoxAscent: 15,
+ actualBoundingBoxDescent: 4,
+ });
+ const dataModel = new DocumentDataModel({
+ id: 'drawingml-runtime-layout',
+ body: {
+ dataStream: 'a b\r\n',
+ textRuns: [{ st: 0, ed: 2, ts: { fs: 10.5 } }, { st: 2, ed: 3, ts: { fs: 18 } }],
+ paragraphs: [{ startIndex: 3, paragraphId: 'mixed-sizes', paragraphStyle: {
+ lineSpacing: 1.5,
+ spacingRule: SpacingRule.AUTO,
+ snapToGrid: BooleanNumber.FALSE,
+ } }],
+ sectionBreaks: [{ sectionId: 'drawingml-section', startIndex: 4, gridType: GridType.DEFAULT }],
+ },
+ documentStyle: { pageSize: { width: 300, height: 300 } },
+ });
+ const snapshot = structuredClone(dataModel.getSnapshot());
+ const univer = new Univer();
+ const locale = univer.__getInjector().get(LocaleService);
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(dataModel), locale);
+ const firstLine = () => skeleton.getSkeletonData()!.pages[0].sections[0].columns[0].lines[0];
+ try {
+ skeleton.calculate();
+ const documentHeight = firstLine().lineHeight;
+ expect(documentHeight).toBeCloseTo(28.5);
+ dataModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.DRAWINGML });
+ skeleton.makeDirty(true);
+ skeleton.calculate();
+ expect(firstLine().lineHeight).toBeCloseTo(43.2);
+ expect(firstLine().divides[0].glyphGroup.find((glyph) => glyph.content === 'a')?.width).toBe(6.125);
+ const fresh = DocumentSkeleton.create(new DocumentViewModel(new DocumentDataModel(dataModel.getSnapshot())), locale);
+ fresh.calculate();
+ expect(normalizeSkeleton(skeleton.getSkeletonData())).toEqual(normalizeSkeleton(fresh.getSkeletonData()));
+ fresh.dispose();
+ dataModel.updateDocumentStyle({ documentFlavor: snapshot.documentStyle.documentFlavor });
+ skeleton.makeDirty(true);
+ skeleton.calculate();
+ expect(firstLine().lineHeight).toBeCloseTo(documentHeight);
+ expect(dataModel.getSnapshot()).toEqual(snapshot);
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ measure.mockRestore();
+ }
+ });
+
+ it.each([2, 6].flatMap((paragraphCount) => [TableRowHeightRule.AUTO, TableRowHeightRule.AT_LEAST, TableRowHeightRule.EXACT].flatMap((hRule) =>
+ [0, 1, 30].map((tailParagraphs) => ({ paragraphCount, hRule, tailParagraphs }))
+ )))('sizes vertically merged cells against the whole row span ($paragraphCount paragraphs, rule $hRule, tail $tailParagraphs)', ({ paragraphCount, hRule, tailParagraphs }) => {
+ const measure = mockCanvasTextMetrics();
+ const paged = tailParagraphs > 0;
+ const tailRowCount = tailParagraphs === 1 ? 20 : 1;
const univer = new Univer();
const T = DataStreamTreeTokenType;
const cell = (text: string) => `${T.TABLE_CELL_START}${text}\n${T.TABLE_CELL_END}`;
const row = (left: string, right: string) => `${T.TABLE_ROW_START}${cell(left)}${cell(right)}${T.TABLE_ROW_END}`;
- const tableStream = `${T.TABLE_START}${row('Merged\r'.repeat(paragraphCount), 'One\r')}${row('\r', 'Two\r')}${T.TABLE_END}`;
+ const tableStream = `${T.TABLE_START}${row('Merged\r'.repeat(paragraphCount), 'One\r')}${row('\r', 'Two\r')}${paged ? row('Tail\r'.repeat(tailParagraphs), 'Other\r'.repeat(tailParagraphs)).repeat(tailRowCount) : ''}${T.TABLE_END}`;
const dataStream = `${tableStream}\rAfter\r\n`;
const snapshot: IDocumentData = {
id: 'merged-cell-height',
body: {
dataStream,
- paragraphs: [...dataStream.matchAll(/\r/g)].filter((match) => match.index !== tableStream.length).map((match, index) => ({ paragraphId: `p-${index}`, startIndex: match.index })),
+ paragraphs: [...dataStream.matchAll(/\r/g)].filter((match) => match.index !== tableStream.length).map((match, index) => ({
+ paragraphId: `p-${index}`,
+ startIndex: match.index,
+ paragraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: 20 },
+ })),
sectionBreaks: [...dataStream.matchAll(/\n/g)].map((match, index) => ({ sectionId: `s-${index}`, startIndex: match.index })),
tables: [{ tableId: 'table', startIndex: 0, endIndex: tableStream.length }],
},
documentStyle: {
documentFlavor: DocumentFlavor.TRADITIONAL,
- pageSize: { width: 400, height: 400 },
+ textStyle: { ff: 'Arial', fs: 11 },
+ pageSize: { width: 400, height: paged ? 200 : 400 },
marginTop: 10,
marginBottom: 10,
marginLeft: 10,
@@ -264,9 +340,10 @@ describe('doc skeleton', () => {
dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
cellMargin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } },
tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 100 } } }, { size: { type: TableSizeType.SPECIFIED, width: { v: 100 } } }],
- tableRows: [0, 1].map((index) => ({
- trHeight: { hRule, val: { v: 25 } },
- tableCells: [{ rowSpan: index === 0 ? 2 : 0, vAlign: VerticalAlignmentType.CENTER }, {}],
+ tableRows: Array.from({ length: paged ? tailRowCount + 2 : 2 }, (_, index) => ({
+ cantSplit: BooleanNumber.FALSE,
+ trHeight: { hRule: index >= 2 ? TableRowHeightRule.AUTO : hRule, val: { v: 25 } },
+ tableCells: [{ rowSpan: [2, 0][index] ?? 1, vAlign: VerticalAlignmentType.CENTER }, { vAlign: VerticalAlignmentType.CENTER }],
})),
} },
};
@@ -275,20 +352,34 @@ describe('doc skeleton', () => {
try {
skeleton.calculate();
const pages = skeleton.getSkeletonData()!.pages;
- expect(pages).toHaveLength(1);
- const table = pages[0].skeTables.get('table')!;
+ expect(pages.length > 1).toBe(paged);
+ const table = [...pages[0].skeTables.values()][0];
const mergedCell = table.rows[0].cells[0];
- const otherCellsHeight = table.rows.reduce((height, row) => height + row.cells[1].height, 0);
+ const mergedRows = table.rows.filter((row) => row.index < 2);
+ const otherCellsHeight = mergedRows.reduce((height, row) => height + row.cells[1].height, 0);
let expectedHeight = Math.max(mergedCell.height, otherCellsHeight);
if (hRule === TableRowHeightRule.EXACT) {
expectedHeight = 50;
} else if (hRule === TableRowHeightRule.AT_LEAST) {
expectedHeight = Math.max(expectedHeight, 50);
}
- expect(table.height).toBeCloseTo(expectedHeight);
- expect(mergedCell.pageHeight).toBeCloseTo(table.height);
- expect(mergedCell.marginTop).toBeCloseTo(Math.max(0, (table.height - mergedCell.height) / 2));
+ expect(mergedRows.reduce((height, row) => height + row.height, 0)).toBeCloseTo(expectedHeight);
+ expect(mergedCell.pageHeight).toBeCloseTo(expectedHeight);
+ expect(mergedCell.marginTop).toBeCloseTo(Math.max(0, (expectedHeight - mergedCell.height) / 2));
expect(table.rows[1].top).toBeCloseTo(table.rows[0].height);
+ if (tailParagraphs > 1) {
+ const fragments = pages.flatMap((page) => [...page.skeTables.values()].flatMap((part) => part.rows.filter((row) => row.index === 2)));
+ expect(fragments.length).toBeGreaterThan(1);
+ expect(fragments.flatMap((row) => row.cells).every((cell) => cell.marginTop === cell.originMarginTop)).toBe(true);
+ for (const cell of fragments.flatMap((row) => row.cells)) {
+ for (const line of cell.sections.flatMap((section) => section.columns.flatMap((column) => column.lines))) {
+ const anchor = skeleton.getSkeletonData()!.drawingAnchor!.get('table')!.get(line.paragraphIndex)!;
+ expect(anchor.elements).toHaveLength(1);
+ expect(anchor.elements[0]).toBe(line);
+ expect(anchor.top).toBeCloseTo(line.top);
+ }
+ }
+ }
expectIncrementalSkeletonToEqualSynchronous(snapshot, univer.__getInjector().get(LocaleService));
} finally {
skeleton.dispose();
@@ -299,13 +390,7 @@ describe('doc skeleton', () => {
});
it('reserves footnote space and carries long notes through synchronous and sliced pagination', () => {
- const measure = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
- width: text.length * 5,
- fontBoundingBoxAscent: 8,
- fontBoundingBoxDescent: 2,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
- }) as TextMetrics);
+ const measure = mockCanvasTextMetrics(11, 5);
const univer = new Univer();
const dataStream = `${'Intro\r'.repeat(30)}Text with reference\uFFFC and more text.\r${'Later body paragraph.\r'.repeat(10)}\n`;
const noteStream = `${'Long explanation that continues onto the following page.\r'.repeat(10)}\n`;
@@ -372,7 +457,7 @@ describe('doc skeleton', () => {
expect(firstNote.top + firstNote.page.height).toBeLessThanOrEqual(page.pageHeight - page.marginBottom + 2);
}
expect(fragments.map((fragment) => fragment.page.sections.flatMap((section) => section.columns.flatMap(
- (column) => column.lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.raw)))
+ (column) => column.lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup.filter((glyph) => glyph.count > 0).map((glyph) => glyph.raw)))
)).join('')).join('')).toBe(noteStream);
expectIncrementalSkeletonToEqualSynchronous(snapshot, univer.__getInjector().get(LocaleService));
const edited = structuredClone(snapshot);
@@ -476,7 +561,328 @@ describe('doc skeleton', () => {
}
});
+ afterEach(() => {
+ vi.restoreAllMocks();
+ Reflect.set(FontCache, '_context', null);
+ FontCache.invalidateMetrics(() => true);
+ });
+
+ it.each([0, 12])('reserves Word header and footer text flow including trailing spacing (%s px)', (spaceAfter) => {
+ const univer = new Univer();
+ const story = (lines: string[]) => {
+ const text = `${lines.join('\r')}\r`;
+ return {
+ dataStream: `${text}\n`,
+ paragraphs: [...text.matchAll(/\r/g)].map((match) => ({
+ paragraphId: `story-${match.index}`,
+ startIndex: match.index!,
+ paragraphStyle: {
+ spacingRule: SpacingRule.EXACT,
+ lineSpacing: 80 / 3,
+ spaceAbove: { v: 0 },
+ spaceBelow: { v: spaceAfter },
+ },
+ })),
+ sectionBreaks: [{ startIndex: text.length, sectionId: 'story-section' }],
+ };
+ };
+ const snapshot: IDocumentData = {
+ id: 'word-story-flow',
+ body: story(['Body']),
+ headers: { header: { headerId: 'header', body: story(['Header1', 'Header2', 'Header3', 'Header4']) } },
+ footers: { footer: { footerId: 'footer', body: story(['Footer1', 'Footer2']) } },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 400, height: 1600 / 3 },
+ marginTop: 32,
+ marginBottom: 32,
+ marginLeft: 40,
+ marginRight: 40,
+ marginHeader: 40 / 3,
+ marginFooter: 40 / 3,
+ defaultHeaderId: 'header',
+ defaultFooterId: 'footer',
+ textStyle: { ff: 'Arial', fs: 12 },
+ },
+ };
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(new DocumentDataModel(snapshot)), univer.__getInjector().get(LocaleService));
+ try {
+ skeleton.calculate();
+ const page = skeleton.getSkeletonData()!.pages[0];
+ // Native Word: body starts at 90 pt; a two-line footer occupies 50 pt.
+ expect(page.marginTop).toBeCloseTo(120 + spaceAfter * 4, 8);
+ expect(page.marginBottom).toBeCloseTo(200 / 3 + spaceAfter * 2, 8);
+ expect(page.originMarginTop).toBe(32);
+ expect(page.originMarginBottom).toBe(32);
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+ });
+
+ it.each([{ xAlign: 'left', left: 0 }, { xAlign: 'center', left: 154 }, { xAlign: 'right', left: 308 }].flatMap((position) => [0, 30].map((y) => ({ ...position, y }))))('positions an unwrapped footer frame without adding a flow line ($xAlign/$y)', ({ xAlign, left, y }) => {
+ mockCanvasTextMetrics(9, 6);
+ const univer = new Univer();
+ const text = '12\rFooter label\r\r\n';
+ const snapshot: IDocumentData = {
+ id: 'footer-text-frame',
+ body: { dataStream: 'Body\r\n', paragraphs: [{ startIndex: 4, paragraphId: 'body' }], sectionBreaks: [{ startIndex: 5, sectionId: 'body-section' }] },
+ footers: { footer: {
+ footerId: 'footer',
+ body: {
+ dataStream: text,
+ paragraphs: [2, 15, 16].map((startIndex, index) => ({
+ startIndex,
+ paragraphId: `footer-${index}`,
+ paragraphStyle: {
+ spacingRule: SpacingRule.EXACT,
+ lineSpacing: 16,
+ spaceAbove: { v: 0 },
+ spaceBelow: { v: 0 },
+ ...(index === 0
+ ? { paragraphFrame: {
+ wrap: 'none',
+ horizontalAnchor: 'margin',
+ verticalAnchor: 'text',
+ xAlign,
+ y: String(y),
+ } }
+ : {}),
+ },
+ })),
+ sectionBreaks: [{ startIndex: 17, sectionId: 'footer-section' }],
+ },
+ } },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 400, height: 600 },
+ marginTop: 40,
+ marginBottom: 0,
+ marginLeft: 40,
+ marginRight: 40,
+ marginFooter: 20,
+ defaultFooterId: 'footer',
+ textStyle: { ff: 'Arial', fs: 9 },
+ },
+ };
+ const model = new DocumentDataModel(snapshot);
+ const original = JSON.stringify(model.getSnapshot());
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));
+ try {
+ skeleton.calculate();
+ const data = skeleton.getSkeletonData()!;
+ const footer = data.skeFooters.get('footer')!.get(400)!;
+ const [frame, label, empty] = footer.sections[0].columns[0].lines;
+ expect(footer.height).toBe(32);
+ expect(data.pages[0].marginBottom).toBe(52);
+ expect(label.top).toBe(0);
+ expect(empty.top).toBe(16);
+ expect(frame.top).toBe(y / 15);
+ const divide = frame.divides[0];
+ expect(divide.left).toBeCloseTo(left);
+ expect(divide.width).toBeCloseTo(12);
+ expect(frame.st).toBe(0);
+ expect(label.st).toBe(3);
+ expect(skeleton.findNodeByCharIndex(0, 'footer', 0)?.content).toBe('1');
+ expect(skeleton.findNodeByCharIndex(3, 'footer', 0)?.content).toBe('F');
+ const footerTop = 600 - footer.height - footer.marginBottom;
+ const hit = skeleton.findNodeByCoord(Vector2.create(40 + left + 3, footerTop + frame.top + 8), PageLayoutType.VERTICAL, 0, 0);
+ expect(hit?.segmentId).toBe('footer');
+ expect(hit?.node.content).toBe('1');
+ const labelHit = skeleton.findNodeByCoord(Vector2.create(70, footerTop + 8), PageLayoutType.VERTICAL, 0, 0);
+ expect(labelHit?.node.parent?.parent).toBe(label);
+ expect(JSON.stringify(model.getSnapshot())).toBe(original);
+ const geometry = normalizeSkeleton(footer);
+ completeIncrementalLayout(skeleton);
+ expect(normalizeSkeleton(skeleton.getSkeletonData()!.skeFooters.get('footer')!.get(400))).toEqual(geometry);
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+ });
+
+ it('keeps multiple-line leading below the text and allows its blank tail past the body page edge', () => {
+ mockCanvasTextMetrics();
+ const univer = new Univer();
+ const snapshot: IDocumentData = {
+ id: 'word-multiple-line-leading',
+ body: {
+ dataStream: 'A\rB\rC\r\n',
+ paragraphs: [1, 3, 5].map((startIndex) => ({ startIndex, paragraphId: `p-${startIndex}`, paragraphStyle: {
+ spacingRule: SpacingRule.AUTO,
+ lineSpacing: 1.5,
+ snapToGrid: BooleanNumber.FALSE,
+ spaceAbove: { v: 0 },
+ spaceBelow: { v: 0 },
+ } })),
+ sectionBreaks: [{ startIndex: 6, sectionId: 'section' }],
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 200, height: 26 },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ textStyle: { ff: 'Word multiple-line regression', fs: 11 },
+ },
+ };
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(new DocumentDataModel(snapshot)), univer.__getInjector().get(LocaleService));
+ try {
+ skeleton.calculate();
+ const { pages } = skeleton.getSkeletonData()!;
+ expect(pages).toHaveLength(2);
+ const lines = pages[0].sections[0].columns[0].lines;
+ expect(lines).toHaveLength(2);
+ expect(lines.map((line) => line.paragraphIndex)).toEqual([1, 3]);
+ expect(lines[0].paddingTop).toBe(0);
+ expect(lines[0].paddingBottom).toBeCloseTo(5);
+ expect(lines[1].top + lines[1].contentHeight).toBeLessThanOrEqual(26);
+ expect(lines[1].top + lines[1].lineHeight).toBeGreaterThan(26);
+ expect(pages[1].sections[0].columns[0].lines[0].paragraphIndex).toBe(5);
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+ });
+
+ it('measures small visible font increases within a traditional line without a two-pixel tolerance', () => {
+ mockCanvasTextMetrics();
+ const univer = new Univer();
+ const snapshot: IDocumentData = {
+ id: 'small-mixed-font-increase',
+ body: {
+ dataStream: 'a b\rnext\r\n',
+ textRuns: [{ st: 0, ed: 2, ts: { fs: 10 } }, { st: 2, ed: 3, ts: { fs: 11 } }],
+ paragraphs: [3, 8].map((startIndex) => ({ startIndex, paragraphId: `p-${startIndex}`, paragraphStyle: {
+ spacingRule: SpacingRule.AT_LEAST,
+ lineSpacing: 1,
+ spaceAbove: { v: 0 },
+ spaceBelow: { v: 0 },
+ } })),
+ sectionBreaks: [{ startIndex: 9, sectionId: 'section' }],
+ },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 400, height: 600 }, textStyle: { ff: 'Arial', fs: 10 } },
+ };
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(new DocumentDataModel(snapshot)), univer.__getInjector().get(LocaleService));
+ try {
+ skeleton.calculate();
+ const [first, second] = skeleton.getSkeletonData()!.pages[0].sections[0].columns[0].lines;
+ const glyph = first.divides[0].glyphGroup.find((glyph) => glyph.content === 'b')!;
+ expect(first.contentHeight).toBeCloseTo(glyph.bBox.ba + glyph.bBox.bd);
+ expect(second.top).toBeCloseTo(first.top + first.lineHeight);
+ expect(first.contentHeight).toBeGreaterThan(second.contentHeight);
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+ });
+
+ it.each(['header', 'footer'] as const)('inherits document typography in the %s without inheriting body margins', (kind) => {
+ const univer = new Univer();
+ const body = {
+ dataStream: 'Same text\r\n',
+ paragraphs: [{ startIndex: 9, paragraphId: 'same-text' }],
+ sectionBreaks: [{ startIndex: 10, sectionId: 'same-text-section' }],
+ };
+ const snapshot: IDocumentData = {
+ id: 'story-typography',
+ body,
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 500, height: 700 },
+ marginLeft: 50,
+ marginRight: 60,
+ marginTop: 100,
+ marginBottom: 100,
+ marginHeader: 20,
+ marginFooter: 20,
+ textStyle: { ff: 'Arial', fs: 18 },
+ ...(kind === 'header' ? { defaultHeaderId: 'story' } : { defaultFooterId: 'story' }),
+ },
+ ...(kind === 'header'
+ ? { headers: { story: { headerId: 'story', body } } }
+ : { footers: { story: { footerId: 'story', body } } }),
+ };
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(new DocumentDataModel(snapshot)), univer.__getInjector().get(LocaleService));
+ try {
+ skeleton.calculate();
+ const data = skeleton.getSkeletonData()!;
+ const bodyLine = data.pages[0].sections[0].columns[0].lines[0];
+ const resources = kind === 'header' ? data.skeHeaders : data.skeFooters;
+ const storyPage = resources.get('story')!.get(500)!;
+ const storyLine = storyPage.sections[0].columns[0].lines[0];
+ expect(storyLine.divides[0].glyphGroup[0].fontStyle).toEqual(bodyLine.divides[0].glyphGroup[0].fontStyle);
+ expect(storyLine.lineHeight).toBe(bodyLine.lineHeight);
+ expect(storyPage.pageWidth).toBe(390);
+ expect(storyPage.marginLeft).toBe(0);
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+ });
+
+ it('lays out a TOC page number through nested field markers at the right tab stop', () => {
+ const univer = new Univer();
+ const snapshot: IDocumentData = {
+ id: 'toc-tab-field-layout',
+ body: {
+ dataStream: '\u001FTitle\t\u001F12\u001E\r\u001E\r\n',
+ paragraphs: [{
+ startIndex: 11,
+ paragraphId: 'toc-entry',
+ paragraphStyle: {
+ tabStops: [{ offset: 500, alignment: TabStopAlignment.END, leader: TabStopLeader.DOT }],
+ },
+ }, { startIndex: 13, paragraphId: 'after-toc' }],
+ sectionBreaks: [{ startIndex: 14, sectionId: 'toc-section' }],
+ customRanges: [{
+ startIndex: 0,
+ endIndex: 12,
+ rangeId: 'toc',
+ rangeType: CustomRangeType.FIELD,
+ wholeEntity: false,
+ properties: { fieldType: 'TOC' },
+ }, {
+ startIndex: 7,
+ endIndex: 10,
+ rangeId: 'page',
+ rangeType: CustomRangeType.FIELD,
+ wholeEntity: false,
+ properties: { fieldType: 'PAGEREF' },
+ }],
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 600, height: 700 },
+ marginTop: 50,
+ marginBottom: 50,
+ marginLeft: 50,
+ marginRight: 50,
+ textStyle: { ff: 'Arial', fs: 12 },
+ },
+ };
+ const skeleton = DocumentSkeleton.create(
+ new DocumentViewModel(new DocumentDataModel(snapshot)),
+ univer.__getInjector().get(LocaleService)
+ );
+ try {
+ skeleton.calculate();
+ const glyphs = skeleton.getSkeletonData()!.pages[0].sections[0].columns[0].lines[0].divides[0].glyphGroup;
+ const tab = glyphs.find((glyph) => glyph.glyphType === GlyphType.TAB)!;
+ const pageNumberEnd = glyphs.findLast((glyph) => glyph.raw === '2')!;
+
+ expect(tab.tabLeader).toBe(TabStopLeader.DOT);
+ expect(pageNumberEnd.left + pageNumberEnd.width).toBeCloseTo(500, 4);
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+ });
+
it.each(['ready', 'cancel', 'failure', 'header', 'footer'])('waits for cold hyphenation rules and matches a warm executor (%s)', async (scenario) => {
+ mockCanvasTextMetrics(12);
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({ height: 8000 / 3 } as DOMRect);
const univer = new Univer();
const content = 'Este documento contiene información sobre la configuración y la administración de los servicios. '
.repeat(scenario === 'header' || scenario === 'footer' ? 1 : 4);
@@ -547,7 +953,12 @@ describe('doc skeleton', () => {
expect(cold.stepIncrementalLayout(coldGeneration, 8)).toMatchObject({ cancelled: true, didPublish: false });
coldGeneration = cold.startIncrementalLayout({ waitForHyphenationPatterns: true });
}
- await vi.waitFor(() => expect(cold.stepIncrementalLayout(coldGeneration, 8).complete).toBe(true));
+ // Each step may publish only one page; drive the scheduler without
+ // spending most of the readiness timeout between layout steps.
+ await vi.waitFor(() => {
+ const progress = cold.stepIncrementalLayout(coldGeneration, 8);
+ expect(progress.complete, JSON.stringify(progress)).toBe(true);
+ }, { interval: 1 });
completeIncrementalLayout(warm);
if (scenario !== 'header' && scenario !== 'footer') {
expect(cold.getSkeletonData()?.pages.length).toBeGreaterThan(1);
@@ -748,105 +1159,349 @@ describe('doc skeleton', () => {
}
});
- it.each([
- { scrollLeft: 0, leadingInsetLeft: 0 },
- { scrollLeft: 8, leadingInsetLeft: 4 },
- ])('hit-tests the first visible table column without counting page padding twice ($scrollLeft/$leadingInsetLeft)', ({ scrollLeft, leadingInsetLeft }) => {
+ it.each([BooleanNumber.FALSE, BooleanNumber.TRUE].flatMap((keepNext) =>
+ [false, true].flatMap((splitTable) =>
+ [10, 20].map((tableLineHeight) => ({ keepNext, tableLineHeight, splitTable })))))('keeps a heading with its following flow table only when they fit ($keepNext/$tableLineHeight/$splitTable)', ({ keepNext, tableLineHeight, splitTable }) => {
+ const measureSpy = mockCanvasTextMetrics();
const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
const T = DataStreamTreeTokenType;
- const table = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_CELL_START}Other${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
- const prefix = `Heading${T.PARAGRAPH}`;
- const dataStream = `${prefix}${table}Tail${T.PARAGRAPH}${T.SECTION_BREAK}`;
- const model = new DocumentDataModel({
- id: 'wide-table-hit-test',
+ const prefix = 'Prefix\rHeading\r';
+ const table = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}One\rTwo\rThree\rFour\r\n${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const dataStream = `${prefix}${table}\r\n`;
+ const snapshot: Partial<IDocumentData> = {
+ id: 'heading-kept-with-table',
body: {
dataStream,
- paragraphs: [...dataStream.matchAll(/\r/g)].map((match, index) => ({ startIndex: match.index!, paragraphId: `wide-table-p-${index}` })),
- sectionBreaks: [...dataStream.matchAll(/\n/g)].map((match, index) => ({ startIndex: match.index!, sectionId: `wide-table-s-${index}` })),
- tables: [{ tableId: 'table', startIndex: prefix.length, endIndex: prefix.length + table.length }],
- },
- tableSource: {
- table: {
- tableId: 'table',
- align: TableAlignmentType.START,
- indent: { v: 0 },
- textWrap: TableTextWrapType.NONE,
- position: {
- positionH: { relativeFrom: ObjectRelativeFromH.PAGE },
- positionV: { relativeFrom: ObjectRelativeFromV.PAGE },
+ paragraphs: [...dataStream.matchAll(/\r/g)].map((match, index) => ({
+ startIndex: match.index,
+ paragraphId: `p-${index}`,
+ paragraphStyle: {
+ spacingRule: SpacingRule.EXACT,
+ lineSpacing: [splitTable ? 40 : 60, 10][index] ?? tableLineHeight,
+ snapToGrid: BooleanNumber.FALSE,
+ ...(index === 1 ? { keepNext, spaceAbove: { v: 4 } } : {}),
},
- dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
- size: { type: TableSizeType.SPECIFIED, width: { v: 400 } },
- tableRows: [{
- tableCells: [{}, {}],
- trHeight: { val: { v: 40 }, hRule: TableRowHeightRule.AT_LEAST },
- }],
- tableColumns: [0, 1].map(() => ({ size: { type: TableSizeType.SPECIFIED, width: { v: 200 } } })),
- },
+ })),
+ sectionBreaks: [...dataStream.matchAll(/\n/g)].map((match, index) => ({ startIndex: match.index, sectionId: `s-${index}` })),
+ tables: [{ tableId: 'table', startIndex: prefix.length, endIndex: prefix.length + table.length }],
},
+ tableSource: { table: {
+ tableId: 'table',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: { positionH: { relativeFrom: ObjectRelativeFromH.PAGE }, positionV: { relativeFrom: ObjectRelativeFromV.PAGE } },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 80 } },
+ cellMargin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } },
+ tableRows: [{ tableCells: [{}], cantSplit: splitTable ? BooleanNumber.FALSE : BooleanNumber.TRUE, trHeight: { val: { v: 0 }, hRule: TableRowHeightRule.AUTO } }],
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 80 } } }],
+ } },
documentStyle: {
documentFlavor: DocumentFlavor.TRADITIONAL,
- pageSize: { width: 600, height: 700 },
- marginLeft: 96,
- marginRight: 96,
- marginTop: 96,
- marginBottom: 96,
+ pageSize: { width: 120, height: 100 },
+ marginTop: 10,
+ marginBottom: 10,
+ marginLeft: 10,
+ marginRight: 10,
},
- });
- const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));
+ };
try {
- skeleton.calculate();
- const page = skeleton.getSkeletonData()!.pages[0];
- const tableSkeleton = [...page.skeTables.values()][0];
- const cell = tableSkeleton.rows[0].cells[0];
- const section = cell.sections[0];
- const column = section.columns[0];
- const line = column.lines[0];
- const divide = line.divides[0];
- const glyph = divide.glyphGroup[0];
- const x = page.marginLeft + tableSkeleton.left + cell.left + cell.marginLeft + column.left + divide.left + glyph.left + glyph.width / 2;
- const y = page.marginTop + tableSkeleton.top + cell.marginTop + section.top + line.top + line.lineHeight / 2;
- expect(skeleton.findNodeByCoord(new Vector2(x, y), PageLayoutType.VERTICAL, 0, 20)?.node === glyph).toBe(true);
- setDocsTableRenderViewportProvider((unitId, tableId) => unitId === model.getUnitId() && tableId === 'table'
- ? { contentWidth: tableSkeleton.width, viewportWidth: 200, scrollLeft, leadingInsetLeft }
- : null);
- for (const restrictions of [undefined, { strict: false, segmentId: '', segmentPage: -1 }, { strict: true, segmentId: '', segmentPage: -1 }]) {
- expect(skeleton.findNodeByCoord(new Vector2(x - scrollLeft, y), PageLayoutType.VERTICAL, 0, 20, restrictions)?.node === glyph).toBe(true);
+ for (const incremental of [false, true]) {
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(new DocumentDataModel(structuredClone(snapshot))), localeService);
+ try {
+ if (incremental) {
+ completeIncrementalLayout(skeleton);
+ } else {
+ skeleton.calculate();
+ }
+ const pages = skeleton.getSkeletonData()!.pages;
+ expect(pages).toHaveLength(2);
+ const kept = !splitTable && keepNext && tableLineHeight === 10;
+ expect(skeleton.findBodyPageIndexByCharIndex(prefix.indexOf('Heading'))).toBe(kept ? 1 : 0);
+ const positionedTable = [...pages[1].skeTables.values()][0];
+ expect(positionedTable.top).toBeCloseTo(kept ? 10 : 0);
+ if (splitTable) {
+ expect([...pages[0].skeTables.values()][0].height).toBeGreaterThan(0);
+ expect(positionedTable.height).toBeLessThan(tableLineHeight * 4);
+ } else {
+ expect(positionedTable.height).toBeCloseTo(tableLineHeight * 4);
+ }
+ const caret = skeleton.findNodePositionByCharIndex(dataStream.indexOf('One'))!;
+ expect(caret.page).toBe(splitTable ? 0 : 1);
+ expect(skeleton.findCharIndexByPosition(caret)).toBe(dataStream.indexOf('One'));
+ } finally {
+ skeleton.dispose();
+ }
}
} finally {
- setDocsTableRenderViewportProvider(null);
- skeleton.dispose();
+ measureSpy.mockRestore();
univer.dispose();
}
});
- it('rejects a new caret on retained geometry until the edited page is published', () => {
+ it.each([false, true])('applies widow control in a split table cell regardless of cached page markers (cached=%s)', (cached) => {
+ const measureSpy = mockCanvasTextMetrics();
const univer = new Univer();
- const skeleton = DocumentSkeleton.create(
- new DocumentViewModel(new DocumentDataModel({
- id: 'unpublished-hit-test',
- body: { dataStream: 'Hello\r\n', paragraphs: [{ startIndex: 5, paragraphId: 'paragraph' }] },
- documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 300, height: 400 } },
- })),
- univer.__getInjector().get(LocaleService)
- );
- skeleton.calculate();
- const page = skeleton.getSkeletonData()!.pages[0];
- const coord = new Vector2(page.marginLeft + 5, page.marginTop + 5);
- expect(skeleton.findNodeByCoord(coord, PageLayoutType.VERTICAL, 0, 20)).toBeTruthy();
- const generation = skeleton.startIncrementalLayout({ reason: 'edit', anchor: 3, reuseUnaffectedTail: false });
-
- expect(skeleton.findNodeByCoord(coord, PageLayoutType.VERTICAL, 0, 20) == null).toBe(true);
- expect(skeleton.findNodeByCoord(new Vector2(coord.x, page.pageHeight * 10), PageLayoutType.VERTICAL, 0, 20) == null)
- .toBe(true);
-
- let progress = skeleton.stepIncrementalLayout(generation, 8);
- for (let i = 0; i < 100 && !progress.complete; i++) {
- progress = skeleton.stepIncrementalLayout(generation, 8);
- }
- expect(progress.complete).toBe(true);
- expect(skeleton.findNodeByCoord(coord, PageLayoutType.VERTICAL, 0, 20)).toBeTruthy();
- skeleton.dispose();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const T = DataStreamTreeTokenType;
+ const paragraph = `${cached ? '\f' : ''}One two three`;
+ const table = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Prefix\r${paragraph}\r\n${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const dataStream = `${table}\r\n`;
+ const snapshot: Partial<IDocumentData> = {
+ id: 'cell-cached-break-widow',
+ body: {
+ dataStream,
+ renderedPageBreaks: cached ? [dataStream.indexOf('\f')] : [],
+ paragraphs: [...dataStream.matchAll(/\r/g)].map((match, index) => ({
+ startIndex: match.index,
+ paragraphId: `p-${index}`,
+ paragraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: 10, snapToGrid: BooleanNumber.FALSE },
+ })),
+ sectionBreaks: [...dataStream.matchAll(/\n/g)].map((match, index) => ({ startIndex: match.index, sectionId: `s-${index}` })),
+ tables: [{ tableId: 'table', startIndex: 0, endIndex: table.length }],
+ },
+ tableSource: { table: {
+ tableId: 'table',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: { positionH: { relativeFrom: ObjectRelativeFromH.PAGE }, positionV: { relativeFrom: ObjectRelativeFromV.PAGE } },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 46 } },
+ cellMargin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } },
+ tableRows: [{ tableCells: [{}], cantSplit: BooleanNumber.FALSE, trHeight: { val: { v: 0 }, hRule: TableRowHeightRule.AUTO } }],
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 46 } } }],
+ } },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 100, height: 50 },
+ marginTop: 10,
+ marginBottom: 10,
+ marginLeft: 10,
+ marginRight: 10,
+ },
+ };
+ try {
+ for (const incremental of [false, true]) {
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(new DocumentDataModel(structuredClone(snapshot))), localeService);
+ try {
+ if (incremental) {
+ completeIncrementalLayout(skeleton);
+ } else {
+ skeleton.calculate();
+ }
+ const paragraphIndex = dataStream.indexOf('\r', dataStream.indexOf('One'));
+ const counts = skeleton.getSkeletonData()!.pages.map((page) => [...page.skeTables.values()]
+ .flatMap((table) => table.rows.flatMap((row) => row.cells))
+ .flatMap((cell) => cell.sections.flatMap((section) => section.columns))
+ .flatMap((column) => column.lines)
+ .filter((line) => line.paragraphIndex === paragraphIndex)
+ .length);
+ expect(counts.filter(Boolean)).toEqual([3]);
+ const caret = skeleton.findNodePositionByCharIndex(dataStream.indexOf('One'))!;
+ expect(caret.page).toBe(1);
+ expect(skeleton.findCharIndexByPosition(caret)).toBe(dataStream.indexOf('One'));
+ } finally {
+ skeleton.dispose();
+ }
+ }
+ } finally {
+ measureSpy.mockRestore();
+ univer.dispose();
+ }
+ });
+
+ it.each([TableRowHeightRule.AUTO, TableRowHeightRule.AT_LEAST].flatMap((hRule) =>
+ [BooleanNumber.FALSE, BooleanNumber.TRUE].flatMap((widowControl) =>
+ [BooleanNumber.FALSE, BooleanNumber.TRUE].flatMap((keepLines) =>
+ [undefined, 12, 14, 15].map((mode) => ({ hRule, widowControl, keepLines, mode }))
+ )
+ )
+ ))('splits a cell according to Word compatibility ($hRule/$widowControl/$keepLines/$mode)', ({ hRule, widowControl, keepLines, mode }) => {
+ const measureSpy = mockCanvasTextMetrics();
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const T = DataStreamTreeTokenType;
+ const rows = [['上', '页'], ['\f投资活动合计', '-57']].map((cells) =>
+ `${T.TABLE_ROW_START}${cells.map((text) => `${T.TABLE_CELL_START}${text}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}`).join('')}${T.TABLE_ROW_END}`
+ ).join('');
+ const table = `${T.TABLE_START}${rows}${T.TABLE_END}`;
+ const dataStream = `${table}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const snapshot: Partial<IDocumentData> = {
+ id: 'split-last-cell-line',
+ body: {
+ dataStream,
+ renderedPageBreaks: [dataStream.indexOf('\f')],
+ paragraphs: [...dataStream.matchAll(/\r/g)].map((match, i) => ({
+ startIndex: match.index!,
+ paragraphId: `p-${i}`,
+ paragraphStyle: { lineSpacing: 20, spacingRule: SpacingRule.EXACT, snapToGrid: BooleanNumber.FALSE, widowControl, keepLines },
+ })),
+ sectionBreaks: [...dataStream.matchAll(/\n/g)].map((match, i) => ({ startIndex: match.index!, sectionId: `s-${i}` })),
+ tables: [{ tableId: 'table', startIndex: 0, endIndex: table.length }],
+ },
+ tableSource: {
+ table: {
+ tableId: 'table',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: { positionH: { relativeFrom: ObjectRelativeFromH.PAGE }, positionV: { relativeFrom: ObjectRelativeFromV.PAGE } },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 104 } },
+ cellMargin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } },
+ tableRows: [95, 18].map((height, row) => ({
+ tableCells: [24, 80].map((width) => ({ size: { type: TableSizeType.SPECIFIED, width: { v: width } } })),
+ cantSplit: BooleanNumber.FALSE,
+ trHeight: { val: { v: height }, hRule: row === 0 ? TableRowHeightRule.EXACT : hRule },
+ })),
+ tableColumns: [24, 80].map((width) => ({ size: { type: TableSizeType.SPECIFIED, width: { v: width } } })),
+ },
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ compatibilitySettings: mode == null ? undefined : { compatibilityMode: String(mode) },
+ pageSize: { width: 160, height: 140 },
+ marginTop: 10,
+ marginBottom: 10,
+ marginLeft: 10,
+ marginRight: 10,
+ },
+ };
+ const synchronous = DocumentSkeleton.create(new DocumentViewModel(new DocumentDataModel(structuredClone(snapshot))), localeService);
+ const incremental = DocumentSkeleton.create(new DocumentViewModel(new DocumentDataModel(structuredClone(snapshot))), localeService);
+ try {
+ synchronous.calculate();
+ completeIncrementalLayout(incremental);
+ const keepWhole = (widowControl || keepLines) && (mode == null || mode >= 15);
+ for (const skeleton of [synchronous, incremental]) {
+ const fragments = skeleton.getSkeletonData()!.pages.flatMap((page) => [...page.skeTables.values()]
+ .flatMap((table) => table.rows.filter((row) => row.index === 1)));
+ expect(fragments).toHaveLength(keepWhole ? 1 : 2);
+ expect(fragments.map((row) => row.height)).toEqual(keepWhole ? [40] : [20, 20]);
+ expect(fragments.map((row) => row.cells.map((cell) => cell.sections.flatMap((section) => section.columns)
+ .flatMap((column) => column.lines)
+ .flatMap((line) => line.divides)
+ .flatMap((divide) => divide.glyphGroup)
+ .map((glyph) => glyph.content)
+ .join(''))))
+ .toEqual(keepWhole ? [['投资活动合计\r', '-57\r']] : [['投资活', '-57\r'], ['动合计\r', '']]);
+ const continuationIndex = dataStream.indexOf('动合计');
+ const caret = skeleton.findNodePositionByCharIndex(continuationIndex)!;
+ expect(caret.page).toBe(1);
+ expect(skeleton.findBodyPageIndexByCharIndex(continuationIndex)).toBe(1);
+ expect(skeleton.findCharIndexByPosition(caret)).toBe(continuationIndex);
+ }
+ expect(normalizeSkeleton(incremental.getSkeletonData()!.pages)).toEqual(normalizeSkeleton(synchronous.getSkeletonData()!.pages));
+ } finally {
+ measureSpy.mockRestore();
+ incremental.dispose();
+ synchronous.dispose();
+ univer.dispose();
+ }
+ });
+
+ it.each([
+ { scrollLeft: 0, leadingInsetLeft: 0 },
+ { scrollLeft: 8, leadingInsetLeft: 4 },
+ ])('hit-tests the first visible table column without counting page padding twice ($scrollLeft/$leadingInsetLeft)', ({ scrollLeft, leadingInsetLeft }) => {
+ const univer = new Univer();
+ const T = DataStreamTreeTokenType;
+ const table = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_CELL_START}Other${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const prefix = `Heading${T.PARAGRAPH}`;
+ const dataStream = `${prefix}${table}Tail${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const model = new DocumentDataModel({
+ id: 'wide-table-hit-test',
+ body: {
+ dataStream,
+ paragraphs: [...dataStream.matchAll(/\r/g)].map((match, index) => ({ startIndex: match.index!, paragraphId: `wide-table-p-${index}` })),
+ sectionBreaks: [...dataStream.matchAll(/\n/g)].map((match, index) => ({ startIndex: match.index!, sectionId: `wide-table-s-${index}` })),
+ tables: [{ tableId: 'table', startIndex: prefix.length, endIndex: prefix.length + table.length }],
+ },
+ tableSource: {
+ table: {
+ tableId: 'table',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: {
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE },
+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE },
+ },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 400 } },
+ tableRows: [{
+ tableCells: [{}, {}],
+ trHeight: { val: { v: 40 }, hRule: TableRowHeightRule.AT_LEAST },
+ }],
+ tableColumns: [0, 1].map(() => ({ size: { type: TableSizeType.SPECIFIED, width: { v: 200 } } })),
+ },
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 600, height: 700 },
+ marginLeft: 96,
+ marginRight: 96,
+ marginTop: 96,
+ marginBottom: 96,
+ },
+ });
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));
+ try {
+ skeleton.calculate();
+ const page = skeleton.getSkeletonData()!.pages[0];
+ const tableSkeleton = [...page.skeTables.values()][0];
+ const cell = tableSkeleton.rows[0].cells[0];
+ const section = cell.sections[0];
+ const column = section.columns[0];
+ const line = column.lines[0];
+ const divide = line.divides[0];
+ const glyph = divide.glyphGroup[0];
+ const x = page.marginLeft + tableSkeleton.left + cell.left + cell.marginLeft + column.left + divide.left + glyph.left + glyph.width / 2;
+ const y = page.marginTop + tableSkeleton.top + cell.marginTop + section.top + line.top + line.lineHeight / 2;
+ expect(skeleton.findNodeByCoord(new Vector2(x, y), PageLayoutType.VERTICAL, 0, 20)?.node === glyph).toBe(true);
+ setDocsTableRenderViewportProvider((unitId, tableId) => unitId === model.getUnitId() && tableId === 'table'
+ ? { contentWidth: tableSkeleton.width, viewportWidth: 200, scrollLeft, leadingInsetLeft }
+ : null);
+ for (const restrictions of [undefined, { strict: false, segmentId: '', segmentPage: -1 }, { strict: true, segmentId: '', segmentPage: -1 }]) {
+ expect(skeleton.findNodeByCoord(new Vector2(x - scrollLeft, y), PageLayoutType.VERTICAL, 0, 20, restrictions)?.node === glyph).toBe(true);
+ }
+ } finally {
+ setDocsTableRenderViewportProvider(null);
+ skeleton.dispose();
+ univer.dispose();
+ }
+ });
+
+ it('rejects a new caret on retained geometry until the edited page is published', () => {
+ const univer = new Univer();
+ const skeleton = DocumentSkeleton.create(
+ new DocumentViewModel(new DocumentDataModel({
+ id: 'unpublished-hit-test',
+ body: { dataStream: 'Hello\r\n', paragraphs: [{ startIndex: 5, paragraphId: 'paragraph' }] },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 300, height: 400 } },
+ })),
+ univer.__getInjector().get(LocaleService)
+ );
+ skeleton.calculate();
+ const page = skeleton.getSkeletonData()!.pages[0];
+ const coord = new Vector2(page.marginLeft + 5, page.marginTop + 5);
+ expect(skeleton.findNodeByCoord(coord, PageLayoutType.VERTICAL, 0, 20)).toBeTruthy();
+ const generation = skeleton.startIncrementalLayout({ reason: 'edit', anchor: 3, reuseUnaffectedTail: false });
+
+ expect(skeleton.findNodeByCoord(coord, PageLayoutType.VERTICAL, 0, 20) == null).toBe(true);
+ expect(skeleton.findNodeByCoord(new Vector2(coord.x, page.pageHeight * 10), PageLayoutType.VERTICAL, 0, 20) == null)
+ .toBe(true);
+
+ let progress = skeleton.stepIncrementalLayout(generation, 8);
+ for (let i = 0; i < 100 && !progress.complete; i++) {
+ progress = skeleton.stepIncrementalLayout(generation, 8);
+ }
+ expect(progress.complete).toBe(true);
+ expect(skeleton.findNodeByCoord(coord, PageLayoutType.VERTICAL, 0, 20)).toBeTruthy();
+ skeleton.dispose();
univer.dispose();
});
@@ -1153,6 +1808,35 @@ describe('doc skeleton', () => {
expect(docViewModel.dispose).toHaveBeenCalled();
});
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('does not count retained geometry as published Worker progress (flavor: %s)', (documentFlavor) => {
+ const univer = new Univer();
+ const model = createDocumentModelWithStyle('Retained paragraph.\r'.repeat(30), {});
+ model.updateDocumentStyle({ documentFlavor });
+ model.updateDocumentDataPageSize(240, 180);
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));
+ skeleton.calculate();
+ const pages = skeleton.getSkeletonData()!.pages;
+ expect(pages.length).toBeGreaterThan(0);
+
+ // A new edit can supersede an external layout before its first publication.
+ for (let edit = 0; edit < 2; edit++) {
+ skeleton.beginExternalLayout({ reason: 'edit' });
+ expect(skeleton.getLayoutProgress()).toMatchObject({
+ complete: false,
+ didPublish: false,
+ processedBlockCount: 0,
+ publishedPageCount: 0,
+ pageCount: pages.length,
+ estimatedPageCount: pages.length,
+ });
+ expect(skeleton.getSkeletonData()!.pages).toBe(pages);
+ }
+
+ skeleton.dispose();
+ model.dispose();
+ univer.dispose();
+ });
+
it('hit-tests imported sections throughout a modern page while Worker layout is pending', () => {
const univer = new Univer();
const content = 'Modern paragraph with an empty paragraph below.\r\r'.repeat(30);
@@ -1401,6 +2085,46 @@ describe('doc skeleton', () => {
]);
});
+ it('restores coordinate state after exact and nearest nested-cell hits', () => {
+ const univer = new Univer();
+ const model = new DocumentDataModel({ id: 'nested-hit-state', body: { dataStream: 'ABC\r\n', paragraphs: [{ startIndex: 3, paragraphId: 'p' }], sectionBreaks: [{ startIndex: 4, sectionId: 's' }] } });
+ const viewModel = new DocumentViewModel(model);
+ const skeleton = DocumentSkeleton.create(viewModel, univer.__getInjector().get(LocaleService));
+ const body = createPage(DocumentSkeletonPageType.BODY, 0);
+ const cell = createPage(DocumentSkeletonPageType.CELL, 0);
+ body.column.lines = [];
+ body.page.pageHeight = 200;
+ cell.page.pageWidth = 80;
+ cell.page.pageHeight = 80;
+ cell.page.left = 15;
+ cell.section.top = 4;
+ cell.column.left = 6;
+ cell.line.top = 7;
+ cell.divide.left = 2;
+ cell.divide.paddingLeft = 3;
+ const row = { top: 10, cells: [cell.page], index: 0 };
+ const table = { tableId: 'nested-hit-table', top: 30, left: 20, width: 100, height: 100, rows: [row] };
+ body.page.skeTables.set(table.tableId, table);
+ const internalSkeleton = skeleton as any;
+ const liquid = internalSkeleton._findLiquid;
+ liquid.translateBy(10, 20);
+ liquid.translateSave();
+ try {
+ for (const [x, y, expected] of [[71, 93, cell.glyphs.glyphA], [79, 125, cell.glyphs.glyphB], [71, 93, cell.glyphs.glyphA]] as const) {
+ const result = internalSkeleton._collectNearestNode(body.page, DocumentSkeletonPageType.BODY, body.page, '', 0, { nearestNodeList: [], nearestNodeDistanceList: [] }, x, y, 1);
+ expect(result?.node).toBe(expected);
+ expect([liquid.x, liquid.y]).toEqual([10, 20]);
+ expect(liquid._translateSaveList).toHaveLength(1);
+ }
+ } finally {
+ liquid.translateRestore();
+ skeleton.dispose();
+ viewModel.dispose();
+ model.dispose();
+ univer.dispose();
+ }
+ });
+
it('resolves char positions inside tables nested in column group columns', () => {
const body = createPage(DocumentSkeletonPageType.BODY, 0);
const columnPage = createPage(DocumentSkeletonPageType.CELL, 100);
@@ -1644,6 +2368,83 @@ describe('doc skeleton', () => {
expect(body.section.columns).toHaveLength(2);
});
+ it.each([
+ { breaks: '', cached: false, firstHeight: 20, drawingPage: 0, pageCount: 1 },
+ { breaks: '\f', cached: false, firstHeight: 20, drawingPage: 0, pageCount: 2 },
+ { breaks: '\f\f', cached: false, firstHeight: 20, drawingPage: 1, pageCount: 3 },
+ { breaks: '\f', cached: false, firstHeight: 20, drawingPage: 1, pageCount: 2, split: true },
+ { breaks: '', cached: false, firstHeight: 135, drawingPage: 1, pageCount: 2 },
+ { breaks: '\f', cached: true, firstHeight: 135, drawingPage: 1, pageCount: 2 },
+ ])('anchors floating drawings to their destination paragraph (%j)', ({ breaks, cached, firstHeight, drawingPage, pageCount, split }) => {
+ const measureSpy = mockCanvasTextMetrics();
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const dataStream = `Before\r${breaks}\b\rAfter\r\n`;
+ const snapshot: Partial<IDocumentData> = {
+ id: 'drawing-after-leading-break',
+ body: {
+ dataStream,
+ paragraphs: [...dataStream.matchAll(/\r/g)].map((match, index) => ({
+ startIndex: match.index,
+ paragraphId: `p-${index}`,
+ paragraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: index === 0 ? firstHeight : 20, snapToGrid: BooleanNumber.FALSE },
+ })),
+ renderedPageBreaks: cached ? [dataStream.indexOf('\f')] : [],
+ sectionBreaks: [{ startIndex: dataStream.length - 1, sectionId: 'drawing-break-section' }],
+ customBlocks: [{ startIndex: dataStream.indexOf('\b'), blockId: 'logo' }],
+ },
+ drawings: {
+ logo: {
+ unitId: 'drawing-after-leading-break',
+ subUnitId: '',
+ drawingId: 'logo',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ docTransform: {
+ size: { width: 20, height: 20 },
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 20 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: -5 },
+ angle: 0,
+ },
+ },
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ splitPageBreakAndParagraphMark: split ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ pageSize: { width: 200, height: 180 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ };
+ try {
+ for (const incremental of [false, true]) {
+ const model = new DocumentDataModel(structuredClone(snapshot));
+ const before = structuredClone(model.getSnapshot());
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), localeService);
+ try {
+ if (incremental) {
+ completeIncrementalLayout(skeleton);
+ } else {
+ skeleton.calculate();
+ }
+ const pages = skeleton.getSkeletonData()!.pages;
+ expect(pages).toHaveLength(pageCount);
+ expect(pages.flatMap((page) => [...page.skeDrawings.keys()])).toEqual(['logo']);
+ const drawing = pages[drawingPage].skeDrawings.get('logo')!;
+ expect(drawing.aTop).toBeCloseTo(drawingPage > 0 ? -5 : 15);
+ expect(model.getSnapshot()).toEqual(before);
+ } finally {
+ skeleton.dispose();
+ }
+ }
+ } finally {
+ measureSpy.mockRestore();
+ univer.dispose();
+ }
+ });
+
it('DOCX golden e2e keeps anchored drawings and continuous columns on stable physical pages', () => {
const firstTitleParagraph = `First title${DataStreamTreeTokenType.PARAGRAPH}`;
const secondTitleParagraph = `Second title${DataStreamTreeTokenType.PARAGRAPH}`;
@@ -2462,11 +3263,7 @@ describe('doc skeleton', () => {
});
it.each([false, true])('reuses a table page tail for offset-preserving metadata edits (placeholder tail: %s)', (placeholderTail) => {
- const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
- width: text.length * 8,
- fontBoundingBoxAscent: 8,
- fontBoundingBoxDescent: 2,
- }) as TextMetrics);
+ const measureSpy = mockCanvasTextMetrics();
const univer = new Univer();
const localeService = univer.__getInjector().get(LocaleService);
const T = DataStreamTreeTokenType;
@@ -3143,13 +3940,7 @@ describe('doc skeleton', () => {
{ paragraphCount: 300, anchorPageIndex: 2, firstParagraph: false, horizontalAlign: HorizontalAlign.LEFT },
{ paragraphCount: 20, anchorPageIndex: 0, firstParagraph: true, horizontalAlign: HorizontalAlign.CENTER },
])('reuses a geometrically stable page tail after a Worker interaction edit ($paragraphCount paragraphs, page $anchorPageIndex, first: $firstParagraph, alignment: $horizontalAlign)', ({ paragraphCount, anchorPageIndex, firstParagraph, horizontalAlign }) => {
- const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
- width: text.length * 8,
- fontBoundingBoxAscent: 8,
- fontBoundingBoxDescent: 2,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
- }));
+ const measureSpy = mockCanvasTextMetrics();
const univer = new Univer();
const localeService = univer.__getInjector().get(LocaleService);
const content = Array.from(
@@ -3624,24 +4415,829 @@ describe('doc skeleton', () => {
const outerCell = outerSkeleton?.rows[0]?.cells[0];
expect(outerCell?.skeTables.has('inner')).toBe(true);
expect(outerCell?.skeTables.get('inner')?.rows[0]?.cells[0]?.sections[0]?.columns[0]?.lines.length).toBeGreaterThan(0);
+ const outerCellLines = outerCell!.sections[0].columns[0].lines;
+ const innerAnchorLine = outerCellLines.find((line) => line.paragraphIndex === innerStart + inner.length);
+ const innerSkeleton = outerCell!.skeTables.get('inner')!;
+ expect(innerAnchorLine?.lineHeight).toBe(0);
+ expect(innerAnchorLine?.top).toBeCloseTo(innerSkeleton.top + innerSkeleton.height);
+ expect(outerCellLines.filter((line) => line !== innerAnchorLine).every((line) => line.lineHeight > 0)).toBe(true);
skeleton.dispose();
univer.dispose();
measureSpy.mockRestore();
});
- it('DOCX golden e2e honors a rendered page break inside a traditional table cell', () => {
- const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
- width: text.length * 8,
- fontBoundingBoxAscent: 8,
- fontBoundingBoxDescent: 2,
- }) as any);
+ it.each([false, true])('sizes an inline-picture cell independently of its large paragraph mark (incremental=%s)', (incremental) => {
+ mockCanvasTextMetrics();
const T = DataStreamTreeTokenType;
- const cell = `Before${T.PARAGRAPH}${T.PAGE_BREAK}After${T.PARAGRAPH}${T.SECTION_BREAK}`;
- const table = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${cell}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
- const dataStream = `${table}${T.PARAGRAPH}${T.SECTION_BREAK}`;
- const documentModel = new DocumentDataModel({
- id: 'rendered-page-break-in-table-cell',
+ const tableStream = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${T.CUSTOM_BLOCK}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const dataStream = `${tableStream}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const model = new DocumentDataModel({
+ id: 'picture-cell-mark-metrics',
+ body: {
+ dataStream,
+ textRuns: [{ st: 3, ed: 4, ts: { fs: 10.5 } }, { st: 4, ed: 5, ts: { fs: 72 } }],
+ customBlocks: [{ startIndex: 3, blockId: 'picture' }],
+ paragraphs: [{
+ startIndex: 4,
+ paragraphId: 'picture-paragraph',
+ paragraphStyle: {
+ snapToGrid: BooleanNumber.FALSE,
+ spacingRule: SpacingRule.AT_LEAST,
+ lineSpacing: 16,
+ spaceAbove: { v: 10.4 },
+ spaceBelow: { v: 10.4 },
+ },
+ }],
+ tables: [{ tableId: 'table', startIndex: 0, endIndex: tableStream.length }],
+ sectionBreaks: [{ sectionId: 'cell', startIndex: 5 }, { sectionId: 'body', startIndex: dataStream.length - 1 }],
+ },
+ drawings: {
+ picture: {
+ drawingId: 'picture',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ unitId: 'picture-cell-mark-metrics',
+ subUnitId: 'picture-cell-mark-metrics',
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ angle: 0,
+ size: { width: 216, height: 54 },
+ positionH: { relativeFrom: ObjectRelativeFromH.COLUMN, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ },
+ },
+ },
+ tableSource: {
+ table: {
+ tableId: 'table',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: {
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 0 },
+ },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 240 } },
+ tableRows: [{
+ tableCells: [{ margin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } } }],
+ trHeight: { val: { v: 0 }, hRule: TableRowHeightRule.AT_LEAST },
+ }],
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 240 } } }],
+ },
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 320, height: 400 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ });
+ const univer = new Univer();
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));
+ if (incremental) {
+ completeIncrementalLayout(skeleton);
+ } else {
+ skeleton.calculate();
+ }
+ const row = skeleton.getSkeletonData()!.pages[0].skeTables.get('table')!.rows[0];
+ const cell = row.cells[0];
+ expect(row.height).toBeCloseTo(74.8, 6);
+ expect(cell.pageHeight).toBeCloseTo(row.height, 6);
+ expect(cell.skeDrawings.get('picture')!.aTop).toBeCloseTo(10.4, 6);
+ expect(cell.sections[0].columns[0].lines[0].asc).toBe(54);
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it.each([false, true].flatMap((incremental) =>
+ [SpacingRule.AUTO, SpacingRule.AT_LEAST, SpacingRule.EXACT].flatMap((spacingRule) =>
+ [1, 2].map((paragraphCount) => ({ incremental, spacingRule, paragraphCount })))
+ ))('preserves explicit blank-cell line height above the row minimum: %j', ({ incremental, spacingRule, paragraphCount }) => {
+ const measureSpy = mockCanvasTextMetrics();
+ const T = DataStreamTreeTokenType;
+ const tableStream = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${T.PARAGRAPH.repeat(paragraphCount)}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const dataStream = `${tableStream}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const minimum = 29 / 15;
+ const lineHeight = 200 / 15;
+ const documentModel = new DocumentDataModel({
+ id: 'blank-cell-line-height',
+ body: {
+ dataStream,
+ paragraphs: Array.from({ length: paragraphCount }, (_, index) => ({
+ startIndex: tableStream.indexOf(T.PARAGRAPH) + index,
+ paragraphId: `spacer-${index}`,
+ paragraphStyle: {
+ paragraphFrame: {},
+ spacingRule,
+ lineSpacing: spacingRule === SpacingRule.AUTO ? 1 : lineHeight,
+ },
+ })),
+ tables: [{ tableId: 'table', startIndex: 0, endIndex: tableStream.length }],
+ sectionBreaks: [
+ { sectionId: 'cell', startIndex: tableStream.indexOf(T.SECTION_BREAK) },
+ { sectionId: 'body', startIndex: dataStream.length - 1 },
+ ],
+ },
+ tableSource: {
+ table: {
+ tableId: 'table',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: {
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 0 },
+ },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 100 } },
+ tableRows: [{
+ tableCells: [{ margin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } } }],
+ trHeight: { val: { v: minimum }, hRule: TableRowHeightRule.AT_LEAST },
+ }],
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 100 } } }],
+ },
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 320, height: 400 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ });
+ const univer = new Univer();
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), univer.__getInjector().get(LocaleService));
+ if (incremental) {
+ completeIncrementalLayout(skeleton);
+ } else {
+ skeleton.calculate();
+ }
+ const row = skeleton.getSkeletonData()!.pages[0].skeTables.get('table')!.rows[0];
+ if (spacingRule === SpacingRule.AUTO && paragraphCount === 1) {
+ expect(row.height).toBeCloseTo(minimum);
+ } else {
+ if (spacingRule === SpacingRule.AUTO) {
+ expect(row.height).toBeGreaterThan(minimum);
+ expect(row.cells[0].sections.flatMap((section) => section.columns.flatMap((column) => column.lines))).toHaveLength(paragraphCount);
+ } else {
+ expect(row.height).toBeGreaterThanOrEqual(lineHeight * paragraphCount);
+ }
+ expect(row.cells[0].pageHeight).toBeCloseTo(row.height);
+ }
+ skeleton.dispose();
+ univer.dispose();
+ measureSpy.mockRestore();
+ });
+
+ it.each(['', 'Following paragraph', '\rFollowing paragraph'].flatMap((followingText) =>
+ [TableRowHeightRule.EXACT, TableRowHeightRule.AT_LEAST].flatMap((hRule) =>
+ [false, true].flatMap((incremental) =>
+ [false, true].map((continuation) => ({ followingText, hRule, incremental, continuation }))
+ )
+ )
+ ))(
+ 'keeps full-page floating tables intact and places following content on the next page: %j',
+ ({ followingText, hRule, incremental, continuation }) => {
+ const T = DataStreamTreeTokenType;
+ const rowStream = `${T.TABLE_ROW_START}${T.TABLE_CELL_START}Full page${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}`;
+ const rowHeights = continuation ? [400, 40] : [400];
+ const tableStream = `${T.TABLE_START}${rowStream.repeat(rowHeights.length)}${T.TABLE_END}`;
+ const dataStream = `${tableStream}${T.PARAGRAPH}${followingText}${followingText ? T.PARAGRAPH : ''}${T.SECTION_BREAK}`;
+ const documentModel = new DocumentDataModel({
+ id: 'page-anchored-floating-table',
+ body: {
+ dataStream,
+ paragraphs: rowHeights.map((_, index) => ({
+ startIndex: 1 + index * rowStream.length + rowStream.indexOf(T.PARAGRAPH),
+ paragraphId: `cell-${index}`,
+ })),
+ tables: [{ tableId: 'table', startIndex: 0, endIndex: tableStream.length }],
+ sectionBreaks: [
+ ...rowHeights.map((_, index) => ({
+ sectionId: `cell-${index}`,
+ startIndex: 1 + index * rowStream.length + rowStream.indexOf(T.SECTION_BREAK),
+ })),
+ { sectionId: 'body', startIndex: dataStream.length - 1 },
+ ],
+ },
+ tableSource: {
+ table: {
+ tableId: 'table',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.WRAP,
+ overlap: BooleanNumber.FALSE,
+ position: {
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 0 },
+ },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 320 } },
+ tableRows: rowHeights.map((height) => ({
+ tableCells: [
+ { size: { type: TableSizeType.SPECIFIED, width: { v: 320 } } },
+ ],
+ trHeight: { val: { v: height }, hRule },
+ })),
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 320 } } }],
+ },
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 320, height: 400 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ });
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+
+ if (incremental) {
+ completeIncrementalLayout(skeleton);
+ } else {
+ skeleton.calculate();
+ }
+
+ const pages = skeleton.getSkeletonData()?.pages ?? [];
+ expect(pages).toHaveLength(followingText || continuation ? 2 : 1);
+ expect([...pages[0]!.skeTables.values()]).toHaveLength(1);
+ expect([...pages[0]!.skeTables.values()][0]!.height).toBe(400);
+ expect([...pages[0]!.skeTables.values()][0]!.left).toBe(-20);
+ if (continuation) {
+ expect([...pages[1]!.skeTables.values()][0]!.height).toBe(40);
+ }
+ if (followingText) {
+ const text = pages[1]!.sections.flatMap((section) => section.columns.flatMap((column) =>
+ column.lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content)))
+ )).join('');
+ expect(text).toContain('Following paragraph');
+ }
+
+ skeleton.dispose();
+ univer.dispose();
+ }
+ );
+
+ it.each([false, true].flatMap((incremental) => [
+ { incremental, contextual: true, spaceBefore: 0, lastSpace: 0, height: 40, textTops: [0, 20], borderWidth: 0, padding: 0 },
+ { incremental, contextual: false, spaceBefore: 0, lastSpace: 12, height: 64, textTops: [0, 32], borderWidth: 0, padding: 0 },
+ { incremental, contextual: true, spaceBefore: 0, lastSpace: 12, height: 52, textTops: [0, 20], borderWidth: 0, padding: 0 },
+ { incremental, contextual: true, spaceBefore: 8, lastSpace: 12, height: 60, textTops: [8, 28], borderWidth: 0, padding: 0 },
+ { incremental, contextual: true, spaceBefore: 0, lastSpace: 0, height: 40, textTops: [0, 20], borderWidth: 4, padding: 0 },
+ { incremental, contextual: true, spaceBefore: 0, lastSpace: 0, height: 40, textTops: [0, 20], borderWidth: 4, padding: 8 },
+ { incremental, contextual: true, spaceBefore: 0, lastSpace: 0, height: 40, textTops: [0, 20], borderWidth: 4, padding: null },
+ ].flatMap((testCase) => (testCase.borderWidth === 4 && testCase.padding === 0 ? [600, 60] : [600])
+ .map((pageHeight) => ({ ...testCase, pageHeight })))))('matches Word cell paragraph spacing (incremental: $incremental, contextual: $contextual, before: $spaceBefore, after: $lastSpace, border: $borderWidth, padding: $padding, page: $pageHeight)', ({ incremental, contextual, spaceBefore, lastSpace, height, textTops, borderWidth, padding, pageHeight }) => {
+ // Protobuf JSON omits numeric zero values in imported margin units.
+ const verticalPadding = padding === null ? JSON.parse('{}') : { v: padding };
+ const T = DataStreamTreeTokenType;
+ const cellStream = `${T.TABLE_CELL_START}A${T.PARAGRAPH}B${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}`;
+ const rowStream = `${T.TABLE_ROW_START}${cellStream}${T.TABLE_ROW_END}`;
+ const tableStream = `${T.TABLE_START}${rowStream}${rowStream}${T.TABLE_END}`;
+ const dataStream = `${tableStream}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const univer = new Univer();
+ const model = new DocumentDataModel({
+ id: 'contextual-table-spacing',
+ body: {
+ dataStream,
+ paragraphs: Array.from(dataStream).flatMap((token, startIndex) => token === T.PARAGRAPH
+ ? [{
+ startIndex,
+ paragraphId: `p-${startIndex}`,
+ styleId: 'List',
+ paragraphStyle: {
+ spacingRule: SpacingRule.EXACT,
+ lineSpacing: 20,
+ contextualSpacing: contextual ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ spaceAbove: { v: spaceBefore },
+ spaceBelow: { v: dataStream[startIndex - 1] === 'A' ? 12 : lastSpace },
+ },
+ }]
+ : []),
+ sectionBreaks: Array.from(dataStream).flatMap((token, startIndex) => token === T.SECTION_BREAK
+ ? [{
+ startIndex,
+ sectionId: `s-${startIndex}`,
+ }]
+ : []),
+ tables: [{ tableId: 'list-table', startIndex: 0, endIndex: tableStream.length }],
+ },
+ tableSource: {
+ 'list-table': {
+ tableId: 'list-table',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: { positionH: { relativeFrom: ObjectRelativeFromH.PAGE }, positionV: { relativeFrom: ObjectRelativeFromV.PAGE } },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 200 } } }],
+ tableRows: [0, 1].map(() => ({
+ tableCells: [{
+ borderTop: { width: { v: borderWidth }, color: { rgb: '#000000' } },
+ borderBottom: { width: { v: borderWidth }, color: { rgb: '#000000' } },
+ }],
+ trHeight: { val: { v: 0 }, hRule: TableRowHeightRule.AUTO },
+ })),
+ size: { type: TableSizeType.SPECIFIED, width: { v: 200 } },
+ cellMargin: { top: verticalPadding, bottom: verticalPadding, start: { v: 0 }, end: { v: 0 } },
+ },
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 400, height: pageHeight },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ },
+ });
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));
+ try {
+ if (incremental) {
+ completeIncrementalLayout(skeleton);
+ } else {
+ skeleton.calculate();
+ }
+ const tables = skeleton.getSkeletonData()!.pages.flatMap((page) => [...page.skeTables.values()]);
+ const rowHeight = height + borderWidth + (padding ?? 0) * 2;
+ expect(tables.map((table) => ({ height: table.height, rows: table.rows.map((row) => ({ index: row.index, height: row.height })) })))
+ .toEqual(pageHeight === 60
+ ? [0, 1].map((index) => ({ height: rowHeight + borderWidth, rows: [{ index, height: rowHeight }] }))
+ : [{ height: rowHeight * 2 + borderWidth, rows: [0, 1].map((index) => ({ index, height: rowHeight })) }]);
+ for (const table of tables) {
+ // Word reserves the outer halves outside the first/last row centreline.
+ expect(table.height).toBe(rowHeight * table.rows.length + borderWidth);
+ expect(table.height).toBeLessThanOrEqual(pageHeight);
+ expect(table.rows.map((row) => row.top)).toEqual(table.rows.map((_, index) => borderWidth / 2 + rowHeight * index));
+ }
+ expect(tables.flatMap((table) => table.rows.map((row) => row.index))).toEqual([0, 1]);
+ for (const row of tables.flatMap((table) => table.rows)) {
+ expect(row.height).toBe(rowHeight);
+ const cell = row.cells[0];
+ expect(cell.height).toBe(height);
+ expect(cell.marginTop).toBe((padding ?? 0) + borderWidth / 2);
+ expect(cell.marginBottom).toBe((padding ?? 0) + borderWidth / 2);
+ const lines = cell.sections[0].columns[0].lines;
+ expect(lines.map((line) => line.top + line.marginTop)).toEqual(textTops);
+ expect(lines.map((line) => line.spaceBelowApply)).toEqual([contextual ? 0 : 12, lastSpace]);
+ }
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+ });
+
+ it.each([
+ { top: 3, bottom: 3, padding: 0, pageHeight: 200, insets: [[1.5, 1.5], [1.5, 1.5]] },
+ { top: 3, bottom: 3, padding: 0, pageHeight: 80, insets: [[1.5, 1.5], [1.5, 1.5]] },
+ { top: 3, bottom: 1, padding: 0, pageHeight: 200, insets: [[1.5, 1.5], [1.5, 0.5]] },
+ { top: 1, bottom: 3, padding: 0, pageHeight: 200, insets: [[0.5, 1.5], [1.5, 1.5]] },
+ { top: 1, bottom: 1, padding: 10, pageHeight: 200, insets: [[10.5, 10.5], [10.5, 10.5]] },
+ { top: 3, bottom: 3, padding: 10, pageHeight: 200, insets: [[11.5, 11.5], [11.5, 11.5]] },
+ ].flatMap((testCase) => [0, 70].map((minimum) => ({ ...testCase, minimum }))))('aligns mixed-border cells to Word row insets ($top/$bottom/$padding/$pageHeight/$minimum)', ({ top, bottom, padding, pageHeight, insets, minimum }) => {
+ mockCanvasTextMetrics();
+ const T = DataStreamTreeTokenType;
+ const rows = [['A\rB\rC', 'X'], ['D\rE', 'X']];
+ const stream = `${T.TABLE_START}${rows.map((row) => `${T.TABLE_ROW_START}${row.map((text) => `${T.TABLE_CELL_START}${text}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}`).join('')}${T.TABLE_ROW_END}`).join('')}${T.TABLE_END}`;
+ const dataStream = `${stream}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ for (const documentFlavor of [DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN]) {
+ for (const incremental of [false, true]) {
+ const univer = new Univer();
+ const model = new DocumentDataModel({
+ id: 'mixed-row-insets',
+ documentStyle: {
+ documentFlavor,
+ paragraphLineGapDefault: 0,
+ pageSize: { width: 500, height: pageHeight },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ },
+ body: {
+ dataStream,
+ paragraphs: Array.from(dataStream).flatMap((token, startIndex) => token === T.PARAGRAPH
+ ? [{
+ startIndex,
+ paragraphId: `p-${startIndex}`,
+ paragraphStyle: {
+ spacingRule: SpacingRule.EXACT,
+ lineSpacing: 20,
+ snapToGrid: BooleanNumber.FALSE,
+ spaceAbove: { v: 0 },
+ spaceBelow: { v: 0 },
+ },
+ }]
+ : []),
+ sectionBreaks: Array.from(dataStream).flatMap((token, startIndex) => token === T.SECTION_BREAK ? [{ startIndex, sectionId: `s-${startIndex}` }] : []),
+ tables: [{ tableId: 'mixed', startIndex: 0, endIndex: stream.length }],
+ },
+ tableSource: {
+ mixed: {
+ tableId: 'mixed',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: { positionH: { relativeFrom: ObjectRelativeFromH.PAGE }, positionV: { relativeFrom: ObjectRelativeFromV.PAGE } },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 400 } },
+ tableColumns: [0, 1].map(() => ({ size: { type: TableSizeType.SPECIFIED, width: { v: 200 } } })),
+ cellMargin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } },
+ tableRows: rows.map(() => ({
+ cantSplit: BooleanNumber.TRUE,
+ trHeight: {
+ val: { v: minimum },
+ hRule: minimum > 0 ? TableRowHeightRule.AT_LEAST : TableRowHeightRule.AUTO,
+ },
+ tableCells: [0, 1].map((col) => ({
+ borderTop: { width: { v: col === 0 ? 1 : top }, color: { rgb: '#000000' } },
+ borderBottom: { width: { v: col === 0 ? 1 : bottom }, color: { rgb: '#000000' } },
+ margin: { top: { v: col === 0 ? 0 : padding }, bottom: { v: col === 0 ? 0 : padding }, start: { v: 0 }, end: { v: 0 } },
+ })),
+ })),
+ },
+ },
+ });
+ const before = JSON.stringify(model.getSnapshot());
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));
+ try {
+ if (incremental) {
+ completeIncrementalLayout(skeleton);
+ } else {
+ skeleton.calculate();
+ }
+ const tables = skeleton.getSkeletonData()!.pages.flatMap((page) => [...page.skeTables.values()]);
+ const actualRows = tables.flatMap((table) => table.rows);
+ expect(actualRows.map((row) => row.index)).toEqual([0, 1]);
+ for (const row of actualRows) {
+ const traditional = documentFlavor === DocumentFlavor.TRADITIONAL;
+ const [above, below] = traditional ? insets[row.index] : [0, 0];
+ const contentHeight = (row.index === 0 ? 60 : 40) + above + below;
+ const minimumHeight = minimum + (traditional ? above + below - padding * 2 : 0);
+ expect(row.height).toBe(Math.max(contentHeight, minimumHeight));
+ for (const [col, cell] of row.cells.entries()) {
+ expect(cell.pageHeight).toBe(row.height);
+ const ownPadding = col === 0 ? 0 : padding;
+ expect(cell.marginTop).toBe(traditional ? above : ownPadding);
+ expect(cell.marginBottom).toBe(traditional ? below : ownPadding);
+ }
+ }
+ expect(JSON.stringify(model.getSnapshot())).toBe(before);
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+ }
+ }
+ });
+
+ it.each([false, true].flatMap((incremental) => [
+ ...[0, 40, 50, 80].map((minimum) => ({ incremental, minimum, repeatHeader: false, lineCount: 4 })),
+ ...[4, 8].map((lineCount) => ({ incremental, minimum: 0, repeatHeader: true, lineCount })),
+ ]))('reserves row minimum and continuation headers when splitting ($incremental/$minimum/$repeatHeader/$lineCount)', ({ incremental, minimum, repeatHeader, lineCount }) => {
+ mockCanvasTextMetrics();
+ const T = DataStreamTreeTokenType;
+ const rows = ['Before\r', Array.from({ length: lineCount }, (_, index) => `Line ${index + 1}\r`).join('')];
+ const stream = `${T.TABLE_START}${rows.map((text) => `${T.TABLE_ROW_START}${T.TABLE_CELL_START}${text}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}`).join('')}${T.TABLE_END}`;
+ const dataStream = `${stream}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const univer = new Univer();
+ const model = new DocumentDataModel({
+ id: 'row-start-minimum',
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 300, height: 60 },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ paragraphLineGapDefault: 0,
+ },
+ body: {
+ dataStream,
+ paragraphs: Array.from(dataStream).flatMap((token, startIndex) => token === T.PARAGRAPH
+ ? [{ startIndex, paragraphId: `p-${startIndex}`, paragraphStyle: {
+ lineSpacing: 20,
+ spacingRule: SpacingRule.EXACT,
+ widowControl: BooleanNumber.FALSE,
+ spaceAbove: { v: 0 },
+ spaceBelow: { v: 0 },
+ } }]
+ : []),
+ sectionBreaks: Array.from(dataStream).flatMap((token, startIndex) => token === T.SECTION_BREAK ? [{ startIndex, sectionId: `s-${startIndex}` }] : []),
+ tables: [{ tableId: 'minimum', startIndex: 0, endIndex: stream.length }],
+ },
+ tableSource: {
+ minimum: {
+ tableId: 'minimum',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: { positionH: { relativeFrom: ObjectRelativeFromH.PAGE }, positionV: { relativeFrom: ObjectRelativeFromV.PAGE } },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 200 } },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 200 } } }],
+ cellMargin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } },
+ tableRows: rows.map((_, index) => ({
+ cantSplit: BooleanNumber.FALSE,
+ repeatHeaderRow: repeatHeader && index === 0 ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ tableCells: [{}],
+ trHeight: { val: { v: index === 0 ? 0 : minimum }, hRule: TableRowHeightRule.AT_LEAST },
+ })),
+ },
+ },
+ });
+ const before = JSON.stringify(model.getSnapshot());
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));
+ try {
+ if (incremental) {
+ completeIncrementalLayout(skeleton);
+ } else {
+ skeleton.calculate();
+ }
+ const fragments = skeleton.getSkeletonData()!.pages.flatMap((page, pageIndex) => [...page.skeTables.values()]
+ .flatMap((table) => table.rows.filter((row) => row.index === 1).map((row) => ({ page: pageIndex, height: row.height }))));
+ if (repeatHeader) {
+ expect(fragments).toEqual(Array.from({ length: lineCount / 2 }, (_, page) => ({ page, height: 40 })));
+ const tables = skeleton.getSkeletonData()!.pages.flatMap((page) => [...page.skeTables.values()]);
+ expect(tables).toHaveLength(lineCount / 2);
+ for (const [index, table] of tables.entries()) {
+ expect(table.rows.map((row) => row.index)).toEqual([0, 1]);
+ expect(table.height).toBe(60);
+ if (index > 0) {
+ expect(table.rows[0].isRepeatRow).toBe(true);
+ }
+ }
+ const cellText = tables.flatMap((table) => table.rows[1].cells.flatMap((cell) => cell.sections.flatMap((section) => section.columns.flatMap((column) => column.lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content))))))).join('');
+ expect(cellText).toBe(rows[1]);
+ } else {
+ expect(fragments).toEqual(minimum === 50
+ ? [{ page: 1, height: 60 }, { page: 2, height: 50 }]
+ : [{ page: 0, height: 40 }, { page: 1, height: Math.min(60, Math.max(40, minimum)) }]);
+ }
+ expect(JSON.stringify(model.getSnapshot())).toBe(before);
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+ });
+
+ it('keeps multi-column table hit-testing and logical caret indices aligned', () => {
+ const T = DataStreamTreeTokenType;
+ const texts = [['East', 'Name', '123456789', '[email protected]'], ['Bank', 'Other', '987654321', '[email protected]']];
+ const stream = `${T.TABLE_START}${texts.map((row) => `${T.TABLE_ROW_START}${row.map((text) => `${T.TABLE_CELL_START}${text}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}`).join('')}${T.TABLE_ROW_END}`).join('')}${T.TABLE_END}`;
+ const dataStream = `${stream}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const widths = [113.4, 94.46666666666664, 151.2, 300.2];
+ const univer = new Univer();
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(new DocumentDataModel({
+ id: 'multi-column-table-caret',
+ body: {
+ dataStream,
+ paragraphs: Array.from(dataStream).flatMap((token, startIndex) => token === T.PARAGRAPH ? [{ startIndex, paragraphId: `p-${startIndex}`, paragraphStyle: { lineSpacing: 16, spacingRule: SpacingRule.EXACT } }] : []),
+ sectionBreaks: Array.from(dataStream).flatMap((token, startIndex) => token === T.SECTION_BREAK ? [{ startIndex, sectionId: `s-${startIndex}` }] : []),
+ tables: [{ tableId: 'contacts', startIndex: 0, endIndex: stream.length }],
+ },
+ tableSource: {
+ contacts: {
+ tableId: 'contacts',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: { positionH: { relativeFrom: ObjectRelativeFromH.PAGE }, positionV: { relativeFrom: ObjectRelativeFromV.PAGE } },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: widths.reduce((sum, width) => sum + width, 0) } },
+ cellMargin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 7.2 }, end: { v: 7.2 } },
+ tableColumns: widths.map((width) => ({ size: { type: TableSizeType.SPECIFIED, width: { v: width } } })),
+ tableRows: texts.map((row) => ({ tableCells: row.map(() => ({})), trHeight: { val: { v: 16 }, hRule: TableRowHeightRule.EXACT } })),
+ },
+ },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 794, height: 1123 }, marginLeft: 53, marginRight: 53, marginTop: 87, marginBottom: 73 },
+ })), univer.__getInjector().get(LocaleService));
+ try {
+ skeleton.calculate();
+ const page = skeleton.getSkeletonData()!.pages[0];
+ const table = page.skeTables.get('contacts')!;
+ for (const [rowIndex, row] of table.rows.entries()) {
+ for (const [columnIndex, cell] of row.cells.entries()) {
+ const section = cell.sections[0];
+ const column = section.columns[0];
+ const line = column.lines[0];
+ const divide = line.divides[0];
+ const glyph = divide.glyphGroup[1];
+ const x = page.marginLeft + table.left + cell.left + cell.marginLeft + column.left + divide.left + divide.paddingLeft + glyph.left + glyph.width / 4;
+ const y = page.marginTop + table.top + row.top + cell.marginTop + section.top + line.top + line.lineHeight / 2;
+ const hit = skeleton.findNodeByCoord(new Vector2(x, y), PageLayoutType.VERTICAL, 0, 0);
+ expect(hit?.node === glyph, `cell ${rowIndex},${columnIndex}`).toBe(true);
+ const position = skeleton.findPositionByGlyph(hit!.node, hit!.segmentPage)!;
+ expect(skeleton.findCharIndexByPosition({ ...position, isBack: true })).toBe(dataStream.indexOf(texts[rowIndex][columnIndex]) + 1);
+ }
+ }
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+ });
+
+ it.each([0, 30])('places the caret in the topmost overlapping table, including its blank padding (%i)', (frontPadding) => {
+ const T = DataStreamTreeTokenType;
+ const streams = ['Bottom', 'Front'].map((text) => `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${text}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`);
+ const frontStart = streams[0].length + 1;
+ const dataStream = `${streams[0]}${T.PARAGRAPH}${streams[1]}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const model = new DocumentDataModel({
+ id: 'overlapping-table-caret',
+ body: {
+ dataStream,
+ paragraphs: Array.from(dataStream).flatMap((token, startIndex) => token === T.PARAGRAPH ? [{ startIndex, paragraphId: `p-${startIndex}` }] : []),
+ sectionBreaks: Array.from(dataStream).flatMap((token, startIndex) => token === T.SECTION_BREAK ? [{ startIndex, sectionId: `s-${startIndex}` }] : []),
+ tables: [{ tableId: 'bottom', startIndex: 0, endIndex: streams[0].length }, { tableId: 'front', startIndex: frontStart, endIndex: frontStart + streams[1].length }],
+ },
+ tableSource: Object.fromEntries(['bottom', 'front'].map((tableId) => [tableId, {
+ tableId,
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.WRAP,
+ overlap: BooleanNumber.TRUE,
+ position: { positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 40 }, positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 80 } },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 150 } },
+ cellMargin: { top: { v: tableId === 'front' ? frontPadding : 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 150 } } }],
+ tableRows: [{ tableCells: [{}], trHeight: { val: { v: 80 }, hRule: TableRowHeightRule.EXACT } }],
+ }])),
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 300, height: 400 }, marginLeft: 20, marginRight: 20, marginTop: 20, marginBottom: 20 },
+ });
+ const univer = new Univer();
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));
+ try {
+ skeleton.calculate();
+ const page = skeleton.getSkeletonData()!.pages[0];
+ const bottom = page.skeTables.get('bottom')!;
+ const front = page.skeTables.get('front')!;
+ expect(front).toMatchObject({ left: bottom.left, top: bottom.top });
+ const cell = bottom.rows[0].cells[0];
+ const line = cell.sections[0].columns[0].lines[0];
+ const divide = line.divides[0];
+ const glyph = divide.glyphGroup.find((item) => item.content === 'B')!;
+ const x = page.marginLeft + bottom.left + cell.left + cell.marginLeft + divide.left + divide.paddingLeft + glyph.left + glyph.width / 2;
+ const y = page.marginTop + bottom.top + bottom.rows[0].top + cell.marginTop + line.top + line.lineHeight / 2;
+ const hit = skeleton.findNodeByCoord(new Vector2(x, y), PageLayoutType.VERTICAL, 0, 0);
+ const frontGlyphs = front.rows[0].cells[0].sections.flatMap((section) => section.columns.flatMap((column) => column.lines.flatMap((item) => item.divides.flatMap((part) => part.glyphGroup))));
+ expect(frontGlyphs).toContain(hit?.node);
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+ });
+
+ it('lays out and hit-tests vertical cell text without changing its stream or physical table width', () => {
+ const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
+ width: text.length * 12,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 3,
+ }) as any);
+ const T = DataStreamTreeTokenType;
+ const text = '上市公司';
+ const tableText = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${text}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const dataStream = `${tableText}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const model = new DocumentDataModel({
+ id: 'vertical-cell',
+ body: {
+ dataStream,
+ paragraphs: [{ startIndex: dataStream.indexOf(T.PARAGRAPH), paragraphId: 'vertical-cell-paragraph', paragraphStyle: { indentFirstLine: { v: 18 } } }],
+ tables: [{ tableId: 'vertical', startIndex: 0, endIndex: tableText.length }],
+ sectionBreaks: [
+ { startIndex: dataStream.indexOf(T.SECTION_BREAK), sectionId: 'cell' },
+ { startIndex: dataStream.length - 1, sectionId: 'body' },
+ ],
+ },
+ tableSource: {
+ vertical: {
+ tableId: 'vertical',
+ align: 0,
+ indent: { v: 0 },
+ textWrap: 0,
+ position: { positionH: { relativeFrom: 0 }, positionV: { relativeFrom: 0 } },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 40 } },
+ cellMargin: { start: { v: 3 }, end: { v: 4 }, top: { v: 5 }, bottom: { v: 6 } },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 40 } } }],
+ tableRows: [{
+ tableCells: [{ textDirection: 'tbRlV' }],
+ trHeight: { val: { v: 120 }, hRule: TableRowHeightRule.EXACT },
+ }],
+ },
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 300, height: 400 },
+ marginLeft: 20,
+ marginRight: 20,
+ marginTop: 20,
+ marginBottom: 20,
+ },
+ });
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), localeService);
+ skeleton.calculate();
+ const page = skeleton.getSkeletonData()!.pages[0];
+ const table = [...page.skeTables.values()][0];
+ const cell = table.rows[0].cells[0];
+ expect(cell).toMatchObject({ pageWidth: 40, pageHeight: 120, cellTextDirection: 'tbRlV', marginLeft: 5, marginTop: 4 });
+ const lines = cell.sections[0].columns[0].lines;
+ expect(lines).toHaveLength(1);
+ const line = lines[0];
+ const divide = line.divides[0];
+ const glyphs = divide.glyphGroup.filter((glyph) => glyph.content && text.includes(glyph.content));
+ expect(glyphs.map((glyph) => glyph.content).join('')).toBe(text);
+ const originX = page.marginLeft + table.left + cell.left;
+ const originY = page.marginTop + table.top + table.rows[0].top;
+ for (const glyph of glyphs) {
+ const logicalX = cell.marginLeft + cell.sections[0].columns[0].left + divide.left + divide.paddingLeft + glyph.left + glyph.width / 2;
+ const logicalY = cell.marginTop + cell.sections[0].top + line.top + line.lineHeight / 2;
+ const hit = skeleton.findNodeByCoord(new Vector2(originX + cell.pageWidth - logicalY, originY + logicalX), PageLayoutType.VERTICAL, 0, 0);
+ expect(hit?.node).toBe(glyph);
+ }
+ expect(model.getBody()!.dataStream).toBe(dataStream);
+ expectIncrementalSkeletonToEqualSynchronous(model.getSnapshot(), localeService);
+ skeleton.dispose();
+ univer.dispose();
+ measureSpy.mockRestore();
+ });
+
+ it.each([false, true])('preserves editable character indexes after a leading cached break (table: %s)', (inTable) => {
+ const T = DataStreamTreeTokenType;
+ const caption = `${T.PAGE_BREAK}图40:标题${T.PARAGRAPH}`;
+ const table = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${caption}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const dataStream = `Intro${T.PARAGRAPH}${inTable ? `${table}${T.PARAGRAPH}` : caption}${T.SECTION_BREAK}`;
+ const tableStart = dataStream.indexOf(T.TABLE_START);
+ const model = new DocumentDataModel({
+ id: 'cached-break-caret',
+ body: {
+ dataStream,
+ renderedPageBreaks: [dataStream.indexOf(T.PAGE_BREAK)],
+ paragraphs: Array.from(dataStream).flatMap((token, startIndex) => token === T.PARAGRAPH ? [{ startIndex, paragraphId: `p-${startIndex}` }] : []),
+ sectionBreaks: Array.from(dataStream).flatMap((token, startIndex) => token === T.SECTION_BREAK ? [{ startIndex, sectionId: `s-${startIndex}` }] : []),
+ tables: inTable ? [{ tableId: 'caption', startIndex: tableStart, endIndex: tableStart + table.length }] : [],
+ },
+ tableSource: inTable
+ ? {
+ caption: {
+ tableId: 'caption',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: {
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE },
+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE },
+ },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 280 } },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 280 } } }],
+ tableRows: [{ tableCells: [{}], trHeight: { val: { v: 0 }, hRule: TableRowHeightRule.AUTO } }],
+ },
+ }
+ : {},
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 320, height: 400 },
+ marginLeft: 20,
+ marginRight: 20,
+ marginTop: 20,
+ marginBottom: 20,
+ },
+ });
+ const univer = new Univer();
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));
+ try {
+ skeleton.calculate();
+ for (const text of ['图', '4', '0', ':', '标', '题']) {
+ const index = dataStream.indexOf(text);
+ const glyph = skeleton.findNodeByCharIndex(index)!;
+ expect(glyph?.content).toBe(text);
+ const position = skeleton.findPositionByGlyph(glyph, -1)!;
+ expect(skeleton.findCharIndexByPosition({ ...position, isBack: true })).toBe(index);
+ }
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+ });
+
+ it('keeps a fitting traditional table cell together despite cached pagination metadata', () => {
+ const measureSpy = mockCanvasTextMetrics();
+ const T = DataStreamTreeTokenType;
+ const cell = `Before${T.PARAGRAPH}${T.PAGE_BREAK}After${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const table = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${cell}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const dataStream = `${table}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const documentModel = new DocumentDataModel({
+ id: 'rendered-page-break-in-table-cell',
body: {
dataStream,
renderedPageBreaks: [dataStream.indexOf(T.PAGE_BREAK)],
@@ -3690,33 +5286,30 @@ describe('doc skeleton', () => {
skeleton.calculate();
const pages = skeleton.getSkeletonData()?.pages ?? [];
- expect(pages).toHaveLength(2);
+ expect(pages).toHaveLength(1);
expect(pages.every((page) => [...page.skeTables.keys()].some((tableId) => tableId.startsWith('table')))).toBe(true);
+ expectIncrementalSkeletonToEqualSynchronous(documentModel.getSnapshot(), localeService);
skeleton.dispose();
univer.dispose();
measureSpy.mockRestore();
});
- it('DOCX golden e2e does not duplicate a table-cell rendered break after natural overflow', () => {
- const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
- width: text.length * 8,
- fontBoundingBoxAscent: 8,
- fontBoundingBoxDescent: 2,
- }) as any);
+ it.each([false, true])('naturally paginates an overflowing cell with or without cached markers: %s', (cached) => {
+ const measureSpy = mockCanvasTextMetrics();
const T = DataStreamTreeTokenType;
- const before = 'Before '.repeat(70);
- const cell = `${before}${T.PARAGRAPH}${T.PAGE_BREAK}After${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const before = 'Before '.repeat(100);
+ const cell = `${before}${T.PARAGRAPH}${cached ? T.PAGE_BREAK : ''}After${T.PARAGRAPH}${T.SECTION_BREAK}`;
const table = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${cell}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
const dataStream = `${table}${T.PARAGRAPH}${T.SECTION_BREAK}`;
const documentModel = new DocumentDataModel({
id: 'natural-overflow-before-rendered-table-break',
body: {
dataStream,
- renderedPageBreaks: [dataStream.indexOf(T.PAGE_BREAK)],
+ renderedPageBreaks: cached ? [dataStream.indexOf(T.PAGE_BREAK)] : [],
paragraphs: [
{ startIndex: dataStream.indexOf(T.PARAGRAPH), paragraphId: 'before' },
- { startIndex: dataStream.indexOf(T.PARAGRAPH, dataStream.indexOf(T.PAGE_BREAK)), paragraphId: 'after' },
+ { startIndex: dataStream.indexOf(T.PARAGRAPH, dataStream.indexOf('After')), paragraphId: 'after' },
],
tables: [{ tableId: 'table', startIndex: 0, endIndex: table.length }],
sectionBreaks: [
@@ -3761,6 +5354,28 @@ describe('doc skeleton', () => {
const pages = skeleton.getSkeletonData()?.pages ?? [];
expect(pages).toHaveLength(2);
expect(pages.every((page) => [...page.skeTables.keys()].some((tableId) => tableId.startsWith('table')))).toBe(true);
+ const incremental = DocumentSkeleton.create(
+ new DocumentViewModel(new DocumentDataModel(structuredClone(documentModel.getSnapshot()))),
+ localeService
+ );
+ completeIncrementalLayout(incremental);
+ const actual = incremental.getSkeletonData()!;
+ const expected = skeleton.getSkeletonData()!;
+ expect(normalizeSkeleton({ ...actual, drawingAnchor: undefined }))
+ .toEqual(normalizeSkeleton({ ...expected, drawingAnchor: undefined }));
+ expect([...actual.drawingAnchor!.keys()]).toEqual([...expected.drawingAnchor!.keys()]);
+ for (const [segmentId, anchors] of expected.drawingAnchor!) {
+ const actualAnchors = actual.drawingAnchor!.get(segmentId)!;
+ expect([...actualAnchors.keys()]).toEqual([...anchors.keys()]);
+ for (const [index, anchor] of anchors) {
+ const actualAnchor = actualAnchors.get(index)!;
+ expect({ ...actualAnchor, elements: [] }).toEqual({ ...anchor, elements: [] });
+ // Measurement retains provisional line references that are not published by the worker.
+ // Final text and geometry are compared through the page tree above, not this scratch array.
+ expect(actualAnchor.elements.length).toBeGreaterThan(0);
+ }
+ }
+ incremental.dispose();
skeleton.dispose();
univer.dispose();
@@ -3768,11 +5383,7 @@ describe('doc skeleton', () => {
});
it('keeps the document-grid line height inside a traditional table cell', () => {
- const measureSpy = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
- width: text.length * 8,
- fontBoundingBoxAscent: 8,
- fontBoundingBoxDescent: 2,
- }) as any);
+ const measureSpy = mockCanvasTextMetrics(12);
const T = DataStreamTreeTokenType;
const qualifyingCell = `${'一'.repeat(30)}${T.PARAGRAPH}${T.SECTION_BREAK}`;
const compactCell = `${'二'.repeat(30)}${T.PARAGRAPH}${T.SECTION_BREAK}`;
@@ -3871,10 +5482,10 @@ describe('doc skeleton', () => {
expect(rows[0]?.height).toBeCloseTo(103.86666666666666);
const compactLines = rows[1]?.cells[0]?.sections[0]?.columns[0]?.lines ?? [];
expect(compactLines.map(({ paragraphIndex, top, lineHeight, spaceBelowApply }) => ({ paragraphIndex, top, lineHeight, spaceBelowApply }))).toEqual([
- { paragraphIndex: secondParagraph, top: 0, lineHeight: 23.4, spaceBelowApply: 0 },
- { paragraphIndex: secondParagraph, top: 23.4, lineHeight: 23.4, spaceBelowApply: 0 },
+ { paragraphIndex: secondParagraph, top: 0, lineHeight: 31.200000000000003, spaceBelowApply: 0 },
+ { paragraphIndex: secondParagraph, top: 31.200000000000003, lineHeight: 31.200000000000003, spaceBelowApply: 0 },
]);
- expect(rows[1]?.height).toBeCloseTo(56.8);
+ expect(rows[1]?.height).toBeCloseTo(72.4);
const bodyLines = skeleton
.getSkeletonData()
?.pages[0]
@@ -3895,6 +5506,7 @@ describe('doc skeleton', () => {
skeleton.calculate();
const changedRows = skeleton.getSkeletonData()!.pages[0].skeTables.get('table')!.rows;
expect(changedRows[0].height).toBeLessThan(rows[0].height);
+ expect(changedRows[1].height).toBeCloseTo(rows[1].height);
skeleton.getViewModel().reset(new DocumentDataModel(originalSnapshot));
skeleton.calculate();
expect(skeleton.getSkeletonData()!.pages[0].skeTables.get('table')!.rows[0].height).toBeCloseTo(rows[0].height);
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/document-layout-page-patch.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/document-layout-page-patch.spec.ts
index 49f512ff7d..1413002f6f 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/document-layout-page-patch.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/document-layout-page-patch.spec.ts
@@ -14,9 +14,21 @@
* limitations under the License.
*/
-import { createDocumentModelWithStyle, DocumentFlavor, LocaleService, Univer } from '@univerjs/core';
+import type { IDocumentData, ITable } from '@univerjs/core';
+import {
+ BooleanNumber,
+ createDocumentModelWithStyle,
+ DataStreamTreeTokenType,
+ DocumentDataModel,
+ DocumentFlavor,
+ LocaleService,
+ TableRowHeightRule,
+ Univer,
+} from '@univerjs/core';
import { describe, expect, it } from 'vitest';
import { DocumentViewModel } from '../../view-model/document-view-model';
+import { createParagraphLayoutTestBed } from '../block/paragraph/__tests__/create-paragraph-layout-test-bed';
+import { cachePrecomputedTableSkeleton, createTableSkeleton } from '../block/table';
import { DocumentSkeleton } from '../doc-skeleton';
import { hydrateDocumentSkeletonPage, serializeDocumentSkeletonPage } from '../document-layout-page-patch';
@@ -41,6 +53,107 @@ function normalizeSkeleton(value: unknown): unknown {
}
describe('document layout page patch', () => {
+ it.each(['header', 'footer'] as const)('keeps precomputed body tables out of a %s at the same stream offset', (kind) => {
+ const T = DataStreamTreeTokenType;
+ const story = (text: string, rowCount: number, rowHeight: number): Required<Pick<IDocumentData, 'body' | 'tableSource'>> => {
+ const row = `${T.TABLE_ROW_START}${T.TABLE_CELL_START}${text}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}`;
+ const tableText = `${T.TABLE_START}${row.repeat(rowCount)}${T.TABLE_END}`;
+ const dataStream = `${tableText}${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const table: ITable = {
+ tableId: 'table-1',
+ align: 0,
+ indent: { v: 0 },
+ textWrap: 0,
+ position: { positionH: { relativeFrom: 0 }, positionV: { relativeFrom: 0 } },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: 1, width: { v: 240 } },
+ cellMargin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } },
+ tableColumns: [{ size: { type: 1, width: { v: 240 } } }],
+ tableRows: Array.from({ length: rowCount }, () => ({
+ tableCells: [{}],
+ trHeight: { hRule: TableRowHeightRule.EXACT, val: { v: rowHeight } },
+ })),
+ };
+ return {
+ body: {
+ dataStream,
+ tables: [{ tableId: 'table-1', startIndex: 0, endIndex: tableText.length - 1 }],
+ paragraphs: Array.from(dataStream).flatMap((c, i) => c === T.PARAGRAPH ? [{ startIndex: i, paragraphId: `p-${i}` }] : []),
+ sectionBreaks: Array.from(dataStream).flatMap((c, i) => c === T.SECTION_BREAK ? [{ startIndex: i, sectionId: `s-${i}` }] : []),
+ },
+ tableSource: { 'table-1': table },
+ };
+ };
+ const snapshot: IDocumentData = {
+ id: 'segment-local-tables',
+ ...story('Body', 4, 100),
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 300, height: 240 },
+ marginLeft: 30,
+ marginRight: 30,
+ marginTop: 40,
+ marginBottom: 40,
+ marginHeader: 10,
+ marginFooter: 10,
+ useFirstPageHeaderFooter: BooleanNumber.TRUE,
+ ...(kind === 'header'
+ ? { defaultHeaderId: 'regular', firstPageHeaderId: 'first' }
+ : { defaultFooterId: 'regular', firstPageFooterId: 'first' }),
+ },
+ ...(kind === 'header'
+ ? { headers: {
+ first: { headerId: 'first', ...story('First', 1, 18) },
+ regular: { headerId: 'regular', ...story('Header', 1, 18) },
+ } }
+ : { footers: {
+ first: { footerId: 'first', ...story('First', 1, 18) },
+ regular: { footerId: 'regular', ...story('Footer', 1, 18) },
+ } }),
+ };
+ const { ctx, curPage, viewModel, sectionBreakConfig } = createParagraphLayoutTestBed('', {
+ ...snapshot,
+ body: { ...snapshot.body },
+ documentStyle: { ...snapshot.documentStyle },
+ });
+ try {
+ const bodyNode = viewModel.getChildren()[0].children[0].children[0];
+ const bodyTable = createTableSkeleton(ctx, curPage, viewModel, bodyNode, sectionBreakConfig)!;
+ cachePrecomputedTableSkeleton(ctx, bodyNode, bodyTable);
+ const resourceViewModel = viewModel.getSelfOrHeaderFooterViewModel('regular');
+ const resourceNode = resourceViewModel.getChildren()[0].children[0].children[0];
+ expect(resourceNode.startIndex).toBe(bodyNode.startIndex);
+ const resourceTable = createTableSkeleton(ctx, curPage, resourceViewModel, resourceNode, sectionBreakConfig)!;
+ expect(resourceTable.rows).toHaveLength(1);
+ expect(resourceTable.height).toBe(18);
+ expect(createTableSkeleton(ctx, curPage, viewModel, bodyNode, sectionBreakConfig)).toBe(bodyTable);
+ } finally {
+ viewModel.dispose();
+ }
+ const univer = new Univer();
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(new DocumentDataModel(snapshot)), univer.__getInjector().get(LocaleService));
+ try {
+ const generation = skeleton.startIncrementalLayout();
+ let complete = false;
+ for (let i = 0; i < 1000 && !complete; i++) {
+ complete = skeleton.stepIncrementalLayout(generation, 1).complete;
+ }
+ expect(complete).toBe(true);
+ const data = skeleton.getSkeletonData()!;
+ expect(data.pages.length).toBeGreaterThan(1);
+ const resources = kind === 'header' ? data.skeHeaders : data.skeFooters;
+ const page = [...resources.get('regular')!.values()][0];
+ const table = [...page.skeTables.values()][0];
+ expect(table.rows).toHaveLength(1);
+ expect(table.height).toBe(18);
+ const hydrated = hydrateDocumentSkeletonPage(structuredClone(serializeDocumentSkeletonPage(page, true)), undefined, snapshot);
+ expect([...hydrated.skeTables.values()][0].rows[0].rowSource).toBe(table.tableSource.tableRows[0]);
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+ });
+
it('survives structured clone and restores render parent links', () => {
const univer = new Univer();
const localeService = univer.__getInjector().get(LocaleService);
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/endnote-layout.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/endnote-layout.spec.ts
index 64500ad89c..d42f9e7dd4 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/endnote-layout.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/endnote-layout.spec.ts
@@ -42,7 +42,17 @@ function snapshot(position: 'docEnd' | 'sectEnd', long = false) {
describe('endnote pagination', () => {
beforeEach(() => {
- vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({ width: text.length * 5, fontBoundingBoxAscent: 8, fontBoundingBoxDescent: 2, actualBoundingBoxAscent: 8, actualBoundingBoxDescent: 2 }) as TextMetrics);
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
+ font: '',
+ measureText(this: CanvasRenderingContext2D, text: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
+ const scale = points / 11;
+ return { width: text.length * 5 * scale, fontBoundingBoxAscent: 8 * scale, fontBoundingBoxDescent: 2 * scale, actualBoundingBoxAscent: 8 * scale, actualBoundingBoxDescent: 2 * scale };
+ },
+ } as unknown as CanvasRenderingContext2D);
+ Reflect.set(FontCache, '_context', null);
+ FontCache.invalidateMetrics(() => true);
});
afterEach(() => vi.restoreAllMocks());
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/footnote-layout.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/footnote-layout.spec.ts
index 2224e0dbee..edba6069f6 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/footnote-layout.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/footnote-layout.spec.ts
@@ -69,17 +69,46 @@ function getPageGlyphs(page: IDocumentSkeletonPage) {
describe('footnote body layout', () => {
beforeEach(() => {
- vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
- width: text.length * 5,
- fontBoundingBoxAscent: 8,
- fontBoundingBoxDescent: 2,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
- }) as TextMetrics);
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
+ font: '',
+ measureText(this: CanvasRenderingContext2D, text: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
+ const scale = points / 11;
+ return { width: text.length * 5 * scale, fontBoundingBoxAscent: 8 * scale, fontBoundingBoxDescent: 2 * scale, actualBoundingBoxAscent: 8 * scale, actualBoundingBoxDescent: 2 * scale };
+ },
+ } as unknown as CanvasRenderingContext2D);
+ Reflect.set(FontCache, '_context', null);
+ FontCache.invalidateMetrics(() => true);
});
afterEach(() => vi.restoreAllMocks());
+ it.each([undefined, false, true])('keeps the anchor but respects note-body marker presence: %s', (showBodyReference) => {
+ const bed = createNoteTestBed(600, {
+ showBodyReference,
+ body: {
+ dataStream: '19 Literal\r\n',
+ paragraphs: [{ paragraphId: 'literal', startIndex: 10 }],
+ sectionBreaks: [{ sectionId: 'literal', startIndex: 11 }],
+ },
+ });
+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);
+ try {
+ skeleton.calculate();
+ const page = skeleton.getSkeletonData()!.pages[0];
+ expect(getPageGlyphs(page).some((glyph) => glyph.noteId === 'note' && glyph.content === 'VIII')).toBe(true);
+ const fragment = page.notes!.find((note) => note.noteId === 'note')!;
+ const text = getPageGlyphs(fragment.page).map((glyph) => glyph.content).join('');
+ expect(text.startsWith(showBodyReference === false ? '19 Literal' : 'VIII19 Literal')).toBe(true);
+ expect(bed.dataModel.getSnapshot().notes!.note.body.dataStream).toBe('19 Literal\r\n');
+ } finally {
+ skeleton.dispose();
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
+
it.each([false, true])('fills the remaining body space with table rows after an earlier footnote (incremental: %s)', (incremental) => {
const T = DataStreamTreeTokenType;
const prefix = `Reference\uFFFC\r${'Filler\r'.repeat(7)}`;
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts
index af6f8ca9c9..e9854b1c19 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts
@@ -19,6 +19,7 @@ import {
AlignTypeH,
AlignTypeV,
BooleanNumber,
+ CustomRangeType,
DataStreamTreeTokenType,
DocumentFlavor,
GridType,
@@ -28,10 +29,10 @@ import {
SectionType,
SpacingRule,
} from '@univerjs/core';
-
import { describe, expect, it, vi } from 'vitest';
import { GlyphType } from '../../../../basics/i-document-skeleton-cached';
import { getDocumentCompatibilityPolicy } from '../../document-compatibility';
+import { createParagraphLayoutTestBed } from '../block/paragraph/__tests__/create-paragraph-layout-test-bed';
import {
clearFontCreateConfigCache,
columnIterator,
@@ -444,7 +445,7 @@ describe('docs layout tools extra', () => {
expect(line1).toMatchObject(paragraphStyle);
});
- it('uses the between border only between adjacent paragraphs with matching border sets', () => {
+ it.each([false, true])('joins adjacent matching border sets with an optional between border (%s)', (between) => {
const { page, line1, line2 } = createPageSkeleton();
line1.paragraphStart = true;
line1.paragraphIndex = 10;
@@ -457,7 +458,7 @@ describe('docs layout tools extra', () => {
borderBottom: { color: { rgb: '#222222' }, width: 2, padding: 2 },
borderLeft: { color: { rgb: '#333333' }, width: 3, padding: 3 },
borderRight: { color: { rgb: '#444444' }, width: 4, padding: 4 },
- borderBetween: { color: { rgb: '#555555' }, width: 5, padding: 5 },
+ borderBetween: between ? { color: { rgb: '#555555' }, width: 5, padding: 5 } : undefined,
};
const ctx = {
paragraphConfigCache: new Map([[
@@ -479,6 +480,30 @@ describe('docs layout tools extra', () => {
expect(line2.borderBottom).toEqual(paragraphStyle.borderBottom);
});
+ it('draws a paragraph border around its text rather than its zero-height floating anchor', () => {
+ const { page, line1, line2 } = createPageSkeleton();
+ const border = { color: { rgb: '#111111' }, width: 1, padding: 1 };
+ const paragraphStyle = { borderTop: border, borderBottom: border };
+ line1.lineHeight = 0;
+ line1.paragraphStart = true;
+ line1.paragraphIndex = 20;
+ line1.borderTop = border;
+ line2.paragraphStart = false;
+ line2.paragraphIndex = 20;
+ line2.ed = 20;
+ line2.borderTopSpace = 2;
+ const ctx = {
+ paragraphConfigCache: new Map([[undefined, new Map([[20, { paragraphStyle }]])]]),
+ };
+
+ updateParagraphBorders(ctx as any, [page] as any);
+
+ expect(line1.borderTop).toBeUndefined();
+ expect(line1.borderBottom).toBeUndefined();
+ expect(line2.borderTop).toEqual(border);
+ expect(line2.borderBottom).toEqual(border);
+ });
+
it('uses cached border styles at retained and reused page boundaries', () => {
const previous = createPageSkeleton();
const current = createPageSkeleton();
@@ -629,6 +654,7 @@ describe('docs layout tools extra', () => {
gridType: GridType.LINES,
charSpace: 1,
pageSize: { width: 500 },
+ balanceSingleByteDoubleByteWidth: BooleanNumber.TRUE,
marginLeft: 10,
marginRight: 20,
} as any,
@@ -636,6 +662,7 @@ describe('docs layout tools extra', () => {
);
expect(fromLastGlyph.pageWidth).toBe(500);
expect(fromLastGlyph.charSpace).toBe(1);
+ expect(fromLastGlyph.balanceSingleByteDoubleByteWidth).toBe(BooleanNumber.TRUE);
const viewModel = {
getTextRun: vi.fn(() => ({ st: 0, ed: 10, ts: { fs: 12, ff: 'Arial', eastAsiaFontFamily: '宋体' } })),
@@ -652,6 +679,7 @@ describe('docs layout tools extra', () => {
gridType: GridType.LINES,
charSpace: 2,
documentTextStyle: { fs: 10, ff: 'Calibri' },
+ balanceSingleByteDoubleByteWidth: BooleanNumber.TRUE,
pageSize: { width: 300 },
marginLeft: 0,
marginRight: 0,
@@ -663,6 +691,7 @@ describe('docs layout tools extra', () => {
const config1 = getFontCreateConfig(0, viewModel as any, paragraphNode as any, sectionBreakConfig as any, paragraph as any);
const config2 = getFontCreateConfig(0, viewModel as any, paragraphNode as any, sectionBreakConfig as any, paragraph as any);
expect(config1).toBe(config2);
+ expect(config1.balanceSingleByteDoubleByteWidth).toBe(BooleanNumber.TRUE);
expect(config1.fontStyle.fontFamily).toBe('Arial, 宋体');
const configWithBullet = getFontCreateConfig(
@@ -684,6 +713,44 @@ describe('docs layout tools extra', () => {
expect(configWithMissingBulletList.textStyle.bl).toBeUndefined();
});
+ it('applies paragraph-mark formatting only to the terminator without leaking through the font cache', () => {
+ clearFontCreateConfigCache();
+ const paragraph = {
+ startIndex: 5,
+ paragraphId: 'formatted-mark',
+ paragraphStyle: {
+ textStyle: { ff: 'Arial' },
+ paragraphMarkTextStyle: { bl: 1, it: 1, fs: 14, cl: { rgb: '#FF0000' } },
+ },
+ };
+ const { viewModel, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('Hello', {
+ body: { paragraphs: [paragraph], textRuns: [{ st: 0, ed: 6, ts: { fs: 10 } }] },
+ });
+ const config = (index: number) => getFontCreateConfig(index, viewModel, paragraphNode, sectionBreakConfig, paragraph);
+ expect(config(5).textStyle).toMatchObject({ bl: 1, it: 1, fs: 14, cl: { rgb: '#FF0000' } });
+ expect(config(0).textStyle).toMatchObject({ ff: 'Arial', fs: 10 });
+ expect(config(0).textStyle.bl).toBeUndefined();
+ expect(config(0).textStyle.it).toBeUndefined();
+ expect(config(0).textStyle.cl).toBeUndefined();
+ });
+
+ it.each([undefined, { s: BooleanNumber.FALSE }, { s: BooleanNumber.TRUE }])('preserves authored hyperlink underline %j in the real font path', (ul) => {
+ clearFontCreateConfigCache();
+ const paragraph = { startIndex: 4, paragraphId: 'mail-paragraph', paragraphStyle: { textStyle: { cl: { rgb: '#123456' } } } };
+ const { dataModel, viewModel, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('Mail', {
+ body: {
+ paragraphs: [paragraph],
+ textRuns: [{ st: 0, ed: 4, ts: { ul, fs: 11 } }],
+ customRanges: [{ startIndex: 0, endIndex: 3, rangeId: 'mail', rangeType: CustomRangeType.HYPERLINK, properties: { url: 'mailto:[email protected]', textStyleMode: 'text' } }],
+ },
+ });
+ const before = JSON.stringify(dataModel.getSnapshot());
+ const result = getFontCreateConfig(0, viewModel, paragraphNode, sectionBreakConfig, paragraph);
+ expect(result.textStyle.ul).toEqual(ul);
+ expect(result.textStyle.cl).toEqual({ rgb: '#123456' });
+ expect(JSON.stringify(dataModel.getSnapshot())).toBe(before);
+ });
+
it('creates default skeleton, prepares section config, and resolves page paths', () => {
const skeleton = getNullSkeleton();
const pages = [{ segmentId: 'seg-1' }, { segmentId: 'seg-2' }] as any[];
@@ -719,6 +786,7 @@ describe('docs layout tools extra', () => {
documentStyle: {
documentFlavor: DocumentFlavor.MODERN,
pageSize: { width: 800, height: 1000 },
+ balanceSingleByteDoubleByteWidth: BooleanNumber.TRUE,
marginLeft: 20,
marginRight: 20,
marginTop: 20,
@@ -734,6 +802,7 @@ describe('docs layout tools extra', () => {
expect(sectionConfig.pageSize?.width).toBe(390);
expect(sectionConfig.marginLeft).toBe(20);
expect(sectionConfig.marginRight).toBe(20);
+ expect(sectionConfig.balanceSingleByteDoubleByteWidth).toBe(BooleanNumber.TRUE);
expect(sectionConfig.headerIds).toEqual({
defaultHeaderId: '',
evenPageHeaderId: '',
@@ -1137,6 +1206,61 @@ describe('docs layout tools extra', () => {
}]);
});
+ it('iterates tables nested inside cells after their parent table', () => {
+ const innerTable = {
+ tableId: 'inner-table',
+ height: 20,
+ left: 8,
+ rows: [],
+ top: 6,
+ width: 40,
+ };
+ const page = {
+ marginLeft: 10,
+ marginTop: 20,
+ pageHeight: 400,
+ sections: [],
+ skeTables: new Map([['outer-table', {
+ tableId: 'outer-table',
+ height: 80,
+ left: 5,
+ rows: [{
+ top: 3,
+ cells: [{
+ left: 4,
+ marginLeft: 2,
+ marginTop: 1,
+ pageHeight: 60,
+ pageWidth: 90,
+ sections: [],
+ skeTables: new Map([['inner-table', innerTable]]),
+ }],
+ }],
+ top: 7,
+ width: 100,
+ }]]),
+ };
+
+ const tables = documentSkeletonTableIterator([page as any], {
+ docsLeft: 100,
+ docsTop: 200,
+ includeCells: false,
+ });
+
+ expect(tables.map(({ source, tableId, tableRect }) => ({ source, tableId, tableRect }))).toEqual([
+ {
+ source: 'page',
+ tableId: 'outer-table',
+ tableRect: { bottom: 307, left: 115, right: 215, top: 227 },
+ },
+ {
+ source: 'table-cell',
+ tableId: 'inner-table',
+ tableRect: { bottom: 257, left: 129, right: 169, top: 237 },
+ },
+ ]);
+ });
+
it('uses the accumulated height of preceding pages for table coordinates', () => {
const createPageWithTable = (pageHeight: number, tableId: string) => {
const { page } = createPageSkeleton();
diff --git a/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.ts b/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.ts
index 209ad3e164..1b31667d1b 100644
--- a/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.ts
@@ -15,12 +15,13 @@
*/
import type { ITable } from '@univerjs/core';
-import type { IParagraphList } from '../../../../../basics/i-document-skeleton-cached';
-import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';
import type { ILayoutContext } from '../../tools';
import {
BooleanNumber,
DocumentFlavor,
+ NumberUnitType,
+ ObjectRelativeFromV,
+ PositionedObjectLayoutType,
TableAlignmentType,
TableRowHeightRule,
TableSizeType,
@@ -38,7 +39,7 @@ import {
getTableIdAndSliceIndex,
getTableLeft,
getTableSliceId,
- rollbackListCache,
+ resolveTableLayoutColumns,
startTableSkeletonBuild,
startTableSkeletonsBuild,
stepTableSkeletonBuild,
@@ -48,7 +49,8 @@ import {
const createSkeletonCellPagesMock = vi.fn();
const createNullCellPageMock = vi.fn();
-vi.mock('../../model/page', () => ({
+vi.mock('../../model/page', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../../model/page')>(),
createSkeletonCellPages: (...args: unknown[]) => createSkeletonCellPagesMock(...args),
createNullCellPage: (...args: unknown[]) => createNullCellPageMock(...args),
startSkeletonCellPagesBuild: (...args: unknown[]) => ({
@@ -175,6 +177,52 @@ function useDocumentFlavor(sectionBreakConfig: Record<string, unknown>, document
}
describe('table utilities', () => {
+ describe('resolveTableLayoutColumns', () => {
+ it('scales imported percentage table grids to the current page or parent-cell width', () => {
+ const table = createMockTable({
+ size: { type: TableSizeType.SPECIFIED, width: { v: 100, u: NumberUnitType.PERCENT } },
+ tableColumns: [
+ { size: { type: TableSizeType.SPECIFIED, width: { v: 80 } } },
+ { size: { type: TableSizeType.SPECIFIED, width: { v: 120 } } },
+ ],
+ });
+
+ const resolved = resolveTableLayoutColumns(table, 600);
+
+ expect(resolved.tableColumns.map((column) => column.size.width.v)).toEqual([240, 360]);
+ expect(table.tableColumns.map((column) => column.size.width.v)).toEqual([80, 120]);
+ });
+
+ it('keeps AutoFit grids because their imported widths already contain Word layout results', () => {
+ const table = createMockTable({
+ size: { type: TableSizeType.UNSPECIFIED, width: { v: 0 } },
+ tableColumns: [
+ { size: { type: TableSizeType.SPECIFIED, width: { v: 80 } } },
+ { size: { type: TableSizeType.SPECIFIED, width: { v: 120 } } },
+ ],
+ });
+
+ expect(resolveTableLayoutColumns(table, 600)).toBe(table);
+ });
+
+ it.each([false, true])('resolves legacy percentage width in frame coordinates (traditional: %s)', (traditional) => {
+ const table = createMockTable({
+ size: { type: TableSizeType.SPECIFIED, width: { v: 100, u: NumberUnitType.PERCENT } },
+ legacyIndentAdjustment: { v: 7.2 },
+ cellMargin: { start: { v: 7.2 }, end: { v: 7.2 }, top: { v: 0 }, bottom: { v: 0 } },
+ tableColumns: [
+ { size: { type: TableSizeType.SPECIFIED, width: { v: 200 } } },
+ { size: { type: TableSizeType.SPECIFIED, width: { v: 493.6 } } },
+ ],
+ });
+ const source = JSON.stringify(table);
+ const resolved = resolveTableLayoutColumns(table, 679.2, traditional);
+ expect(resolved.tableColumns.reduce((width, column) => width + column.size.width.v, 0))
+ .toBeCloseTo(traditional ? 693.6 : 679.2);
+ expect(JSON.stringify(table)).toBe(source);
+ });
+ });
+
describe('getTableLeft', () => {
it('centers a table within the supplied column width', () => {
expect(getTableLeft(243, 243, TableAlignmentType.CENTER)).toBe(0);
@@ -226,92 +274,6 @@ describe('table utilities', () => {
expect(skeleton.tableSource).toBe(table);
});
});
-
- describe('rollbackListCache', () => {
- it('removes paragraph lists whose startIndex is inside the table range', () => {
- const paragraphList1: IParagraphList = {
- bullet: {} as unknown as IParagraphList['bullet'],
- paragraph: { startIndex: 5 } as unknown as IParagraphList['paragraph'],
- };
- const paragraphList2: IParagraphList = {
- bullet: {} as unknown as IParagraphList['bullet'],
- paragraph: { startIndex: 15 } as unknown as IParagraphList['paragraph'],
- };
- const paragraphList3: IParagraphList = {
- bullet: {} as unknown as IParagraphList['bullet'],
- paragraph: { startIndex: 25 } as unknown as IParagraphList['paragraph'],
- };
-
- const listLevel = new Map<string, IParagraphList[][]>([
- ['list1', [[paragraphList1, paragraphList2, paragraphList3]]],
- ]);
-
- const tableNode = {
- startIndex: 10,
- endIndex: 20,
- } as DataStreamTreeNode;
-
- rollbackListCache(listLevel, tableNode);
-
- const result = listLevel.get('list1')![0];
- expect(result).toHaveLength(1);
- expect(result[0].paragraph.startIndex).toBe(5);
- });
-
- it('does not remove paragraph lists outside the table range', () => {
- const paragraphList1: IParagraphList = {
- bullet: {} as unknown as IParagraphList['bullet'],
- paragraph: { startIndex: 1 } as unknown as IParagraphList['paragraph'],
- };
- const paragraphList2: IParagraphList = {
- bullet: {} as unknown as IParagraphList['bullet'],
- paragraph: { startIndex: 2 } as unknown as IParagraphList['paragraph'],
- };
-
- const listLevel = new Map<string, IParagraphList[][]>([
- ['list1', [[paragraphList1, paragraphList2]]],
- ]);
-
- const tableNode = {
- startIndex: 10,
- endIndex: 20,
- } as DataStreamTreeNode;
-
- rollbackListCache(listLevel, tableNode);
-
- const result = listLevel.get('list1')![0];
- expect(result).toHaveLength(2);
- });
-
- it('handles empty listLevel', () => {
- const listLevel = new Map<string, IParagraphList[][]>();
- const tableNode = {
- startIndex: 10,
- endIndex: 20,
- } as DataStreamTreeNode;
-
- expect(() => rollbackListCache(listLevel, tableNode)).not.toThrow();
- });
-
- it('skips sparse paragraph list levels', () => {
- const paragraphList: IParagraphList = {
- bullet: {} as unknown as IParagraphList['bullet'],
- paragraph: { startIndex: 25 } as unknown as IParagraphList['paragraph'],
- };
- const paragraphLists = [] as unknown as IParagraphList[][];
- paragraphLists[2] = [paragraphList];
- const listLevel = new Map<string, IParagraphList[][]>([
- ['list1', paragraphLists],
- ]);
- const tableNode = {
- startIndex: 10,
- endIndex: 20,
- } as DataStreamTreeNode;
-
- expect(() => rollbackListCache(listLevel, tableNode)).not.toThrow();
- expect(listLevel.get('list1')![2]).toHaveLength(1);
- });
- });
});
describe('docs table layout', () => {
@@ -334,6 +296,24 @@ describe('docs table layout', () => {
);
});
+ it.each([false, true])('retains omitted grid columns on both sides of a row (sliced: %s)', (sliced) => {
+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();
+ tableSource.tableColumns = [15, 60, 60, 25].map((width) => ({ size: { type: TableSizeType.SPECIFIED, width: { v: width } } }));
+ tableSource.tableRows[0].gridBefore = 1;
+ tableSource.tableRows[0].gridAfter = 1;
+ tableSource.tableRows[1].gridBefore = 0;
+ tableSource.tableRows[1].gridAfter = 0;
+ const source = JSON.stringify(tableSource);
+ const tables = sliced
+ ? createTableSkeletons(ctx, curPage, viewModel, tableNode, sectionBreakConfig, 90).skeTables
+ : [createTableSkeleton(ctx, curPage, viewModel, tableNode, sectionBreakConfig)!];
+ expect(tables[0].rows[0].cells.map((cell) => cell.left)).toEqual([15, 75]);
+ expect(tables[0].width).toBe(160);
+ const secondRow = tables.flatMap((table) => table.rows).find((row) => row.index === 1)!;
+ expect(secondRow.cells[0].left).toBe(0);
+ expect(JSON.stringify(tableSource)).toBe(source);
+ });
+
it('creates table skeleton and applies row/cell alignment data', () => {
const { ctx, curPage, viewModel, tableNode, sectionBreakConfig } = createContextAndTable();
@@ -347,6 +327,38 @@ describe('docs table layout', () => {
expect(skeleton?.rows[0].cells[1].marginTop).toBeGreaterThanOrEqual(1);
});
+ it.each([VerticalAlignmentType.CENTER, VerticalAlignmentType.BOTTOM])(
+ 'keeps cell-relative floating anchors fixed while vertically aligning text (%s)',
+ (vAlign) => {
+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();
+ tableSource.tableRows[0].trHeight = { hRule: TableRowHeightRule.EXACT, val: { v: 180 } };
+ tableSource.tableRows[0].tableCells[0].vAlign = vAlign;
+ const anchors = [
+ ['margin', ObjectRelativeFromV.MARGIN, PositionedObjectLayoutType.WRAP_NONE],
+ ['page', ObjectRelativeFromV.PAGE, PositionedObjectLayoutType.WRAP_NONE],
+ ['paragraph', ObjectRelativeFromV.PARAGRAPH, PositionedObjectLayoutType.WRAP_NONE],
+ ['inline', ObjectRelativeFromV.MARGIN, PositionedObjectLayoutType.INLINE],
+ ] as const;
+ const cell = {
+ ...makeCellPage(60, 20),
+ skeDrawings: new Map(anchors.map(([drawingId, relativeFrom, layoutType]) => [drawingId, {
+ aTop: 10,
+ drawingOrigin: { layoutType, docTransform: { positionV: { relativeFrom, posOffset: 10 } } },
+ }])),
+ };
+ createSkeletonCellPagesMock.mockImplementationOnce(() => [cell]);
+
+ const skeleton = createTableSkeleton(ctx, curPage, viewModel, tableNode, sectionBreakConfig)!;
+ const result = skeleton.rows[0].cells[0];
+
+ expect(result.marginTop).toBeGreaterThan(cell.originMarginTop);
+ expect(result.marginTop + result.skeDrawings.get('margin')!.aTop).toBe(11);
+ expect(result.marginTop + result.skeDrawings.get('page')!.aTop).toBe(11);
+ expect(result.skeDrawings.get('paragraph')!.aTop).toBe(10);
+ expect(result.skeDrawings.get('inline')!.aTop).toBe(10);
+ }
+ );
+
it('builds a table one source cell at a time', () => {
const { ctx, curPage, viewModel, tableNode, sectionBreakConfig } = createContextAndTable();
const state = startTableSkeletonBuild(ctx, curPage, viewModel, tableNode, sectionBreakConfig);
@@ -372,7 +384,7 @@ describe('docs table layout', () => {
while (!stepTableSkeletonBuild(state)) {
// Build all source rows through the resumable path before pagination consumes them.
}
- cachePrecomputedTableSkeleton(ctx, tableNode.startIndex, state.tableSkeleton);
+ cachePrecomputedTableSkeleton(ctx, tableNode, state.tableSkeleton);
const callsBeforePagination = createSkeletonCellPagesMock.mock.calls.length;
const result = createTableSkeletons(ctx, curPage, viewModel, tableNode, sectionBreakConfig, 90);
@@ -399,7 +411,7 @@ describe('docs table layout', () => {
}
expect(state.result).not.toBeNull();
- cachePrecomputedSlicedTableSkeletons(ctx, tableNode.startIndex, 90, state.result!);
+ cachePrecomputedSlicedTableSkeletons(ctx, tableNode, 90, state.result!);
const callsBeforeConsume = createSkeletonCellPagesMock.mock.calls.length;
const result = createTableSkeletons(ctx, curPage, viewModel, tableNode, sectionBreakConfig, 90);
@@ -448,7 +460,7 @@ describe('docs table layout', () => {
}
cachePrecomputedSlicedTableSkeletons(
ctx,
- tableNode.startIndex,
+ tableNode,
request!.availableHeight,
state.result!
);
@@ -566,6 +578,43 @@ describe('docs table layout', () => {
);
});
+ it.each([
+ { flavor: DocumentFlavor.MODERN, fixedLastRow: false, heights: [22, 80] },
+ { flavor: DocumentFlavor.TRADITIONAL, fixedLastRow: false, heights: [22, 80] },
+ { flavor: DocumentFlavor.TRADITIONAL, fixedLastRow: true, heights: [74, 28] },
+ ])('expands the last flexible row of a vertical merge ($flavor, fixed last: $fixedLastRow)', ({ flavor, fixedLastRow, heights }) => {
+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();
+ useDocumentFlavor(sectionBreakConfig, flavor);
+ if (fixedLastRow) {
+ tableSource.tableRows[1].trHeight.hRule = TableRowHeightRule.EXACT;
+ }
+ tableSource.tableRows[0].tableCells = [
+ { rowSpan: 2, vAlign: VerticalAlignmentType.TOP },
+ { vAlign: VerticalAlignmentType.TOP },
+ ];
+ tableSource.tableRows[1].tableCells = [
+ { rowSpan: 0, columnSpan: 0, vAlign: VerticalAlignmentType.TOP },
+ { vAlign: VerticalAlignmentType.TOP },
+ ];
+ createSkeletonCellPagesMock.mockImplementation(
+ (
+ _ctx: unknown,
+ _viewModel: unknown,
+ _cellNode: unknown,
+ _section: unknown,
+ _table: unknown,
+ row: number,
+ col: number
+ ) => [makeCellPage(60, row === 0 && col === 0 ? 100 : row === 0 ? 20 : 30)]
+ );
+
+ const skeleton = createTableSkeleton(ctx, curPage, viewModel, tableNode, sectionBreakConfig);
+
+ expect(skeleton?.height).toBe(102);
+ expect(skeleton?.rows.map((row) => row.height)).toEqual(heights);
+ expect(skeleton?.rows[0].cells[0].pageHeight).toBe(102);
+ });
+
it('treats at-least row height as a minimum so wrapped cell content remains visible', () => {
const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();
tableSource.tableRows[0].trHeight = {
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts
index 7c2e5cf937..0b0e0f085c 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
@@ -19,26 +19,44 @@ import type { IParagraphConfig } from '../../../../../../basics/interfaces';
import {
AlignTypeH,
BooleanNumber,
+ characterSpacingControlType,
DataStreamTreeTokenType,
DocumentFlavor,
DrawingTypeEnum,
GridType,
+ HorizontalAlign,
+ ListGlyphType,
+ MODERN_DOCUMENT_DEFAULT_MARGIN,
+ NumberUnitType,
ObjectRelativeFromH,
ObjectRelativeFromV,
PositionedObjectLayoutType,
+ SectionType,
SpacingRule,
TableAlignmentType,
+ TableRowHeightRule,
+ TableSizeType,
TableTextWrapType,
+ TabStopAlignment,
WrapTextType,
} from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { GlyphType, LineType } from '../../../../../../basics/i-document-skeleton-cached';
+import {
+ DocumentSkeletonPageType,
+ GlyphType,
+ LineType,
+} from '../../../../../../basics/i-document-skeleton-cached';
import { setDocsCustomBlockRenderViewportProvider } from '../../../../custom-block-render-viewport';
+import { getDocumentCompatibilityPolicy } from '../../../../document-compatibility';
import { DocumentSkeleton } from '../../../doc-skeleton';
import { Lang } from '../../../hyphenation/lang';
import { BreakPointType } from '../../../line-breaker/break';
import { createSkeletonCustomBlockGlyph } from '../../../model/glyph';
+import { FontCache } from '../../../shaping-engine/font-cache';
+import { clearFontCreateConfigCache, updateBlockIndex, updateInlineDrawingCoordsAndBorder } from '../../../tools';
+import { createTableSkeleton } from '../../table';
import { __testing, getLineHeightMetrics, layoutParagraph, updateInlineDrawingPosition } from '../layout-ruler';
+import { lineAdjustment } from '../line-adjustment';
import { lineBreaking } from '../linebreaking';
import { shaping } from '../shaping';
import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';
@@ -46,23 +64,94 @@ import issue1207Snapshot from './fixtures/issue-1207-bullet-style.snapshot.json'
describe('layout-ruler', () => {
beforeEach(() => {
+ clearFontCreateConfigCache();
vi.stubGlobal('document', {
createElement: () => ({
getContext: () => ({
font: '',
textBaseline: 'alphabetic',
- measureText: (value: string) => ({
- width: value.length * 8,
- fontBoundingBoxAscent: 10,
- fontBoundingBoxDescent: 4,
- actualBoundingBoxAscent: 10,
- actualBoundingBoxDescent: 4,
- }),
+ measureText(this: CanvasRenderingContext2D, value: string) {
+ const size = this.font.match(/([\d.]+)(px|pt)/);
+ const points = size ? Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) : 11;
+ return {
+ width: value.length * 8 * points / 11,
+ fontBoundingBoxAscent: 10,
+ fontBoundingBoxDescent: 4,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 4,
+ };
+ },
}),
}),
});
});
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN].flatMap((documentFlavor) =>
+ [false, true].flatMap((incremental) => [BooleanNumber.FALSE, BooleanNumber.TRUE].flatMap((tcHideMark) =>
+ [false, true].map((emptyEndMark) => ({ documentFlavor, incremental, tcHideMark, emptyEndMark }))))))('excludes only the final cell mark from row height (flavor: $documentFlavor, incremental: $incremental, hideMark: $tcHideMark, empty: $emptyEndMark)', ({ documentFlavor, incremental, tcHideMark, emptyEndMark }) => {
+ const T = DataStreamTreeTokenType;
+ const cellContent = emptyEndMark ? 'Cell\r\r\r' : 'Cell\r';
+ const tableStream = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}${cellContent}\n${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const dataStream = `${tableStream}\rAfter\r\n`;
+ const bed = createParagraphLayoutTestBed('', {
+ documentStyle: { documentFlavor },
+ body: {
+ dataStream,
+ paragraphs: [...dataStream.matchAll(/\r/g)].filter((match) => match.index !== tableStream.length).map((match, index) => ({ paragraphId: `p-${index}`, startIndex: match.index })),
+ sectionBreaks: [{ sectionId: 'cell', startIndex: dataStream.indexOf('\n') }, { sectionId: 'body', startIndex: dataStream.length - 1 }],
+ tables: [{ tableId: 'table', startIndex: 0, endIndex: tableStream.length }],
+ },
+ tableSource: { table: {
+ tableId: 'table',
+ align: 0,
+ indent: { v: 0 },
+ textWrap: 0,
+ size: { type: 0, width: { v: 200 } },
+ cellMargin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } },
+ tableRows: [{ tableCells: [{ tcHideMark }], trHeight: { val: { v: 0 }, hRule: 0 } }],
+ tableColumns: [{ size: { type: 0, width: { v: 200 } } }],
+ } },
+ });
+ const snapshot = JSON.stringify(bed.dataModel.getSnapshot());
+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);
+ try {
+ if (incremental) {
+ const generation = skeleton.startIncrementalLayout();
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let step = 0; step < 50 && !progress.complete; step++) {
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+ expect(progress.complete).toBe(true);
+ } else {
+ skeleton.calculate();
+ }
+ const table = skeleton.getSkeletonData()!.pages[0].skeTables.get('table')!;
+ const cell = table.rows[0].cells[0];
+ const lines = cell.sections.flatMap((section) => section.columns.flatMap((column) => column.lines));
+ expect(lines).toHaveLength(emptyEndMark ? 3 : 1);
+ expect(lines[0].lineHeight).toBeGreaterThan(0);
+ const hidden = documentFlavor === DocumentFlavor.TRADITIONAL && tcHideMark === BooleanNumber.TRUE;
+ const lastLine = lines[lines.length - 1];
+ const endMark = lastLine.divides.flatMap((divide) => divide.glyphGroup).find((glyph) => glyph.streamType === T.PARAGRAPH)!;
+ if (hidden) {
+ expect(endMark.bBox.ba + endMark.bBox.bd).toBe(0);
+ }
+ if (emptyEndMark) {
+ expect(lines[1].lineHeight).toBeGreaterThan(0);
+ if (hidden) {
+ expect(lastLine.lineHeight).toBe(0);
+ } else {
+ expect(lastLine.lineHeight).toBeGreaterThan(0);
+ }
+ }
+ expect(table.rows[0].height).toBeCloseTo(lines.reduce((height, line) => height + line.lineHeight, 0));
+ expect(JSON.stringify(bed.dataModel.getSnapshot())).toBe(snapshot);
+ } finally {
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
+
it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN].flatMap((documentFlavor) =>
[false, true].map((incremental) => ({ documentFlavor, incremental }))))('preserves table terminators without adding traditional blank lines (flavor: $documentFlavor, incremental: $incremental)', ({ documentFlavor, incremental }) => {
const T = DataStreamTreeTokenType;
@@ -249,6 +338,126 @@ describe('layout-ruler', () => {
return metrics.paddingTop + metrics.contentHeight + metrics.paddingBottom;
}
+ it.each([' ', '\t', '\u3000', '\u00A0', 'X'])('uses visible content and the paragraph mark for whitespace line height (%j)', (content) => {
+ for (const documentFlavor of [DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN]) {
+ const heights = [false, true].map((large) => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage, viewModel, dataModel } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor },
+ body: {
+ paragraphs: [{ startIndex: content.length, paragraphStyle: { snapToGrid: BooleanNumber.FALSE } }],
+ },
+ });
+ const snapshot = JSON.stringify(dataModel.getSnapshot());
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ for (const part of shaped) {
+ for (const glyph of part.glyphs) {
+ if (large && glyph.content === content) {
+ // Canvas is mocked; supply the measured metrics of a larger run.
+ glyph.bBox.ba = 40;
+ glyph.bBox.bd = 10;
+ glyph.bBox.normalLineHeight = 60;
+ }
+ }
+ }
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ const lines = pages[0].sections[0].columns[0].lines;
+ expect(JSON.stringify(dataModel.getSnapshot())).toBe(snapshot);
+ return lines.reduce((height, line) => height + line.lineHeight, 0);
+ });
+ expect(heights[0]).toBeGreaterThan(0);
+ if (documentFlavor === DocumentFlavor.TRADITIONAL && content !== '\u00A0' && content !== 'X') {
+ expect(heights[1]).toBeCloseTo(heights[0]);
+ } else {
+ expect(heights[1]).toBeGreaterThan(heights[0]);
+ }
+ }
+ });
+
+ it.each(['paragraph', 'text', 'text-and-paragraph'].flatMap((kind) =>
+ [SpacingRule.AUTO, SpacingRule.AT_LEAST].flatMap((spacingRule) =>
+ [1.5, 18].map((growth) => ({ kind, spacingRule, growth })))))('keeps paragraph-mark metrics separate from visible-run leading ($kind/$spacingRule/$growth)', ({ kind, spacingRule, growth }) => {
+ const visibleRun = kind === 'text';
+ const { ctx, curPage, sectionBreakConfig } = createParagraphLayoutTestBed('AB', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ const first = createGlyph('A', 8);
+ first.bBox = { ...first.bBox, ba: 15, bd: 3, normalLineHeight: 18.005 };
+ const incoming = createGlyph(visibleRun ? 'B' : '\r', visibleRun ? 8 : 0);
+ incoming.streamType = visibleRun ? DataStreamTreeTokenType.LETTER : DataStreamTreeTokenType.PARAGRAPH;
+ incoming.bBox = { ...incoming.bBox, ba: 15 + growth, bd: 3, normalLineHeight: 18.005 + growth };
+ const config = {
+ paragraphIndex: 2,
+ paragraphStyle: { snapToGrid: BooleanNumber.FALSE, spacingRule, lineSpacing: spacingRule === SpacingRule.AUTO ? 1 : 17 },
+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL),
+ useWordStyleLineHeight: true,
+ } as IParagraphConfig;
+ const pages = layoutParagraph(ctx, [first], [curPage], sectionBreakConfig, config, true);
+ const incomingGlyphs = kind === 'text-and-paragraph' ? [{ ...first, raw: 'B', content: 'B' }, incoming] : [incoming];
+ layoutParagraph(ctx, incomingGlyphs, pages, sectionBreakConfig, config, false);
+ let expectedHeight = visibleRun ? 18 + growth : 18;
+ if (spacingRule === SpacingRule.AUTO) {
+ expectedHeight = visibleRun ? 18.005 + growth : 18.005;
+ }
+ expect(pages[0].sections[0].columns[0].lines[0].lineHeight).toBeCloseTo(expectedHeight);
+ });
+
+ it('expands an at-least line when a later font has extra leading but the same font box', () => {
+ const { ctx, curPage, sectionBreakConfig } = createParagraphLayoutTestBed('AB', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ const first = createGlyph('A', 8);
+ first.bBox = { ...first.bBox, ba: 15, bd: 3, normalLineHeight: 18 };
+ const incoming = createGlyph('B', 8);
+ incoming.bBox = { ...first.bBox, normalLineHeight: 30 };
+ const config = {
+ paragraphIndex: 2,
+ paragraphStyle: { snapToGrid: BooleanNumber.FALSE, spacingRule: SpacingRule.AT_LEAST, lineSpacing: 16 },
+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL),
+ useWordStyleLineHeight: true,
+ } as IParagraphConfig;
+ const pages = layoutParagraph(ctx, [first], [curPage], sectionBreakConfig, config, true);
+ layoutParagraph(ctx, [incoming], pages, sectionBreakConfig, config, false);
+ const line = pages[0].sections[0].columns[0].lines[0];
+ expect(line.lineHeight).toBe(30);
+ expect(line.contentHeight).toBe(18);
+ expect(line.paddingTop).toBe(6);
+ expect(line.paddingBottom).toBe(6);
+ });
+
+ it.each([BooleanNumber.FALSE, BooleanNumber.TRUE])('preserves mixed-font reflow metrics after a zero-height page hint (grid: %s)', (snapToGrid) => {
+ const { ctx, curPage, sectionBreakConfig } = createParagraphLayoutTestBed('3.3外', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ sectionBreakConfig.gridType = GridType.LINES;
+ sectionBreakConfig.linePitch = 20.8;
+ const hint = createGlyph('', 0);
+ hint.raw = DataStreamTreeTokenType.PAGE_BREAK;
+ hint.streamType = DataStreamTreeTokenType.PAGE_BREAK;
+ hint.bBox = { ...hint.bBox, ba: 0, bd: 0, aba: 0, abd: 0 };
+ const latin = [...'3.3'].map((content) => {
+ const glyph = createGlyph(content, 11);
+ glyph.bBox = { ...glyph.bBox, ba: 18, bd: 4, normalLineHeight: 23 };
+ return glyph;
+ });
+ const cjk = createGlyph('外', 20);
+ cjk.bBox = { ...cjk.bBox, ba: 21, bd: 5, normalLineHeight: 26 };
+ const config = {
+ paragraphIndex: 4,
+ paragraphStyle: { snapToGrid, spacingRule: SpacingRule.AUTO, lineSpacing: 1 },
+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL),
+ useWordStyleLineHeight: true,
+ } as IParagraphConfig;
+ const pages = layoutParagraph(ctx, [hint], [curPage], sectionBreakConfig, config, true);
+ layoutParagraph(ctx, latin, pages, sectionBreakConfig, config, false);
+ layoutParagraph(ctx, [cjk], pages, sectionBreakConfig, config, false);
+ const lines = pages[0].sections[0].columns[0].lines;
+ expect(pages).toHaveLength(1);
+ expect(lines).toHaveLength(1);
+ expect(lines[0].divides.flatMap((divide) => divide.glyphGroup).map((glyph) => glyph.content).join('')).toBe('3.3外');
+ expect(lines[0].contentHeight).toBeCloseTo(26);
+ expect(lines[0].lineHeight).toBeCloseTo(snapToGrid === BooleanNumber.TRUE ? 41.6 : 26);
+ });
+
it('lays out first shaped text with bullet skeleton', () => {
const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Item');
const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.viewModel, paragraphNode, sectionBreakConfig);
@@ -314,6 +523,132 @@ describe('layout-ruler', () => {
expect(result[0].sections[0].columns[0].lines[0].divides[0].glyphGroup[0].width).toBe(42);
});
+ it.each([
+ { documentFlavor: DocumentFlavor.TRADITIONAL, expectedWidth: 29 + 1 / 3 },
+ { documentFlavor: DocumentFlavor.MODERN, expectedWidth: 112 },
+ { documentFlavor: undefined, expectedWidth: 112 },
+ ])('uses authored list hanging instead of default tabs only in traditional documents ($documentFlavor)', ({ documentFlavor, expectedWidth }) => {
+ const content = 'Investment summary text. '.repeat(8);
+ const hanging = 29 + 1 / 3;
+ const indentStart = 33 + 8 / 15;
+ const { ctx, paragraphNode, sectionBreakConfig, curPage, viewModel } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor, defaultTabStop: 56 },
+ body: {
+ paragraphs: [{
+ startIndex: content.length,
+ paragraphId: 'imported-list-paragraph',
+ bullet: { listId: 'imported-list', listType: 'imported-list', nestingLevel: 0 },
+ }],
+ },
+ lists: {
+ 'imported-list': {
+ listType: 'imported-list',
+ nestingLevel: [{
+ paragraphProperties: { hanging: { v: hanging }, indentStart: { v: indentStart } },
+ glyphSymbol: '\u25CF',
+ glyphType: 0,
+ textStyle: { ff: 'Arial', fs: 9 },
+ }],
+ },
+ },
+ });
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ const lines = pages[0].sections[0].columns[0].lines;
+ const firstDivide = lines[0].divides[0];
+
+ expect(firstDivide.glyphGroup[0].glyphType).toBe(GlyphType.LIST);
+ expect(firstDivide.glyphGroup[0].width).toBeCloseTo(expectedWidth);
+ expect(firstDivide.left + firstDivide.paddingLeft + firstDivide.glyphGroup[1].left)
+ .toBeCloseTo(indentStart - hanging + expectedWidth);
+ expect(lines.length).toBeGreaterThan(1);
+ expect(lines[1].divides[0].left + lines[1].divides[0].paddingLeft).toBeCloseTo(indentStart);
+ });
+
+ it.each([13 + 2 / 3, 200])('keeps an empty list paragraph on one line in a %spx content box', (width) => {
+ const bed = createParagraphLayoutTestBed('', {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width, height: 600 },
+ marginLeft: 0,
+ marginRight: 0,
+ defaultTabStop: 48,
+ textStyle: { ff: 'Arial', fs: 8 },
+ },
+ body: {
+ paragraphs: [{
+ startIndex: 0,
+ paragraphId: 'empty-list-paragraph',
+ bullet: { listId: 'empty-list', listType: 'empty-list', nestingLevel: 0 },
+ }],
+ },
+ lists: {
+ 'empty-list': {
+ listType: 'empty-list',
+ nestingLevel: [{
+ paragraphProperties: { hanging: { v: 0 }, indentStart: { v: 0 } },
+ glyphSymbol: '1.',
+ glyphType: 0,
+ textStyle: { ff: 'Arial', fs: 8 },
+ }],
+ },
+ },
+ });
+ try {
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = bed;
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ const lines = pages[0].sections[0].columns[0].lines;
+
+ expect(lines).toHaveLength(1);
+ const glyphs = lines[0].divides.flatMap((divide) => divide.glyphGroup);
+ expect(glyphs[0].glyphType).toBe(GlyphType.LIST);
+ expect(glyphs.some((glyph) => glyph.streamType === DataStreamTreeTokenType.PARAGRAPH)).toBe(true);
+ expect(glyphs.reduce((count, glyph) => count + glyph.count, 0)).toBe(paragraphNode.content!.length);
+ expect(bed.dataModel.getBody()!.dataStream).toBe('\r\n');
+ } finally {
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
+
+ it.each([
+ [DocumentFlavor.DRAWINGML, 0, '\u25CF', 8],
+ [DocumentFlavor.DRAWINGML, 0, '12345', 40],
+ [DocumentFlavor.DRAWINGML, 12, '\u25CF', 12],
+ [DocumentFlavor.UNSPECIFIED, 0, '\u25CF', 54],
+ [DocumentFlavor.MODERN, 0, '\u25CF', 54],
+ [DocumentFlavor.TRADITIONAL, 0, '\u25CF', 54],
+ ])('respects bullet advance for flavor %s, hanging %s and marker %s', (flavor, hanging, symbol, width) => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Item');
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(flavor);
+ sectionBreakConfig.defaultTabStop = 27;
+ const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.viewModel, paragraphNode, sectionBreakConfig);
+ const paragraphConfig = {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: { hanging: { v: hanging }, indentStart: { v: 18 } },
+ bulletSkeleton: {
+ listId: 'drawing-list',
+ symbol,
+ ts: { ff: 'Arial', fs: 11 },
+ startIndexItem: 1,
+ },
+ } as IParagraphConfig;
+ const pages = layoutParagraph(
+ ctx,
+ shapedTextList[0].glyphs,
+ [curPage],
+ sectionBreakConfig,
+ paragraphConfig,
+ true
+ );
+ const glyphs = pages[0].sections[0].columns[0].lines[0].divides[0].glyphGroup;
+
+ expect(glyphs[0].content).toBe(symbol);
+ expect(glyphs[0].width).toBe(width);
+ expect(glyphs[1].left - glyphs[0].left).toBe(width);
+ });
+
it('preserves bullet styles from a real PowerPoint import snapshot', () => {
const expectedCases = {
'case-A': {
@@ -410,10 +745,103 @@ describe('layout-ruler', () => {
expect(text[0]).toBe(`${prefix}abc`);
});
+ it.each([
+ { prefix: 'A', indent: 0, defaultTabStop: 48, expected: 48 },
+ { prefix: 'AAAAAA', indent: 0, defaultTabStop: 48, expected: 96 },
+ { prefix: 'A', indent: 15, defaultTabStop: 48, expected: 48 },
+ { prefix: 'A', indent: 0, defaultTabStop: 36, expected: 36 },
+ { prefix: '', indent: 0, defaultTabStop: 48, expected: 48 },
+ ])('advances default tabs to the next stop instead of inserting a fixed gap: %j', ({ prefix, indent, defaultTabStop, expected }) => {
+ for (const documentFlavor of [DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN]) {
+ const content = `${prefix}\tB\tC`;
+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ body: {
+ paragraphs: [{ startIndex: content.length, paragraphId: 'tabs', paragraphStyle: {
+ indentStart: { v: indent },
+ tabStops: prefix ? [{ offset: 4, alignment: 0 }] : [],
+ } }],
+ },
+ documentStyle: { documentFlavor, defaultTabStop },
+ });
+ const sourceBefore = JSON.stringify(dataModel.getSnapshot());
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ const line = curPage.sections[0].columns[0].lines[0];
+ const divide = line.divides[0];
+ const glyphs = divide.glyphGroup;
+ const b = glyphs.find((glyph) => glyph.content === 'B')!;
+ const c = glyphs.find((glyph) => glyph.content === 'C')!;
+ if (documentFlavor === DocumentFlavor.TRADITIONAL) {
+ expect(divide.left + divide.paddingLeft + b.left).toBeCloseTo(expected);
+ expect(c.left - b.left).toBeCloseTo(defaultTabStop);
+ } else {
+ expect(c.left - b.left).toBeCloseTo(b.width + defaultTabStop);
+ }
+ expect(JSON.stringify(dataModel.getSnapshot())).toBe(sourceBefore);
+ }
+ });
+
+ it.each([
+ { indent: 20.4, hanging: 20.4, stop: undefined, noTabHangInd: undefined, expected: 20.4 },
+ { indent: 30.4, hanging: 20.4, stop: undefined, noTabHangInd: BooleanNumber.FALSE, expected: 30.4 },
+ { indent: 80, hanging: 80, stop: undefined, noTabHangInd: undefined, expected: 80 },
+ { indent: 20.4, hanging: 20.4, stop: 16, noTabHangInd: undefined, expected: 16 },
+ { indent: 20.4, hanging: 20.4, stop: 100, noTabHangInd: undefined, expected: 20.4 },
+ { indent: 20.4, hanging: 20.4, stop: undefined, noTabHangInd: BooleanNumber.TRUE, expected: 48 },
+ { indent: 20.4, hanging: 20.4, stop: undefined, noTabHangInd: undefined, expected: 20.4, width: 30 },
+ ])('uses the hanging indent as an implicit tab stop: %j', ({ indent, hanging, stop, noTabHangInd, expected, width = 400 }) => {
+ const content = 'A\tB';
+ const bed = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ defaultTabStop: 48,
+ compatibilityFlags: noTabHangInd == null ? {} : { noTabHangInd },
+ pageSize: { width, height: 600 },
+ marginLeft: 0,
+ marginRight: 0,
+ },
+ body: { paragraphs: [{ startIndex: content.length, paragraphId: 'hanging-tabs', paragraphStyle: {
+ indentStart: { v: indent },
+ hanging: { v: hanging },
+ tabStops: stop == null ? [] : [{ offset: stop, alignment: TabStopAlignment.START }],
+ } }] },
+ });
+ try {
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = bed;
+ const before = JSON.stringify(bed.dataModel.getSnapshot());
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ const lines = pages[0].sections[0].columns[0].lines;
+ expect(lines).toHaveLength(1);
+ const divide = lines[0].divides[0];
+ const b = divide.glyphGroup.find((glyph) => glyph.content === 'B')!;
+ expect(divide.left + divide.paddingLeft + b.left).toBeCloseTo(expected);
+ expect(JSON.stringify(bed.dataModel.getSnapshot())).toBe(before);
+ } finally {
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
+
+ it('uses the default grid when the only inherited tab stop was cleared', () => {
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('A\tB', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, defaultTabStop: 48 },
+ body: { paragraphs: [{ startIndex: 3, paragraphStyle: {
+ tabStops: [{ offset: 200, alignment: TabStopAlignment.START, clear: true }],
+ } }] },
+ });
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ const glyphs = pages[0].sections[0].columns[0].lines[0].divides[0].glyphGroup;
+ expect(glyphs.find((glyph) => glyph.content === 'B')?.left).toBeCloseTo(48);
+ });
+
it('aligns following text to an explicit end tab stop', () => {
const tab = createGlyph(DataStreamTreeTokenType.TAB, 36);
tab.glyphType = GlyphType.TAB;
tab.left = 100;
+ tab.width = 464;
+ tab.bBox.width = 464;
const pageNumber = createGlyph('1', 8);
const paragraphMark = createGlyph(DataStreamTreeTokenType.PARAGRAPH, 8);
const divide = { glyphGroup: [tab], width: 580 } as IDocumentSkeletonDivide;
@@ -430,86 +858,700 @@ describe('layout-ruler', () => {
expect(tab.tabLeader).toBe(2);
});
- it('uses trailing CJK punctuation shrinkability when deciding line overflow', () => {
- const text = createGlyph('字', 10);
- const punctuation = createGlyph(',', 10);
- punctuation.adjustability.shrinkability = [0, 5];
+ it('realigns an end tab when a zero-width field marker separates it from a page number', () => {
+ const tab = createGlyph(DataStreamTreeTokenType.TAB, 36);
+ tab.glyphType = GlyphType.TAB;
+ tab.left = 100;
+ tab.width = 464;
+ tab.bBox.width = 464;
+ const fieldStart = createGlyph(DataStreamTreeTokenType.CUSTOM_RANGE_START, 0);
+ fieldStart.left = 564;
+ const divide = { glyphGroup: [tab, fieldStart], width: 580 } as IDocumentSkeletonDivide;
+ const paragraphConfig = {
+ paragraphStyle: {
+ tabStops: [{ offset: 560, alignment: 3, leader: 2 }],
+ },
+ } as IParagraphConfig;
- expect(__testing.isGlyphGroupBeyondDivideWidth([text, punctuation], 85, 100)).toBe(false);
- punctuation.adjustability.shrinkability = [0, 0];
- expect(__testing.isGlyphGroupBeyondDivideWidth([text, punctuation], 85, 100)).toBe(true);
+ __testing.adjustExplicitTabStop(divide, [createGlyph('12', 16)], paragraphConfig);
+
+ expect(tab.width).toBe(444);
+ expect(fieldStart.left).toBe(544);
+ expect(tab.tabLeader).toBe(2);
});
- it('allows explicit hanging punctuation to extend beyond the line end', () => {
- const text = createGlyph('字', 10);
- const punctuation = createGlyph('。', 10);
- punctuation.adjustability.shrinkability = [0, 0];
+ it.each([
+ ['margin', 3, 460],
+ ['indent', 3, 420],
+ ['margin', 2, 190],
+ ['indent', 2, 180],
+ ] as const)('aligns a positioned tab relative to %s with alignment %s', (relativeTo, alignment, expectedWidth) => {
+ const tab = createGlyph(DataStreamTreeTokenType.TAB, 36);
+ tab.glyphType = GlyphType.TAB;
+ tab.left = 20;
+ tab.ts = { positionedTab: { alignment, relativeTo } };
+ tab.tabAlignedTextWidth = 60;
+ const divide = {
+ glyphGroup: [tab],
+ width: 500,
+ left: 0,
+ paddingLeft: 60,
+ parent: { parent: { width: 600 }, paragraphPaddingLeft: 20, paragraphPaddingRight: 40 },
+ } as IDocumentSkeletonDivide;
+ __testing.adjustExplicitTabStop(divide, [createGlyph('First', 10)], {} as IParagraphConfig);
+ expect(tab.width).toBe(expectedWidth);
+ });
- expect(__testing.isGlyphGroupBeyondDivideWidth([text, punctuation], 85, 100)).toBe(true);
- expect(__testing.isGlyphGroupBeyondDivideWidth([text, punctuation], 85, 100, true)).toBe(false);
+ it.each([false, true])('measures every word after a tab up to the next tab (positioned: %s)', (positioned) => {
+ const { ctx, paragraphNode, viewModel, sectionBreakConfig } = createParagraphLayoutTestBed('\tone two\tlast', {
+ body: { textRuns: [{ st: 0, ed: 1, ts: positioned ? { positionedTab: { alignment: 3, relativeTo: 'margin' } } : {} }] },
+ });
+ const glyphs = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig).flatMap((text) => text.glyphs);
+ const firstTab = glyphs[0];
+ const nextTab = glyphs.findIndex((glyph, index) => index > 0 && glyph.glyphType === GlyphType.TAB);
+ expect(firstTab.tabAlignedTextWidth).toBeGreaterThan(0);
+ expect(firstTab.tabAlignedTextWidth).toBe(glyphs.slice(1, nextTab).reduce((width, glyph) => width + glyph.width, 0));
});
- it('keeps direct paragraph indents before bullet list defaults', () => {
- const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Item');
- const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.viewModel, paragraphNode, sectionBreakConfig);
- const bulletSkeleton = {
- listId: 'list-1',
- symbol: '-',
- ts: { ff: 'Arial', fs: 9 },
- startIndexItem: 1,
- paragraphProperties: {
- indentFirstLine: { v: 0 },
- hanging: { v: 24 },
- indentStart: { v: 48 },
+ it.each([TabStopAlignment.CENTER, TabStopAlignment.END])('aligns a complete multiword page field at an explicit tab (%s)', (alignment) => {
+ const content = 'Version: 2.0\tPagina \u001F35\u001E van 36';
+ const offset = alignment === TabStopAlignment.CENTER ? 240 : 360;
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: {
+ paragraphs: [{ startIndex: content.length, paragraphStyle: { tabStops: [
+ { offset: 120, alignment: TabStopAlignment.START, clear: true },
+ { offset, alignment },
+ ] } }],
},
- };
+ });
+ 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)));
+ expect(lines).toHaveLength(1);
+ const glyphs = lines[0].divides[0].glyphGroup;
+ const tabIndex = glyphs.findIndex((glyph) => glyph.glyphType === GlyphType.TAB);
+ const text = glyphs.slice(tabIndex + 1).filter((glyph) => glyph.width > 0 && glyph.content !== '\r');
+ expect(text.map((glyph) => glyph.content).join('')).toBe('Pagina 35 van 36');
+ const start = text[0].left;
+ const end = text[text.length - 1].left + text[text.length - 1].width;
+ expect(alignment === TabStopAlignment.END ? end : (start + end) / 2).toBeCloseTo(offset);
+ });
- const paragraphConfig = {
- paragraphIndex: paragraphNode.endIndex,
- paragraphStyle: {
- hanging: { v: 12 },
- indentStart: { v: 12 },
+ it('keeps the entire positioned end-tab field on an indented line', () => {
+ const bed = createParagraphLayoutTestBed('\t行业点评', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: {
+ textRuns: [{ st: 0, ed: 1, ts: { positionedTab: { alignment: 3, relativeTo: 'margin' } } }],
+ paragraphs: [{ startIndex: 5, paragraphStyle: { indentFirstLine: { v: 157.92 }, snapToGrid: 0 } }],
},
- bulletSkeleton,
- } as unknown as IParagraphConfig;
-
- layoutParagraph(
- ctx,
- shapedTextList[0].glyphs,
- [curPage],
- sectionBreakConfig,
- paragraphConfig,
- true
- );
-
- expect(paragraphConfig.paragraphStyle?.indentStart).toEqual({ v: 12 });
- expect(paragraphConfig.paragraphStyle?.hanging).toEqual({ v: 12 });
- expect(curPage.sections[0].columns[0].lines[0].divides[0].paddingLeft).toBe(0);
- expect(curPage.sections[0].columns[0].lines[0].divides[0].glyphGroup[0].width).toBe(12);
+ });
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = bed;
+ 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)));
+ expect(lines).toHaveLength(1);
+ const divide = lines[0].divides[0];
+ const text = divide.glyphGroup.filter((glyph) => glyph.content && glyph.content !== '\t' && glyph.content !== '\r');
+ expect(divide.glyphGroup.find((glyph) => glyph.glyphType === GlyphType.TAB)?.ts?.positionedTab).toEqual({ alignment: 3, relativeTo: 'margin' });
+ expect(text.map((glyph) => glyph.content).join('')).toBe('行业点评');
+ const lastGlyph = text[text.length - 1];
+ expect(divide.left + divide.paddingLeft + lastGlyph.left + lastGlyph.width).toBeCloseTo(lines[0].parent!.width);
});
- it('lays out first shaped text without bullet', () => {
- const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Hello world');
- const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.viewModel, paragraphNode, sectionBreakConfig);
-
- const paragraphConfig = {
- paragraphIndex: paragraphNode.endIndex,
- paragraphStyle: {},
- } as unknown as IParagraphConfig;
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('wraps fitting URLs as words only in traditional layout (%s)', (documentFlavor) => {
+ const prefix = '说明文字'.repeat(4);
+ const url = 'http://www.example.com';
+ const content = `${prefix}${url}网站`;
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor, pageSize: { width: 280, height: 600 } },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { snapToGrid: BooleanNumber.FALSE } }] },
+ });
+ const shaped = shaping(ctx, 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(''));
+ expect(lines.join('')).toBe(content);
+ if (documentFlavor === DocumentFlavor.TRADITIONAL) {
+ expect(lines[0]).toBe(prefix);
+ expect(lines[1]).toContain(url);
+ } else {
+ expect(lines[0].length).toBeGreaterThan(prefix.length);
+ }
+ });
- const result = layoutParagraph(
- ctx,
- shapedTextList[0].glyphs,
- [curPage],
- sectionBreakConfig,
- paragraphConfig,
- true
- );
+ it('splits a URL wider than an empty traditional line without losing glyphs', () => {
+ const content = `http://www.${'a'.repeat(60)}.com网站`;
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 200, height: 600 } },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { snapToGrid: BooleanNumber.FALSE } }] },
+ });
+ const shaped = shaping(ctx, 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)));
+ expect(lines.length).toBeGreaterThan(2);
+ expect(lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup)).map((glyph) => glyph.content).join('')).toBe(content);
+ for (const line of lines) {
+ for (const divide of line.divides) {
+ expect(divide.glyphGroup.reduce((width, glyph) => width + glyph.width, 0)).toBeLessThanOrEqual(divide.width);
+ }
+ }
+ });
- expect(result.length).toBe(1);
+ it.each([
+ { documentFlavor: DocumentFlavor.TRADITIONAL, compression: undefined, fits: true },
+ { documentFlavor: DocumentFlavor.TRADITIONAL, compression: characterSpacingControlType.doNotCompress, fits: false },
+ { documentFlavor: DocumentFlavor.MODERN, compression: undefined, fits: false },
+ ])('uses remaining punctuation compression at a native report Western-space-to-Han boundary ($documentFlavor/$compression)', ({ documentFlavor, compression, fits }) => {
+ const prefix = '年“煤改电”项目的推进下公司凭借完整的热泵专用压缩机系列提升了市场知名度。2018 ';
+ const content = `${prefix}年下半年开始`;
+ const measure = vi.spyOn(FontCache, 'getTextSize').mockImplementation((text) => {
+ let width = 13.333333333333334;
+ if (text === ' ') {
+ width = 3.7034912109375;
+ } else if (/^\d$/.test(text)) {
+ width = 7.413497924804688;
+ }
+ return { width, ba: 14, bd: 3, aba: 11, abd: 1, sp: 0, sbr: 0, sbo: 0, spr: 0, spo: 0 };
+ });
+ try {
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor,
+ characterSpacingControl: compression,
+ textStyle: { ff: 'Arial', eastAsiaFontFamily: '微软雅黑', fs: 10 },
+ pageSize: { width: 564.8, height: 600 },
+ },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { snapToGrid: BooleanNumber.FALSE, horizontalAlign: HorizontalAlign.BOTH } }] },
+ });
+ const shaped = shaping(ctx, 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)));
+ const firstLine = lines[0].divides[0].glyphGroup.map((glyph) => glyph.content).join('');
+ if (fits) {
+ expect(firstLine).toBe(`${prefix}年`);
+ } else {
+ expect(firstLine.length).toBeLessThanOrEqual(prefix.length);
+ }
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ expect(lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup)).map((glyph) => glyph.content).join('')).toBe(content);
+ if (fits) {
+ expect(lines[0].divides[0].glyphGroupWidth).toBeCloseTo(524.8);
+ }
+ expect(lines[0].divides[0].glyphGroupWidth).toBeLessThanOrEqual(lines[0].divides[0].width + 1e-8);
+ } finally {
+ measure.mockRestore();
+ }
});
- it('lays out non-first shaped text into existing page', () => {
+ it.each([HorizontalAlign.CENTER, HorizontalAlign.RIGHT].flatMap((horizontalAlign) =>
+ [DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN].flatMap((documentFlavor) =>
+ [undefined, characterSpacingControlType.doNotCompress].map((compression) => ({ horizontalAlign, documentFlavor, compression }))
+ )
+ ))('fits aligned table text using punctuation space ($horizontalAlign/$documentFlavor/$compression)', ({ horizontalAlign, documentFlavor, compression }) => {
+ const content = '12匹喷焓款产品(R410A)';
+ const widths: Record<string, number> = { R: 7.836, A: 8.448, ')': 4.008, '\r': 0 };
+ const measure = vi.spyOn(FontCache, 'getTextSize').mockImplementation((text) => ({
+ width: widths[text] ?? (/^\d$/.test(text) ? 7.032 : 12),
+ ba: 13,
+ bd: 3,
+ aba: 12,
+ abd: 1,
+ sp: 0,
+ sbr: 0,
+ sbo: 0,
+ spr: 0,
+ spo: 0,
+ }));
+ const bed = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor,
+ characterSpacingControl: compression,
+ textStyle: { ff: '微软雅黑', fs: 9 },
+ pageSize: { width: 136.8 + (documentFlavor === DocumentFlavor.MODERN ? 2 * MODERN_DOCUMENT_DEFAULT_MARGIN : 40), height: 600 },
+ },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { horizontalAlign, snapToGrid: BooleanNumber.FALSE } }] },
+ });
+ try {
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = bed;
+ 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)));
+ expect(lines).toHaveLength(documentFlavor === DocumentFlavor.TRADITIONAL && compression === undefined ? 1 : 2);
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ const glyphs = lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup));
+ expect(glyphs.map((glyph) => glyph.content).join('')).toBe(`${content}\r`);
+ for (const line of lines) {
+ const divide = line.divides[0];
+ expect(divide.glyphGroupWidth).toBeLessThanOrEqual(divide.width + 1e-6);
+ expect(divide.paddingLeft).toBeGreaterThanOrEqual(0);
+ }
+ for (const glyph of glyphs.filter((glyph) => /^[匹喷焓款产品]$/.test(glyph.content))) {
+ expect(glyph.bBox.width).toBe(12);
+ }
+ } finally {
+ measure.mockRestore();
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
+
+ it.each([HorizontalAlign.CENTER, HorizontalAlign.RIGHT])('retains Western word spacing with alignment %s', (horizontalAlign) => {
+ const content = 'AAAA AAAA AAAA';
+ const measure = vi.spyOn(FontCache, 'getTextSize').mockImplementation((text) => ({
+ width: text === '\r' ? 0 : 8,
+ ba: 10,
+ bd: 4,
+ aba: 10,
+ abd: 4,
+ sp: 0,
+ sbr: 0,
+ sbo: 0,
+ spr: 0,
+ spo: 0,
+ }));
+ const bed = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 142, height: 600 } },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { horizontalAlign } }] },
+ });
+ try {
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = bed;
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ const lines = pages[0].sections[0].columns[0].lines;
+ expect(lines).toHaveLength(2);
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ expect(lines[0].divides[0].glyphGroup.find((glyph) => glyph.content === ' ')?.width).toBe(8);
+ } finally {
+ measure.mockRestore();
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
+
+ it('does not pull an extra Han character onto a traditional line by pre-compressing a punctuation pair', () => {
+ const content = '甲),乙丙丁戊己庚辛';
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 90, height: 600 } },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { snapToGrid: BooleanNumber.FALSE, horizontalAlign: HorizontalAlign.BOTH } }] },
+ });
+ const shaped = shaping(ctx, 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)));
+ expect(lines[0].divides[0].glyphGroup.map((glyph) => glyph.content).join('')).toBe('甲),乙丙丁');
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ const divide = lines[0].divides[0];
+ const lastGlyph = divide.glyphGroup[divide.glyphGroup.length - 1];
+ expect(lastGlyph.left + lastGlyph.width).toBeCloseTo(divide.width);
+ });
+
+ it.each([undefined, characterSpacingControlType.doNotCompress])('matches the 9pt left-aligned report line without shrinking Han advances: %s', (compression) => {
+ // Native report line: 57 full-width glyphs in 509.4pt, with two punctuation
+ // advances reduced from 9pt to 7.2pt. The following Han glyph starts a new line.
+ const firstLine = `${'甲'.repeat(35)},${'乙'.repeat(13)}、${'丙'.repeat(7)}`;
+ const content = `${firstLine}丁戊己`;
+ const measure = vi.spyOn(FontCache, 'getTextSize').mockReturnValue({
+ width: 12,
+ ba: 10,
+ bd: 4,
+ aba: 10,
+ abd: 4,
+ sp: 0,
+ sbr: 0,
+ sbo: 0,
+ spr: 0,
+ spo: 0,
+ });
+ try {
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ characterSpacingControl: compression,
+ textStyle: { ff: 'Arial', fs: 9 },
+ pageSize: { width: 679.2 + 40, height: 600 },
+ },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { snapToGrid: BooleanNumber.FALSE, horizontalAlign: HorizontalAlign.LEFT } }] },
+ });
+ const shaped = shaping(ctx, 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)));
+ const divide = lines[0].divides[0];
+ expect(divide.glyphGroup.map((glyph) => glyph.content).join(''))
+ .toBe(compression === undefined ? firstLine : firstLine.slice(0, -1));
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ for (const glyph of divide.glyphGroup) {
+ const punctuation = glyph.content === ',' || glyph.content === '、';
+ expect(glyph.width).toBeCloseTo(punctuation && compression === undefined ? 9.6 : 12);
+ }
+ } finally {
+ measure.mockRestore();
+ }
+ });
+
+ it.each([
+ [undefined, false],
+ [0, true],
+ [-1, false],
+ [Number.NaN, false],
+ ] as const)('honors explicit line-wrap tolerance without changing legacy defaults (%s)', (tolerance, overflow) => {
+ const glyph = createGlyph('外', 10);
+ // The extra CJK character fits within the legacy 3px allowance, but not within the box.
+ expect(__testing.isGlyphGroupBeyondDivideWidth([glyph], 840, 847.428, false, undefined, false, tolerance)).toBe(overflow);
+ expect(__testing.isGlyphGroupBeyondDivideWidth([glyph], 837.428, 847.428, false, undefined, false, tolerance)).toBe(false);
+ });
+
+ it('does not wrap an exactly fitting fractional advance because of floating-point residue', () => {
+ expect(__testing.isGlyphGroupBeyondDivideWidth([createGlyph('甲', 0.1)], 0.2, 0.3, false, undefined, false, 0)).toBe(false);
+ expect(__testing.isGlyphGroupBeyondDivideWidth([createGlyph('甲', 0.101)], 0.2, 0.3, false, undefined, false, 0)).toBe(true);
+ });
+
+ it('uses trailing CJK punctuation shrinkability when deciding line overflow', () => {
+ const text = createGlyph('字', 10);
+ const punctuation = createGlyph(',', 10);
+ punctuation.adjustability.shrinkability = [0, 5];
+
+ expect(__testing.isGlyphGroupBeyondDivideWidth([text, punctuation], 85, 100)).toBe(false);
+ punctuation.adjustability.shrinkability = [0, 0];
+ expect(__testing.isGlyphGroupBeyondDivideWidth([text, punctuation], 85, 100)).toBe(true);
+ });
+
+ it.each([
+ { documentFlavor: DocumentFlavor.TRADITIONAL, compression: undefined, horizontalAlign: HorizontalAlign.JUSTIFIED, suffix: '2021年末', firstLine: '甲,乙,丙,2021' },
+ { documentFlavor: DocumentFlavor.TRADITIONAL, compression: characterSpacingControlType.doNotCompress, horizontalAlign: HorizontalAlign.JUSTIFIED, suffix: '2021年末', firstLine: '甲,乙,丙,' },
+ { documentFlavor: DocumentFlavor.MODERN, compression: undefined, horizontalAlign: HorizontalAlign.JUSTIFIED, suffix: '2021年末', firstLine: '甲,乙,丙,' },
+ { documentFlavor: DocumentFlavor.TRADITIONAL, compression: undefined, horizontalAlign: HorizontalAlign.LEFT, suffix: '2021年末', firstLine: '甲,乙,丙,2021' },
+ { documentFlavor: DocumentFlavor.TRADITIONAL, compression: characterSpacingControlType.doNotCompress, horizontalAlign: HorizontalAlign.LEFT, suffix: '2021年末', firstLine: '甲,乙,丙,' },
+ { documentFlavor: DocumentFlavor.TRADITIONAL, compression: undefined, horizontalAlign: HorizontalAlign.JUSTIFIED, suffix: '文字排版正常', firstLine: '甲,乙,丙,文字排' },
+ { documentFlavor: DocumentFlavor.TRADITIONAL, compression: undefined, horizontalAlign: HorizontalAlign.BOTH, suffix: '文字排版正常', firstLine: '甲,乙,丙,文字排' },
+ { documentFlavor: DocumentFlavor.TRADITIONAL, compression: undefined, horizontalAlign: HorizontalAlign.BOTH, suffix: '丁,文字排版正常', firstLine: '甲,乙,丙,丁,文' },
+ { documentFlavor: DocumentFlavor.TRADITIONAL, compression: undefined, horizontalAlign: HorizontalAlign.DISTRIBUTED, suffix: '文字排版正常', firstLine: '甲,乙,丙,文字排' },
+ { documentFlavor: DocumentFlavor.TRADITIONAL, compression: undefined, horizontalAlign: HorizontalAlign.LEFT, suffix: '文字排版正常', firstLine: '甲,乙,丙,文字排' },
+ ])('respects traditional character compression independently of justification: $documentFlavor/$compression/$horizontalAlign/$suffix', ({ documentFlavor, compression, horizontalAlign, suffix, firstLine }) => {
+ const content = `甲,乙,丙,${suffix}`;
+ const margin = documentFlavor === DocumentFlavor.MODERN ? MODERN_DOCUMENT_DEFAULT_MARGIN : 20;
+ const { ctx, paragraphNode, viewModel, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor, characterSpacingControl: compression, pageSize: { width: 72 + margin * 2, height: 600 } },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { snapToGrid: BooleanNumber.FALSE, horizontalAlign } }] },
+ });
+ const shaped = shaping(ctx, 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)));
+ const firstDivide = lines[0].divides[0];
+ expect(firstDivide.glyphGroup.map((glyph) => glyph.content).join(''))
+ .toBe(firstLine);
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ const glyphs = firstDivide.glyphGroup;
+ for (let i = 1; i < glyphs.length; i++) {
+ expect(glyphs[i].left).toBeCloseTo(glyphs[i - 1].left + glyphs[i - 1].width);
+ }
+ if (firstLine !== '甲,乙,丙,') {
+ const lastGlyph = glyphs[glyphs.length - 1];
+ expect(lastGlyph.left + lastGlyph.width).toBeLessThanOrEqual(firstDivide.width + 1e-8);
+ }
+ });
+
+ it.each([HorizontalAlign.JUSTIFIED, HorizontalAlign.BOTH])('justifies Western word spaces even when East Asian punctuation compression is disabled (%s)', (horizontalAlign) => {
+ const content = 'aa bb cc dd';
+ const { ctx, paragraphNode, viewModel, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ characterSpacingControl: characterSpacingControlType.doNotCompress,
+ pageSize: { width: 108, height: 600 },
+ textStyle: { fs: 11 },
+ },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { horizontalAlign } }] },
+ });
+ const shaped = shaping(ctx, content, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ const lines = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));
+ expect(lines[0].divides[0].glyphGroup.map((glyph) => glyph.content).join('').trimEnd()).toBe('aa bb cc');
+ const visibleGlyphs = lines[0].divides[0].glyphGroup.filter((glyph) => glyph.content.trim());
+ const lastVisibleGlyph = visibleGlyphs[visibleGlyphs.length - 1];
+ expect(lastVisibleGlyph.left + lastVisibleGlyph.width).toBeCloseTo(68);
+ });
+
+ it.each([
+ { content: 'aa bb cc dddd ee', width: 98, horizontalAlign: HorizontalAlign.BOTH, hanging: false, first: 'aa bb cc dddd', count: 2 },
+ { content: 'aa bb cc dddd ee', width: 97.9, horizontalAlign: HorizontalAlign.BOTH, hanging: false, first: 'aa bb cc', count: 2 },
+ { content: 'aa bb cc dddd ee', width: 98, horizontalAlign: HorizontalAlign.LEFT, hanging: false, first: 'aa bb cc', count: 2 },
+ { content: 'aa bb cc dd ee', width: 82, horizontalAlign: HorizontalAlign.BOTH, hanging: false, first: 'aa bb cc', count: 2 },
+ { content: 'aa bb cc dd ee', width: 84, horizontalAlign: HorizontalAlign.BOTH, hanging: false, first: 'aa bb cc dd', count: 2 },
+ { content: 'aa bb cc dd.', width: 86, horizontalAlign: HorizontalAlign.BOTH, hanging: true, first: 'aa bb cc dd.', count: 1 },
+ { content: 'aa bb cc dd.', width: 86, horizontalAlign: HorizontalAlign.BOTH, hanging: false, first: 'aa bb cc', count: 2 },
+ { content: 'aa bb cc dd.x', width: 86, horizontalAlign: HorizontalAlign.BOTH, hanging: true, first: 'aa bb cc', count: 2 },
+ { content: 'aa bb cc dd....', width: 86, horizontalAlign: HorizontalAlign.BOTH, hanging: true, first: 'aa bb cc', count: 2 },
+ ])('bounds Word justified compression and terminal punctuation ($content/$width/$horizontalAlign/$hanging)', ({ content, width, horizontalAlign, hanging, first, count }) => {
+ const { ctx, paragraphNode, viewModel, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ characterSpacingControl: characterSpacingControlType.doNotCompress,
+ pageSize: { width: width + 40, height: 600 },
+ },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { horizontalAlign, hangingPunctuation: hanging ? BooleanNumber.TRUE : BooleanNumber.FALSE } }] },
+ });
+ const shaped = shaping(ctx, content, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ const lines = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));
+ expect(lines).toHaveLength(count);
+ expect(lines[0].divides[0].glyphGroup.map((glyph) => glyph.content).join('').trimEnd()).toBe(first);
+ const visible = lines[0].divides[0].glyphGroup.filter((glyph) => glyph.content.trim());
+ const last = visible[visible.length - 1];
+ const overhang = hanging && last.content === '.' ? last.bBox.width * 0.8 : 0;
+ expect(last.left + last.width).toBeLessThanOrEqual(width + overhang + 1e-6);
+ expect(lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content))).join('').trimEnd()).toBe(content);
+ });
+
+ it.each([undefined, HorizontalAlign.LEFT, HorizontalAlign.JUSTIFIED, HorizontalAlign.BOTH].flatMap((horizontalAlign) => [41, 62].map((width) => ({ horizontalAlign, width }))))('chooses the same Western word break before justification ($horizontalAlign/$width)', ({ horizontalAlign, width }) => {
+ const content = 'aa bb cc';
+ const { ctx, paragraphNode, viewModel, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: width + 40, height: 600 } },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { horizontalAlign } }] },
+ });
+ const shaped = shaping(ctx, content, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ const lines = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));
+ expect(lines).toHaveLength(2);
+ expect(lines[0].divides[0].glyphGroup.map((glyph) => glyph.content).join('')).toBe('aa bb ');
+ if (horizontalAlign === HorizontalAlign.JUSTIFIED || horizontalAlign === HorizontalAlign.BOTH) {
+ const visibleGlyphs = lines[0].divides[0].glyphGroup.filter((glyph) => glyph.content.trim());
+ const lastVisibleGlyph = visibleGlyphs[visibleGlyphs.length - 1];
+ expect(lastVisibleGlyph.left + lastVisibleGlyph.width).toBeCloseTo(width);
+ const trailingSpace = lines[0].divides[0].glyphGroup[lines[0].divides[0].glyphGroup.length - 1];
+ expect(trailingSpace.width).toBeCloseTo(trailingSpace.bBox.width);
+ } else {
+ const spaces = lines[0].divides[0].glyphGroup.filter((glyph) => glyph.content === ' ');
+ for (const space of spaces) {
+ expect(space.width).toBeCloseTo(space.bBox.width);
+ }
+ }
+ });
+
+ it.each([
+ { width: 74, suffix: '文字排版正常', firstLine: '甲,乙,丙,文字排' },
+ { width: 77, suffix: '文字排版正常', firstLine: '甲,乙,丙,文字排版' },
+ { width: 59, suffix: '21。后续', firstLine: '甲,乙,丙,21。' },
+ { width: 89, suffix: '丁,戊2021年末', firstLine: '甲,乙,丙,丁,戊2021' },
+ { width: 88, suffix: '丁,戊2021年末', firstLine: '甲,乙,丙,丁,戊' },
+ ])('chooses the closer legal CJK break after line-end punctuation adjustment ($width/$suffix)', ({ width, suffix, firstLine }) => {
+ const content = `甲,乙,丙,${suffix}`;
+ const { ctx, paragraphNode, viewModel, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: width + 40, height: 600 } },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { snapToGrid: BooleanNumber.FALSE, horizontalAlign: HorizontalAlign.BOTH } }] },
+ });
+ 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)));
+ const divide = lines[0].divides[0];
+ expect(divide.glyphGroup.map((glyph) => glyph.content).join('')).toBe(firstLine);
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ expect(divide.glyphGroupWidth).toBeCloseTo(width, 5);
+ expect(lines.flatMap((line) => line.divides.flatMap((part) => part.glyphGroup)).map((glyph) => glyph.content).join(''))
+ .toBe(`${content}\r`);
+ viewModel.dispose();
+ });
+
+ it.each([
+ { offsetLeft: 485, wordWidth: 40, punctuationShrink: 24.2, overflows: false },
+ { offsetLeft: 485, wordWidth: 40, punctuationShrink: 23, overflows: true },
+ { offsetLeft: 505, wordWidth: 10, punctuationShrink: 20, overflows: true },
+ ])('limits Western-word compression to a fitting preceding line and pixel rounding ($offsetLeft/$punctuationShrink)', ({ offsetLeft, wordWidth, punctuationShrink, overflows }) => {
+ const punctuation = createGlyph(',', 60);
+ punctuation.adjustability.shrinkability = [0, punctuationShrink];
+ expect(__testing.isGlyphGroupBeyondDivideWidth(
+ [createGlyph('2024', wordWidth)],
+ offsetLeft,
+ 500,
+ false,
+ [createGlyph('文', offsetLeft - 60), punctuation]
+ )).toBe(overflows);
+ });
+
+ it.each([
+ { preceding: '8', space: ' ', incoming: '年', punctuationShrink: 20, overflows: false },
+ { preceding: 'A', space: ' ', incoming: '中', punctuationShrink: 20, overflows: false },
+ { preceding: '8', space: ' ', incoming: '年', punctuationShrink: 10, overflows: true },
+ { preceding: '字', space: ' ', incoming: '年', punctuationShrink: 20, overflows: true },
+ { preceding: '8', space: ' ', incoming: 'A', punctuationShrink: 20, overflows: true },
+ { preceding: '8', space: '\u00A0', incoming: '年', punctuationShrink: 20, overflows: true },
+ ])('bounds punctuation borrowing at explicit Western-space boundaries ($preceding/$space/$incoming/$punctuationShrink)', ({ preceding, space, incoming, punctuationShrink, overflows }) => {
+ const punctuation = createGlyph(',', 40);
+ punctuation.adjustability.shrinkability = [0, punctuationShrink];
+ expect(__testing.isGlyphGroupBeyondDivideWidth(
+ [createGlyph(incoming, 10)],
+ 505,
+ 500,
+ false,
+ [createGlyph('文', 455), punctuation, createGlyph(preceding, 7), createGlyph(space, 3)]
+ )).toBe(overflows);
+ });
+
+ it.each([0, 2])('prefers natural gap expansion only at a new Western-to-Han boundary (%i)', (autoSpacing) => {
+ const preceding = createGlyph('甲A乙B', 94);
+ preceding.adjustability.stretchability = [0, 6];
+ preceding.adjustability.shrinkability = [0, 6];
+ const incoming = createGlyph('中', 10 + autoSpacing);
+ incoming.autoSpacing = [autoSpacing, 0];
+ incoming.adjustability.stretchability = [autoSpacing / 2, 0];
+ incoming.adjustability.shrinkability = [autoSpacing / 2, 0];
+ expect(__testing.isGlyphGroupBeyondDivideWidth([incoming], 94, 100, false, [preceding]))
+ .toBe(autoSpacing > 0);
+ });
+
+ it('does not borrow compression across a fixed tab anchor', () => {
+ const punctuation = createGlyph(',', 20);
+ punctuation.adjustability.shrinkability = [0, 10];
+ const word = createGlyph('2021', 20);
+ const tab = createGlyph('\t', 0);
+ tab.glyphType = GlyphType.TAB;
+ expect(__testing.isGlyphGroupBeyondDivideWidth([word], 85, 100, false, [punctuation])).toBe(false);
+ expect(__testing.isGlyphGroupBeyondDivideWidth([createGlyph('文字', 20)], 85, 100, false, [punctuation])).toBe(false);
+ expect(__testing.isGlyphGroupBeyondDivideWidth([word], 85, 100, false, [punctuation, tab])).toBe(true);
+ expect(__testing.isGlyphGroupBeyondDivideWidth([tab, word], 85, 100, false, [punctuation])).toBe(true);
+ });
+
+ it.each([
+ { content: '中A文B', width: 8, expectedLines: ['中', 'A', '文', 'B\r'], widths: [8, 8, 8, 8] },
+ { content: '中A文B', width: 100, expectedLines: ['中A文B\r'], widths: [10, 8, 12, 8] },
+ { content: 'A中文B', width: 26, expectedLines: ['A中文', 'B\r'], widths: [8, 10, 8, 8] },
+ ])('keeps automatic CJK/Latin spacing only between glyphs on the same line: $content/$width', ({ content, width, expectedLines, widths }) => {
+ const { ctx, paragraphNode, viewModel, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: width + 40, height: 600 } },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { snapToGrid: BooleanNumber.FALSE, horizontalAlign: HorizontalAlign.LEFT } }] },
+ });
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ const lines = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));
+ expect(lines.map((line) => line.divides.flatMap((divide) => divide.glyphGroup).map((glyph) => glyph.content).join(''))).toEqual(expectedLines);
+ const glyphs = lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup))
+ .filter((glyph) => glyph.content !== '\r' && glyph.content !== '');
+ expect(glyphs.map((glyph) => glyph.width)).toEqual(widths);
+ for (const line of lines) {
+ expect(line.divides[0].glyphGroup[0].xOffset).toBe(0);
+ }
+ viewModel.dispose();
+ });
+
+ it.each(['', '\r', '\u2028'])('allows explicit hanging punctuation before a terminal control (%j)', (control) => {
+ const text = createGlyph('字', 10);
+ const punctuation = createGlyph('。', 10);
+ punctuation.adjustability.shrinkability = [0, 0];
+ const glyphs = [text, punctuation];
+ if (control) {
+ glyphs.push(createGlyph(control, 0), createGlyph('', 0));
+ }
+
+ expect(__testing.isGlyphGroupBeyondDivideWidth(glyphs, 85, 100)).toBe(true);
+ expect(__testing.isGlyphGroupBeyondDivideWidth(glyphs, 85, 100, true)).toBe(false);
+ });
+
+ it.each([0, 1, 2])('allows hanging punctuation before %s structural terminators', (terminatorCount) => {
+ const text = createGlyph('字', 10);
+ const punctuation = createGlyph('。', 10);
+ punctuation.adjustability.shrinkability = [0, 0];
+ const paragraph = createGlyph(DataStreamTreeTokenType.PARAGRAPH, 8);
+ const section = createGlyph(DataStreamTreeTokenType.SECTION_BREAK, 8);
+ section.streamType = DataStreamTreeTokenType.SECTION_BREAK;
+ const glyphs = [text, punctuation, ...[paragraph, section].slice(0, terminatorCount)];
+ expect(__testing.isGlyphGroupBeyondDivideWidth(glyphs, 85, 100)).toBe(true);
+ expect(__testing.isGlyphGroupBeyondDivideWidth(glyphs, 85, 100, true)).toBe(false);
+ });
+
+ it.each([
+ ['ja-JP', undefined, ')', true],
+ ['ja', undefined, '」', true],
+ ['JA-jp', undefined, '!', true],
+ ['ja-JP', undefined, '。', false],
+ ['ja-JP', undefined, '、', false],
+ ['ja-JP', undefined, '.', false],
+ ['ja-JP', undefined, ',', false],
+ ['zh-CN', undefined, ')', false],
+ [undefined, undefined, ')', false],
+ ['ja-JP', 'en-US', ')', true],
+ ['ja-JP', 'ja-JP', ')', true],
+ ['ja-JP', 'zh-CN', ')', false],
+ ['ja-JP', 'zh-TW', ')', false],
+ ['ja-JP', 'ko-KR', ')', false],
+ ['zh-CN', 'ja-JP', ')', true],
+ ['zh-CN', 'en-US', ')', false],
+ ['en-US', 'ja-JP', ')', true],
+ ['ko-KR', 'ja-JP', ')', true],
+ ] as const)('uses authored language %s / %s for hanging %s without changing compression', (lang, altLang, content, overflow) => {
+ const text = createGlyph('字', 10);
+ const punctuation = createGlyph(content, 10);
+ punctuation.ts = { lang, altLang };
+ punctuation.adjustability.shrinkability = [0, 0];
+ const glyphs = [text, punctuation, createGlyph('\r', 0)];
+ expect(__testing.isGlyphGroupBeyondDivideWidth(glyphs, 85, 100, true)).toBe(overflow);
+ expect(__testing.isGlyphGroupBeyondDivideWidth(glyphs, 85, 100, false)).toBe(true);
+ punctuation.adjustability.shrinkability = [0, 5];
+ expect(__testing.isGlyphGroupBeyondDivideWidth(glyphs, 85, 100, false)).toBe(false);
+ });
+
+ it('keeps direct paragraph indents before bullet list defaults', () => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Item');
+ const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.viewModel, paragraphNode, sectionBreakConfig);
+ const bulletSkeleton = {
+ listId: 'list-1',
+ symbol: '-',
+ ts: { ff: 'Arial', fs: 9 },
+ startIndexItem: 1,
+ paragraphProperties: {
+ indentFirstLine: { v: 0 },
+ hanging: { v: 24 },
+ indentStart: { v: 48 },
+ },
+ };
+
+ const paragraphConfig = {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: {
+ hanging: { v: 12 },
+ indentStart: { v: 12 },
+ },
+ bulletSkeleton,
+ } as unknown as IParagraphConfig;
+
+ layoutParagraph(
+ ctx,
+ shapedTextList[0].glyphs,
+ [curPage],
+ sectionBreakConfig,
+ paragraphConfig,
+ true
+ );
+
+ expect(paragraphConfig.paragraphStyle?.indentStart).toEqual({ v: 12 });
+ expect(paragraphConfig.paragraphStyle?.hanging).toEqual({ v: 12 });
+ expect(curPage.sections[0].columns[0].lines[0].divides[0].paddingLeft).toBe(0);
+ expect(curPage.sections[0].columns[0].lines[0].divides[0].glyphGroup[0].width).toBe(12);
+ });
+
+ it('lays out first shaped text without bullet', () => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Hello world');
+ const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.viewModel, paragraphNode, sectionBreakConfig);
+
+ const paragraphConfig = {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: {},
+ } as unknown as IParagraphConfig;
+
+ const result = layoutParagraph(
+ ctx,
+ shapedTextList[0].glyphs,
+ [curPage],
+ sectionBreakConfig,
+ paragraphConfig,
+ true
+ );
+
+ expect(result.length).toBe(1);
+ });
+
+ it('lays out non-first shaped text into existing page', () => {
const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Hello world this is a test');
const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.viewModel, paragraphNode, sectionBreakConfig);
@@ -742,6 +1784,208 @@ describe('layout-ruler', () => {
expect(lastPage.sections.length).toBeGreaterThan(0);
});
+ it.each([[90, 1], [100, 2]])('uses character scale %s when choosing line breaks', (sa, lineCount) => {
+ const text = '一二三四五六七八九十一二';
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(text, {
+ body: {
+ textRuns: [{ st: 0, ed: text.length, ts: { sa } }],
+ paragraphs: [{ startIndex: text.length, paragraphId: 'scaled', paragraphStyle: { snapToGrid: BooleanNumber.FALSE, textStyle: { sa } } }],
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 130, height: 600 },
+ },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL);
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ expect(shaped.flatMap((part) => part.glyphs).filter((glyph) => glyph.content !== '\r').reduce((sum, glyph) => sum + glyph.width, 0)).toBeCloseTo(96 * sa / 100);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ expect(pages[0].sections[0].columns[0].lines).toHaveLength(lineCount);
+ });
+
+ it.each([
+ [DocumentFlavor.TRADITIONAL, false, true, false],
+ [DocumentFlavor.TRADITIONAL, true, false, false],
+ [DocumentFlavor.MODERN, false, false, false],
+ [DocumentFlavor.TRADITIONAL, true, true, true],
+ [DocumentFlavor.MODERN, true, false, true],
+ ])('keeps only structural table anchors heightless: flavor=%s authored=%s heightless=%s framed=%s', (documentFlavor, authored, heightless, framed) => {
+ const T = DataStreamTreeTokenType;
+ const tableStream = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const paragraphFrame = framed ? { wrap: 'around', horizontalAnchor: 'page', verticalAnchor: 'page', x: '1', y: '1' } : undefined;
+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(`${tableStream}${T.PARAGRAPH}`, {
+ body: {
+ paragraphs: [
+ { startIndex: tableStream.indexOf(T.PARAGRAPH), paragraphId: 'cell' },
+ ...(authored ? [{ startIndex: tableStream.length, paragraphId: 'authored-anchor', paragraphStyle: { paragraphFrame } }] : []),
+ { startIndex: tableStream.length + 1, paragraphId: 'following-empty-paragraph', paragraphStyle: { paragraphFrame } },
+ ],
+ tables: [{ tableId: 'table', startIndex: 0, endIndex: tableStream.length }],
+ },
+ tableSource: {
+ table: {
+ tableId: 'table',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: {
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE },
+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE },
+ },
+ dist: { top: 0, bottom: 0, left: 0, right: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 280 } },
+ tableRows: [{
+ tableCells: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 280 } } }],
+ trHeight: { val: { v: 80 }, hRule: TableRowHeightRule.EXACT },
+ }],
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 280 } } }],
+ },
+ },
+ documentStyle: { documentFlavor },
+ });
+ const table = createTableSkeleton(ctx, curPage, viewModel, paragraphNode.children[0], sectionBreakConfig);
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, table);
+ const anchorLine = pages[0].sections[0].columns[0].lines[0];
+
+ expect(table?.height).toBe(80);
+ expect(anchorLine.top).toBeCloseTo(table!.top + table!.height);
+ if (heightless) {
+ expect(anchorLine.lineHeight).toBe(0);
+ } else {
+ expect(anchorLine.lineHeight).toBeGreaterThan(0);
+ }
+
+ const followingNode = viewModel.getChildren()[0].children[1];
+ const followingShaped = shaping(ctx, followingNode.content!, viewModel, followingNode, sectionBreakConfig);
+ const followingPages = lineBreaking(ctx, viewModel, followingShaped, pages[0], followingNode, sectionBreakConfig, null);
+ const followingLine = followingPages[0].sections[0].columns[0].lines[1];
+ expect(followingLine.lineHeight).toBeGreaterThan(0);
+ expect(followingLine.top).toBeCloseTo(anchorLine.top + anchorLine.lineHeight);
+ expect(dataModel.getBody()?.dataStream).toBe(`${tableStream}${T.PARAGRAPH}${T.PARAGRAPH}${T.SECTION_BREAK}`);
+ });
+
+ it.each([
+ [DocumentFlavor.TRADITIONAL, BooleanNumber.TRUE, 0],
+ [DocumentFlavor.MODERN, BooleanNumber.TRUE, 23.4],
+ [DocumentFlavor.TRADITIONAL, BooleanNumber.FALSE, null],
+ [DocumentFlavor.MODERN, BooleanNumber.FALSE, 23.4],
+ [DocumentFlavor.TRADITIONAL, { horizontalSpace: 12, wrap: 'around', verticalAnchor: 'page', horizontalAnchor: 'page', x: '1', y: '1' }, null],
+ [DocumentFlavor.MODERN, { horizontalSpace: 12, wrap: 'around', verticalAnchor: 'page', horizontalAnchor: 'page', x: '1', y: '1' }, 23.4],
+ ] as const)('preserves authored frame blanks except legacy structural markers: %s, %j', (documentFlavor, paragraphFrame, expectedHeight) => {
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('', {
+ body: {
+ paragraphs: [{
+ startIndex: 0,
+ paragraphId: 'empty-frame',
+ paragraphStyle: { paragraphFrame },
+ }],
+ },
+ documentStyle: { documentFlavor },
+ });
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+
+ const lineHeight = pages[0].sections[0].columns[0].lines[0].lineHeight;
+ if (expectedHeight == null) {
+ expect(lineHeight).toBeGreaterThan(0);
+ } else {
+ expect(lineHeight).toBe(expectedHeight);
+ }
+ });
+
+ it('retains visible text and its authored spacing inside a positioned Word frame', () => {
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Frame text', {
+ body: {
+ paragraphs: [{
+ startIndex: 10,
+ paragraphId: 'visible-frame',
+ paragraphStyle: {
+ paragraphFrame: { wrap: 'around', horizontalAnchor: 'page', verticalAnchor: 'page', x: '1', y: '1' },
+ spaceAbove: { v: 10 },
+ spaceBelow: { v: 12 },
+ },
+ }],
+ },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ const line = pages[0].sections[0].columns[0].lines[0];
+
+ expect(line.lineHeight).toBeGreaterThan(10);
+ expect(line.spaceBelowApply).toBe(12);
+ expect(line.divides.flatMap((divide) => divide.glyphGroup).map((glyph) => glyph.content).join('')).toContain('Frame text');
+ });
+
+ it.each([
+ [DocumentFlavor.UNSPECIFIED, undefined, 1],
+ [DocumentFlavor.MODERN, undefined, 1],
+ [DocumentFlavor.TRADITIONAL, undefined, 2],
+ [DocumentFlavor.TRADITIONAL, 1, 1],
+ [DocumentFlavor.DRAWINGML, undefined, 2],
+ [DocumentFlavor.DRAWINGML, 1, 1],
+ ] as const)('uses the host wrapping default with an optional explicit tolerance (%s, %s)', (documentFlavor, lineWrapTolerance, expectedLines) => {
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('甲乙', {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.UNSPECIFIED,
+ pageSize: { width: 55.5, height: 300 },
+ marginLeft: 20,
+ marginRight: 20,
+ marginTop: 0,
+ marginBottom: 0,
+ spaceWidthEastAsian: BooleanNumber.FALSE,
+ renderConfig: { lineWrapTolerance, zeroWidthParagraphBreak: BooleanNumber.TRUE },
+ },
+ body: { paragraphs: [{ startIndex: 2, paragraphId: 'host-wrapping', paragraphStyle: { snapToGrid: BooleanNumber.FALSE } }] },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(documentFlavor);
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ expect(pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)))).toHaveLength(expectedLines);
+ });
+
+ it.each([DocumentFlavor.DRAWINGML, DocumentFlavor.UNSPECIFIED, DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN]
+ .flatMap((documentFlavor) => [undefined, BooleanNumber.FALSE, BooleanNumber.TRUE]
+ .flatMap((zeroWidthParagraphBreak) => [false, true].map((empty) => ({ documentFlavor, zeroWidthParagraphBreak, empty })))))('preserves paragraph marks without wrapping fitting DrawingML text ($documentFlavor, $zeroWidthParagraphBreak, empty=$empty)', ({ documentFlavor, zeroWidthParagraphBreak, empty }) => {
+ clearFontCreateConfigCache();
+ const content = empty ? '' : 'AA BB';
+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.UNSPECIFIED,
+ pageSize: { width: 81, height: 300 },
+ marginLeft: 20,
+ marginRight: 20,
+ marginTop: 0,
+ marginBottom: 0,
+ renderConfig: { zeroWidthParagraphBreak },
+ },
+ body: {
+ textRuns: [{ st: content.length, ed: content.length + 1, ts: { fs: 11, bl: BooleanNumber.TRUE } }],
+ paragraphs: [{ startIndex: content.length, paragraphId: 'paragraph-mark-width', paragraphStyle: { snapToGrid: BooleanNumber.FALSE } }],
+ },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(documentFlavor);
+ const before = JSON.stringify(dataModel.getSnapshot());
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const mark = shaped.flatMap((item) => item.glyphs).find((glyph) => glyph.content === '\r')!;
+ const zeroWidth = zeroWidthParagraphBreak === BooleanNumber.TRUE || documentFlavor === DocumentFlavor.TRADITIONAL ||
+ (zeroWidthParagraphBreak == null && documentFlavor === DocumentFlavor.DRAWINGML);
+ const authoredMarkAdvance = 8;
+ const expectedMarkAdvance = documentFlavor === DocumentFlavor.DRAWINGML
+ ? Math.round(authoredMarkAdvance * 8) / 8
+ : authoredMarkAdvance;
+ expect(mark.width).toBe(zeroWidth ? 0 : expectedMarkAdvance);
+ expect(mark.count).toBe(1);
+ expect(mark.ts).toMatchObject({ fs: 11, bl: BooleanNumber.TRUE });
+ 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)));
+ expect(lines).toHaveLength(empty || zeroWidth ? 1 : 2);
+ expect(lines.every((line) => line.lineHeight > 0)).toBe(true);
+ expect(lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup)).map((glyph) => glyph.content).join('')).toBe(`${content}\r`);
+ expect(JSON.stringify(dataModel.getSnapshot())).toBe(before);
+ });
+
it('keeps imported shape text on one line when browser glyph bboxes slightly exceed the box', () => {
const text = '\u4F01\u4E1A\u6587\u5316\u5EFA\u8BBE';
const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(text, {
@@ -774,22 +2018,467 @@ describe('layout-ruler', () => {
expect(lines[0].divides[0].glyphGroup.map((glyph) => glyph.content).join('')).toBe(text);
});
+ it.each([DocumentFlavor.DRAWINGML, DocumentFlavor.UNSPECIFIED, DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN]
+ .flatMap((documentFlavor) => [false, true].flatMap((empty) => [false, true].map((split) => ({ documentFlavor, empty, split })))))('uses paragraph-end metrics only for empty Office lines ($documentFlavor, empty=$empty, split=$split)', ({ documentFlavor, empty, split }) => {
+ const measure = (markSize: number) => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(empty ? '' : 'a', {
+ documentStyle: { pageSize: { width: 300, height: 300 }, marginTop: 0, marginBottom: 0, paragraphLineGapDefault: 0 },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(documentFlavor);
+ const textGlyph = createGlyph('a', 12);
+ textGlyph.fontStyle!.originFontSize = 10.5;
+ textGlyph.bBox.ba = 12;
+ textGlyph.bBox.bd = 3;
+ const markGlyph = createGlyph('\r', 0);
+ markGlyph.streamType = DataStreamTreeTokenType.PARAGRAPH;
+ markGlyph.fontStyle!.originFontSize = markSize;
+ markGlyph.bBox.ba = markSize;
+ markGlyph.bBox.bd = markSize / 4;
+ const paragraphConfig: IParagraphConfig = {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: { lineSpacing: 1, spacingRule: SpacingRule.AUTO, snapToGrid: BooleanNumber.FALSE },
+ useWordStyleLineHeight: false,
+ skeHeaders: ctx.skeletonResourceReference.skeHeaders,
+ skeFooters: ctx.skeletonResourceReference.skeFooters,
+ };
+ if (split && !empty) {
+ layoutParagraph(ctx, [textGlyph], [curPage], sectionBreakConfig, paragraphConfig, true);
+ }
+ const glyphs = empty || split ? [markGlyph] : [textGlyph, markGlyph];
+ const pages = layoutParagraph(ctx, glyphs, [curPage], sectionBreakConfig, paragraphConfig, empty || !split);
+ updateBlockIndex(pages, -1, sectionBreakConfig.documentCompatibilityPolicy);
+ const lines = pages[0].sections[0].columns[0].lines;
+ expect(lines).toHaveLength(1);
+ expect(markGlyph.fontStyle!.originFontSize).toBe(markSize);
+ return [lines[0].contentHeight, lines[0].paddingTop, lines[0].paddingBottom, lines[0].lineHeight, lines[0].asc, lines[0].dsc];
+ };
+ const small = measure(18);
+ const large = measure(36);
+ if ((documentFlavor === DocumentFlavor.DRAWINGML || documentFlavor === DocumentFlavor.TRADITIONAL) && !empty) {
+ expect(large).toEqual(small);
+ } else {
+ expect(large).not.toEqual(small);
+ }
+ });
+
it('uses glyph height as the base for auto line spacing when grid snapping is not explicitly enabled', () => {
const metrics = getLineHeightMetrics(16, 0, 15.6, GridType.LINES, 1.5, SpacingRule.AUTO, BooleanNumber.FALSE, true);
- expect(getLineBoxHeight(metrics)).toBeCloseTo(24, 4);
+ expect(getLineBoxHeight(metrics)).toBeCloseTo(24, 4);
+ });
+
+ it.each([
+ { fontSize: 10.5, lineSpacing: 1.5, spacingRule: SpacingRule.AUTO, expectedHeight: 25.2 },
+ { fontSize: 9, lineSpacing: 1.5, spacingRule: SpacingRule.AUTO, expectedHeight: 21.6 },
+ { fontSize: 10.5, lineSpacing: 12, spacingRule: SpacingRule.EXACT, expectedHeight: 12 },
+ { fontSize: 9, lineSpacing: 11, spacingRule: SpacingRule.EXACT, expectedHeight: 11 },
+ ].map((entry) => ({ ...entry, documentFlavor: DocumentFlavor.DRAWINGML, inlineBlock: false })).concat([
+ { fontSize: 10.5, lineSpacing: 1.5, spacingRule: SpacingRule.AUTO, expectedHeight: 28.5, documentFlavor: DocumentFlavor.UNSPECIFIED, inlineBlock: false },
+ { fontSize: 10.5, lineSpacing: 12, spacingRule: SpacingRule.EXACT, expectedHeight: 12, documentFlavor: DocumentFlavor.UNSPECIFIED, inlineBlock: false },
+ { fontSize: 10.5, lineSpacing: 12, spacingRule: SpacingRule.EXACT, expectedHeight: 19, documentFlavor: DocumentFlavor.DRAWINGML, inlineBlock: true },
+ ]))('preserves line spacing $lineSpacing / $spacingRule at $fontSize pt with layout $documentFlavor and inline block $inlineBlock', ({ fontSize, lineSpacing, spacingRule, expectedHeight, documentFlavor, inlineBlock }) => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('ab', {
+ documentStyle: {
+ pageSize: { width: 300, height: 300 },
+ marginTop: 0,
+ marginBottom: 0,
+ paragraphLineGapDefault: 0,
+ },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(documentFlavor);
+ const glyphs = ['a', 'b', '\r'].map((character) => {
+ const glyph = createGlyph(character, character === '\r' ? 0 : 12);
+ glyph.fontStyle!.originFontSize = character === '\r' ? 14 : fontSize;
+ glyph.bBox.ba = 15;
+ glyph.bBox.bd = 4;
+ if (character === '\r') {
+ glyph.streamType = DataStreamTreeTokenType.PARAGRAPH;
+ } else if (inlineBlock && character === 'b') {
+ glyph.streamType = DataStreamTreeTokenType.CUSTOM_BLOCK;
+ }
+ return glyph;
+ });
+ const paragraphConfig: IParagraphConfig = {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: { lineSpacing, spacingRule, snapToGrid: BooleanNumber.FALSE },
+ useWordStyleLineHeight: false,
+ skeHeaders: ctx.skeletonResourceReference.skeHeaders,
+ skeFooters: ctx.skeletonResourceReference.skeFooters,
+ };
+ const result = layoutParagraph(ctx, glyphs, [curPage], sectionBreakConfig, paragraphConfig, true);
+ const lines = result[0].sections[0].columns[0].lines;
+ expect(lines).toHaveLength(1);
+ expect(lines[0].lineHeight).toBeCloseTo(expectedHeight, 4);
+ });
+
+ it.each([1, 1.15, 1.5, 2].flatMap((lineSpacing) => [DocumentFlavor.DRAWINGML, DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL, DocumentFlavor.UNSPECIFIED].map((documentFlavor) => ({ lineSpacing, documentFlavor }))))('preserves automatic baseline intervals but excludes terminal leading in $documentFlavor at $lineSpacing', ({ lineSpacing, documentFlavor }) => {
+ for (const lineCount of [1, 2]) {
+ const { ctx, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('a\ra', {
+ documentStyle: { pageSize: { width: 300, height: 300 }, marginTop: 0, marginBottom: 0, paragraphLineGapDefault: 0 },
+ });
+ const policy = getDocumentCompatibilityPolicy(documentFlavor);
+ sectionBreakConfig.documentCompatibilityPolicy = policy;
+ let pages = [curPage];
+ for (let index = 0; index < lineCount; index++) {
+ const glyphs = ['a', '\r'].map((content) => {
+ const glyph = createGlyph(content, content === 'a' ? 8 : 0);
+ glyph.fontStyle!.originFontSize = 9;
+ glyph.bBox.ba = 11;
+ glyph.bBox.bd = 3;
+ if (content === '\r') {
+ glyph.streamType = DataStreamTreeTokenType.PARAGRAPH;
+ }
+ return glyph;
+ });
+ const paragraphConfig: IParagraphConfig = {
+ paragraphIndex: index * 2 + 1,
+ paragraphStyle: { lineSpacing, spacingRule: SpacingRule.AUTO, snapToGrid: BooleanNumber.FALSE },
+ useWordStyleLineHeight: false,
+ skeHeaders: ctx.skeletonResourceReference.skeHeaders,
+ skeFooters: ctx.skeletonResourceReference.skeFooters,
+ };
+ pages = layoutParagraph(ctx, glyphs, pages, sectionBreakConfig, paragraphConfig, true);
+ }
+ const lines = pages[0].sections[0].columns[0].lines;
+ expect(lines).toHaveLength(lineCount);
+ const heights = lines.map((line) => line.lineHeight);
+ const expectedInterval = (documentFlavor === DocumentFlavor.DRAWINGML ? 14.4 : 14) * lineSpacing;
+ const expandedDrawingML = documentFlavor === DocumentFlavor.DRAWINGML && lineSpacing > 1;
+ const expectedTerminal = expandedDrawingML ? Math.max(14.4, expectedInterval * 0.75 + 3) : expectedInterval;
+ for (let pass = 0; pass < 2; pass++) {
+ updateBlockIndex(pages, -1, policy);
+ expect(lines.map((line) => line.lineHeight)).toEqual(heights);
+ expect(lines[lineCount - 1].top).toBeCloseTo((lineCount - 1) * expectedInterval, 6);
+ expect(pages[0].height).toBeCloseTo((lineCount - 1) * expectedInterval + expectedTerminal, 6);
+ if (expandedDrawingML) {
+ expect(lines[0].paddingTop + lines[0].asc).toBeCloseTo(expectedInterval * 0.75, 6);
+ }
+ }
+ }
+ });
+
+ it.each([
+ { lineSpacing: 22, ascent: 18, descent: 4, expectedBaseline: 18 },
+ { lineSpacing: 28, ascent: 22, descent: 5, expectedBaseline: 22 },
+ { lineSpacing: 28, ascent: 23, descent: 6, expectedBaseline: 22 },
+ ])('keeps DrawingML fixed spacing near natural glyph height within the font edges ($lineSpacing, $ascent, $descent)', ({ lineSpacing, ascent, descent, expectedBaseline }) => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('ab', {
+ documentStyle: { pageSize: { width: 300, height: 300 }, marginTop: 0, marginBottom: 0, paragraphLineGapDefault: 0 },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(DocumentFlavor.DRAWINGML);
+ const paragraphConfig: IParagraphConfig = {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: { lineSpacing, spacingRule: SpacingRule.EXACT, snapToGrid: BooleanNumber.FALSE },
+ useWordStyleLineHeight: false,
+ skeHeaders: ctx.skeletonResourceReference.skeHeaders,
+ skeFooters: ctx.skeletonResourceReference.skeFooters,
+ };
+ const first = createGlyph('a', 12);
+ first.bBox.ba = ascent;
+ first.bBox.bd = descent;
+ const pages = layoutParagraph(ctx, [first], [curPage], sectionBreakConfig, paragraphConfig, true);
+ const line = pages[0].sections[0].columns[0].lines[0];
+ expect(line.paddingTop + ascent).toBeCloseTo(expectedBaseline, 6);
+ updateBlockIndex(pages, -1, sectionBreakConfig.documentCompatibilityPolicy);
+ expect(line.paddingTop + line.asc).toBeCloseTo(expectedBaseline, 6);
+ const larger = createGlyph('b', 12);
+ larger.bBox.ba = 46;
+ larger.bBox.bd = 13;
+ line.divides[0].glyphGroup.push(larger);
+ for (let pass = 0; pass < 2; pass++) {
+ updateBlockIndex(pages, -1, sectionBreakConfig.documentCompatibilityPolicy);
+ const updatedLine = pages[0].sections[0].columns[0].lines[0];
+ expect(updatedLine.paddingTop + updatedLine.asc).toBeCloseTo(lineSpacing * 0.75, 6);
+ expect(updatedLine.lineHeight).toBeCloseTo(lineSpacing, 6);
+ }
+ });
+
+ it.each([12, 48].flatMap((lineSpacing) => [DocumentFlavor.DRAWINGML, DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL, DocumentFlavor.UNSPECIFIED].map((documentFlavor) => ({ lineSpacing, documentFlavor }))))('keeps fixed-line baselines independent of font ascent in $documentFlavor at $lineSpacing', ({ lineSpacing, documentFlavor }) => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('ab', {
+ documentStyle: { pageSize: { width: 300, height: 300 }, marginTop: 0, marginBottom: 0, paragraphLineGapDefault: 0 },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(documentFlavor);
+ const paragraphConfig: IParagraphConfig = {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: { lineSpacing, spacingRule: SpacingRule.EXACT, snapToGrid: BooleanNumber.FALSE },
+ useWordStyleLineHeight: false,
+ skeHeaders: ctx.skeletonResourceReference.skeHeaders,
+ skeFooters: ctx.skeletonResourceReference.skeFooters,
+ };
+ const first = createGlyph('a', 12);
+ first.bBox.ba = 23;
+ first.bBox.bd = 6;
+ const second = createGlyph('b', 12);
+ second.bBox.ba = 46;
+ second.bBox.bd = 13;
+ let pages = layoutParagraph(ctx, [first], [curPage], sectionBreakConfig, paragraphConfig, true);
+ for (const append of [false, true]) {
+ if (append) {
+ pages = layoutParagraph(ctx, [second], pages, sectionBreakConfig, paragraphConfig, false);
+ }
+ updateBlockIndex(pages, -1, sectionBreakConfig.documentCompatibilityPolicy);
+ const line = pages[0].sections[0].columns[0].lines[0];
+ // Native PowerPoint H-glyph baselines: 9/36 at fixed spacing 12/48, across Arial/Calibri 24/48 pt.
+ const expectedBaseline = documentFlavor === DocumentFlavor.DRAWINGML
+ ? lineSpacing * 0.75
+ : (lineSpacing - line.contentHeight) / 2 + line.asc;
+ expect(line.paddingTop + line.asc).toBeCloseTo(expectedBaseline, 6);
+ expect(line.lineHeight).toBeCloseTo(lineSpacing, 6);
+ updateBlockIndex(pages, -1, sectionBreakConfig.documentCompatibilityPolicy);
+ expect(line.paddingTop + line.asc).toBeCloseTo(expectedBaseline, 6);
+ }
+ });
+
+ it.each([12, 18].flatMap((fontSize) => [
+ { lineSpacing: 0.7, spacingRule: SpacingRule.AUTO },
+ { lineSpacing: 1.4, spacingRule: SpacingRule.AUTO },
+ { lineSpacing: 18, spacingRule: SpacingRule.EXACT },
+ { lineSpacing: 36, spacingRule: SpacingRule.EXACT },
+ ].flatMap((spacing) => [NumberUnitType.LINE, NumberUnitType.PERCENT].map((unit) => ({ fontSize, unit, ...spacing })))))('resolves DrawingML relative paragraph spacing independently of line spacing ($fontSize, $lineSpacing, $spacingRule, $unit)', ({ fontSize, unit, lineSpacing, spacingRule }) => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('ab', {
+ documentStyle: { pageSize: { width: 300, height: 300 }, marginTop: 0, marginBottom: 0, paragraphLineGapDefault: 0 },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(DocumentFlavor.DRAWINGML);
+ const glyphs = ['a', 'b', '\r'].map((character) => {
+ const glyph = createGlyph(character, character === '\r' ? 0 : 12);
+ glyph.fontStyle!.originFontSize = character === '\r' ? 40 : fontSize;
+ glyph.bBox.ba = 15;
+ glyph.bBox.bd = 4;
+ if (character === '\r') {
+ glyph.streamType = DataStreamTreeTokenType.PARAGRAPH;
+ }
+ return glyph;
+ });
+ const paragraphConfig: IParagraphConfig = {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: {
+ lineSpacing,
+ spacingRule,
+ snapToGrid: BooleanNumber.FALSE,
+ spaceAbove: { v: 0.2, u: unit },
+ spaceBelow: { v: 0.3, u: unit },
+ },
+ useWordStyleLineHeight: false,
+ skeHeaders: ctx.skeletonResourceReference.skeHeaders,
+ skeFooters: ctx.skeletonResourceReference.skeFooters,
+ };
+ const result = layoutParagraph(ctx, glyphs, [curPage], sectionBreakConfig, paragraphConfig, true);
+ const lines = result[0].sections[0].columns[0].lines;
+ expect(lines).toHaveLength(1);
+ // PowerPoint's 16/24 pt spacing matrix: 20% is based on a normal line, not the selected line spacing.
+ const normalHeight = fontSize === 12 ? 19.2 : 28.8;
+ expect(lines[0].marginTop).toBeCloseTo(normalHeight * 0.2, 4);
+ expect(lines[0].spaceBelowApply).toBeCloseTo(normalHeight * 0.3, 4);
+ });
+
+ it.each([DocumentFlavor.DRAWINGML, DocumentFlavor.UNSPECIFIED, DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN].flatMap((documentFlavor) =>
+ [undefined, NumberUnitType.POINT, NumberUnitType.PIXEL, NumberUnitType.CHARACTER, NumberUnitType.LINE, NumberUnitType.PERCENT]
+ .map((unit) => ({ documentFlavor, unit }))))('retains absolute spacing and non-DrawingML relative spacing ($documentFlavor, $unit)', ({ documentFlavor, unit }) => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('a', {
+ documentStyle: { pageSize: { width: 300, height: 300 }, marginTop: 0, marginBottom: 0, paragraphLineGapDefault: 0 },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(documentFlavor);
+ const glyph = createGlyph('a', 12);
+ glyph.fontStyle!.originFontSize = 12;
+ glyph.bBox.ba = 15;
+ glyph.bBox.bd = 4;
+ const paragraphConfig: IParagraphConfig = {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: {
+ lineSpacing: 36,
+ spacingRule: SpacingRule.EXACT,
+ snapToGrid: BooleanNumber.FALSE,
+ spaceAbove: { v: 4, u: NumberUnitType.POINT },
+ spaceBelow: { v: 0.2, u: unit },
+ },
+ useWordStyleLineHeight: false,
+ skeHeaders: ctx.skeletonResourceReference.skeHeaders,
+ skeFooters: ctx.skeletonResourceReference.skeFooters,
+ };
+ const result = layoutParagraph(ctx, [glyph], [curPage], sectionBreakConfig, paragraphConfig, true);
+ const line = result[0].sections[0].columns[0].lines[0];
+ let benchmark = 36;
+ if (unit == null || unit === NumberUnitType.POINT || unit === NumberUnitType.PIXEL) {
+ benchmark = 1;
+ } else if (documentFlavor === DocumentFlavor.DRAWINGML && unit !== NumberUnitType.CHARACTER) {
+ benchmark = 19.2;
+ }
+ expect(line.spaceBelowApply).toBeCloseTo(0.2 * benchmark, 4);
+ if (documentFlavor === DocumentFlavor.DRAWINGML) {
+ expect(line.marginTop).toBe(4);
+ }
+ });
+
+ it.each([DocumentFlavor.DRAWINGML, DocumentFlavor.UNSPECIFIED, DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN]
+ .flatMap((documentFlavor) => [[0, 0], [9, 6], [6, 9], [6, 6], [9, 0], [0, 6]]
+ .map(([before, after]) => ({ documentFlavor, before, after }))))('resolves adjacent paragraph gaps for $documentFlavor (before=$before, after=$after)', ({ documentFlavor, before, after }) => {
+ const { ctx, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('a\rb', {
+ body: { paragraphs: [{ startIndex: 1 }, { startIndex: 3 }] },
+ documentStyle: { pageSize: { width: 300, height: 300 }, marginTop: 0, marginBottom: 0, paragraphLineGapDefault: 0 },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(documentFlavor);
+ const config = (index: number): IParagraphConfig => ({
+ paragraphIndex: index * 2 + 1,
+ paragraphStyle: {
+ lineSpacing: 1,
+ spacingRule: SpacingRule.AUTO,
+ snapToGrid: BooleanNumber.FALSE,
+ spaceAbove: { v: index === 1 ? before : 0, u: NumberUnitType.POINT },
+ spaceBelow: { v: index === 0 ? after : 0, u: NumberUnitType.POINT },
+ },
+ useWordStyleLineHeight: false,
+ skeHeaders: ctx.skeletonResourceReference.skeHeaders,
+ skeFooters: ctx.skeletonResourceReference.skeFooters,
+ });
+ const first = layoutParagraph(ctx, [createGlyph('a', 12)], [curPage], sectionBreakConfig, config(0), true);
+ const firstLine = first[0].sections[0].columns[0].lines[0];
+ const firstBottom = firstLine.top + firstLine.lineHeight;
+ const result = layoutParagraph(ctx, [createGlyph('b', 12)], first, sectionBreakConfig, config(1), true);
+ const lines = result[0].sections[0].columns[0].lines;
+ expect(lines).toHaveLength(2);
+ const gap = lines[1].top + lines[1].marginTop - firstBottom;
+ // Native PowerPoint shape/table renders add both; preserve the existing Word-host collapse.
+ expect(gap).toBeCloseTo(documentFlavor === DocumentFlavor.DRAWINGML ? before + after : Math.max(before, after), 4);
+ });
+
+ it('uses the font normal line height as the base for Word auto spacing', () => {
+ const metrics = getLineHeightMetrics(17, 0, 24, GridType.DEFAULT, 1.5, SpacingRule.AUTO, BooleanNumber.FALSE, true, true, 18.6666666667);
+
+ expect(getLineBoxHeight(metrics)).toBeCloseTo(28, 4);
+ });
+
+ it.each([
+ [false, false, SpacingRule.AUTO, 33],
+ [true, false, SpacingRule.AUTO, 33],
+ [false, true, SpacingRule.AUTO, 22],
+ [true, true, SpacingRule.AUTO, 22],
+ [false, false, SpacingRule.EXACT, 16],
+ [true, false, SpacingRule.EXACT, 16],
+ [false, true, SpacingRule.EXACT, 22],
+ [true, true, SpacingRule.EXACT, 22],
+ ])('combines baseline extents when appending glyphs (reversed=%s, inline=%s, rule=%s)', (reversed, inline, spacingRule, expectedHeight) => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('AB', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ const text = createGlyph('A', 10);
+ text.bBox.ba = 14;
+ text.bBox.bd = 4;
+ const raised = createGlyph('B', 18);
+ raised.bBox.ba = 18;
+ raised.bBox.bd = 0;
+ if (inline) {
+ raised.streamType = DataStreamTreeTokenType.CUSTOM_BLOCK;
+ }
+ const glyphs = reversed ? [raised, text] : [text, raised];
+ const paragraphConfig = {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: {
+ lineSpacing: spacingRule === SpacingRule.AUTO ? 1.5 : 16,
+ spacingRule,
+ snapToGrid: BooleanNumber.FALSE,
+ spaceAbove: { v: 0 },
+ spaceBelow: { v: 0 },
+ },
+ useWordStyleLineHeight: true,
+ } as IParagraphConfig;
+ let pages = [curPage];
+ for (const [index, glyph] of glyphs.entries()) {
+ pages = layoutParagraph(ctx, [glyph], pages, sectionBreakConfig, paragraphConfig, index === 0);
+ }
+ const line = pages[0].sections[0].columns[0].lines[0];
+ expect(line.contentHeight).toBe(22);
+ expect(line.lineHeight).toBeCloseTo(expectedHeight);
+ expect(line.divides.flatMap((divide) => divide.glyphGroup)).toEqual(glyphs);
+
+ pages = layoutParagraph(ctx, [text], pages, sectionBreakConfig, paragraphConfig, true);
+ const nextLine = pages[0].sections[0].columns[0].lines[1];
+ expect(nextLine.top - line.top).toBeCloseTo(expectedHeight);
+ });
+
+ it('does not multiply inline custom block height by auto line spacing', () => {
+ const metrics = getLineHeightMetrics(624, 0, 15.6, GridType.LINES, 1.5, SpacingRule.AUTO, BooleanNumber.FALSE, true, false);
+
+ expect(getLineBoxHeight(metrics)).toBeCloseTo(624, 4);
+ });
+
+ it('retains text leading beside a tall inline object without multiplying the object height', () => {
+ const metrics = getLineHeightMetrics(624, 0, 15.6, GridType.DEFAULT, 1.5, SpacingRule.AUTO, BooleanNumber.FALSE, true, false, 18);
+
+ expect(metrics.contentHeight).toBe(624);
+ expect(getLineBoxHeight(metrics)).toBeCloseTo(633, 4);
});
- it('uses the font normal line height as the base for Word auto spacing', () => {
- const metrics = getLineHeightMetrics(17, 0, 24, GridType.DEFAULT, 1.5, SpacingRule.AUTO, BooleanNumber.FALSE, true, true, 18.6666666667);
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN].flatMap((flavor) =>
+ [false, true].flatMap((incremental) => [false, true].map((markerFirst) => ({ flavor, incremental, markerFirst })))))('keeps list marker height separate from text leading ($flavor/$incremental/$markerFirst)', ({ flavor, incremental, markerFirst }) => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('AB', {
+ documentStyle: { documentFlavor: flavor },
+ });
+ const text = createGlyph('A', 10);
+ text.bBox = { ...text.bBox, ba: 14, bd: 4, normalLineHeight: 18 };
+ const marker = createGlyph('B', 10);
+ marker.glyphType = GlyphType.LIST;
+ marker.bBox = { ...marker.bBox, ba: 18, bd: 4, normalLineHeight: 22 };
+ const glyphs = markerFirst ? [marker, text] : [text, marker];
+ const paragraphConfig = {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: { lineSpacing: 1.5, spacingRule: SpacingRule.AUTO, snapToGrid: BooleanNumber.FALSE },
+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(flavor),
+ useWordStyleLineHeight: true,
+ } as IParagraphConfig;
+ let pages = [curPage];
+ const groups = incremental ? glyphs.map((glyph) => [glyph]) : [glyphs];
+ for (const [index, group] of groups.entries()) {
+ pages = layoutParagraph(ctx, group, pages, sectionBreakConfig, paragraphConfig, index === 0);
+ }
+ const line = pages[0].sections[0].columns[0].lines[0];
+ const expected = flavor === DocumentFlavor.TRADITIONAL ? 31 : 33;
+ expect(line.contentHeight).toBe(22);
+ expect(line.lineHeight).toBeCloseTo(expected);
+ expect(line.divides.flatMap((divide) => divide.glyphGroup)).toEqual(glyphs);
+ pages = layoutParagraph(ctx, [text], pages, sectionBreakConfig, paragraphConfig, true);
+ expect(pages[0].sections[0].columns[0].lines[1].top).toBeCloseTo(expected);
+ });
- expect(getLineBoxHeight(metrics)).toBeCloseTo(28, 4);
+ it.each([
+ { pictureFirst: false, flavor: DocumentFlavor.TRADITIONAL, expectedHeight: 31 },
+ { pictureFirst: true, flavor: DocumentFlavor.TRADITIONAL, expectedHeight: 31 },
+ { pictureFirst: false, flavor: DocumentFlavor.MODERN, expectedHeight: 22 },
+ { pictureFirst: true, flavor: DocumentFlavor.MODERN, expectedHeight: 22 },
+ ])('resolves mixed inline leading across batches in $flavor (pictureFirst=$pictureFirst)', ({ pictureFirst, flavor, expectedHeight }) => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('AB', {
+ documentStyle: { documentFlavor: flavor },
+ });
+ const text = createGlyph('A', 10);
+ text.bBox.ba = 14;
+ text.bBox.bd = 4;
+ text.bBox.normalLineHeight = 18;
+ const picture = createGlyph('B', 18);
+ picture.streamType = DataStreamTreeTokenType.CUSTOM_BLOCK;
+ picture.bBox.ba = 18;
+ picture.bBox.bd = 0;
+ const glyphs = pictureFirst ? [picture, text] : [text, picture];
+ const paragraphConfig = {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: { lineSpacing: 1.5, spacingRule: SpacingRule.AUTO, snapToGrid: BooleanNumber.FALSE },
+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(flavor),
+ useWordStyleLineHeight: true,
+ } as IParagraphConfig;
+ let pages = [curPage];
+ for (const [index, glyph] of glyphs.entries()) {
+ pages = layoutParagraph(ctx, [glyph], pages, sectionBreakConfig, paragraphConfig, index === 0);
+ }
+ const line = pages[0].sections[0].columns[0].lines[0];
+ expect(line.contentHeight).toBe(22);
+ expect(line.lineHeight).toBeCloseTo(expectedHeight);
+ expect(line.divides.flatMap((divide) => divide.glyphGroup)).toEqual(glyphs);
+ pages = layoutParagraph(ctx, [text], pages, sectionBreakConfig, paragraphConfig, true);
+ expect(pages[0].sections[0].columns[0].lines[1].top - line.top).toBeCloseTo(expectedHeight);
});
- it('does not multiply inline custom block height by auto line spacing', () => {
- const metrics = getLineHeightMetrics(624, 0, 15.6, GridType.LINES, 1.5, SpacingRule.AUTO, BooleanNumber.FALSE, true, false);
+ it.each([[206.2, 208], [209.46666666666667, 228.8]])('fits a %s px inline object into whole document-grid lines', (height, expectedHeight) => {
+ const metrics = getLineHeightMetrics(height, 0, 20.8, GridType.LINES, 1, SpacingRule.AUTO, BooleanNumber.TRUE, true, false, undefined, true);
- expect(getLineBoxHeight(metrics)).toBeCloseTo(624, 4);
+ expect(getLineBoxHeight(metrics)).toBeCloseTo(expectedHeight, 4);
});
it('does not collapse an inline custom block to exact text line spacing', () => {
@@ -830,6 +2519,16 @@ describe('layout-ruler', () => {
expect(getLineBoxHeight(expandedMetrics)).toBeCloseTo(40, 4);
});
+ it.each([10, 40])('retains natural font leading under an at-least line minimum of %s', (minimum) => {
+ // Native Word keeps YaHei single spacing when the requested minimum is
+ // smaller; it must not collapse to the shorter font bounding box.
+ const metrics = getLineHeightMetrics(20, 0, 15.6, GridType.DEFAULT, minimum, SpacingRule.AT_LEAST, BooleanNumber.FALSE, true, true, 28);
+ expect(getLineBoxHeight(metrics)).toBe(Math.max(minimum, 28));
+ expect(metrics.contentHeight).toBe(20);
+ expect(metrics.paddingTop).toBe((Math.max(minimum, 28) - 20) / 2);
+ expect(metrics.paddingBottom).toBe(metrics.paddingTop);
+ });
+
it('treats exact spacing as the requested line box height even when glyphs are taller', () => {
const metrics = getLineHeightMetrics(16, 0, 15.6, GridType.LINES, 10, SpacingRule.EXACT, BooleanNumber.FALSE, true);
@@ -837,10 +2536,16 @@ describe('layout-ruler', () => {
expect(metrics.contentHeight).toBeGreaterThan(getLineBoxHeight(metrics));
});
- it('uses document grid line pitch as the minimum exact line box height for snapped docx paragraphs', () => {
+ it('lets exact docx line spacing override the document grid pitch', () => {
const metrics = getLineHeightMetrics(16, 0, 30.46666666666667, GridType.LINES_AND_CHARS, 26.666666666666668, SpacingRule.EXACT, BooleanNumber.TRUE, true);
- expect(getLineBoxHeight(metrics)).toBeCloseTo(30.46666666666667, 4);
+ expect(getLineBoxHeight(metrics)).toBeCloseTo(26.666666666666668, 4);
+ });
+
+ it.each([16, 0.9333333333333332])('preserves a compact exact line box of %s pixels on a line grid', (lineSpacing) => {
+ const metrics = getLineHeightMetrics(16, 0, 20.8, GridType.LINES, lineSpacing, SpacingRule.EXACT, BooleanNumber.TRUE, true);
+
+ expect(getLineBoxHeight(metrics)).toBeCloseTo(lineSpacing, 4);
});
it('stops dirty relayout after a floating object reaches the reposition limit', () => {
@@ -991,6 +2696,51 @@ describe('layout-ruler', () => {
expect(getLineBoxHeight(metrics)).toBeCloseTo(23.4, 4);
});
+ it.each([16, 80])('aligns traditional inline images to the shared text baseline with %s px minimum leading', (lineSpacing) => {
+ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}g`;
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ body: {
+ customBlocks: [{ startIndex: 0, blockId: 'baseline-image' }],
+ paragraphs: [{
+ startIndex: content.length,
+ paragraphId: 'inline-baseline',
+ paragraphStyle: {
+ spacingRule: SpacingRule.AT_LEAST,
+ lineSpacing,
+ spaceAbove: { v: 10.4 },
+ spaceBelow: { v: 10.4 },
+ snapToGrid: BooleanNumber.FALSE,
+ },
+ }],
+ },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ drawings: {
+ 'baseline-image': {
+ drawingId: 'baseline-image',
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: { angle: 0, size: { width: 100, height: 54 } },
+ },
+ },
+ });
+ const pages = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig),
+ curPage,
+ paragraphNode,
+ sectionBreakConfig,
+ null
+ );
+ updateInlineDrawingCoordsAndBorder(ctx, pages);
+ const line = pages[0].sections[0].columns[0].lines[0];
+ const glyphs = line.divides.flatMap((divide) => divide.glyphGroup);
+ const baseline = pages[0].sections[0].top + line.top + line.marginTop + line.paddingTop +
+ Math.max(...glyphs.map((glyph) => glyph.bBox.ba));
+ const drawing = pages[0].skeDrawings.get('baseline-image')!;
+ expect(drawing.aTop + drawing.height).toBeCloseTo(baseline, 6);
+ expect(line.contentHeight).toBeGreaterThan(drawing.height);
+ });
+
it('positions inline custom block drawings relative to their glyph box', () => {
const drawing = {
drawingId: 'image-1',
@@ -1086,6 +2836,33 @@ describe('layout-ruler', () => {
expect(table.left).toBe(369);
});
+ it('positions flow tables below page-anchored floating tables that disallow overlap', () => {
+ const floatingTable = {
+ top: -98,
+ left: 0,
+ width: 788,
+ height: 1123,
+ tableSource: {
+ textWrap: TableTextWrapType.WRAP,
+ overlap: BooleanNumber.FALSE,
+ dist: { distB: 4 },
+ },
+ } as any;
+ const table = {
+ top: 42,
+ left: 0,
+ width: 684,
+ height: 874,
+ } as any;
+ const page = {
+ skeTables: new Map([['floating', floatingTable]]),
+ } as any;
+
+ __testing.avoidNonOverlappingFloatingTables(table, page);
+
+ expect(table.top).toBe(1029);
+ });
+
it('positions a sliced table continuation in its current column', () => {
const table = {
tableId: 'table#-#1',
@@ -1136,7 +2913,757 @@ describe('layout-ruler', () => {
expect(page.skeTables.get(table.tableId)).toBe(table);
});
- it('stores custom block render viewport on inline skeleton drawings', () => {
+ it.each([
+ [ObjectRelativeFromH.PAGE, -53],
+ [ObjectRelativeFromH.MARGIN, 1],
+ [ObjectRelativeFromH.COLUMN, 31],
+ ])('normalizes floating table horizontal anchor %s to the content origin', (relativeFrom, expectedLeft) => {
+ const page = { pageWidth: 794, marginLeft: 54, marginRight: 60, sections: [] };
+ const section = { top: 0, parent: page };
+ const column = { left: 30, width: 650, lines: [], parent: section };
+ const table = {
+ width: 788,
+ height: 1123,
+ tableSource: {
+ position: {
+ positionH: { relativeFrom, posOffset: 1 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ },
+ },
+ };
+
+ expect(__testing.getWrapTablePosition(table as never, column as never, 0, 16)?.left).toBe(expectedLeft);
+ });
+
+ it.each([
+ [DocumentSkeletonPageType.BODY, 40, 20],
+ [DocumentSkeletonPageType.CELL, 40, 20],
+ [DocumentSkeletonPageType.CELL, 60, 50],
+ ])('preserves only fitting cell after-spacing when the next paragraph overflows: %s, %s', (pageType, capacity, expectedHeight) => {
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('A\rB', {
+ body: {
+ paragraphs: [
+ { startIndex: 1, paragraphId: 'first', paragraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: 20, spaceBelow: { v: 30 } } },
+ { startIndex: 3, paragraphId: 'second', paragraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: 20 } },
+ ],
+ },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 200, height: capacity + 40 } },
+ });
+ curPage.type = pageType;
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL);
+ const firstShaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ lineBreaking(ctx, viewModel, firstShaped, curPage, paragraphNode, sectionBreakConfig, null);
+ const secondNode = viewModel.getChildren()[0].children[1];
+ const secondShaped = shaping(ctx, secondNode.content!, viewModel, secondNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, secondShaped, curPage, secondNode, sectionBreakConfig, null);
+ expect(pages).toHaveLength(2);
+ const lastLine = pages[0].sections[0].columns[0].lines[0];
+ expect(lastLine.lineHeight).toBe(expectedHeight);
+ expect(lastLine.marginBottom).toBe(expectedHeight - 20);
+ expect(pages[1].sections[0].columns[0].lines[0].top).toBe(0);
+ });
+
+ it.each([false, true].flatMap((incremental) =>
+ [TableTextWrapType.WRAP, TableTextWrapType.NONE].map((textWrap) => ({ incremental, textWrap }))))(
+ 'moves a fitting text-anchored float intact without changing inline pagination ($incremental, $textWrap)',
+ ({ incremental, textWrap }) => {
+ const T = DataStreamTreeTokenType;
+ const prefix = `Before${T.PARAGRAPH}`;
+ const row = `${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}`;
+ const tableStream = `${T.TABLE_START}${row.repeat(2)}${T.TABLE_END}`;
+ const content = `${prefix}${tableStream}${T.PARAGRAPH}After`;
+ const paragraphs = [...content.matchAll(/\r/g)].filter((match) => match.index !== prefix.length + tableStream.length).map((match) => ({
+ startIndex: match.index,
+ paragraphId: `p-${match.index}`,
+ paragraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: match.index === prefix.length - 1 ? 80 : 20 },
+ }));
+ paragraphs.push({ startIndex: content.length, paragraphId: 'after', paragraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: 20 } });
+ const bed = createParagraphLayoutTestBed(content, {
+ body: {
+ paragraphs,
+ tables: [{ tableId: 'table', startIndex: prefix.length, endIndex: prefix.length + tableStream.length }],
+ },
+ tableSource: { table: {
+ tableId: 'table',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap,
+ position: {
+ positionH: { relativeFrom: ObjectRelativeFromH.MARGIN },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 10 },
+ },
+ dist: {},
+ size: { type: TableSizeType.SPECIFIED, width: { v: 160 } },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 160 } } }],
+ tableRows: [0, 1].map(() => ({
+ tableCells: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 160 } } }],
+ trHeight: { val: { v: 60 }, hRule: TableRowHeightRule.EXACT },
+ })),
+ } },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 200, height: 200 } },
+ });
+ const sourceBefore = JSON.stringify(bed.dataModel.getSnapshot());
+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);
+ try {
+ if (incremental) {
+ const generation = skeleton.startIncrementalLayout();
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let step = 0; step < 100 && !progress.complete; step++) {
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+ expect(progress.complete).toBe(true);
+ } else {
+ skeleton.calculate();
+ }
+ const pages = skeleton.getSkeletonData()!.pages;
+ expect(pages).toHaveLength(2);
+ if (textWrap === TableTextWrapType.WRAP) {
+ expect(pages[0].skeTables.size).toBe(0);
+ const table = [...pages[1].skeTables.values()][0];
+ expect(table.rows).toHaveLength(2);
+ expect(table.height).toBe(120);
+ expect(table.top).toBe(10);
+ } else {
+ expect(pages.map((page) => [...page.skeTables.values()].map((table) => table.rows.length))).toEqual([[1], [1]]);
+ }
+ expect(JSON.stringify(bed.dataModel.getSnapshot())).toBe(sourceBefore);
+ } finally {
+ skeleton.dispose();
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ }
+ );
+
+ it.each([
+ { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 30 },
+ { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 10 },
+ ].flatMap((positionV) => [undefined, '12', '14', '15'].map((mode) => ({ positionV, mode }))))('respects Word floating table pagination mode $mode at $positionV.relativeFrom', ({ positionV, mode }) => {
+ const T = DataStreamTreeTokenType;
+ const rows = ['First', 'Second', 'Third', 'Fourth'].map((text) =>
+ `${T.TABLE_ROW_START}${T.TABLE_CELL_START}${text}${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}`
+ );
+ const tableStream = `${T.TABLE_START}${rows.join('')}${T.TABLE_END}`;
+ const content = `${tableStream}${T.PARAGRAPH}After`;
+ const paragraphs = [];
+ for (let index = 0; index < tableStream.length; index++) {
+ if (tableStream[index] === T.PARAGRAPH) {
+ paragraphs.push({ startIndex: index, paragraphId: `cell-${index}` });
+ }
+ }
+ paragraphs.push({ startIndex: content.length, paragraphId: 'after' });
+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ body: { paragraphs, tables: [{ tableId: 'floating', startIndex: 0, endIndex: tableStream.length }] },
+ tableSource: {
+ floating: {
+ tableId: 'floating',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.WRAP,
+ position: {
+ positionH: { relativeFrom: ObjectRelativeFromH.MARGIN },
+ positionV,
+ },
+ dist: {},
+ size: { type: TableSizeType.SPECIFIED, width: { v: 160 } },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 160 } } }],
+ tableRows: rows.map(() => ({
+ tableCells: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 160 } } }],
+ trHeight: { val: { v: 80 }, hRule: TableRowHeightRule.EXACT },
+ })),
+ },
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 200, height: 200 },
+ ...(mode == null ? {} : { compatibilitySettings: { compatibilityMode: mode } }),
+ },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL);
+ const sourceBefore = JSON.stringify(dataModel.getSnapshot());
+ const table = createTableSkeleton(ctx, curPage, viewModel, paragraphNode.children[0], sectionBreakConfig);
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, table);
+ if (mode === '12' || mode === '14') {
+ expect(pages).toHaveLength(1);
+ const intact = [...pages[0].skeTables.values()];
+ expect(intact).toHaveLength(1);
+ expect(intact[0].rows).toHaveLength(4);
+ expect(intact[0].height).toBeGreaterThan(curPage.pageHeight);
+ expect(JSON.stringify(dataModel.getSnapshot())).toBe(sourceBefore);
+ return;
+ }
+ expect(pages).toHaveLength(3);
+ const slices = pages.flatMap((page) => [...page.skeTables.values()]);
+ expect(slices.map((slice) => slice.rows.length)).toEqual([1, 2, 1]);
+ expect(slices.map((slice) => slice.left)).toEqual([0, 0, 0]);
+ expect(slices.map((slice) => slice.top)).toEqual([10, 0, 0]);
+ expect(slices.every((slice) => slice.tableSource.textWrap === TableTextWrapType.WRAP)).toBe(true);
+ const lastPage = pages[pages.length - 1];
+ const followingNode = viewModel.getChildren()[0].children[1];
+ const followingShaped = shaping(ctx, followingNode.content!, viewModel, followingNode, sectionBreakConfig);
+ const followingPages = lineBreaking(ctx, viewModel, followingShaped, lastPage, followingNode, sectionBreakConfig, null);
+ const followingLine = followingPages[0].sections[0].columns[0].lines.find((line) => line.paragraphIndex === content.length);
+ expect(followingLine?.top).toBeGreaterThanOrEqual(slices[2].top + slices[2].height);
+ expect(JSON.stringify(dataModel.getSnapshot())).toBe(sourceBefore);
+ });
+
+ it.each([
+ { relativeFrom: ObjectRelativeFromH.MARGIN, align: AlignTypeH.LEFT },
+ { relativeFrom: ObjectRelativeFromH.MARGIN, align: AlignTypeH.CENTER },
+ { relativeFrom: ObjectRelativeFromH.MARGIN, align: AlignTypeH.RIGHT },
+ { relativeFrom: ObjectRelativeFromH.MARGIN, posOffset: 30 },
+ { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 30 },
+ { relativeFrom: ObjectRelativeFromH.PAGE, align: AlignTypeH.RIGHT },
+ { relativeFrom: ObjectRelativeFromH.COLUMN, posOffset: 30 },
+ ])('positions floating drawings in the same content coordinates as text: %j', (positionH) => {
+ for (const documentFlavor of [DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN]) {
+ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}Hello`;
+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ body: { customBlocks: [{ startIndex: 0, blockId: 'image' }] },
+ drawings: {
+ image: {
+ drawingId: 'image',
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ docTransform: {
+ size: { width: 80, height: 40 },
+ positionH,
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ },
+ },
+ },
+ documentStyle: { documentFlavor, marginLeft: 45, marginRight: 60 },
+ });
+ const sourceBefore = JSON.stringify(dataModel.getSnapshot());
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ const { marginLeft, marginRight, pageWidth } = curPage;
+ const isMargin = positionH.relativeFrom === ObjectRelativeFromH.MARGIN;
+ const anchorWidth = isMargin ? pageWidth - marginLeft - marginRight : pageWidth;
+ let expectedLeft = positionH.posOffset ?? 0;
+ if (positionH.align === AlignTypeH.RIGHT) {
+ expectedLeft = anchorWidth - 80;
+ } else if (positionH.align === AlignTypeH.CENTER) {
+ expectedLeft = (anchorWidth - 80) / 2;
+ }
+ if (isMargin && documentFlavor === DocumentFlavor.MODERN) {
+ expectedLeft += marginLeft;
+ } else if (positionH.relativeFrom === ObjectRelativeFromH.PAGE && documentFlavor === DocumentFlavor.TRADITIONAL) {
+ expectedLeft -= marginLeft;
+ }
+ expect(curPage.skeDrawings.get('image')?.aLeft).toBeCloseTo(expectedLeft);
+ expect(JSON.stringify(dataModel.getSnapshot())).toBe(sourceBefore);
+ }
+ });
+
+ it.each([false, true])('suppresses automatic spacing only at Word cell boundaries (incremental: %s)', (incremental) => {
+ const heights = [false, true].map((automatic) => {
+ const T = DataStreamTreeTokenType;
+ const tableStream = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell\r\n${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const content = `${tableStream}\rAfter\r\n`;
+ const bed = createParagraphLayoutTestBed('', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: {
+ dataStream: content,
+ paragraphs: [{ startIndex: content.indexOf('\r'), paragraphStyle: {
+ spaceAbove: { v: 10 },
+ spaceBelow: { v: 10 },
+ beforeAutoSpacing: automatic ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ afterAutoSpacing: automatic ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ } }, { startIndex: content.length - 2 }],
+ sectionBreaks: [{ startIndex: content.indexOf('\n') }, { startIndex: content.length - 1 }],
+ tables: [{ tableId: 'table', startIndex: 0, endIndex: tableStream.length }],
+ },
+ tableSource: { table: {
+ tableId: 'table',
+ align: 0,
+ textWrap: 0,
+ size: { type: 0, width: { v: 200 } },
+ cellMargin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } },
+ tableRows: [{ tableCells: [{}], trHeight: { val: { v: 0 }, hRule: 0 } }],
+ tableColumns: [{ size: { type: 0, width: { v: 200 } } }],
+ } },
+ });
+ try {
+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);
+ if (incremental) {
+ const generation = skeleton.startIncrementalLayout();
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let step = 0; step < 50 && !progress.complete; step++) {
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+ expect(progress.complete).toBe(true);
+ } else {
+ skeleton.calculate();
+ }
+ return skeleton.getSkeletonData()!.pages[0].skeTables.get('table')!.rows[0].height;
+ } finally {
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
+ expect(heights[0] - heights[1]).toBeCloseTo(20);
+ });
+
+ it.each([SpacingRule.AUTO, SpacingRule.EXACT, SpacingRule.AT_LEAST].flatMap((spacingRule) =>
+ [4, 24].map((spaceAbove) => ({ spacingRule, spaceAbove }))))('ignores fully hidden paragraphs without losing adjacent spacing (rule: $spacingRule, before: $spaceAbove)', ({ spacingRule, spaceAbove }) => {
+ const positions = [false, true].map((includeHidden) => {
+ const content = includeHidden ? 'Before\rHidden\r\rAfter\r\n' : 'Before\r\rAfter\r\n';
+ const hiddenEnd = content.indexOf('\r', 7);
+ const bed = createParagraphLayoutTestBed('', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: {
+ dataStream: content,
+ sectionBreaks: [{ startIndex: content.length - 1 }],
+ textRuns: includeHidden ? [{ st: 7, ed: hiddenEnd + 1, ts: { hidden: true } }] : [],
+ paragraphs: [...content.matchAll(/\r/g)].map((match) => ({
+ startIndex: match.index,
+ paragraphStyle: {
+ spacingRule,
+ lineSpacing: spacingRule === SpacingRule.AUTO ? 1 : 40,
+ spaceAbove: { v: match.index === 6 ? 0 : spaceAbove },
+ spaceBelow: { v: 12 },
+ ...(includeHidden && match.index === hiddenEnd ? { paragraphMarkTextStyle: { hidden: true } } : {}),
+ },
+ })),
+ },
+ });
+ const before = JSON.stringify(bed.dataModel.getSnapshot());
+ try {
+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);
+ skeleton.calculate();
+ const lines = skeleton.getSkeletonData()!.pages[0].sections[0].columns[0].lines;
+ const after = lines.find((line) => line.divides.some((divide) => divide.glyphGroup.some((glyph) => glyph.content.includes('A'))))!;
+ expect(after).toBeDefined();
+ expect(JSON.stringify(bed.dataModel.getSnapshot())).toBe(before);
+ return after.top + after.marginTop + after.paddingTop + after.asc;
+ } finally {
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
+ expect(positions[1]).toBeCloseTo(positions[0]);
+ });
+
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN].flatMap((documentFlavor) =>
+ [0, 1, 5].flatMap((pageNumberStart) => [0, 1].flatMap((pageOffset) => [false, true].map((isInsideTable) => ({ documentFlavor, pageNumberStart, pageOffset, isInsideTable }))))))('preserves first-page before-spacing independently of the displayed page number: %j', ({ documentFlavor, pageNumberStart, pageOffset, isInsideTable }) => {
+ const bed = createParagraphLayoutTestBed('Cell', { documentStyle: { documentFlavor } });
+ if (isInsideTable) {
+ bed.curPage.type = DocumentSkeletonPageType.CELL;
+ }
+ bed.curPage.pageNumber = (isInsideTable ? 1 : pageNumberStart) + pageOffset;
+ bed.sectionBreakConfig.pageNumberStart = pageNumberStart;
+ const paragraphConfig = {
+ paragraphIndex: bed.paragraphNode.endIndex,
+ paragraphStyle: { spaceAbove: { v: 12 } },
+ isInsideTable,
+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(documentFlavor),
+ } as IParagraphConfig;
+ try {
+ const pages = layoutParagraph(bed.ctx, [createGlyph('Cell', 32)], [bed.curPage], bed.sectionBreakConfig, paragraphConfig, true);
+ const line = pages[0].sections[0].columns[0].lines[0];
+ expect(line.marginTop).toBe(documentFlavor === DocumentFlavor.TRADITIONAL && pageOffset > 0 ? 0 : 12);
+ } finally {
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
+
+ it.each([false, true].flatMap((incremental) => [0, 6, 18].map((previousAfter) => ({ incremental, previousAfter }))))('collapses paragraph spacing across a later section start: %j', ({ incremental, previousAfter }) => {
+ const bed = createParagraphLayoutTestBed('', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: {
+ dataStream: 'First\r\nSecond\r\n',
+ paragraphs: [
+ { startIndex: 5, paragraphStyle: { spaceBelow: { v: previousAfter } } },
+ { startIndex: 13, paragraphStyle: { spaceAbove: { v: 12 } } },
+ ],
+ sectionBreaks: [
+ { startIndex: 6, sectionId: 'first-section', sectionType: SectionType.NEXT_PAGE },
+ { startIndex: 14, sectionId: 'second-section', sectionType: SectionType.NEXT_PAGE },
+ ],
+ },
+ });
+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);
+ try {
+ if (incremental) {
+ const generation = skeleton.startIncrementalLayout();
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let step = 0; step < 50 && !progress.complete; step++) {
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+ expect(progress.complete).toBe(true);
+ } else {
+ skeleton.calculate();
+ }
+ const pages = skeleton.getSkeletonData()!.pages;
+ expect(pages).toHaveLength(2);
+ expect(pages[1].pageNumber).toBe(2);
+ expect(pages[1].sections[0].columns[0].lines[0].marginTop).toBe(Math.max(0, 12 - previousAfter));
+ expect(bed.dataModel.getSnapshot().body!.paragraphs![1].paragraphStyle!.spaceAbove).toEqual({ v: 12 });
+ } finally {
+ skeleton.dispose();
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
+
+ it('preserves authored first-paragraph spacing around inline drawings in headers and footers', () => {
+ const storyBody = {
+ dataStream: '\b\t\rFollowing\r\n',
+ customBlocks: [{ startIndex: 0, blockId: 'image' }],
+ paragraphs: [{ startIndex: 2, paragraphStyle: { spaceAbove: { v: 32 } } }, { startIndex: 12 }],
+ sectionBreaks: [{ startIndex: 13 }],
+ };
+ const bed = createParagraphLayoutTestBed('Body', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, defaultHeaderId: 'header', defaultFooterId: 'footer' },
+ drawings: { image: {
+ drawingId: 'image',
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: { size: { width: 100, height: 44 }, positionH: {}, positionV: {}, angle: 0 },
+ } },
+ headers: { header: { headerId: 'header', body: storyBody } },
+ footers: { footer: { footerId: 'footer', body: storyBody } },
+ });
+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);
+ try {
+ skeleton.calculate();
+ const { skeHeaders, skeFooters } = skeleton.getSkeletonData()!;
+ for (const stories of [skeHeaders, skeFooters]) {
+ const story = [...stories.values()][0].get(bed.curPage.pageWidth)!;
+ const line = story.sections[0].columns[0].lines[0];
+ expect(line.marginTop).toBe(32);
+ expect(line.lineHeight).toBeGreaterThanOrEqual(76);
+ expect(story.sections[0].columns[0].lines[1].top).toBeGreaterThanOrEqual(line.lineHeight);
+ }
+ } finally {
+ skeleton.dispose();
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
+
+ it.each([
+ { prefix: '', expectedSpaceAbove: 24 },
+ { prefix: 'Before\r', expectedSpaceAbove: 24 },
+ { prefix: '\r', expectedSpaceAbove: 24 },
+ ])('applies first-line spacing after a non-flow drawing anchor with preceding text "$prefix"', ({ prefix, expectedSpaceAbove }) => {
+ const content = `${prefix}${DataStreamTreeTokenType.CUSTOM_BLOCK}Hello`;
+ const { viewModel, ctx, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ body: {
+ paragraphs: [
+ ...(prefix ? [{ startIndex: prefix.length - 1, paragraphId: 'before' }] : []),
+ { startIndex: content.length, paragraphId: 'heading', paragraphStyle: { spaceAbove: { v: 24 }, indentFirstLine: { v: 12 } } },
+ ],
+ customBlocks: [{ startIndex: prefix.length, blockId: 'background' }],
+ },
+ drawings: {
+ background: {
+ drawingId: 'background',
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ behindDoc: BooleanNumber.TRUE,
+ docTransform: {
+ size: { width: 120, height: 90 },
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 0 },
+ angle: 0,
+ },
+ },
+ },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ for (const node of viewModel.getChildren()[0].children) {
+ lineBreaking(ctx, viewModel, shaping(ctx, node.content!, viewModel, node, sectionBreakConfig), curPage, node, sectionBreakConfig, null);
+ }
+ const lines = curPage.sections[0].columns[0].lines;
+ const anchor = lines.find((line) => line.divides.some((divide) => divide.glyphGroup.some((glyph) => glyph.drawingId === 'background')))!;
+ const text = lines.find((line) => line.divides.some((divide) => divide.glyphGroup.some((glyph) => glyph.content === 'H')))!;
+ expect(anchor.lineHeight).toBe(0);
+ expect(text.marginTop).toBe(expectedSpaceAbove);
+ expect(text.divides[0].left).toBe(12);
+ });
+
+ it.each(['', DataStreamTreeTokenType.PAGE_BREAK].flatMap((boundary) => [
+ PositionedObjectLayoutType.WRAP_NONE,
+ PositionedObjectLayoutType.WRAP_SQUARE,
+ PositionedObjectLayoutType.WRAP_TIGHT,
+ PositionedObjectLayoutType.WRAP_THROUGH,
+ ].map((layoutType) => ({ boundary, layoutType }))))('preserves the authored paragraph height after a floating-only anchor ($boundary, $layoutType)', ({ boundary, layoutType }) => {
+ const anchorText = `${boundary}${DataStreamTreeTokenType.CUSTOM_BLOCK}`;
+ const content = `${anchorText}\rHello`;
+ const { dataModel, viewModel, ctx, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ body: {
+ paragraphs: [
+ { startIndex: anchorText.length, paragraphId: 'anchor', paragraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: 18 } },
+ { startIndex: content.length, paragraphId: 'following' },
+ ],
+ customBlocks: [{ startIndex: boundary.length, blockId: 'background' }],
+ renderedPageBreaks: boundary ? [0] : [],
+ },
+ drawings: {
+ background: {
+ drawingId: 'background',
+ layoutType,
+ behindDoc: BooleanNumber.TRUE,
+ docTransform: {
+ size: { width: 120, height: 90 },
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 0 },
+ angle: 0,
+ },
+ },
+ },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ const sourceBefore = JSON.stringify(dataModel.getSnapshot());
+ for (const node of viewModel.getChildren()[0].children) {
+ lineBreaking(ctx, viewModel, shaping(ctx, node.content!, viewModel, node, sectionBreakConfig), curPage, node, sectionBreakConfig, null);
+ }
+ const lines = curPage.sections[0].columns[0].lines;
+ const paragraph = lines.filter((line) => line.paragraphIndex === anchorText.length);
+ expect(paragraph.reduce((height, line) => height + line.lineHeight, 0)).toBeCloseTo(18);
+ expect(lines.find((line) => line.paragraphIndex === content.length)?.top).toBeCloseTo(18);
+ expect(JSON.stringify(dataModel.getSnapshot())).toBe(sourceBefore);
+ });
+
+ it('moves an empty cell paragraph with its after-spacing to the next page', () => {
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('A\r\rB', {
+ body: {
+ paragraphs: [
+ { startIndex: 1, paragraphId: 'first', paragraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: 20 } },
+ { startIndex: 2, paragraphId: 'blank', paragraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: 22, spaceBelow: { v: 13 } } },
+ { startIndex: 4, paragraphId: 'last', paragraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: 20 } },
+ ],
+ },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ curPage.type = DocumentSkeletonPageType.CELL;
+ curPage.segmentId = 'cell';
+ curPage.sections[0].height = 50;
+ let pages = [curPage];
+ for (const node of viewModel.getChildren()[0].children) {
+ const result = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, node.content!, viewModel, node, sectionBreakConfig),
+ pages[pages.length - 1],
+ node,
+ sectionBreakConfig,
+ null
+ );
+ pages = [...pages.slice(0, -1), ...result];
+ }
+ expect(pages).toHaveLength(2);
+ expect(pages[0].sections[0].columns[0].lines.map((line) => line.paragraphIndex)).toEqual([paragraphNode.endIndex]);
+ const continuation = pages[1].sections[0].columns[0].lines;
+ expect(continuation.map((line) => line.paragraphIndex)).toEqual([2, 4]);
+ expect(continuation[1].top).toBe(35);
+ expect(pages[1].segmentId).toBe('cell');
+ expect(pages[1].type).toBe(DocumentSkeletonPageType.CELL);
+ });
+
+ it('keeps list numbering across split cell pages and resumes it after the table', () => {
+ const T = DataStreamTreeTokenType;
+ const tableStream = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}One\rTwo\rThree\rFour\rFive\r${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const content = `${tableStream}\rSix`;
+ const paragraphs = [];
+ for (let index = 0; index < tableStream.length; index++) {
+ if (tableStream[index] === T.PARAGRAPH) {
+ paragraphs.push({
+ startIndex: index,
+ paragraphId: `item-${index}`,
+ bullet: { listId: 'continuous', listType: 'decimal', nestingLevel: 0 },
+ paragraphStyle: { lineSpacing: 35, spacingRule: SpacingRule.EXACT },
+ });
+ }
+ }
+ paragraphs.push({ ...paragraphs[0], startIndex: content.length, paragraphId: 'after' });
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ body: { paragraphs, tables: [{ tableId: 'numbered', startIndex: 0, endIndex: tableStream.length }] },
+ lists: {
+ decimal: {
+ listType: 'decimal',
+ nestingLevel: [{ bulletAlignment: 1, glyphFormat: '%1.', startNumber: 0, glyphType: ListGlyphType.DECIMAL }],
+ },
+ },
+ tableSource: {
+ numbered: {
+ tableId: 'numbered',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ size: { type: TableSizeType.SPECIFIED, width: { v: 160 } },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 160 } } }],
+ tableRows: [{ tableCells: [{}], trHeight: { val: { v: 0 }, hRule: TableRowHeightRule.AT_LEAST } }],
+ },
+ },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 200, height: 140 } },
+ });
+ const table = createTableSkeleton(ctx, curPage, viewModel, paragraphNode.children[0], sectionBreakConfig);
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, table);
+ expect(pages.length).toBeGreaterThan(1);
+ const symbols = pages.flatMap((page) => [...page.skeTables.values()])
+ .flatMap((slice) => slice.rows.flatMap((row) => row.cells))
+ .flatMap((cell) => cell.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)))
+ .flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup))
+ .filter((glyph) => glyph.glyphType === GlyphType.LIST)
+ .map((glyph) => glyph.content);
+ expect(symbols).toEqual(['1.', '2.', '3.', '4.', '5.']);
+ const followingNode = viewModel.getChildren()[0].children[1];
+ lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, followingNode.content!, viewModel, followingNode, sectionBreakConfig),
+ pages[pages.length - 1],
+ followingNode,
+ sectionBreakConfig,
+ null
+ );
+ expect(ctx.paragraphConfigCache.get('')?.get(content.length)?.bulletSkeleton?.symbol).toBe('6.');
+ });
+
+ it.each([0, 50, 100, 110, 120])('reserves the Word row minimum on its final continuation without exceeding a page: %s', (minimumHeight) => {
+ const T = DataStreamTreeTokenType;
+ const tableStream = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}One\rTwo\rThree\rFour\rFive\r${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const paragraphs = [];
+ for (let index = 0; index < tableStream.length; index++) {
+ if (tableStream[index] === T.PARAGRAPH) {
+ paragraphs.push({
+ startIndex: index,
+ paragraphId: `line-${index}`,
+ paragraphStyle: { lineSpacing: 20, spacingRule: SpacingRule.EXACT, widowControl: BooleanNumber.FALSE },
+ });
+ }
+ }
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(tableStream, {
+ body: { paragraphs, tables: [{ tableId: 'minimum', startIndex: 0, endIndex: tableStream.length }] },
+ tableSource: {
+ minimum: {
+ tableId: 'minimum',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ size: { type: TableSizeType.SPECIFIED, width: { v: 160 } },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 160 } } }],
+ tableRows: [{
+ tableCells: [{ margin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } } }],
+ trHeight: { val: { v: minimumHeight }, hRule: TableRowHeightRule.AT_LEAST },
+ }],
+ },
+ },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 200, height: 100 } },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL);
+ const table = createTableSkeleton(ctx, curPage, viewModel, paragraphNode.children[0], sectionBreakConfig);
+ const pages = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig),
+ curPage,
+ paragraphNode,
+ sectionBreakConfig,
+ table
+ );
+ const fragments = pages.flatMap((page) => [...page.skeTables.values()].flatMap((slice) => slice.rows));
+ const finalHeight = Math.min(60, Math.max(40, minimumHeight));
+ expect(fragments.map((row) => row.height)).toEqual([60, finalHeight]);
+ expect(fragments.map((row) => row.cells[0].pageHeight)).toEqual([60, finalHeight]);
+ });
+
+ it('moves a table row together when a cell cannot start because of widow control', () => {
+ const T = DataStreamTreeTokenType;
+ const cell = (text: string) => `${T.TABLE_CELL_START}${text}\r${T.SECTION_BREAK}${T.TABLE_CELL_END}`;
+ const row = (left: string, right: string) => `${T.TABLE_ROW_START}${cell(left)}${cell(right)}${T.TABLE_ROW_END}`;
+ const tableStream = `${T.TABLE_START}${row('Before', 'Before')}${row('aaaa bbbb cccc dddd eeee ffff', 'A/I')}${T.TABLE_END}`;
+ const paragraphs = [];
+ for (let index = 0; index < tableStream.length; index++) {
+ if (tableStream[index] === T.PARAGRAPH) {
+ paragraphs.push({
+ startIndex: index,
+ paragraphId: `line-${index}`,
+ paragraphStyle: {
+ lineSpacing: 20,
+ spacingRule: SpacingRule.EXACT,
+ widowControl: BooleanNumber.TRUE,
+ spaceBelow: { v: 13 },
+ },
+ });
+ }
+ }
+ const tableCells = [0, 1].map(() => ({ margin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } } }));
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(tableStream, {
+ body: { paragraphs, tables: [{ tableId: 'widow-row', startIndex: 0, endIndex: tableStream.length }] },
+ tableSource: {
+ 'widow-row': {
+ tableId: 'widow-row',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ size: { type: TableSizeType.SPECIFIED, width: { v: 160 } },
+ tableColumns: [0, 1].map(() => ({ size: { type: TableSizeType.SPECIFIED, width: { v: 80 } } })),
+ tableRows: [
+ { tableCells, trHeight: { val: { v: 75 }, hRule: TableRowHeightRule.EXACT } },
+ { tableCells, trHeight: { val: { v: 0 }, hRule: TableRowHeightRule.AT_LEAST } },
+ ],
+ },
+ },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 200, height: 140 } },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL);
+ const table = createTableSkeleton(ctx, curPage, viewModel, paragraphNode.children[0], sectionBreakConfig);
+ const pages = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig),
+ curPage,
+ paragraphNode,
+ sectionBreakConfig,
+ table
+ );
+ const slices = pages.flatMap((page) => [...page.skeTables.values()]);
+ expect(slices.map((slice) => slice.rows.map((row) => row.index))).toEqual([[0], [1]]);
+ expect(slices[1].rows[0].height).toBe(73);
+ expect(slices[1].rows[0].cells.map((cell) => cell.pageHeight)).toEqual([73, 73]);
+ });
+
+ it.each([
+ { cellWidth: 100, positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 }, expectedLeft: 0 },
+ { cellWidth: 100, positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: -5 }, expectedLeft: -5 },
+ { cellWidth: 100, positionH: { relativeFrom: ObjectRelativeFromH.PAGE, align: AlignTypeH.CENTER }, expectedLeft: 21 },
+ { cellWidth: 52, positionH: { relativeFrom: ObjectRelativeFromH.PAGE, align: AlignTypeH.CENTER }, expectedLeft: 0 },
+ ])('keeps floating table alignment within its cell without changing authored offsets ($cellWidth, $expectedLeft)', ({ cellWidth, positionH, expectedLeft }) => {
+ const page = {
+ type: DocumentSkeletonPageType.CELL,
+ pageWidth: cellWidth,
+ pageHeight: 200,
+ marginTop: 10,
+ marginBottom: 10,
+ marginLeft: 0,
+ marginRight: 0,
+ sections: [] as any[],
+ } as any;
+ const section = { top: 0, columns: [] as any[], parent: page } as any;
+ const column = { left: 0, width: cellWidth, lines: [], parent: section } as any;
+ page.sections = [section];
+ section.columns = [column];
+ const table = {
+ width: 58,
+ height: 120,
+ tableSource: {
+ position: {
+ positionH,
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: -104 },
+ },
+ },
+ } as any;
+
+ const source = JSON.stringify(table.tableSource);
+ expect(__testing.getWrapTablePosition(table, column, 0, 16)).toEqual({ left: expectedLeft, top: 0 });
+ expect(JSON.stringify(table.tableSource)).toBe(source);
+ });
+
+ it.each([undefined, { left: 2, top: 3, right: 7, bottom: 11 }])('stores an inline viewport without resizing it for effect bounds (%j)', (effectExtent) => {
setDocsCustomBlockRenderViewportProvider(() => ({
bleedLeft: 12,
bleedWidth: 360,
@@ -1178,6 +3705,7 @@ describe('layout-ruler', () => {
drawingId: 'b1',
drawingType: DrawingTypeEnum.DRAWING_DOM,
layoutType: PositionedObjectLayoutType.INLINE,
+ effectExtent,
docTransform: {
angle: 0,
size: { height: 60, width: 120 },
@@ -1203,7 +3731,8 @@ describe('layout-ruler', () => {
},
snapToGrid: BooleanNumber.FALSE,
textStyle: {},
- }, 180, 80, 'b1');
+ }, 180 + (effectExtent?.left ?? 0) + (effectExtent?.right ?? 0), 80 + (effectExtent?.top ?? 0), 'b1');
+ glyph.bBox.bd = effectExtent?.bottom ?? 0;
updateInlineDrawingPosition({
divides: [{
@@ -1211,7 +3740,7 @@ describe('layout-ruler', () => {
left: 0,
paddingLeft: 0,
}],
- lineHeight: 100,
+ lineHeight: 100 + (effectExtent?.top ?? 0) + (effectExtent?.bottom ?? 0),
marginBottom: 0,
parent: column,
top: 10,
@@ -1228,6 +3757,7 @@ describe('layout-ruler', () => {
expect(drawing?.customBlockRenderViewport?.pageContentWidth).toBe(300);
expect(drawing?.customBlockRenderViewport?.viewScale).toBe(1.5);
expect(drawing?.customBlockRenderViewport?.viewportHeight).toBe(64);
- expect(drawing?.aTop).toBe(30);
+ expect(drawing?.aTop).toBe(30 + (effectExtent?.top ?? 0));
+ expect(drawing?.aLeft).toBe(effectExtent?.left ?? 0);
});
});
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts
index 1c35ad8669..6960cf3ac3 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts
@@ -14,14 +14,370 @@
* limitations under the License.
*/
-import { DataStreamTreeTokenType, HorizontalAlign } from '@univerjs/core';
-import { describe, expect, it } from 'vitest';
+import {
+ BooleanNumber,
+ characterSpacingControlType,
+ DataStreamTreeTokenType,
+ DocumentFlavor,
+ HorizontalAlign,
+ SpacingRule,
+ WrapStrategy,
+} from '@univerjs/core';
+import { describe, expect, it, onTestFinished, vi } from 'vitest';
+import { getFontStyleString } from '../../../../../../basics/tools';
+import { getDocumentCompatibilityPolicy } from '../../../../document-compatibility';
+import { getGlyphGroupFontBoundingBox } from '../../../model/glyph';
+import { FontCache } from '../../../shaping-engine/font-cache';
+import { clearFontCreateConfigCache } from '../../../tools';
import { lineAdjustment } from '../line-adjustment';
import { lineBreaking } from '../linebreaking';
import { shaping } from '../shaping';
import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';
describe('line-adjustment', () => {
+ it.each([12, 17, 22, 30].flatMap((points) => [DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN].map((documentFlavor) => ({ points, documentFlavor }))))('aligns exact-spaced text like Word without changing line boxes: %j', ({ points, documentFlavor }) => {
+ const measure = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
+ width: text.length * 8,
+ fontBoundingBoxAscent: 12,
+ fontBoundingBoxDescent: 4,
+ }) as TextMetrics);
+ onTestFinished(() => measure.mockRestore());
+ const content = 'Exact line';
+ const bed = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: points / 0.75, snapToGrid: BooleanNumber.FALSE } }] },
+ });
+ const before = JSON.stringify(bed.dataModel.getSnapshot());
+ 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);
+ const line = pages[0].sections[0].columns[0].lines[0];
+ const height = line.lineHeight;
+ const paddingTop = line.paddingTop;
+ lineAdjustment(pages, bed.viewModel, bed.paragraphNode, bed.sectionBreakConfig);
+ const { boundingBoxAscent } = getGlyphGroupFontBoundingBox(bed.sectionBreakConfig.documentCompatibilityPolicy, ...line.divides.map((divide) => divide.glyphGroup));
+ if (documentFlavor === DocumentFlavor.TRADITIONAL) {
+ expect(line.paddingTop + boundingBoxAscent).toBeCloseTo(points / 0.75 * 0.8);
+ } else {
+ expect(line.paddingTop).toBe(paddingTop);
+ }
+ const baselinePadding = line.paddingTop;
+ lineAdjustment(pages, bed.viewModel, bed.paragraphNode, bed.sectionBreakConfig);
+ expect(line.paddingTop).toBeCloseTo(baselinePadding);
+ expect(line.lineHeight).toBe(height);
+ expect(JSON.stringify(bed.dataModel.getSnapshot())).toBe(before);
+ } finally {
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
+
+ it.each([' '.repeat(20), '\u3000'.repeat(3), '\u00A0'.repeat(3), '\t'])('matches Word trailing-space alignment without changing the text (%j)', (suffix) => {
+ const measure = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
+ width: text.length * 8,
+ fontBoundingBoxAscent: 8,
+ fontBoundingBoxDescent: 2,
+ }) as TextMetrics);
+ onTestFinished(() => measure.mockRestore());
+ for (const documentFlavor of [DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN]) {
+ for (const horizontalAlign of [HorizontalAlign.CENTER, HorizontalAlign.RIGHT]) {
+ const offsets = ['', suffix].map((ending) => {
+ const content = `Aligned text${ending}`;
+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { horizontalAlign, snapToGrid: BooleanNumber.FALSE } }] },
+ });
+ const before = JSON.stringify(dataModel.getSnapshot());
+ try {
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ const lines = pages[0].sections[0].columns[0].lines;
+ expect(lines).toHaveLength(1);
+ const divide = lines[0].divides[0];
+ const offset = divide.paddingLeft;
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ expect(divide.paddingLeft).toBeCloseTo(offset);
+ expect(JSON.stringify(dataModel.getSnapshot())).toBe(before);
+ return offset;
+ } finally {
+ viewModel.dispose();
+ dataModel.dispose();
+ }
+ });
+ if (documentFlavor === DocumentFlavor.TRADITIONAL && (suffix[0] === ' ' || suffix[0] === '\u3000')) {
+ expect(offsets[1]).toBeCloseTo(offsets[0]);
+ } else {
+ expect(offsets[1]).toBeLessThan(offsets[0]);
+ }
+ }
+ }
+ });
+
+ it.each([undefined, BooleanNumber.FALSE])('preserves native no-compression hanging punctuation and explicit overrides (%s)', (hangingPunctuation) => {
+ const firstLine = '本报告由上海申银万国证券研究所有限公司(隶属于申万宏源证券有限公司,以下简称“本公司”)在中华人民共和国内地(香港、';
+ const content = `${firstLine}澳门、台湾除外)发布。`;
+ const measure = vi.spyOn(FontCache, 'getTextSize').mockReturnValue({
+ width: 12,
+ ba: 14,
+ bd: 3,
+ aba: 11,
+ abd: 1,
+ sp: 0,
+ sbr: 0,
+ sbo: 0,
+ spr: 0,
+ spo: 0,
+ });
+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ characterSpacingControl: characterSpacingControlType.doNotCompress,
+ defaultParagraphStyle: { hangingPunctuation: BooleanNumber.TRUE },
+ textStyle: { ff: '微软雅黑', fs: 9 },
+ pageSize: { width: 719.2, height: 600 },
+ },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: {
+ horizontalAlign: HorizontalAlign.BOTH,
+ snapToGrid: BooleanNumber.FALSE,
+ hangingPunctuation,
+ } }] },
+ });
+ try {
+ const shaped = shaping(ctx, content, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ const lines = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));
+ const divide = lines[0].divides[0];
+ const text = divide.glyphGroup.map((glyph) => glyph.content).join('');
+ const lastGlyph = divide.glyphGroup[divide.glyphGroup.length - 1];
+ if (hangingPunctuation === undefined) {
+ expect(text).toBe(firstLine);
+ expect(lastGlyph.content).toBe('、');
+ expect(lastGlyph.width).toBeCloseTo(12);
+ expect(lastGlyph.left).toBeCloseTo(divide.width);
+ expect(divide.glyphGroupWidth).toBeCloseTo(691.2);
+ } else {
+ expect(text).not.toBe(firstLine);
+ expect(lastGlyph.left + lastGlyph.width).toBeLessThanOrEqual(divide.width + 1e-8);
+ }
+ expect(lines.flatMap((line) => line.divides.flatMap((part) => part.glyphGroup)).map((glyph) => glyph.content).join('')).toBe(content);
+ } finally {
+ viewModel.dispose();
+ dataModel.dispose();
+ measure.mockRestore();
+ }
+ });
+
+ it.each([
+ { flavor: DocumentFlavor.TRADITIONAL, topLinePunct: undefined, expectedWidth: 8 },
+ { flavor: DocumentFlavor.TRADITIONAL, topLinePunct: BooleanNumber.FALSE, expectedWidth: 8 },
+ { flavor: DocumentFlavor.TRADITIONAL, topLinePunct: BooleanNumber.TRUE, expectedWidth: 4 },
+ { flavor: DocumentFlavor.MODERN, topLinePunct: undefined, expectedWidth: 4 },
+ { flavor: DocumentFlavor.MODERN, topLinePunct: BooleanNumber.FALSE, expectedWidth: 8 },
+ ])('respects line-start punctuation compression before alignment: $flavor/$topLinePunct', ({ flavor, topLinePunct, expectedWidth }) => {
+ const measure = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
+ width: text.length * 8,
+ fontBoundingBoxAscent: 8,
+ fontBoundingBoxDescent: 2,
+ }) as TextMetrics);
+ try {
+ const traditional = flavor === DocumentFlavor.TRADITIONAL;
+ for (const content of traditional ? ['(AB)', '甲乙丙丁(AB)'] : ['(AB)']) {
+ const { dataModel, ctx, paragraphNode, viewModel, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: flavor, pageSize: { width: traditional ? 72 : 400, height: 600 } },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: {
+ topLinePunct,
+ snapToGrid: BooleanNumber.FALSE,
+ horizontalAlign: HorizontalAlign.LEFT,
+ } }] },
+ });
+ try {
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ const lines = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));
+ const divide = lines.flatMap((line) => line.divides).find((divide) => divide.glyphGroup[0]?.content === '(')!;
+ expect(divide).toBeDefined();
+ expect(divide.glyphGroup[0].width).toBe(expectedWidth);
+ expect(divide.glyphGroup[0].xOffset).toBe(expectedWidth - 8);
+ expect(divide.glyphGroup[1].left).toBe(expectedWidth);
+ } finally {
+ viewModel.dispose();
+ dataModel.dispose();
+ }
+ }
+ } finally {
+ measure.mockRestore();
+ }
+ });
+
+ it('fills a mixed-script line with automatic spacing before compressing another Han character onto it', () => {
+ const measure = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
+ width: text.length * 8,
+ fontBoundingBoxAscent: 8,
+ fontBoundingBoxDescent: 2,
+ }) as TextMetrics);
+ const content = '甲A乙B丙C丁D戊后';
+ const { dataModel, ctx, paragraphNode, viewModel, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 124, height: 600 } },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { snapToGrid: BooleanNumber.FALSE, horizontalAlign: HorizontalAlign.BOTH } }] },
+ });
+ 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)));
+ const first = lines[0].divides[0];
+ expect(first.glyphGroup.map((glyph) => glyph.content).join('')).toBe('甲A乙B丙C丁D');
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ expect(first.glyphGroupWidth).toBeCloseTo(84);
+ expect(first.glyphGroup[0].width).toBeCloseTo(10 + 6 / 7);
+ expect(first.glyphGroup[2].width).toBeCloseTo(12 + 12 / 7);
+ expect(first.glyphGroup[2].xOffset).toBeCloseTo(2 + 6 / 7);
+ const continuation = lines[1].divides[0];
+ expect(continuation.glyphGroup[0].content).toBe('戊');
+ expect(continuation.glyphGroup[0].xOffset).toBe(0);
+ expect(continuation.glyphGroup[0].adjustability.stretchability).toEqual([0, 0]);
+ expect(continuation.glyphGroupWidth).toBeLessThan(84);
+ for (const line of lines) {
+ const glyphs = line.divides[0].glyphGroup;
+ for (let index = 1; index < glyphs.length; index++) {
+ expect(glyphs[index].left).toBeCloseTo(glyphs[index - 1].left + glyphs[index - 1].width);
+ }
+ }
+ expect(lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup)).map((glyph) => glyph.content).join(''))
+ .toBe(`${content}\r`);
+ } finally {
+ viewModel.dispose();
+ dataModel.dispose();
+ measure.mockRestore();
+ }
+ });
+
+ it.each([HorizontalAlign.CENTER, HorizontalAlign.RIGHT, HorizontalAlign.DISTRIBUTED])(
+ 'aligns DrawingML trailing breakable spaces without deleting editable glyphs (%s)',
+ (horizontalAlign) => {
+ const textStyle = { ff: 'DrawingML trailing-space regression', fs: 12 };
+ const font = getFontStyleString(textStyle).fontString;
+ const outlineFont = font.replace(/\b\d+(?:\.\d+)?(?:pt|px)\b/, '1024px');
+ for (const text of ['A', 'B', 'C', 'D', ' ', '\u3000', '\u00A0', '\t', '\u2028', '\r']) {
+ FontCache.setFontMeasureCache(font, text, {
+ width: text === '\r' ? 0 : 10,
+ fontBoundingBoxAscent: 12,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 2,
+ });
+ FontCache.setFontMeasureCache(outlineFont, text, {
+ width: text === '\r' ? 0 : 10 * 64,
+ fontBoundingBoxAscent: 12 * 64,
+ fontBoundingBoxDescent: 3 * 64,
+ actualBoundingBoxAscent: 10 * 64,
+ actualBoundingBoxDescent: 2 * 64,
+ });
+ }
+ try {
+ for (const documentFlavor of [DocumentFlavor.UNSPECIFIED, DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL, DocumentFlavor.DRAWINGML]) {
+ for (const wrapStrategy of [WrapStrategy.WRAP, WrapStrategy.OVERFLOW]) {
+ for (const ending of ['', '\u2028CD']) {
+ const results = ['', ' ', ' ', '\u3000', '\u00A0', '\t'].map((suffix) => {
+ clearFontCreateConfigCache();
+ const content = `AB${suffix}${ending}`;
+ const context = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor,
+ textStyle,
+ pageSize: { width: 240, height: 600 },
+ marginLeft: 0,
+ marginRight: 0,
+ autoHyphenation: BooleanNumber.FALSE,
+ renderConfig: { wrapStrategy },
+ },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { horizontalAlign } }] },
+ });
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = context;
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(documentFlavor);
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ const divide = pages[0].sections[0].columns[0].lines[0].divides[0];
+ const characters = divide.glyphGroup.map(({ content, count }) => ({ content, count }));
+ const trailingWidths = divide.glyphGroup.filter((glyph) => suffix.includes(glyph.content) && glyph.content !== '')
+ .map((glyph) => glyph.width);
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ expect(divide.glyphGroup.map(({ content, count }) => ({ content, count }))).toEqual(characters);
+ if (horizontalAlign !== HorizontalAlign.DISTRIBUTED || (documentFlavor === DocumentFlavor.DRAWINGML && [' ', ' ', '\u3000'].includes(suffix))) {
+ expect(divide.glyphGroup.filter((glyph) => suffix.includes(glyph.content) && glyph.content !== '')
+ .map((glyph) => glyph.width)).toEqual(trailingWidths);
+ }
+ const positions = divide.glyphGroup.filter((glyph) => /[AB]/.test(glyph.content))
+ .map((glyph) => divide.paddingLeft + glyph.left);
+ viewModel.dispose();
+ return positions;
+ });
+ if (documentFlavor === DocumentFlavor.DRAWINGML ||
+ (documentFlavor === DocumentFlavor.TRADITIONAL && wrapStrategy === WrapStrategy.WRAP && ending === '' && horizontalAlign !== HorizontalAlign.DISTRIBUTED)) {
+ for (const index of [1, 2, 3]) {
+ expect(results[index], `${wrapStrategy}/${ending}/${index}`).toEqual(results[0]);
+ }
+ } else {
+ expect(results[1]).not.toEqual(results[0]);
+ }
+ expect(results[4]).not.toEqual(results[0]);
+ expect(results[5]).not.toEqual(results[0]);
+ }
+ }
+ }
+ } finally {
+ FontCache.clearFontMeasureCache(font);
+ FontCache.clearFontMeasureCache(outlineFont);
+ clearFontCreateConfigCache();
+ }
+ }
+ );
+
+ it('justifies a wrapped DrawingML line using internal spaces without stretching trailing spaces', () => {
+ const content = 'A B CCCCCCC';
+ const textStyle = { ff: 'DrawingML justified-space regression', fs: 12 };
+ const font = getFontStyleString(textStyle).fontString;
+ for (const text of ['A', 'B', 'C', ' ']) {
+ FontCache.setFontMeasureCache(font, text, {
+ width: 10,
+ fontBoundingBoxAscent: 12,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 2,
+ });
+ }
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.DRAWINGML,
+ textStyle,
+ pageSize: { width: 50, height: 600 },
+ marginLeft: 0,
+ marginRight: 0,
+ autoHyphenation: BooleanNumber.FALSE,
+ },
+ body: { paragraphs: [{ startIndex: content.length, paragraphStyle: { horizontalAlign: HorizontalAlign.JUSTIFIED } }] },
+ });
+ try {
+ clearFontCreateConfigCache();
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(DocumentFlavor.DRAWINGML);
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ const divide = pages[0].sections[0].columns[0].lines[0].divides[0];
+ expect(divide.glyphGroup.map((glyph) => glyph.content).join('')).toBe('A B ');
+ expect(divide.isFull).toBe(true);
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+ expect(divide.glyphGroup.map((glyph) => glyph.width)).toEqual([10, 30, 10, 10, 10]);
+ expect(divide.glyphGroup.map((glyph) => glyph.left)).toEqual([0, 10, 40, 50, 60]);
+ expect(divide.glyphGroupWidth).toBe(70);
+ } finally {
+ viewModel.dispose();
+ FontCache.clearFontMeasureCache(font);
+ clearFontCreateConfigCache();
+ }
+ });
+
it.each([0, 1024])('adjusts a late paragraph without revisiting unrelated cell lines (%i following lines)', (followingLineCount) => {
const prefixCount = 1024;
const prefix = 'A\r'.repeat(prefixCount);
@@ -83,6 +439,13 @@ describe('line-adjustment', () => {
}
function createPagesWithLine(divide: any, horizontalAlign: HorizontalAlign) {
+ const { dataModel, viewModel, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('', {
+ body: { paragraphs: [{ startIndex: 0, paragraphStyle: { horizontalAlign } }] },
+ });
+ onTestFinished(() => {
+ viewModel.dispose();
+ dataModel.dispose();
+ });
const line = {
paragraphIndex: 0,
divides: [divide],
@@ -102,18 +465,9 @@ describe('line-adjustment', () => {
return {
pages: [page] as any[],
- viewModel: {
- getParagraph: () => ({
- startIndex: 0,
- paragraphStyle: {
- horizontalAlign,
- },
- }),
- } as any,
- paragraphNode: {
- endIndex: 1,
- } as any,
- sectionBreakConfig: {} as any,
+ viewModel,
+ paragraphNode,
+ sectionBreakConfig,
};
}
@@ -279,7 +633,7 @@ describe('line-adjustment', () => {
expect(rightDivide.paddingLeft).toBe(50);
});
- it('expands justifiable spaces to fill a full justified divide', () => {
+ it.each([HorizontalAlign.JUSTIFIED, HorizontalAlign.BOTH])('expands justifiable spaces to fill a full justified divide (%s)', (alignment) => {
const space = createGlyph(' ', 5);
const divide = {
width: 40,
@@ -287,7 +641,7 @@ describe('line-adjustment', () => {
paddingLeft: 0,
glyphGroup: [createGlyph('A', 10), space, createGlyph('B', 10)],
} as any;
- const context = createPagesWithLine(divide, HorizontalAlign.JUSTIFIED);
+ const context = createPagesWithLine(divide, alignment);
lineAdjustment(context.pages, context.viewModel, context.paragraphNode, context.sectionBreakConfig);
@@ -296,9 +650,46 @@ describe('line-adjustment', () => {
expect(divide.paddingLeft).toBe(0);
});
- it('restores extra CJK spacing for a full line ending in CJK text', () => {
+ it.each([HorizontalAlign.JUSTIFIED, HorizontalAlign.BOTH])('justifies wrapped CJK lines without stretching the paragraph ending (%s)', (horizontalAlign) => {
+ const measure = vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => ({
+ width: text.length * 8,
+ fontBoundingBoxAscent: 8,
+ fontBoundingBoxDescent: 2,
+ }) as TextMetrics);
+ const text = '公司产品市场持续增长'.repeat(12);
+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(text, {
+ body: {
+ paragraphs: [{ startIndex: text.length, paragraphStyle: { horizontalAlign, snapToGrid: BooleanNumber.FALSE } }],
+ },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 500, height: 1200 } },
+ });
+ try {
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const pages = lineBreaking(ctx, viewModel, shaped, curPage, paragraphNode, sectionBreakConfig, null);
+ const divides = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines.flatMap((line) => line.divides))));
+ expect(divides.length).toBeGreaterThan(1);
+ const lastDivide = divides[divides.length - 1];
+ const lastWidths = lastDivide.glyphGroup.map((glyph) => glyph.width);
+
+ lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig);
+
+ for (const divide of divides.slice(0, -1)) {
+ expect(divide.glyphGroupWidth).toBeCloseTo(divide.width, 5);
+ const lastGlyph = divide.glyphGroup[divide.glyphGroup.length - 1];
+ expect(lastGlyph.width).toBeCloseTo(lastGlyph.bBox.width, 5);
+ }
+ expect(lastDivide.glyphGroup.map((glyph) => glyph.width)).toEqual(lastWidths);
+ } finally {
+ viewModel.dispose();
+ dataModel.dispose();
+ measure.mockRestore();
+ }
+ });
+
+ it.each([{ autoSpacing: undefined }, { autoSpacing: [0, 5] }])('removes only recorded automatic spacing at line end: $autoSpacing', ({ autoSpacing }) => {
const cjkGlyph = createGlyph('中', 20, {
xOffset: 5,
+ autoSpacing,
bBox: { width: 10 },
adjustability: {
stretchability: [0, 0],
@@ -315,7 +706,10 @@ describe('line-adjustment', () => {
lineAdjustment(context.pages, context.viewModel, context.paragraphNode, context.sectionBreakConfig);
- expect(cjkGlyph.width).toBe(15);
- expect(cjkGlyph.adjustability.shrinkability[1]).toBe(0);
+ expect(cjkGlyph.width).toBe(autoSpacing ? 15 : 20);
+ expect(cjkGlyph.adjustability.shrinkability[1]).toBe(autoSpacing ? 4.5 : 7);
+ expect(cjkGlyph.xOffset).toBe(5);
+ lineAdjustment(context.pages, context.viewModel, context.paragraphNode, context.sectionBreakConfig);
+ expect(cjkGlyph.width).toBe(autoSpacing ? 15 : 20);
});
});
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts
index 33e5fae810..77d25e54a6 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts
@@ -19,6 +19,7 @@ import {
AlignTypeH,
AlignTypeV,
BooleanNumber,
+ BulletAlignment,
DataStreamTreeTokenType,
DocumentBlockRangeType,
DocumentFlavor,
@@ -29,6 +30,7 @@ import {
ObjectRelativeFromV,
PositionedObjectLayoutType,
SpacingRule,
+ TableTextWrapType,
WrapTextType,
} from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -122,6 +124,45 @@ describe('linebreaking', () => {
expect(result[0].sections.length).toBeGreaterThan(0);
});
+ it.each([
+ { content: 'A M', leading: 20 },
+ { content: 'M A', leading: 20 },
+ { content: 'A M', leading: 14.8 },
+ ])('includes $leading px auto-leading regardless of run position: $content', ({ content, leading }) => {
+ const { viewModel, ctx, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed(['A', content], {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, gridType: GridType.DEFAULT },
+ body: {
+ paragraphs: [{
+ startIndex: 1,
+ paragraphId: 'preceding-paragraph',
+ paragraphStyle: { lineSpacing: 1, spacingRule: SpacingRule.AUTO, spaceBelow: { v: 10 } },
+ }, {
+ startIndex: content.length + 2,
+ paragraphId: 'mixed-leading',
+ paragraphStyle: { lineSpacing: 1, spacingRule: SpacingRule.AUTO, snapToGrid: BooleanNumber.FALSE },
+ }],
+ },
+ });
+ let result = [curPage];
+ for (const paragraphNode of sectionNode.children) {
+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ for (const run of shapedTextList) {
+ for (const glyph of run.glyphs) {
+ glyph.bBox = { ...glyph.bBox, ba: 10, bd: 4, normalLineHeight: glyph.content === 'M' ? leading : 14 };
+ }
+ }
+ result = lineBreaking(ctx, viewModel, shapedTextList, result[result.length - 1], paragraphNode, sectionBreakConfig, null);
+ }
+ expect(paragraphLines(result[0], sectionNode.children[0].endIndex)[0].lineHeight).toBeCloseTo(24);
+ const lines = paragraphLines(result[0], sectionNode.children[1].endIndex);
+ expect(lines).toHaveLength(1);
+ expect(lines[0].top).toBeCloseTo(24);
+ expect(lines[0].lineHeight).toBeCloseTo(leading);
+ expect(lines[0].contentHeight).toBe(14);
+ expect(lines[0].paddingTop).toBeCloseTo((leading - 14) / 2);
+ expect(lines[0].paddingBottom).toBeCloseTo((leading - 14) / 2);
+ });
+
it.each([
{ name: 'explicitly disabled', snapToGrid: BooleanNumber.FALSE, expectedLineHeight: 21 },
{ name: 'enabled by default', snapToGrid: undefined, expectedLineHeight: 41.6 },
@@ -173,7 +214,7 @@ describe('linebreaking', () => {
}
});
- it('suppresses paragraph space above at the top of a traditional page', () => {
+ it.each([1, 2])('preserves initial paragraph spacing but suppresses it on following traditional pages (%s)', (pageNumber) => {
const content = 'Heading';
const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
documentStyle: {
@@ -189,6 +230,7 @@ describe('linebreaking', () => {
},
});
+ curPage.pageNumber = pageNumber;
const result = lineBreaking(
ctx,
viewModel,
@@ -200,10 +242,43 @@ describe('linebreaking', () => {
);
const firstLine = result[0].sections[0].columns[0].lines[0];
- expect(firstLine.marginTop).toBe(0);
+ expect(firstLine.marginTop).toBe(pageNumber === 1 ? 22 : 0);
expect(firstLine.top).toBe(0);
});
+ it.each([1, 2].flatMap((pageNumber) => [false, true].map((structural) => ({ pageNumber, structural }))))('handles page-top spacing after an empty anchor ($pageNumber, structural: $structural)', ({ pageNumber, structural }) => {
+ const bed = createSectionLayoutTestBed(['', 'Heading'], {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: {
+ paragraphs: [
+ { startIndex: 0, paragraphStyle: structural ? { paragraphFrame: BooleanNumber.TRUE } : {} },
+ { startIndex: 8, paragraphStyle: { spaceAbove: { v: 22 } } },
+ ],
+ },
+ });
+ bed.curPage.pageNumber = pageNumber;
+ let page = bed.curPage;
+ for (const node of bed.sectionNode.children) {
+ const pages = lineBreaking(
+ bed.ctx,
+ bed.viewModel,
+ shaping(bed.ctx, node.content!, bed.viewModel, node, bed.sectionBreakConfig),
+ page,
+ node,
+ bed.sectionBreakConfig,
+ null
+ );
+ expect(pages).toHaveLength(1);
+ page = pages[0];
+ }
+ const lines = page.sections[0].columns[0].lines;
+ expect(lines).toHaveLength(2);
+ expect(lines[0].lineHeight === 0).toBe(structural);
+ expect(lines[1].marginTop).toBe(pageNumber > 1 && structural ? 0 : 22);
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ });
+
it('starts pageBreakBefore paragraphs on the next physical page without doubling a blank page', () => {
const { viewModel, ctx, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed(['First', 'Second'], {
documentStyle: {
@@ -444,7 +519,7 @@ describe('linebreaking', () => {
}
);
- it('does not create a blank page for a manual page break at the top of an empty page', () => {
+ it('preserves an authored blank page for a manual page break at the top of an empty page', () => {
const testBed = createParagraphLayoutTestBed(DataStreamTreeTokenType.PAGE_BREAK, {
documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
});
@@ -465,7 +540,127 @@ describe('linebreaking', () => {
null
);
+ expect(result).toHaveLength(2);
+ });
+
+ it.each([
+ [DocumentFlavor.TRADITIONAL, false, false],
+ [DocumentFlavor.MODERN, false, true],
+ [DocumentFlavor.TRADITIONAL, true, false],
+ ])('distinguishes terminal manual breaks from cached metadata (%s, cached: %s)', (documentFlavor, cached, hasBlankLine) => {
+ const content = `Before${DataStreamTreeTokenType.PAGE_BREAK}`;
+ const testBed = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor },
+ body: { renderedPageBreaks: cached ? [content.length - 1] : [] },
+ });
+ const result = lineBreaking(
+ testBed.ctx,
+ testBed.viewModel,
+ shaping(testBed.ctx, testBed.paragraphNode.content!, testBed.viewModel, testBed.paragraphNode, testBed.sectionBreakConfig),
+ testBed.curPage,
+ testBed.paragraphNode,
+ testBed.sectionBreakConfig,
+ null
+ );
+
+ expect(result).toHaveLength(cached ? 1 : 2);
+ expect(result[1] ? paragraphLines(result[1], testBed.paragraphNode.endIndex).length > 0 : false).toBe(hasBlankLine);
+ expect(result.map(pageText).join('')).toBe(`Before${DataStreamTreeTokenType.PARAGRAPH}`);
+ if (!hasBlankLine) {
+ const glyphs = paragraphLines(result[0], testBed.paragraphNode.endIndex)
+ .flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup));
+ expect(glyphs.map((glyph) => glyph.raw).join('')).toBe(testBed.paragraphNode.content);
+ }
+ });
+
+ it.each([false, true].flatMap((blankParagraph) => [
+ { blankParagraph, pageHeight: 80 },
+ { blankParagraph, pageHeight: 600 },
+ ]))('starts a heading after a standalone manual break without removing authored blank paragraphs: %j', ({ blankParagraph, pageHeight }) => {
+ const contents = ['Before', DataStreamTreeTokenType.PAGE_BREAK, ...(blankParagraph ? [''] : []), 'Title'];
+ let endIndex = -1;
+ const paragraphs = contents.map((content, index) => {
+ endIndex += content.length + 1;
+ return {
+ startIndex: endIndex,
+ paragraphId: `break-paragraph-${index}`,
+ paragraphStyle: { lineSpacing: index === 0 ? 40 : 20, spacingRule: SpacingRule.EXACT },
+ };
+ });
+ const { ctx, viewModel, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed(contents, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 400, height: pageHeight } },
+ body: { paragraphs },
+ });
+ let pages = [curPage];
+ for (const paragraph of sectionNode.children) {
+ const result = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, paragraph.content!, viewModel, paragraph, sectionBreakConfig),
+ pages[pages.length - 1],
+ paragraph,
+ sectionBreakConfig,
+ null
+ );
+ pages = [...pages.slice(0, -1), ...result];
+ }
+
+ expect(pages).toHaveLength(2);
+ const heading = sectionNode.children[sectionNode.children.length - 1];
+ const headingLine = paragraphLines(pages[1], heading.endIndex)[0];
+ expect(headingLine.top > 0).toBe(blankParagraph);
+ expect(pageText(pages[1])).toBe(`${blankParagraph ? '\r' : ''}Title\r`);
+ expect(pageText(pages[0])).toBe('Before\r\r');
+ });
+
+ it('does not add an empty line for a leading cached pagination marker', () => {
+ const content = `${DataStreamTreeTokenType.PAGE_BREAK}Title`;
+ const testBed = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: { renderedPageBreaks: [0] },
+ });
+ const result = lineBreaking(
+ testBed.ctx,
+ testBed.viewModel,
+ shaping(testBed.ctx, testBed.paragraphNode.content!, testBed.viewModel, testBed.paragraphNode, testBed.sectionBreakConfig),
+ testBed.curPage,
+ testBed.paragraphNode,
+ testBed.sectionBreakConfig,
+ null
+ );
+
expect(result).toHaveLength(1);
+ const lines = paragraphLines(result[0], testBed.paragraphNode.endIndex);
+ expect(lines).toHaveLength(1);
+ expect(lines[0].top).toBe(0);
+ expect(pageText(result[0])).toContain('Title');
+ });
+
+ it.each([1, 9])('ignores a leading cached page break regardless of the current page ordinal: %s', (pageNumber) => {
+ const text = '利润率整体稳中向好,期间费用率有所提升。2023年公司毛利率';
+ const { ctx, viewModel, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed(
+ ['Before', `${DataStreamTreeTokenType.PAGE_BREAK}${text}`],
+ {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: { renderedPageBreaks: [7] },
+ }
+ );
+ curPage.pageNumber = pageNumber;
+ let pages = [curPage];
+ for (const paragraph of sectionNode.children) {
+ const result = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, paragraph.content!, viewModel, paragraph, sectionBreakConfig),
+ pages[pages.length - 1],
+ paragraph,
+ sectionBreakConfig,
+ null
+ );
+ pages = [...pages.slice(0, -1), ...result];
+ }
+ expect(pages).toHaveLength(1);
+ expect(pageText(pages[0])).toBe(`Before\r${text}\r`);
});
it('keeps the entry contract for empty shaped text while initializing paragraph caches', () => {
@@ -611,6 +806,41 @@ describe('linebreaking', () => {
expect(listGlyphCounts).toEqual([1, 0]);
});
+ it.each(['', 'Intro'])('applies first-line indentation only at the paragraph start across a cached break after "%s"', (beforeBreak) => {
+ const content = `${beforeBreak}${DataStreamTreeTokenType.PAGE_BREAK}敏锐如热泵领域针对市面上的产品`;
+ const bed = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 120, height: 200 },
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ body: {
+ renderedPageBreaks: [beforeBreak.length],
+ paragraphs: [{
+ startIndex: content.length,
+ paragraphStyle: { indentFirstLine: { v: 16 }, snapToGrid: BooleanNumber.FALSE },
+ }],
+ },
+ });
+ const pages = lineBreaking(
+ bed.ctx,
+ bed.viewModel,
+ shaping(bed.ctx, bed.paragraphNode.content!, bed.viewModel, bed.paragraphNode, bed.sectionBreakConfig),
+ bed.curPage,
+ bed.paragraphNode,
+ bed.sectionBreakConfig,
+ null
+ );
+ expect(pages).toHaveLength(1);
+ const lines = paragraphLines(pages[0], bed.paragraphNode.endIndex);
+ expect(lines[0].paragraphStart).toBe(true);
+ expect(lines[0].divides[0].width).toBe(64);
+ expect(lines.slice(1).every((line) => !line.paragraphStart && line.divides[0].width === 80)).toBe(true);
+ expect(pageText(pages[0])).toBe(`${beforeBreak}敏锐如热泵领域针对市面上的产品\r`);
+ bed.viewModel.dispose();
+ });
+
it('does not add a second boundary when a rendered page break follows natural overflow', () => {
const beforeBreak = 'One two three four five six seven eight nine ten '.repeat(8);
const content = `${beforeBreak}${DataStreamTreeTokenType.PAGE_BREAK}After`;
@@ -657,6 +887,11 @@ describe('linebreaking', () => {
});
it.each([0, 19])('an obsolete rendered page marker at offset %s does not change wrapping or disable widow control', (offset) => {
+ vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text, font) => {
+ const size = /([\d.]+)(px|pt)/.exec(font)!;
+ const scale = Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) / 11;
+ return { width: text.length * 8 * scale, fontBoundingBoxAscent: 10 * scale, fontBoundingBoxDescent: 4 * scale, actualBoundingBoxAscent: 10 * scale, actualBoundingBoxDescent: 4 * scale };
+ });
vi.spyOn(FontCache, 'getNormalLineHeight').mockReturnValue(14.8);
const text = 'One two three four five six seven eight nine ten eleven twelve';
const layout = (marker: boolean) => {
@@ -698,8 +933,7 @@ describe('linebreaking', () => {
expect(layout(true)).toEqual(expected);
});
- it('preserves a rendered page break before a fitting inline drawing', () => {
- const beforeBreak = 'Intro';
+ it.each([360, 360.4, 365].flatMap((drawingWidth) => ['', 'Intro'].map((beforeBreak) => ({ drawingWidth, beforeBreak }))))('ignores cached pagination before a $drawingWidth px inline drawing after "$beforeBreak"', ({ drawingWidth, beforeBreak }) => {
const content = `${beforeBreak}${DataStreamTreeTokenType.PAGE_BREAK}${DataStreamTreeTokenType.CUSTOM_BLOCK}`;
const createBed = (rendered: boolean) => createParagraphLayoutTestBed(content, {
documentStyle: {
@@ -723,7 +957,7 @@ describe('linebreaking', () => {
positionH: {},
positionV: {},
// DOCX EMU-to-pixel conversion can leave a sub-pixel width over the column.
- size: { width: 360.4, height: 90 },
+ size: { width: drawingWidth, height: 90 },
},
},
},
@@ -740,116 +974,46 @@ describe('linebreaking', () => {
const renderedResult = layout(createBed(true));
const manualResult = layout(createBed(false));
- expect(renderedResult).toHaveLength(manualResult.length);
-
- expect({
- rendered: paginationSignature(renderedResult),
- manual: paginationSignature(manualResult),
- }).toMatchInlineSnapshot(`
- {
- "manual": [
- {
- "breakType": 0,
- "pageNumber": 1,
- "sections": [
- {
- "columns": [
- {
- "lines": [
- {
- "divideCount": 1,
- "lineIndex": 0,
- "paragraphIndex": 7,
- "top": 0,
- },
- ],
- },
- ],
- },
- ],
- },
- {
- "breakType": 1,
- "pageNumber": 2,
- "sections": [
- {
- "columns": [
- {
- "lines": [
- {
- "divideCount": 1,
- "lineIndex": 0,
- "paragraphIndex": 7,
- "top": 0,
- },
- {
- "divideCount": 1,
- "lineIndex": 1,
- "paragraphIndex": 7,
- "top": 90,
- },
- ],
- },
- ],
- },
- ],
- },
- ],
- "rendered": [
- {
- "breakType": 0,
- "pageNumber": 1,
- "sections": [
- {
- "columns": [
- {
- "lines": [
- {
- "divideCount": 1,
- "lineIndex": 0,
- "paragraphIndex": 7,
- "top": 0,
- },
- ],
- },
- ],
- },
- ],
- },
- {
- "breakType": 1,
- "pageNumber": 2,
- "sections": [
- {
- "columns": [
- {
- "lines": [
- {
- "divideCount": 1,
- "lineIndex": 0,
- "paragraphIndex": 7,
- "top": 0,
- },
- {
- "divideCount": 1,
- "lineIndex": 1,
- "paragraphIndex": 7,
- "top": 90,
- },
- ],
- },
- ],
- },
- ],
- },
- ],
- }
- `);
+ expect(manualResult).toHaveLength(2);
+ expect(renderedResult).toHaveLength(1);
+ const lines = paragraphLines(renderedResult[0], content.length);
+ expect(lines).toHaveLength(beforeBreak ? 2 : 1);
+ const glyphs = lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup));
+ expect(glyphs.filter((glyph) => glyph.drawingId === 'inline-image')).toHaveLength(1);
+ expect(glyphs.map((glyph) => glyph.raw).join('')).toBe(`${content}\r\n`);
+ expect(glyphs[glyphs.length - 1].parent).toBe(glyphs.find((glyph) => glyph.drawingId === 'inline-image')?.parent);
+ });
+
+ it('honors manual boundaries without promoting a later cached marker to a page break', () => {
+ const contents = ['First\fSecond', '\fThird'];
+ const testBed = createSectionLayoutTestBed(contents, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: { renderedPageBreaks: [contents[0].length + 1] },
+ });
+ const pages = [testBed.curPage];
+ for (const paragraph of testBed.sectionNode.children) {
+ const result = lineBreaking(
+ testBed.ctx,
+ testBed.viewModel,
+ shaping(testBed.ctx, paragraph.content!, testBed.viewModel, paragraph, testBed.sectionBreakConfig),
+ pages[pages.length - 1],
+ paragraph,
+ testBed.sectionBreakConfig,
+ null
+ );
+ pages.splice(pages.length - 1, 1, ...result);
+ }
+
+ expect(pages).toHaveLength(2);
+ expect(pages.map(pageText)).toEqual([
+ 'First',
+ 'Second\rThird\r',
+ ]);
});
it('does not duplicate a rendered page boundary already reached by an earlier paragraph', () => {
const overflowingParagraph = 'One two three four five six seven eight nine ten '.repeat(8);
- const beforeBreak = 'Short paragraph';
+ const beforeBreak = 'Pre ';
const breakParagraph = `${beforeBreak}${DataStreamTreeTokenType.PAGE_BREAK}After`;
const renderedBreakIndex = overflowingParagraph.length + 1 + beforeBreak.length;
const testBed = createSectionLayoutTestBed([overflowingParagraph, breakParagraph], {
@@ -902,10 +1066,10 @@ describe('linebreaking', () => {
section.columns.some((column) => !column.isFull)
)).toBe(true);
expect(secondPages).toHaveLength(1);
- expect(paragraphLines(secondPages[0], secondParagraph.endIndex).length).toBeGreaterThan(0);
+ expect(paragraphLines(secondPages[0], secondParagraph.endIndex)).toHaveLength(1);
});
- it('exposes cell-local rendered page breaks to the outer table paginator', () => {
+ it('does not split a table cell at a cached pagination marker', () => {
const beforeBreak = 'Before';
const content = `${beforeBreak}${DataStreamTreeTokenType.PAGE_BREAK}After`;
const testBed = createParagraphLayoutTestBed(content, {
@@ -932,7 +1096,9 @@ describe('linebreaking', () => {
null
);
- expect(result).toHaveLength(2);
+ expect(result).toHaveLength(1);
+ expect(paragraphLines(result[0], testBed.paragraphNode.endIndex)).toHaveLength(1);
+ expect(pageText(result[0])).toBe('BeforeAfter\r');
});
it.each([
@@ -1053,14 +1219,15 @@ describe('linebreaking', () => {
expect(result[0].sections[0].columns).toHaveLength(2);
});
- it('DOCX golden e2e moves a split keepLines paragraph when it fits on an empty page', () => {
+ it.each([0, 4].flatMap((spaceAbove) => [0, 1, 5].map((pageNumberStart) => ({ spaceAbove, pageNumberStart }))))('moves split keepLines paragraphs without carrying $spaceAbove px before-spacing onto the next page (start=$pageNumberStart)', ({ spaceAbove, pageNumberStart }) => {
const contents = ['Filler filler filler filler', 'One two three four five'];
const firstEnd = contents[0].length;
const secondEnd = firstEnd + 1 + contents[1].length;
const { viewModel, ctx, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed(contents, {
documentStyle: {
documentFlavor: DocumentFlavor.TRADITIONAL,
- pageSize: { width: 120, height: 100 },
+ pageSize: { width: 120, height: 150 },
+ defaultParagraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: 20 },
marginTop: 20,
marginBottom: 20,
marginLeft: 20,
@@ -1072,12 +1239,14 @@ describe('linebreaking', () => {
{
startIndex: secondEnd,
paragraphId: 'kept',
- paragraphStyle: { keepLines: BooleanNumber.TRUE },
+ paragraphStyle: { keepLines: BooleanNumber.TRUE, spaceAbove: { v: spaceAbove } },
},
],
},
});
const [firstParagraph, secondParagraph] = sectionNode.children;
+ curPage.pageNumber = pageNumberStart;
+ sectionBreakConfig.pageNumberStart = pageNumberStart;
const firstPages = lineBreaking(
ctx,
viewModel,
@@ -1100,13 +1269,24 @@ describe('linebreaking', () => {
expect(result.length).toBeGreaterThanOrEqual(2);
expect(paragraphLines(result[0], secondParagraph.endIndex)).toHaveLength(0);
expect(paragraphLines(result[1], secondParagraph.endIndex).length).toBeGreaterThan(1);
+ expect(paragraphLines(result[1], secondParagraph.endIndex)[0].marginTop).toBe(0);
+ expect(ctx.paginationMetrics!.movedLineCount).toBeGreaterThan(0);
});
- it('keeps a heading tail with the following paragraph when the pair fits on an empty page', () => {
+ it.each([[0, 0], [4, 8], [8, 4]].flatMap(([spaceBelow, spaceAbove]) => [false, true].map((softBreak) => ({
+ spaceBelow,
+ spaceAbove,
+ softBreak,
+ }))))('keeps a heading with the following paragraph, spacing $spaceBelow/$spaceAbove, soft break $softBreak', ({ spaceBelow, spaceAbove, softBreak }) => {
const contents = [
- 'Prefix prefix prefix prefix prefix prefix',
+ 'Prefix',
'Heading',
- 'Following paragraph words',
+ `${softBreak ? '\v' : ''}Following paragraph words`,
+ ];
+ const paragraphStyles = [
+ { lineSpacing: 50, spacingRule: SpacingRule.EXACT },
+ { keepNext: BooleanNumber.TRUE, spaceBelow: { v: spaceBelow } },
+ { spaceAbove: { v: spaceAbove } },
];
let offset = 0;
const paragraphs = contents.map((content, index) => {
@@ -1114,9 +1294,7 @@ describe('linebreaking', () => {
const paragraph = {
startIndex: offset,
paragraphId: `paragraph-${index}`,
- ...(index === 1
- ? { paragraphStyle: { keepNext: BooleanNumber.TRUE } }
- : {}),
+ paragraphStyle: paragraphStyles[index],
};
offset += 1;
return paragraph;
@@ -1124,7 +1302,7 @@ describe('linebreaking', () => {
const { viewModel, ctx, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed(contents, {
documentStyle: {
documentFlavor: DocumentFlavor.TRADITIONAL,
- pageSize: { width: 120, height: 100 },
+ pageSize: { width: 120, height: 120 },
marginTop: 20,
marginBottom: 20,
marginLeft: 20,
@@ -1154,6 +1332,58 @@ describe('linebreaking', () => {
expect(paragraphLines(lastResult[0], headingIndex)).toHaveLength(0);
expect(paragraphLines(lastResult[1], headingIndex).length).toBeGreaterThan(0);
expect(paragraphLines(lastResult[1], followingIndex).length).toBeGreaterThan(0);
+ const headingLines = paragraphLines(lastResult[1], headingIndex);
+ const headingLast = headingLines[headingLines.length - 1];
+ const followingFirst = paragraphLines(lastResult[1], followingIndex)[0];
+ const headingBottom = headingLast.top + headingLast.lineHeight - (headingLast.marginBottom ?? 0);
+ expect(followingFirst.top + followingFirst.marginTop - headingBottom).toBeCloseTo(Math.max(spaceBelow, spaceAbove));
+ });
+
+ it('does not count already-applied heading after-spacing twice when keepLines moves its follower', () => {
+ const contents = ['Prefix', 'Heading', 'First\vSecond'];
+ let offset = -1;
+ const paragraphs = contents.map((content, index) => {
+ offset += content.length + 1;
+ return {
+ startIndex: offset,
+ paragraphId: `relocated-spacing-${index}`,
+ paragraphStyle: {
+ spacingRule: SpacingRule.EXACT,
+ lineSpacing: index === 0 ? 80 : 20,
+ keepNext: index === 1 ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ keepLines: index === 2 ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ spaceBelow: { v: index === 1 ? 10.4 : 0 },
+ },
+ };
+ });
+ const bed = createSectionLayoutTestBed(contents, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 200, height: 180 },
+ marginTop: 20,
+ marginBottom: 20,
+ },
+ body: { paragraphs },
+ });
+ let pages = [bed.curPage];
+ for (const paragraph of bed.sectionNode.children) {
+ const result = lineBreaking(
+ bed.ctx,
+ bed.viewModel,
+ shaping(bed.ctx, paragraph.content!, bed.viewModel, paragraph, bed.sectionBreakConfig),
+ pages[pages.length - 1],
+ paragraph,
+ bed.sectionBreakConfig,
+ null
+ );
+ pages = [...pages.slice(0, -1), ...result];
+ }
+ expect(pages).toHaveLength(2);
+ const heading = paragraphLines(pages[1], paragraphs[1].startIndex)[0];
+ const following = paragraphLines(pages[1], paragraphs[2].startIndex)[0];
+ expect(heading.top).toBe(0);
+ expect(following.top).toBeCloseTo(30.4);
+ bed.viewModel.dispose();
});
it('DOCX golden e2e moves a bounded keepNext chain and stops at a manual break', () => {
@@ -1324,7 +1554,7 @@ describe('linebreaking', () => {
expect(testBed.ctx.paginationMetrics?.retryCount).toBeLessThanOrEqual(contents.length);
});
- it.each([2, 3])('keeps a short %s-line paragraph together instead of leaving a single widow or orphan', (lineCount) => {
+ it.each([2, 3].flatMap((lineCount) => [12, 14, 15].map((mode) => ({ lineCount, mode }))))('keeps a short $lineCount-line body paragraph together in Word mode $mode', ({ lineCount, mode }) => {
const layout = (widowControl: BooleanNumber) => {
const contents = [...Array.from({ length: 4 - lineCount }, () => 'Prefix'), new Array(lineCount).fill('abcdefg').join(' ')];
let offset = 0;
@@ -1335,6 +1565,7 @@ describe('linebreaking', () => {
const bed = createSectionLayoutTestBed(contents, {
documentStyle: {
documentFlavor: DocumentFlavor.TRADITIONAL,
+ compatibilitySettings: { compatibilityMode: String(mode) },
pageSize: { width: 120, height: 85 },
},
body: { paragraphs },
@@ -1361,6 +1592,11 @@ describe('linebreaking', () => {
});
it('DOCX golden e2e avoids a single natural widow line and lets oversized keepLines paragraphs terminate', () => {
+ vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text, font) => {
+ const size = /([\d.]+)(px|pt)/.exec(font)!;
+ const scale = Number(size[1]) * (size[2] === 'px' ? 0.75 : 1) / 11;
+ return { width: text.length * 8 * scale, fontBoundingBoxAscent: 10 * scale, fontBoundingBoxDescent: 4 * scale, actualBoundingBoxAscent: 10 * scale, actualBoundingBoxDescent: 4 * scale };
+ });
const content = 'One two three four five six seven eight nine ten eleven twelve';
const widowBed = createParagraphLayoutTestBed(content, {
documentStyle: {
@@ -1436,6 +1672,43 @@ describe('linebreaking', () => {
paragraphLines(page, oversizedBed.paragraphNode.endIndex).length > 0)).toBe(true);
});
+ it.each(['widowControl', 'keepLines'] as const)('does not insert after-spacing inside a paragraph relocated by %s', (constraint) => {
+ const content = 'aaaa bbbb cccc dddd eeee ffff';
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 120, height: 200 },
+ },
+ body: {
+ paragraphs: [{
+ startIndex: content.length,
+ paragraphId: 'relocated',
+ paragraphStyle: {
+ [constraint]: BooleanNumber.TRUE,
+ lineSpacing: 20,
+ spacingRule: SpacingRule.EXACT,
+ spaceBelow: { v: 13 },
+ },
+ }],
+ },
+ });
+ curPage.sections[0].height = 25;
+ const pages = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig),
+ curPage,
+ paragraphNode,
+ sectionBreakConfig,
+ null
+ );
+ expect(pages).toHaveLength(2);
+ expect(paragraphLines(pages[0], paragraphNode.endIndex)).toHaveLength(0);
+ const lines = paragraphLines(pages[1], paragraphNode.endIndex);
+ expect(lines.map((line) => line.top)).toEqual([0, 20, 40]);
+ expect(lines[2].spaceBelowApply).toBe(13);
+ });
+
it('DOCX golden e2e does not soften a manual page break with keep or widow constraints', () => {
const content = `Before${DataStreamTreeTokenType.PAGE_BREAK}After`;
const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
@@ -1567,6 +1840,174 @@ describe('linebreaking', () => {
expect(first.metrics.peakCheckpointLineCount).toBeLessThanOrEqual(first.metrics.measuredLineCount);
});
+ it.each([
+ { name: 'same named style', ids: ['List', 'List', 'List'], flags: [1, 1, 1], tops: [8, 28, 48] },
+ { name: 'different named styles', ids: ['List', 'Other', 'List'], flags: [1, 1, 1], tops: [8, 40, 72] },
+ { name: 'one-sided opt-out', ids: ['List', 'List', 'List'], flags: [1, 0, 1], tops: [8, 36, 68] },
+ { name: 'implicit default style', ids: [undefined, undefined, undefined], flags: [1, 1, 1], tops: [8, 28, 48] },
+ ])('applies Word contextual spacing for $name', ({ ids, flags, tops }) => {
+ const paragraphs = ids.map((styleId, index) => ({
+ startIndex: index * 2 + 1,
+ paragraphId: `p-${index}`,
+ styleId,
+ paragraphStyle: {
+ spacingRule: SpacingRule.EXACT,
+ lineSpacing: 20,
+ spaceAbove: { v: 8 },
+ spaceBelow: { v: 12 },
+ contextualSpacing: flags[index],
+ },
+ }));
+ const { viewModel, ctx, sectionNode, sectionBreakConfig, curPage } = createSectionLayoutTestBed(['A', 'B', 'C'], {
+ body: { paragraphs },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ for (const [index, node] of sectionNode.children.entries()) {
+ const shaped = shaping(ctx, node.content!, viewModel, node, sectionBreakConfig);
+ lineBreaking(ctx, viewModel, shaped, curPage, node, sectionBreakConfig, null, false, sectionNode.children[index + 1]);
+ }
+ const lines = curPage.sections[0].columns[0].lines;
+ expect(lines.map((line) => line.top + line.marginTop)).toEqual(tops);
+ expect(lines[2].spaceBelowApply).toBe(12);
+ expect(viewModel.getBody()?.paragraphs?.map((paragraph) => paragraph.paragraphStyle?.spaceBelow?.v)).toEqual([12, 12, 12]);
+ });
+
+ it.each([
+ { sameStyle: true, contextual: 1, wrap: TableTextWrapType.NONE, after: 0 },
+ { sameStyle: false, contextual: 1, wrap: TableTextWrapType.NONE, after: 12 },
+ { sameStyle: true, contextual: 0, wrap: TableTextWrapType.NONE, after: 12 },
+ { sameStyle: true, contextual: 1, wrap: TableTextWrapType.WRAP, after: 12 },
+ ])('compares contextual spacing with the first paragraph of a following flow table: %j', ({ sameStyle, contextual, wrap, after }) => {
+ const T = DataStreamTreeTokenType;
+ const table = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell\r${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const dataStream = `Before\r${table}\r\n`;
+ const bed = createSectionLayoutTestBed(['Before', table], {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: {
+ paragraphs: [...dataStream.matchAll(/\r/g)].map((match, index) => ({
+ startIndex: match.index,
+ styleId: index === 1 && !sameStyle ? 'Other' : 'Normal',
+ paragraphStyle: { spacingRule: SpacingRule.EXACT, lineSpacing: 20, spaceBelow: { v: 12 }, contextualSpacing: contextual },
+ })),
+ tables: [{ tableId: 'table', startIndex: 7, endIndex: 7 + table.length }],
+ },
+ tableSource: { table: { tableId: 'table', textWrap: wrap } },
+ });
+ const [paragraph, next] = bed.sectionNode.children;
+ lineBreaking(bed.ctx, bed.viewModel, shaping(bed.ctx, paragraph.content!, bed.viewModel, paragraph, bed.sectionBreakConfig), bed.curPage, paragraph, bed.sectionBreakConfig, null, false, next);
+ expect(bed.curPage.sections[0].columns[0].lines[0].spaceBelowApply).toBe(after);
+ expect(bed.viewModel.getBody()!.paragraphs![0].paragraphStyle!.spaceBelow!.v).toBe(12);
+ });
+
+ it.each([0, 2])('adds traditional border clearance outside collapsed paragraph spacing (width %s)', (width) => {
+ const border = { color: { rgb: '#000000' }, padding: 3, width };
+ const borderSpace = width > 0 ? 5 : 0;
+ const paragraphs = [1, 3, 5].map((startIndex, index) => ({
+ startIndex,
+ paragraphId: `border-${index}`,
+ paragraphStyle: {
+ spacingRule: SpacingRule.EXACT,
+ lineSpacing: 20,
+ spaceAbove: { v: 8 },
+ spaceBelow: { v: 12 },
+ ...(index === 1 ? { borderTop: border, borderBottom: border } : {}),
+ },
+ }));
+ const bed = createSectionLayoutTestBed(['A', 'B', 'C'], {
+ body: { paragraphs },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ for (const [index, node] of bed.sectionNode.children.entries()) {
+ lineBreaking(bed.ctx, bed.viewModel, shaping(bed.ctx, node.content!, bed.viewModel, node, bed.sectionBreakConfig), bed.curPage, node, bed.sectionBreakConfig, null, false, bed.sectionNode.children[index + 1]);
+ }
+ const lines = bed.curPage.sections[0].columns[0].lines;
+ expect(lines.map((line) => line.top + line.marginTop + (line.borderTopSpace ?? 0))).toEqual([8, 40 + borderSpace, 72 + 2 * borderSpace]);
+ expect(bed.viewModel.getBody()?.paragraphs).toEqual(paragraphs);
+ });
+
+ it('reserves outer border clearance only on the first and final lines of wrapped text', () => {
+ const content = 'A bordered paragraph with enough words to wrap onto several lines and retain its final border.';
+ const border = { color: { rgb: '#000000' }, padding: 3, width: 2 };
+ const bed = createParagraphLayoutTestBed(content, {
+ body: { paragraphs: [{
+ startIndex: content.length,
+ paragraphId: 'border-wrapped',
+ paragraphStyle: {
+ spacingRule: SpacingRule.EXACT,
+ lineSpacing: 20,
+ borderTop: border,
+ borderBottom: border,
+ },
+ }] },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL, pageSize: { width: 180, height: 600 } },
+ });
+ lineBreaking(bed.ctx, bed.viewModel, shaping(bed.ctx, bed.paragraphNode.content!, bed.viewModel, bed.paragraphNode, bed.sectionBreakConfig), bed.curPage, bed.paragraphNode, bed.sectionBreakConfig, null);
+ const lines = bed.curPage.sections[0].columns[0].lines;
+ expect(lines.length).toBeGreaterThan(2);
+ expect(lines.reduce((space, line) => space + (line.borderTopSpace ?? 0), 0)).toBe(5);
+ expect(lines.reduce((space, line) => space + (line.borderBottomSpace ?? 0), 0)).toBe(5);
+ expect(lines[0].borderTopSpace).toBe(5);
+ expect(lines[lines.length - 1].borderBottomSpace).toBe(5);
+ expect(lines.reduce((height, line) => height + line.lineHeight, 0)).toBe(lines.length * 20 + 10);
+ });
+
+ it('paginates a bordered paragraph when its text fits but its border does not', () => {
+ const border = { color: { rgb: '#000000' }, padding: 3, width: 2 };
+ const bed = createSectionLayoutTestBed(['A', 'B'], {
+ body: { paragraphs: [1, 3].map((startIndex, index) => ({
+ startIndex,
+ paragraphId: `border-${index}`,
+ paragraphStyle: {
+ spacingRule: SpacingRule.EXACT,
+ lineSpacing: 20,
+ spaceAbove: { v: 0 },
+ spaceBelow: { v: 0 },
+ ...(index === 1 ? { borderTop: border, borderBottom: border } : {}),
+ },
+ })) },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ bed.curPage.sections[0].height = 46;
+ const pages = [bed.curPage];
+ for (const [index, node] of bed.sectionNode.children.entries()) {
+ const result = lineBreaking(bed.ctx, bed.viewModel, shaping(bed.ctx, node.content!, bed.viewModel, node, bed.sectionBreakConfig), pages[pages.length - 1], node, bed.sectionBreakConfig, null, false, bed.sectionNode.children[index + 1]);
+ pages.push(...result.slice(1));
+ }
+ expect(pages).toHaveLength(2);
+ const line = pages[1].sections[0].columns[0].lines[0];
+ expect(line.lineHeight).toBe(30);
+ expect(line.borderTopSpace).toBe(5);
+ expect(line.borderBottomSpace).toBe(5);
+ expect(pages[0].sections[0].columns[0].lines).toHaveLength(1);
+ });
+
+ it.each([undefined, { color: { rgb: '#000000' }, padding: 3, width: 2 }])(
+ 'joins adjacent border spacing even when the previous layout cache was evicted (%j)',
+ (borderBetween) => {
+ const border = { color: { rgb: '#000000' }, padding: 3, width: 2 };
+ const paragraphStyle = {
+ spacingRule: SpacingRule.EXACT,
+ lineSpacing: 20,
+ spaceAbove: { v: 0 },
+ spaceBelow: { v: 0 },
+ borderTop: border,
+ borderBottom: border,
+ borderBetween,
+ };
+ const bed = createSectionLayoutTestBed(['A', 'B'], {
+ body: { paragraphs: [1, 3].map((startIndex) => ({ startIndex, paragraphStyle })) },
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ for (const [index, node] of bed.sectionNode.children.entries()) {
+ bed.ctx.paragraphConfigCache.get(bed.curPage.segmentId)?.clear();
+ lineBreaking(bed.ctx, bed.viewModel, shaping(bed.ctx, node.content!, bed.viewModel, node, bed.sectionBreakConfig), bed.curPage, node, bed.sectionBreakConfig, null, false, bed.sectionNode.children[index + 1]);
+ }
+ const lines = bed.curPage.sections[0].columns[0].lines;
+ expect(lines.map((line) => line.borderTopSpace ?? 0)).toEqual([5, 0]);
+ expect(lines.map((line) => line.borderBottomSpace ?? 0)).toEqual([borderBetween ? 5 : 0, 5]);
+ }
+ );
+
it('reserves bottom-border clearance when paragraph spacing is smaller', () => {
const content = 'Rule';
const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
@@ -1719,13 +2160,17 @@ describe('linebreaking', () => {
expect(result.length).toBeGreaterThanOrEqual(1);
});
- it('handles bullet list paragraphs', () => {
- const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('List item', {
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN].flatMap((documentFlavor) =>
+ [undefined, 8].flatMap((markerSize) => [undefined, BooleanNumber.FALSE, BooleanNumber.TRUE]
+ .map((markerUnderline) => ({ documentFlavor, markerSize, markerUnderline })))))('inherits list fonts but not Word paragraph-mark underlines: %s', ({ documentFlavor, markerSize, markerUnderline }) => {
+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('List item', {
+ documentStyle: { documentFlavor, textStyle: { fs: 12 } },
body: {
dataStream: 'List item\r\n',
- textRuns: [{ st: 0, ed: 11, ts: {} }],
+ textRuns: [{ st: 0, ed: 9, ts: { fs: 10, ul: { s: BooleanNumber.TRUE } } }],
paragraphs: [{
startIndex: 9,
+ paragraphStyle: { paragraphMarkTextStyle: { fs: 20, ul: { s: BooleanNumber.TRUE } } },
bullet: {
listId: 'list-1',
listType: 'test-list',
@@ -1742,15 +2187,90 @@ describe('linebreaking', () => {
glyphFormat: '%1.',
startNumber: 1,
glyphType: 0,
+ textStyle: {
+ ...(markerSize == null ? {} : { fs: markerSize }),
+ ...(markerUnderline == null ? {} : { ul: { s: markerUnderline } }),
+ },
}],
},
},
});
- const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ try {
+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);
+ const glyphs = result.flatMap((page) => paragraphLines(page, 9).flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup)));
+ const marker = glyphs.find((glyph) => glyph.glyphType === GlyphType.LIST)!;
+ const inheritedSize = documentFlavor === DocumentFlavor.TRADITIONAL ? 20 : 10;
+ expect(marker.fontStyle?.fontSize).toBe(markerSize ?? inheritedSize);
+ expect(marker.ts?.ul?.s).toBe(markerUnderline ?? (documentFlavor === DocumentFlavor.TRADITIONAL ? BooleanNumber.FALSE : BooleanNumber.TRUE));
+ expect(glyphs.find((glyph) => glyph.content.includes('L'))?.ts?.ul?.s).toBe(BooleanNumber.TRUE);
+ expect(dataModel.getSnapshot().body?.paragraphs?.[0].paragraphStyle?.paragraphMarkTextStyle?.ul?.s).toBe(BooleanNumber.TRUE);
+ expect(glyphs.find((glyph) => glyph.content.includes('L'))?.fontStyle?.fontSize).toBe(10);
+ } finally {
+ viewModel.dispose();
+ dataModel.dispose();
+ }
+ });
- const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);
+ it.each(([BulletAlignment.START, BulletAlignment.CENTER, BulletAlignment.END] as const).flatMap((alignment) =>
+ [1, 3].map((startNumber) => ({ alignment, startNumber }))))('retains Word marker ink alignment after line positioning ($alignment, $startNumber)', ({ alignment, startNumber }) => {
+ const bed = createParagraphLayoutTestBed('List item', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: {
+ dataStream: 'List item\r\n',
+ paragraphs: [{ startIndex: 9, paragraphStyle: { indentStart: { v: 48 }, hanging: { v: 24 } }, bullet: { listId: 'list-1', listType: 'roman-list', nestingLevel: 0, startNumber } }],
+ sectionBreaks: [{ startIndex: 10 }],
+ },
+ lists: { 'roman-list': { listType: 'roman-list', nestingLevel: [{
+ bulletAlignment: alignment,
+ glyphFormat: '%1.',
+ startNumber: 0,
+ glyphType: ListGlyphType.LOWER_ROMAN,
+ }] } },
+ });
+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);
+ try {
+ skeleton.calculate();
+ const divide = skeleton.getSkeletonData()!.pages[0].sections[0].columns[0].lines[0].divides[0];
+ const marker = divide.glyphGroup[0];
+ const markerWidth = FontCache.getTextSize(marker.content, marker.fontStyle!, true).width;
+ const alignmentFactor = { [BulletAlignment.START]: 0, [BulletAlignment.CENTER]: 0.5, [BulletAlignment.END]: 1 }[alignment];
+ expect(marker.glyphType).toBe(GlyphType.LIST);
+ expect(marker.left + marker.xOffset + markerWidth * alignmentFactor).toBeCloseTo(0);
+ expect(divide.glyphGroup[1].left).toBeCloseTo(24);
+ expect(bed.dataModel.getSnapshot().body!.paragraphs![0].paragraphStyle!.hanging).toEqual({ v: 24 });
+ } finally {
+ skeleton.dispose();
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
- expect(result.length).toBeGreaterThanOrEqual(1);
+ it.each(['\f', '\f\f', '\fText', '\t\f', ' ', ''])('retains list data while suppressing page-break-only markers (%j)', (middle) => {
+ const contents = ['First', middle, 'Second'];
+ let end = 0;
+ const bullet = { listId: 'list-1', listType: 'numbered', nestingLevel: 0 };
+ const paragraphs = contents.map((text) => {
+ end += text.length;
+ return { startIndex: end++, bullet: { ...bullet } };
+ });
+ const bed = createSectionLayoutTestBed(contents, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: { paragraphs },
+ lists: { numbered: { listType: 'numbered', nestingLevel: [{ glyphFormat: '%1.', glyphType: ListGlyphType.DECIMAL, startNumber: 0, bulletAlignment: 1 }] } },
+ });
+ const skeleton = DocumentSkeleton.create(bed.viewModel, bed.ctx.docsConfig.localeService);
+ const snapshot = JSON.stringify(bed.dataModel.getSnapshot());
+ try {
+ skeleton.calculate();
+ const markers = skeleton.getSkeletonData()!.pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup.filter((glyph) => glyph.glyphType === GlyphType.LIST).map((glyph) => glyph.content))))));
+ expect(markers).toEqual(/^\f+$/.test(middle) ? ['1.', '2.'] : ['1.', '2.', '3.']);
+ expect(JSON.stringify(bed.dataModel.getSnapshot())).toBe(snapshot);
+ } finally {
+ skeleton.dispose();
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
});
it('continues numbering when the first paragraph starts at a deeper level', () => {
@@ -1924,8 +2444,9 @@ describe('linebreaking', () => {
lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);
const line = curPage.sections[0].columns[0].lines[0];
- expect(line.contentHeight).toBeCloseTo(96);
- expect(line.lineHeight).toBeCloseTo(96);
+ const textDescent = Math.max(...shapedTextList.flatMap((run) => run.glyphs.map((glyph) => glyph.bBox.bd)));
+ expect(line.contentHeight).toBeCloseTo(96 + textDescent);
+ expect(line.lineHeight).toBeCloseTo(96 + textDescent);
});
it.each([
@@ -2019,7 +2540,7 @@ describe('linebreaking', () => {
expect(textLine?.top).toBeGreaterThanOrEqual((drawing?.aTop ?? 0) + (drawing?.height ?? 0));
});
- it('keeps inline custom block height when the paragraph terminator relayouts its line', () => {
+ it('does not add the paragraph-mark descent to a traditional picture-only line', () => {
const content = DataStreamTreeTokenType.CUSTOM_BLOCK;
const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
body: {
@@ -2117,6 +2638,48 @@ describe('linebreaking', () => {
expect(result[1].breakType).toBe(1);
});
+ it.each([
+ { flavor: DocumentFlavor.TRADITIONAL, precedingText: '', followingText: '', drawingPage: 0 },
+ { flavor: DocumentFlavor.TRADITIONAL, precedingText: 'Before', followingText: '', drawingPage: 0 },
+ { flavor: DocumentFlavor.TRADITIONAL, precedingText: 'Before', followingText: 'After', drawingPage: 1 },
+ { flavor: DocumentFlavor.MODERN, precedingText: 'Before', followingText: '', drawingPage: 1 },
+ ])('anchors a terminal floating picture to its manual-break paragraph ($flavor, "$precedingText", "$followingText")', ({ flavor, precedingText, followingText, drawingPage }) => {
+ const content = `${precedingText}${DataStreamTreeTokenType.PAGE_BREAK}${DataStreamTreeTokenType.CUSTOM_BLOCK}${followingText}`;
+ const { ctx, viewModel, paragraphNode, curPage, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: flavor },
+ body: { customBlocks: [{ startIndex: precedingText.length + 1, blockId: 'corner' }] },
+ drawings: {
+ corner: {
+ drawingId: 'corner',
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ docTransform: {
+ size: { width: 60, height: 100 },
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 300 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 0 },
+ angle: 0,
+ },
+ },
+ },
+ });
+ const pages = lineBreaking(
+ ctx,
+ viewModel,
+ shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig),
+ curPage,
+ paragraphNode,
+ sectionBreakConfig,
+ null
+ );
+ expect(pages).toHaveLength(2);
+ expect(pages[drawingPage].skeDrawings.has('corner')).toBe(true);
+ expect(pages[1 - drawingPage].skeDrawings.has('corner')).toBe(false);
+ const raw = pages.flatMap((page) => paragraphLines(page, paragraphNode.endIndex))
+ .flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup))
+ .map((glyph) => glyph.raw)
+ .join('');
+ expect(raw).toBe(paragraphNode.content);
+ });
+
it('keeps floating custom blocks after a page break on the next page', () => {
const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}${DataStreamTreeTokenType.PAGE_BREAK}${DataStreamTreeTokenType.CUSTOM_BLOCK}`;
const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
@@ -2367,6 +2930,37 @@ describe('linebreaking', () => {
expect(inlineDrawing.aTop).toBeGreaterThanOrEqual(floatingDrawing.aTop + floatingDrawing.height);
});
+ it('keeps a trailing non-flow picture on its existing text line', () => {
+ const content = `Heading${DataStreamTreeTokenType.CUSTOM_BLOCK}`;
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: {
+ customBlocks: [{ startIndex: 7, blockId: 'decoration' }],
+ paragraphs: [{ startIndex: content.length, paragraphStyle: { spaceAbove: { v: 24 }, spaceBelow: { v: 2 } } }],
+ },
+ drawings: {
+ decoration: {
+ drawingId: 'decoration',
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ behindDoc: BooleanNumber.TRUE,
+ docTransform: {
+ size: { width: 120, height: 90 },
+ positionH: { posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ angle: 0,
+ },
+ },
+ },
+ });
+ const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const result = lineBreaking(ctx, viewModel, shapedTextList, curPage, paragraphNode, sectionBreakConfig, null);
+ const lines = paragraphLines(result[0], paragraphNode.endIndex);
+
+ expect(lines).toHaveLength(1);
+ expect(lines[0].divides.flatMap((divide) => divide.glyphGroup).some((glyph) => glyph.drawingId === 'decoration')).toBe(true);
+ expect(result[0].skeDrawings.has('decoration')).toBe(true);
+ });
+
it('does not move a zero-width wrap-none floating anchor to a new page at the page bottom', () => {
const content = DataStreamTreeTokenType.CUSTOM_BLOCK;
const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
@@ -2530,11 +3124,12 @@ describe('linebreaking', () => {
expect(result).toHaveLength(1);
expect(result[0].skeDrawings.get('cover-background')).toMatchObject({
- aLeft: 0,
+ aLeft: -result[0].marginLeft,
aTop: 0,
width: 400,
height: 600,
});
+ expect(result[0].marginLeft + result[0].skeDrawings.get('cover-background')!.aLeft).toBe(0);
});
it('keeps DOCX manual line breaks in the same page instead of treating them as column breaks', () => {
@@ -2597,6 +3192,30 @@ describe('linebreaking', () => {
expect(renderedText).toContain('SECOND');
});
+ it.each([1, 2, 3])('preserves the height of %s consecutive authored soft line breaks', (count) => {
+ const content = `Before${DataStreamTreeTokenType.COLUMN_BREAK.repeat(count)}After`;
+ const bed = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ const pages = lineBreaking(
+ bed.ctx,
+ bed.viewModel,
+ shaping(bed.ctx, bed.paragraphNode.content!, bed.viewModel, bed.paragraphNode, bed.sectionBreakConfig),
+ bed.curPage,
+ bed.paragraphNode,
+ bed.sectionBreakConfig,
+ null
+ );
+ expect(pages).toHaveLength(1);
+ const lines = paragraphLines(pages[0], bed.paragraphNode.endIndex);
+ expect(lines).toHaveLength(count + 1);
+ expect(lines.every((line) => line.lineHeight > 0)).toBe(true);
+ expect(lines[lines.length - 1].top).toBeCloseTo(lines[0].lineHeight * count);
+ expect(lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup)).map((glyph) => glyph.raw).join(''))
+ .toBe(bed.dataModel.getBody()!.dataStream);
+ bed.viewModel.dispose();
+ });
+
it('treats marked DOCX column breaks as column breaks in traditional documents', () => {
const content = `FIRST${DataStreamTreeTokenType.COLUMN_BREAK}SECOND`;
const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
@@ -2744,7 +3363,7 @@ describe('linebreaking', () => {
expect(ctx.layoutStartPointer['']).toBe(paragraphNode.endIndex);
});
- it('starts normal text on a new flow line after a zero-width wrap-none floating anchor', () => {
+ it.each([false, true])('starts normal text after a zero-width floating anchor, retaining border clearance (%s)', (bordered) => {
const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}Hello`;
const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
documentStyle: {
@@ -2752,6 +3371,16 @@ describe('linebreaking', () => {
},
body: {
customBlocks: [{ startIndex: 0, blockId: 'behind-picture' }],
+ paragraphs: [{
+ startIndex: content.length,
+ paragraphId: 'floating-anchor',
+ paragraphStyle: bordered
+ ? {
+ borderTop: { color: { rgb: '#000000' }, width: 2, padding: 3 },
+ borderBottom: { color: { rgb: '#000000' }, width: 2, padding: 3 },
+ }
+ : {},
+ }],
},
drawings: {
'behind-picture': {
@@ -2808,6 +3437,9 @@ describe('linebreaking', () => {
expect(lines[0].lineHeight).toBe(0);
expect(lines[0].divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.drawingId))).toContain('behind-picture');
expect(lines[1].lineHeight).toBeGreaterThan(0);
+ expect(lines[0].borderTopSpace ?? 0).toBe(0);
+ expect(lines[1].borderTopSpace ?? 0).toBe(bordered ? 5 : 0);
+ expect(lines[1].borderBottomSpace ?? 0).toBe(bordered ? 5 : 0);
expect(lines[1].divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content)).join('')).toContain('Hello');
});
@@ -3126,7 +3758,12 @@ describe('linebreaking', () => {
const terminatorGlyphs = allGlyphs.filter((glyph) =>
glyph.streamType === DataStreamTreeTokenType.PARAGRAPH ||
glyph.streamType === DataStreamTreeTokenType.SECTION_BREAK
- );
+ ).map((glyph) => ({
+ ...glyph,
+ // These are synthetic terminators moved before Hello, not the authored
+ // paragraph mark after Hello; only the latter carries paragraph height.
+ bBox: { ...glyph.bBox, ba: 0, bd: 0, normalLineHeight: 0 },
+ }));
const textGlyphs = allGlyphs
.filter((glyph) => glyph.streamType !== DataStreamTreeTokenType.CUSTOM_BLOCK)
.filter((glyph) => glyph.streamType !== DataStreamTreeTokenType.PARAGRAPH)
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/paragraph-layout.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/paragraph-layout.spec.ts
index 0420b8234e..cf4677bf47 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/paragraph-layout.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/paragraph-layout.spec.ts
@@ -14,11 +14,143 @@
* limitations under the License.
*/
+import { BooleanNumber, DocumentFlavor } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
+import { getFontStyleString } from '../../../../../../basics/tools';
+import { getDocumentCompatibilityPolicy } from '../../../../document-compatibility';
+import { FontCache } from '../../../shaping-engine/font-cache';
+import { clearFontCreateConfigCache } from '../../../tools';
import { dealWidthParagraph } from '../paragraph-layout';
import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';
describe('paragraph-layout', () => {
+ it.each([' ', ' ', '  '].flatMap((spaces) => [true, false].map((trailing) => ({ spaces, trailing }))))('preserves spaces $spaces with trailing=$trailing and hangs them only at the line end', ({ spaces, trailing }) => {
+ const textStyle = { ff: 'Trailing space regression', fs: 12 };
+ const font = getFontStyleString(textStyle).fontString;
+ for (const text of ['中', '文', ' ', ' ', '\r']) {
+ FontCache.setFontMeasureCache(font, text, {
+ width: 10,
+ fontBoundingBoxAscent: 12,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 2,
+ });
+ }
+ try {
+ for (const flavor of [DocumentFlavor.DRAWINGML, DocumentFlavor.UNSPECIFIED]) {
+ clearFontCreateConfigCache();
+ const content = trailing ? `中文${spaces}` : `中${spaces}文`;
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: flavor,
+ textStyle,
+ pageSize: { width: 20, height: 600 },
+ marginLeft: 0,
+ marginRight: 0,
+ renderConfig: { lineWrapTolerance: 0 },
+ },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(flavor);
+ const pages = dealWidthParagraph(ctx, viewModel, paragraphNode, curPage, sectionBreakConfig);
+ const lines = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));
+ const glyphs = lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup));
+ expect(glyphs.map((glyph) => glyph.raw).join('')).toBe(`${content}\r\n`);
+ expect(glyphs.reduce((count, glyph) => count + glyph.count, 0)).toBe(content.length + 2);
+ if (trailing && (flavor === DocumentFlavor.DRAWINGML || spaces === ' ')) {
+ expect(lines).toHaveLength(1);
+ } else {
+ expect(lines.length).toBeGreaterThan(1);
+ }
+ }
+ } finally {
+ FontCache.clearFontMeasureCache(font);
+ clearFontCreateConfigCache();
+ }
+ });
+
+ it.each([27, 28].flatMap((width) => [false, true].map((caps) => ({ width, caps }))))('includes space-letter kerning when fitting width $width with caps $caps', ({ width, caps }) => {
+ const textStyle = { ff: 'Space kerning regression', fs: 12, kerning: 12, caps };
+ const font = getFontStyleString(textStyle).fontString;
+ for (const mode of ['normal', 'none']) {
+ for (const text of ['A', 'V', ' ', '\r', 'A ', ' V']) {
+ FontCache.setFontMeasureCache(`${font}\u0000${mode}`, text, {
+ width: text === ' V' && mode === 'normal' ? 18 : text.length * 10,
+ fontBoundingBoxAscent: 12,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 2,
+ });
+ }
+ }
+ try {
+ clearFontCreateConfigCache();
+ const raw = caps ? 'a v' : 'A V';
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(raw, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.DRAWINGML,
+ textStyle,
+ pageSize: { width, height: 600 },
+ marginLeft: 0,
+ marginRight: 0,
+ autoHyphenation: BooleanNumber.FALSE,
+ renderConfig: { lineWrapTolerance: 0 },
+ },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(DocumentFlavor.DRAWINGML);
+ const pages = dealWidthParagraph(ctx, viewModel, paragraphNode, curPage, sectionBreakConfig);
+ const lines = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));
+ const glyphs = lines.map((line) => line.divides.flatMap((divide) => divide.glyphGroup));
+ expect(glyphs.map((line) => line.map((glyph) => glyph.content).join('')))
+ .toEqual(width === 28 ? ['A V\r'] : ['A ', 'V\r']);
+ expect(glyphs.flat().map((glyph) => glyph.raw).join('')).toBe(`${raw}\r\n`);
+ expect(glyphs.flat().reduce((count, glyph) => count + glyph.count, 0)).toBe(raw.length + 2);
+ expect(glyphs[0][1].width).toBe(width === 28 ? 8 : 10);
+ expect(glyphs[glyphs.length - 1].find((glyph) => glyph.content === 'V')?.left).toBe(width === 28 ? 18 : 0);
+ } finally {
+ for (const mode of ['normal', 'none']) {
+ FontCache.clearFontMeasureCache(`${font}\u0000${mode}`);
+ }
+ clearFontCreateConfigCache();
+ }
+ });
+
+ it.each([0, 2])('keeps fitting text on its line before a DrawingML explicit break with tracking %s', (sc) => {
+ const content = 'AAAA BB \u2028CC';
+ const textStyle = { ff: 'Explicit break regression', fs: 12, sc };
+ const font = getFontStyleString(textStyle).fontString;
+ for (const text of ['A', 'B', 'C', ' ', '\u2028', '\r']) {
+ FontCache.setFontMeasureCache(font, text, {
+ width: 10,
+ fontBoundingBoxAscent: 12,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 2,
+ });
+ }
+ try {
+ clearFontCreateConfigCache();
+ const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(content, {
+ documentStyle: {
+ documentFlavor: DocumentFlavor.DRAWINGML,
+ textStyle,
+ pageSize: { width: 85 + 8 * sc, height: 600 },
+ marginLeft: 0,
+ marginRight: 0,
+ autoHyphenation: BooleanNumber.FALSE,
+ renderConfig: { lineWrapTolerance: 0 },
+ },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(DocumentFlavor.DRAWINGML);
+ const pages = dealWidthParagraph(ctx, viewModel, paragraphNode, curPage, sectionBreakConfig);
+ const lines = pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));
+ expect(lines.map((line) => line.divides.flatMap((divide) => divide.glyphGroup).map((glyph) => glyph.content).join('')))
+ .toEqual(['AAAA BB \u2028', 'CC\r']);
+ } finally {
+ FontCache.clearFontMeasureCache(font);
+ clearFontCreateConfigCache();
+ }
+ });
+
it('lays out a normal text paragraph', () => {
const { ctx, viewModel, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Hello world');
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.ts
index c1c1bb9d8b..a1e104f511 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
@@ -15,14 +15,349 @@
*/
import type { ICustomRangeForInterceptor } from '@univerjs/core';
-import { BooleanNumber, CustomRangeType, DataStreamTreeTokenType, PositionedObjectLayoutType } from '@univerjs/core';
+import {
+ BooleanNumber,
+ characterSpacingControlType,
+ CustomRangeType,
+ DataStreamTreeTokenType,
+ DocumentFlavor,
+ NamedStyleType,
+ PositionedObjectLayoutType,
+} from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
+import { getFontStyleString } from '../../../../../../basics/tools';
+import { setDocsCustomBlockRenderViewportProvider } from '../../../../custom-block-render-viewport';
+import { getDocumentCompatibilityPolicy } from '../../../../document-compatibility';
import { Lang } from '../../../hyphenation/lang';
+import { BreakPointType } from '../../../line-breaker/break';
import { createSkeletonLetterGlyph } from '../../../model/glyph';
+import { FontCache } from '../../../shaping-engine/font-cache';
+import { clearFontCreateConfigCache } from '../../../tools';
import { shaping } from '../shaping';
import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';
describe('shaping', () => {
+ it.each(['…', '….', '....', ',...'])('keeps spaced trailing punctuation with its preceding Word token (%s)', (punctuation) => {
+ const content = `Before word ${punctuation} after`;
+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ try {
+ const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ expect(result.map((item) => item.text)).toContain(`word ${punctuation} `);
+ } finally {
+ viewModel.dispose();
+ dataModel.dispose();
+ }
+ });
+
+ it.each([
+ { flavor: DocumentFlavor.TRADITIONAL, separator: ' ', joined: true },
+ { flavor: DocumentFlavor.MODERN, separator: ' ', joined: false },
+ { flavor: DocumentFlavor.TRADITIONAL, separator: '\t', joined: false },
+ { flavor: DocumentFlavor.TRADITIONAL, separator: '\v', joined: false },
+ ])('preserves the mode and authored boundaries around ellipses: %s', ({ flavor, separator, joined }) => {
+ const content = `Before word${separator}… after`;
+ const bed = createParagraphLayoutTestBed(content, { documentStyle: { documentFlavor: flavor } });
+ const before = JSON.stringify(bed.dataModel.getSnapshot());
+ try {
+ const result = shaping(bed.ctx, bed.paragraphNode.content!, bed.viewModel, bed.paragraphNode, bed.sectionBreakConfig);
+ expect(result.some((item) => item.text.includes(`word${separator}…`))).toBe(joined);
+ expect(result.map((item) => item.text).join('')).toBe(`${content.replace('\v', '')}\r`);
+ if (separator === '\v') {
+ expect(result.find((item) => item.text.endsWith('word'))?.breakPointType).toBe(BreakPointType.Mandatory);
+ }
+ expect(JSON.stringify(bed.dataModel.getSnapshot())).toBe(before);
+ } finally {
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
+
+ it.each([
+ { flavor: DocumentFlavor.TRADITIONAL, enabled: BooleanNumber.TRUE, sa: 100, sc: 0 },
+ { flavor: DocumentFlavor.TRADITIONAL, enabled: BooleanNumber.TRUE, sa: 50, sc: 1.5 },
+ { flavor: DocumentFlavor.TRADITIONAL, enabled: BooleanNumber.FALSE, sa: 100, sc: 0 },
+ { flavor: DocumentFlavor.TRADITIONAL, enabled: undefined, sa: 100, sc: 0 },
+ { flavor: DocumentFlavor.MODERN, enabled: BooleanNumber.TRUE, sa: 100, sc: 0 },
+ ])('balances authored Latin whitespace only with Word compatibility enabled: %j', ({ flavor, enabled, sa, sc }) => {
+ // Native Word COM: leading/trailing and consecutive spaces become half-em;
+ // an isolated inter-word space keeps its font advance, even in the same run.
+ const measure = vi.spyOn(FontCache, 'getMeasureText').mockReturnValue({
+ width: 6,
+ fontBoundingBoxAscent: 10,
+ fontBoundingBoxDescent: 2,
+ actualBoundingBoxAscent: 0,
+ actualBoundingBoxDescent: 0,
+ });
+ const content = ' A B C ';
+ const shape = (balanceSingleByteDoubleByteWidth?: BooleanNumber) => {
+ clearFontCreateConfigCache();
+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: flavor, balanceSingleByteDoubleByteWidth },
+ body: { textRuns: [
+ { st: 0, ed: 5, ts: { ff: 'Calibri', fs: 12, sa, sc } },
+ { st: 5, ed: content.length, ts: { ff: 'Calibri', fs: 24, sa, sc } },
+ ] },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(flavor);
+ const before = JSON.stringify(dataModel.getSnapshot());
+ const glyphs = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig)
+ .flatMap((item) => item.glyphs);
+ expect(JSON.stringify(dataModel.getSnapshot())).toBe(before);
+ expect(glyphs.map((glyph) => glyph.content).join('')).toBe(`${content}\r`);
+ return glyphs;
+ };
+ try {
+ const ordinary = shape(BooleanNumber.FALSE);
+ const balanced = shape(enabled);
+ for (let index = 0; index < content.length; index++) {
+ if (flavor === DocumentFlavor.TRADITIONAL && enabled === BooleanNumber.TRUE && [0, 4, 5, 7].includes(index)) {
+ const halfEm = (index < 5 ? 12 : 24) / 0.75 / 2 * sa / 100;
+ expect(balanced[index].width).toBeCloseTo(halfEm + sc / 0.75);
+ expect(balanced[index].bBox.width).toBeCloseTo(halfEm);
+ } else {
+ expect(balanced[index].width).toBe(ordinary[index].width);
+ }
+ }
+ } finally {
+ measure.mockRestore();
+ clearFontCreateConfigCache();
+ }
+ });
+
+ it('keeps hidden runs in source offsets and honors explicit visible overrides', () => {
+ const content = 'A隐藏😀Visible';
+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
+ documentStyle: { textStyle: { hidden: true }, documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: { textRuns: [
+ { st: 0, ed: 1, ts: { hidden: false } },
+ { st: 1, ed: 5, ts: { fs: 80 } },
+ { st: 5, ed: content.length + 1, ts: { hidden: false } },
+ ] },
+ });
+ const shaped = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ const glyphs = shaped.flatMap((item) => item.glyphs);
+ const hidden = glyphs.filter((glyph) => glyph.ts?.hidden);
+ expect(hidden.map((glyph) => glyph.raw).join('')).toContain('隐藏😀');
+ expect(hidden.every((glyph) => glyph.width === 0 && glyph.bBox.ba === 0 && glyph.bBox.bd === 0)).toBe(true);
+ expect(glyphs.map((glyph) => glyph.content).join('')).toContain('AVisible');
+ expect(shaped.map((item) => item.text).join('')).not.toContain('隐藏');
+ expect(glyphs.reduce((count, glyph) => count + glyph.count, 0)).toBe(paragraphNode.content!.length);
+ expect(dataModel.getSnapshot().body?.dataStream).toBe(`${content}\r\n`);
+ });
+
+ it.each([PositionedObjectLayoutType.INLINE, PositionedObjectLayoutType.WRAP_SQUARE])('keeps effect extents separate from drawing geometry (%s)', (layoutType) => {
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('\b', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: { customBlocks: [{ startIndex: 0, blockId: 'effects' }] },
+ drawings: {
+ effects: {
+ drawingId: 'effects',
+ layoutType,
+ effectExtent: { left: 2, top: 3, right: 7, bottom: 11 },
+ docTransform: { size: { width: 40, height: 50 }, positionH: {}, positionV: {}, angle: 0 },
+ },
+ },
+ });
+ const glyph = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig).flatMap((item) => item.glyphs)[0];
+ expect(glyph.width).toBe(layoutType === PositionedObjectLayoutType.INLINE ? 49 : 0);
+ expect(glyph.bBox.ba).toBe(layoutType === PositionedObjectLayoutType.INLINE ? 53 : 0);
+ expect(glyph.bBox.bd).toBe(layoutType === PositionedObjectLayoutType.INLINE ? 11 : 0);
+ expect(viewModel.getDataModel().getSnapshot().drawings?.effects.docTransform.size).toEqual({ width: 40, height: 50 });
+ });
+
+ it.each([PositionedObjectLayoutType.INLINE, PositionedObjectLayoutType.WRAP_SQUARE, PositionedObjectLayoutType.WRAP_NONE])(
+ 'resolves pictures and run styles after a wrapped table: %s',
+ (layoutType) => {
+ const table = '\x1A\x1B\x1CCell\r\n\x1D\x0E\x0F';
+ const content = `${table}\bTail`;
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: {
+ paragraphs: [
+ { startIndex: 7, paragraphId: 'cell' },
+ { startIndex: content.length, paragraphId: 'table-tail' },
+ ],
+ customBlocks: [{ startIndex: table.length, blockId: 'tail-picture' }],
+ textRuns: [
+ { st: 0, ed: table.length, ts: { ff: 'Arial', fs: 9 } },
+ { st: table.length, ed: content.length + 1, ts: { ff: 'Cambria', fs: 18 } },
+ ],
+ },
+ drawings: {
+ 'tail-picture': {
+ drawingId: 'tail-picture',
+ layoutType,
+ docTransform: { size: { width: 40, height: 50 }, positionH: {}, positionV: {}, angle: 0 },
+ },
+ },
+ });
+ expect(paragraphNode.startIndex).toBe(0);
+ expect(paragraphNode.content).toBe('\bTail\r\n');
+ const glyphs = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig)
+ .flatMap((item) => item.glyphs);
+ expect(glyphs[0].drawingId).toBe('tail-picture');
+ expect(glyphs[0].width).toBe(layoutType === PositionedObjectLayoutType.INLINE ? 40 : 0);
+ expect(glyphs.find((glyph) => glyph.content === 'T')?.ts).toMatchObject({ ff: 'Cambria', fs: 18 });
+ }
+ );
+
+ it.each([undefined, 'Heading5'])('preserves resolved Word heading formatting while retaining native presets: %s', (styleId) => {
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('Title', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ body: {
+ paragraphs: [{
+ startIndex: 5,
+ paragraphId: 'heading-font',
+ styleId,
+ paragraphStyle: {
+ namedStyleType: NamedStyleType.HEADING_5,
+ textStyle: { ff: 'Cambria', fs: 12 },
+ },
+ }],
+ },
+ });
+ const glyph = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig)[0].glyphs[0];
+ expect(glyph.ts?.ff).toBe('Cambria');
+ expect(glyph.ts?.fs).toBe(12);
+ expect(glyph.ts?.bl === BooleanNumber.TRUE).toBe(styleId == null);
+ });
+
+ it('uses document font alternates for rendering without replacing authored run fonts', () => {
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('Hello', {
+ documentStyle: {
+ documentFlavor: 1,
+ fontFamilyFallbacks: { 'Mind Meridian': 'Cambria', Cambria: 'Mind Meridian' },
+ },
+ body: { textRuns: [{ st: 0, ed: 5, ts: { ff: 'Mind Meridian', fs: 12 } }] },
+ });
+ const glyphs = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig)
+ .flatMap((item) => item.glyphs);
+ expect(glyphs[0].fontStyle?.fontFamily).toBe('"Mind Meridian", Cambria');
+ expect(glyphs[0].fontStyle?.fontString).toContain('12pt "Mind Meridian", Cambria');
+ expect(glyphs[0].ts?.ff).toBe('Mind Meridian');
+ expect(viewModel.getDataModel().getBody()?.textRuns?.[0].ts?.ff).toBe('Mind Meridian');
+ });
+
+ it.each(['Ae\u0301👩‍💻', 'Aمرحبا', '中\uFE00A', 'A中A'])('preserves source graphemes and inherited tracking in %s', (content) => {
+ const textStyle = { ff: 'Tracking shaping', fs: 12, sc: -3 };
+ const font = getFontStyleString(textStyle).fontString;
+ for (const text of ['A', 'e\u0301', '👩‍💻', 'مرحبا', '中\uFE00', '中']) {
+ FontCache.setFontMeasureCache(font, text, {
+ width: 10,
+ fontBoundingBoxAscent: 12,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 2,
+ });
+ }
+ try {
+ clearFontCreateConfigCache();
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
+ documentStyle: { textStyle, spaceWidthEastAsian: content === 'A中A' ? BooleanNumber.TRUE : BooleanNumber.FALSE },
+ });
+ const glyphs = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig)
+ .flatMap((item) => item.glyphs)
+ .filter((glyph) => glyph.streamType === DataStreamTreeTokenType.LETTER);
+ expect(glyphs.map((glyph) => glyph.content).join('')).toBe(content);
+ expect(glyphs.reduce((count, glyph) => count + glyph.count, 0)).toBe(content.length);
+ if (content === 'A中A') {
+ const advance = 10 + textStyle.sc / 0.75;
+ expect(glyphs.map((glyph) => glyph.width)).toEqual([advance, advance + 5, advance]);
+ } else {
+ const advance = 10 + textStyle.sc / 0.75;
+ expect(glyphs.map((glyph) => glyph.width)).toEqual(content === 'Ae\u0301👩‍💻' ? [advance, advance, advance] : [advance, advance]);
+ }
+ } finally {
+ FontCache.clearFontMeasureCache(font);
+ clearFontCreateConfigCache();
+ }
+ });
+
+ it.each([DocumentFlavor.UNSPECIFIED, DocumentFlavor.DRAWINGML])('selects font metrics from runtime layout semantics: %s', (documentFlavor) => {
+ const measuredWidth = 6.1572265625;
+ const measure = vi.spyOn(FontCache, 'getMeasureText').mockReturnValue({
+ width: measuredWidth,
+ fontBoundingBoxAscent: 11,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 11,
+ actualBoundingBoxDescent: 3,
+ });
+ try {
+ clearFontCreateConfigCache();
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('h', {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(documentFlavor);
+ const glyph = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig)
+ .flatMap((item) => item.glyphs)
+ .find((item) => item.content === 'h')!;
+ expect(glyph.width).toBe(documentFlavor === DocumentFlavor.DRAWINGML ? 6.125 : measuredWidth);
+ expect(glyph.bBox.width).toBe(glyph.width);
+ const explicit = createSkeletonLetterGlyph('h', {
+ fontStyle: glyph.fontStyle!,
+ textStyle: {},
+ charSpace: 0,
+ snapToGrid: BooleanNumber.FALSE,
+ documentCompatibilityPolicy: sectionBreakConfig.documentCompatibilityPolicy,
+ }, 6.157);
+ expect(explicit.width).toBe(6.157);
+ } finally {
+ measure.mockRestore();
+ }
+ });
+
+ it.each([
+ [undefined, undefined, true],
+ [BooleanNumber.FALSE, undefined, false],
+ [BooleanNumber.FALSE, BooleanNumber.TRUE, true],
+ [BooleanNumber.TRUE, BooleanNumber.FALSE, false],
+ ] as const)('resolves link wrapping from document %s and paragraph %s', (defaultWordWrap, wordWrap, allowBreaks) => {
+ const link = 'http://www.swsresearch.com';
+ const content = `公司${link}网站`;
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
+ documentStyle: { defaultParagraphStyle: { wordWrap: defaultWordWrap } },
+ body: { paragraphs: [{ startIndex: content.length, paragraphId: 'link', paragraphStyle: { wordWrap } }] },
+ });
+ const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ expect(result.map((item) => item.text).join('')).toBe(`${content}\r`);
+ expect(result.some((item) => item.text === link)).toBe(!allowBreaks);
+ });
+
+ it('honors disabled East Asian spacing while preserving the default and explicit enabled spacing', () => {
+ // Node has no canvas font measurements; keep the browser boundary deterministic.
+ const measure = vi.spyOn(FontCache, 'getMeasureText').mockReturnValue({
+ width: 24,
+ fontBoundingBoxAscent: 20,
+ fontBoundingBoxDescent: 4,
+ actualBoundingBoxAscent: 20,
+ actualBoundingBoxDescent: 4,
+ });
+ const shape = (spaceWidthEastAsian?: BooleanNumber) => {
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('中A文2字 文 A', {
+ documentStyle: { spaceWidthEastAsian },
+ });
+ return shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig)
+ .flatMap((item) => item.glyphs)
+ .map(({ content, width, xOffset, adjustability }) => ({ content, width, xOffset, adjustability }));
+ };
+ try {
+ const disabled = shape(BooleanNumber.FALSE);
+ const enabled = shape(BooleanNumber.TRUE);
+ expect(shape()).toEqual(enabled);
+ expect(disabled.map((glyph) => glyph.content)).toEqual(enabled.map((glyph) => glyph.content));
+ const plainWidth = disabled[0].width;
+ expect(plainWidth).toBeGreaterThan(0);
+ expect(enabled[0].width - disabled[0].width).toBeCloseTo(plainWidth / 4);
+ expect(enabled[2].width - disabled[2].width).toBeCloseTo(plainWidth / 2);
+ expect(enabled[4].xOffset - disabled[4].xOffset).toBeCloseTo(plainWidth / 4);
+ expect(enabled.slice(5)).toEqual(disabled.slice(5));
+ } finally {
+ measure.mockRestore();
+ }
+ });
+
it('uses paragraph text style for an empty traditional paragraph mark', () => {
const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('', {
documentStyle: {
@@ -57,6 +392,71 @@ describe('shaping', () => {
expect(result[0].glyphs.length).toBeGreaterThan(0);
});
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('keeps slash-connected Western words together only in traditional layout (%s)', (documentFlavor) => {
+ const content = 'Case Breyer/Duitsland follows';
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor },
+ });
+ const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ expect(result.map((item) => item.text).join('')).toBe(`${content}\r`);
+ expect(result.some((item) => item.text === 'Breyer/')).toBe(documentFlavor === DocumentFlavor.MODERN);
+ if (documentFlavor === DocumentFlavor.TRADITIONAL) {
+ expect(result.some((item) => item.text === 'Breyer/Duitsland ')).toBe(true);
+ }
+ });
+
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('allows Word signed-value breaks only in traditional CJK layout (%s)', (documentFlavor) => {
+ const content = '甲-3.09%、-0.57%、+3.47%、乙';
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor },
+ });
+ const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ expect(result.map((item) => item.text)).toEqual(documentFlavor === DocumentFlavor.TRADITIONAL
+ ? ['甲', '-3.09%、', '-0.57%、', '+3.47%、', '乙\r']
+ : ['甲-3.09%、-0.57%、+3.47%、', '乙\r']);
+ });
+
+ it.each(['、', ','])('breaks signed lists at CJK separators without requiring a Han letter (%s)', (separator) => {
+ const content = `-3.09%${separator}-0.57%${separator}+3.47%`;
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ expect(result.map((item) => item.text)).toEqual([`-3.09%${separator}`, `-0.57%${separator}`, '+3.47%\r']);
+ });
+
+ it('keeps opening parentheses with signed values in traditional CJK text', () => {
+ const content = '甲(-3.09)、(+3.47)乙';
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },
+ });
+ const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ expect(result.map((item) => item.text)).toEqual(['甲', '(-3.09)、', '(+3.47)', '乙\r']);
+ });
+
+ it.each([
+ { flavor: DocumentFlavor.TRADITIONAL, compression: characterSpacingControlType.doNotCompress, expected: true },
+ { flavor: DocumentFlavor.TRADITIONAL, compression: characterSpacingControlType.compressPunctuation, expected: false },
+ { flavor: DocumentFlavor.TRADITIONAL, compression: undefined, expected: false },
+ { flavor: DocumentFlavor.MODERN, compression: characterSpacingControlType.doNotCompress, expected: false },
+ ])('uses Word numeric-hyphen breaks with uncompressed punctuation: %j', ({ flavor, compression, expected }) => {
+ // Word COM: at 50pt, doNotCompress yields "甲甲甲-" / "2.19%,乙";
+ // compressPunctuation keeps the minus on the following numeric line.
+ const content = '甲甲甲-2.19%,乙+3.4%,(-5.6%)';
+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor: flavor, characterSpacingControl: compression },
+ });
+ const before = JSON.stringify(dataModel.getSnapshot());
+ const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
+ let offset = 0;
+ const breaks = result.map((item) => (offset += item.text.length));
+ expect(result.map((item) => item.text).join('')).toBe(`${content}\r`);
+ expect(breaks.includes(content.indexOf('-') + 1)).toBe(expected);
+ expect(breaks.includes(content.lastIndexOf('-') + 1)).toBe(expected);
+ expect(breaks.includes(content.indexOf('+') + 1)).toBe(false);
+ expect(JSON.stringify(dataModel.getSnapshot())).toBe(before);
+ });
+
it('shapes text with spaces', () => {
const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('Hello world test');
@@ -241,6 +641,26 @@ describe('shaping', () => {
expect(emojiGlyph).toBeDefined();
});
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('preserves offsets across mixed script dispatch in %s', (documentFlavor) => {
+ const content = 'Latin😀مرحبا你好ཀཁกข\tEnd';
+ const { dataModel, viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
+ documentStyle: { documentFlavor },
+ });
+ const before = JSON.stringify(dataModel.getSnapshot());
+ const source = paragraphNode.content!;
+ try {
+ const glyphs = shaping(ctx, source, viewModel, paragraphNode, sectionBreakConfig)
+ .flatMap((item) => item.glyphs);
+ expect(glyphs.map((glyph) => glyph.raw).join('')).toBe(source);
+ expect(glyphs.reduce((count, glyph) => count + glyph.count, 0)).toBe(source.length);
+ expect(JSON.stringify(dataModel.getSnapshot())).toBe(before);
+ } finally {
+ viewModel.dispose();
+ dataModel.dispose();
+ clearFontCreateConfigCache();
+ }
+ });
+
it('shapes text with Arabic characters', () => {
const arabicText = '\u0645\u0631\u062D\u0628\u0627'; // 'مرحبا'
const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(arabicText);
@@ -296,14 +716,44 @@ describe('shaping', () => {
expect(allGlyphs.length).toBeGreaterThan(0);
});
- it('applies punctuation space adjustment for consecutive CJK punctuation', () => {
- const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(',。');
-
- const result = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
-
- const allGlyphs = result.flatMap((r) => r.glyphs);
- expect(allGlyphs.some((g) => g.content === ',')).toBe(true);
- expect(allGlyphs.some((g) => g.content === '。')).toBe(true);
+ it.each(['),', '》、', '”)'])('distinguishes fixed punctuation pairs from traditional line compression: %s', (pair) => {
+ const measure = vi.spyOn(FontCache, 'getTextSize').mockReturnValue({
+ width: 20,
+ ba: 18,
+ bd: 4,
+ aba: 18,
+ abd: 4,
+ sp: 0,
+ sbr: 0,
+ sbo: 0,
+ spr: 0,
+ spo: 0,
+ });
+ try {
+ for (const { documentFlavor, compression } of [
+ { documentFlavor: DocumentFlavor.TRADITIONAL, compression: undefined },
+ { documentFlavor: DocumentFlavor.TRADITIONAL, compression: characterSpacingControlType.doNotCompress },
+ { documentFlavor: DocumentFlavor.MODERN, compression: undefined },
+ { documentFlavor: undefined, compression: undefined },
+ ]) {
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(pair, {
+ documentStyle: { documentFlavor, characterSpacingControl: compression, textStyle: { ff: 'Arial', fs: 15 } },
+ body: { paragraphs: [{ startIndex: pair.length, paragraphStyle: { snapToGrid: BooleanNumber.FALSE } }] },
+ });
+ const glyphs = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig)
+ .flatMap((item) => item.glyphs)
+ .filter((glyph) => pair.includes(glyph.content) && glyph.content !== '');
+ expect(glyphs.map((glyph) => glyph.content).join('')).toBe(pair);
+ const compressPair = documentFlavor === DocumentFlavor.TRADITIONAL
+ ? compression === characterSpacingControlType.doNotCompress
+ : pair !== '”)';
+ expect(glyphs.reduce((sum, glyph) => sum + glyph.width, 0)).toBe(compressPair ? 30 : 40);
+ // Deferred compression remains available to the line fitter, not permanently discarded.
+ expect(glyphs.reduce((sum, glyph) => sum + glyph.adjustability.shrinkability[1], 0)).toBe(compressPair ? 10 : 20);
+ }
+ } finally {
+ measure.mockRestore();
+ }
});
it('adds CJK Latin spacing for mixed text', () => {
@@ -331,6 +781,31 @@ describe('shaping', () => {
expect(paragraphGlyph!.width).toBe(0);
});
+ it.each([undefined, BooleanNumber.FALSE])('preserves explicit custom-range metrics on a DrawingML paragraph mark (%s)', (zeroWidthParagraphBreak) => {
+ clearFontCreateConfigCache();
+ const range: ICustomRangeForInterceptor = {
+ startIndex: 1,
+ endIndex: 1,
+ rangeId: 'paragraph-custom-metrics',
+ rangeType: CustomRangeType.CUSTOM,
+ glyphWidthEm: 2,
+ glyphAscentEm: 1.5,
+ glyphDescentEm: 0.5,
+ };
+ const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed('A', {
+ documentStyle: { textStyle: { fs: 12 }, renderConfig: { zeroWidthParagraphBreak } },
+ body: { customRanges: [range] },
+ });
+ sectionBreakConfig.documentCompatibilityPolicy = getDocumentCompatibilityPolicy(DocumentFlavor.DRAWINGML);
+ const glyphs = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig)
+ .flatMap((item) => item.glyphs);
+ const mark = glyphs.find((glyph) => glyph.content === '\r')!;
+ expect(mark.width).toBe(32);
+ expect(mark.bBox.ba).toBe(24);
+ expect(mark.bBox.bd).toBe(8);
+ expect(glyphs.map((glyph) => glyph.content).join('')).toBe('A\r');
+ });
+
it('shapes custom block when drawing is not found', () => {
const content = `A${DataStreamTreeTokenType.CUSTOM_BLOCK}B`;
const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content);
@@ -383,6 +858,35 @@ describe('shaping', () => {
expect(result.length).toBeGreaterThan(1);
});
+ it.each([0, 90])('rotates measured inline object bounds after resolving its unrotated size (%s degrees)', (angle) => {
+ const bed = createParagraphLayoutTestBed('\b', {
+ body: { customBlocks: [{ startIndex: 0, blockId: 'autofit' }] },
+ drawings: { autofit: {
+ drawingId: 'autofit',
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: { angle, size: { width: 100, height: 60 } },
+ } },
+ });
+ const unregister = setDocsCustomBlockRenderViewportProvider((_unitId, blockId, input) => {
+ if (blockId !== 'autofit') {
+ return null;
+ }
+ expect(input).toMatchObject({ fallbackWidth: 100, fallbackHeight: 60 });
+ return { width: 120, height: 80 };
+ });
+ try {
+ const glyph = shaping(bed.ctx, bed.paragraphNode.content!, bed.viewModel, bed.paragraphNode, bed.sectionBreakConfig)
+ .flatMap((run) => run.glyphs)
+ .find((item) => item.drawingId === 'autofit')!;
+ expect(glyph.width).toBeCloseTo(angle === 0 ? 120 : 80);
+ expect(glyph.bBox.ba + glyph.bBox.bd).toBeCloseTo(angle === 0 ? 80 : 120);
+ } finally {
+ unregister();
+ bed.viewModel.dispose();
+ bed.dataModel.dispose();
+ }
+ });
+
it('shapes floating custom block without splitting', () => {
const content = `A${DataStreamTreeTokenType.CUSTOM_BLOCK}B`;
const { viewModel, ctx, paragraphNode, sectionBreakConfig } = createParagraphLayoutTestBed(content, {
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.ts
index 4810404ebb..fe63d9a5f7 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.ts
@@ -44,6 +44,7 @@ export function otherHandler(
let src = charArray;
while (src.length) {
+ const config = getFontCreateConfig(index + step, viewModel, paragraphNode, sectionBreakConfig, paragraph);
// Keep ordinary ASCII cheap, but never expose a caret stop inside a combining sequence.
const char = src.match(/^\p{ASCII}(?![\p{Mark}\u200D])/u)?.[0] ?? getFirstGrapheme(src);
@@ -51,11 +52,10 @@ export function otherHandler(
break;
}
- if (hasSpace(char) || startWithEmoji(charArray.substring(step))) {
+ if (hasSpace(char) || startWithEmoji(charArray.substring(step)) || (config.textStyle.sc && hasArabic(char))) {
break;
}
- const config = getFontCreateConfig(index + step, viewModel, paragraphNode, sectionBreakConfig, paragraph);
const glyph = createSkeletonLetterGlyph(char, config, getCustomRangeGlyphMetrics(index + step, viewModel, paragraphNode, config));
glyphGroup.push(glyph);
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts
index d35acbd448..264d5d0e0b 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { INumberUnit, IParagraphProperties, Nullable } from '@univerjs/core';
+import type { INumberUnit, IParagraphProperties, ITabStop, Nullable } from '@univerjs/core';
import type {
IDocumentSkeletonColumn,
IDocumentSkeletonDivide,
@@ -32,10 +32,13 @@ import type {
} from '../../tools';
import {
BooleanNumber,
+ characterSpacingControlType,
DataStreamTreeTokenType,
DocumentFlavor,
GridType,
+ HorizontalAlign,
NAMED_STYLE_SPACE_MAP,
+ NumberUnitType,
ObjectRelativeFromH,
ObjectRelativeFromV,
PositionedObjectLayoutType,
@@ -44,12 +47,26 @@ import {
TabStopAlignment,
WrapStrategy,
} from '@univerjs/core';
-import { DocumentSkeletonPageType, GlyphType, LineType } from '../../../../../basics/i-document-skeleton-cached';
+import { cjk } from '../../../../../basics/cjk-regexp';
+import {
+ DocumentSkeletonPageType,
+ GlyphType,
+ LineType,
+} from '../../../../../basics/i-document-skeleton-cached';
import { isCjkLeftAlignedPunctuation } from '../../../../../basics/tools';
import { getDocsCustomBlockRenderViewport } from '../../../custom-block-render-viewport';
-import { isTraditionalDocumentCompatibility } from '../../../document-compatibility';
+import { getNominalFontLineHeight, isTraditionalDocumentCompatibility } from '../../../document-compatibility';
import { BreakPointType } from '../../line-breaker/break';
-import { addGlyphToDivide, createSkeletonBulletGlyph } from '../../model/glyph';
+import {
+ addGlyphToDivide,
+ applyGlyphKerning,
+ createSkeletonBulletGlyph,
+ getGlyphGroupFontBoundingBox,
+ getGlyphGroupShrinkability,
+ getGlyphGroupStretchability,
+ getGlyphPairKerningAdjustment,
+ preserveLineStartPunctuationSpace,
+} from '../../model/glyph';
import {
calculateLineTopByDrawings,
collisionDetection,
@@ -65,6 +82,7 @@ import {
FloatObjectType,
getCharSpaceApply,
getCharSpaceConfig,
+ getDrawingMLLineBaseline,
getLastLineByColumn,
getLastNotFullColumnInfo,
getLastNotFullDivideInfo,
@@ -79,7 +97,7 @@ import {
lineIterator,
reachesNextDocumentGridLine,
} from '../../tools';
-import { createTableSkeletons, getTableLeft, rollbackListCache } from '../table';
+import { cachePrecomputedTableSkeleton, createTableSkeletons, getTableLeft } from '../table';
const LINE_LAYOUT_OVERFLOW_TOLERANCE = 2;
const FLOAT_OBJECT_RELAYOUT_LIMIT = 5;
@@ -90,31 +108,136 @@ const RELATIVE_LINE_WIDTH_TOLERANCE = 0.01;
interface IDefaultSpanMetrics {
lineHeight: number;
hasInlineCustomBlock: boolean;
+ hasListGlyph?: boolean;
+ normalLineHeight?: number;
+ drawingMLLineHeight?: number;
+ paragraphEnd?: boolean;
}
-function isBeyondDivideWidth(width: number, divideWidth: number) {
- const tolerance = Math.min(
+function isBeyondDivideWidth(width: number, divideWidth: number, lineWrapTolerance?: number) {
+ const defaultTolerance = Math.min(
MAX_LINE_WIDTH_TOLERANCE,
Math.max(MIN_LINE_WIDTH_TOLERANCE, divideWidth * RELATIVE_LINE_WIDTH_TOLERANCE)
);
- return width - divideWidth > tolerance;
+ const tolerance = lineWrapTolerance != null && Number.isFinite(lineWrapTolerance) && lineWrapTolerance >= 0
+ ? lineWrapTolerance
+ : defaultTolerance;
+
+ return width - divideWidth > tolerance + 1e-6;
}
function isGlyphGroupBeyondDivideWidth(
glyphGroup: IDocumentSkeletonGlyph[],
offsetLeft: number,
divideWidth: number,
- hangingPunctuation = false
+ hangingPunctuation = false,
+ precedingGlyphs?: IDocumentSkeletonGlyph[],
+ preserveWordSpacing = false,
+ lineWrapTolerance?: number,
+ includeParagraphMark = false,
+ justifyWordSpacing = false
) {
- const width = __getGlyphGroupWidth(glyphGroup);
- const trailingGlyph = glyphGroup[glyphGroup.length - 1];
- const trailingShrinkability = trailingGlyph?.adjustability?.shrinkability?.[1] ?? 0;
- const trailingHangingWidth = hangingPunctuation && trailingGlyph && isCjkLeftAlignedPunctuation(trailingGlyph.content)
+ let trailingIndex = glyphGroup.length - 1;
+ while (trailingIndex >= 0 && (
+ glyphGroup[trailingIndex].width === 0 ||
+ glyphGroup[trailingIndex].content === DataStreamTreeTokenType.PARAGRAPH ||
+ glyphGroup[trailingIndex].streamType === DataStreamTreeTokenType.SECTION_BREAK
+ )) {
+ trailingIndex--;
+ }
+ if (trailingIndex < 0) {
+ // A paragraph terminator remains on its line even after an oversized inline object.
+ return false;
+ }
+ // A candidate line has no adjacent Latin glyph beyond either outer edge.
+ const trailingAutoSpacing = glyphGroup[trailingIndex].autoSpacing?.[1] ?? 0;
+ const leadingAutoSpacing = offsetLeft === 0 ? glyphGroup[0].autoSpacing?.[0] ?? 0 : 0;
+ const width = __getGlyphGroupWidth(glyphGroup, includeParagraphMark) - trailingAutoSpacing - leadingAutoSpacing;
+ if (preserveWordSpacing) {
+ let trailingSpace = 0;
+ for (let index = trailingIndex; index >= 0 && glyphGroup[index].content === DataStreamTreeTokenType.SPACE; index--) {
+ trailingSpace += glyphGroup[index].width;
+ }
+ const overflow = offsetLeft + width - trailingSpace - divideWidth;
+ if (overflow <= 1e-6) {
+ return false;
+ }
+ const trailingGlyph = glyphGroup[trailingIndex];
+ const hanging = hangingPunctuation && /^[.,]$/.test(trailingGlyph.content)
+ ? trailingGlyph.width * 0.8
+ : 0;
+ if (!justifyWordSpacing || (trailingSpace === 0 && hanging === 0)) {
+ return true;
+ }
+ const preceding = precedingGlyphs ?? [];
+ if (preceding.some((glyph) => glyph.glyphType === GlyphType.TAB)
+ || glyphGroup.some((glyph) => glyph.glyphType === GlyphType.TAB)) {
+ return true;
+ }
+ // Word can tighten justified spaces by one quarter, but chooses the
+ // closer legal break. A terminal line also needs hanging punctuation.
+ const spaces = [...preceding, ...glyphGroup.slice(0, trailingIndex + 1)]
+ .filter((glyph) => glyph.content === DataStreamTreeTokenType.SPACE);
+ const shrink = spaces.reduce((sum, glyph) => sum + glyph.width / 4, 0) - trailingSpace / 4;
+ return overflow - hanging > shrink + 1e-6
+ || overflow + trailingSpace - hanging > Math.max(0, divideWidth - offsetLeft) + 1e-6;
+ }
+ if (!isBeyondDivideWidth(offsetLeft + width, divideWidth, lineWrapTolerance)) {
+ return false;
+ }
+ const trailingGlyph = glyphGroup[trailingIndex];
+ const trailingShrinkability = Math.max(0, (trailingGlyph?.adjustability?.shrinkability?.[1] ?? 0) - trailingAutoSpacing / 2);
+ const alternateLanguage = trailingGlyph?.ts?.altLang;
+ // Office uses the alternate East Asian language for CJK punctuation in mixed-language runs.
+ const punctuationLanguage = /^(?:ja|zh|ko)(?:-|$)/i.test(alternateLanguage ?? '')
+ ? alternateLanguage
+ : trailingGlyph?.ts?.lang;
+ // JLREQ hanging punctuation covers full stops and commas, not closing brackets.
+ // Keep punctuation compression and the legacy behavior for unspecified languages separate.
+ const permitsHanging = trailingGlyph && (/^ja(?:-|$)/i.test(punctuationLanguage ?? '')
+ ? /^[。.、,]$/.test(trailingGlyph.content)
+ : isCjkLeftAlignedPunctuation(trailingGlyph.content));
+ const trailingHangingWidth = hangingPunctuation && permitsHanging
? trailingGlyph.width
: 0;
-
- return isBeyondDivideWidth(offsetLeft + width - Math.max(trailingShrinkability, trailingHangingWidth), divideWidth);
+ const hangingExtra = Math.max(0, trailingHangingWidth - trailingShrinkability);
+ // ponytail: Other scripts retain the closer-break rule until covered by matching source-document fixtures.
+ const wordFitsWithPunctuationCompression = precedingGlyphs !== undefined
+ && offsetLeft <= divideWidth
+ && glyphGroup.some((glyph) => /[a-z\d]/i.test(glyph.content))
+ && glyphGroup.every((glyph) => !cjk.hasCJKText(glyph.content))
+ && offsetLeft + width - getGlyphGroupShrinkability(precedingGlyphs, true)
+ - getGlyphGroupShrinkability(glyphGroup, true) - hangingExtra <= divideWidth + MIN_LINE_WIDTH_TOLERANCE;
+ const precedingLineCanStretch = precedingGlyphs !== undefined
+ && (glyphGroup[0].autoSpacing?.[0] ?? 0) > 0
+ && offsetLeft < divideWidth
+ && divideWidth - offsetLeft <= getGlyphGroupStretchability(precedingGlyphs);
+ // ponytail: Native legacy-report fixtures allow a Han glyph after a Western
+ // word's explicit space to use remaining punctuation compression. Other
+ // already-compressed boundaries keep the closer-break rule until verified.
+ const spacedWesternWordFits = precedingGlyphs !== undefined
+ && offsetLeft > divideWidth
+ && precedingGlyphs[precedingGlyphs.length - 1]?.content === ' '
+ && /[a-z\d]/i.test(precedingGlyphs[precedingGlyphs.length - 2]?.content ?? '')
+ && cjk.hasCJKText(glyphGroup[0].content)
+ && offsetLeft + width - getGlyphGroupShrinkability(precedingGlyphs, true)
+ - getGlyphGroupShrinkability(glyphGroup, true) - hangingExtra <= divideWidth + MIN_LINE_WIDTH_TOLERANCE;
+
+ // Prefer the closer legal break: do not compress more than leaving the group on the next line would expand.
+ // Keep a Western word when punctuation alone can accommodate it, without extending an already compressed line.
+ // Line-end punctuation already sheds its trailing space before line-wide justification.
+ // At a Western-to-Han boundary, retain a line that can fill using its existing adjustable gaps.
+ // Fixed tab anchors cannot borrow space from text on their other side.
+ const shrinkability = precedingGlyphs !== undefined
+ && (wordFitsWithPunctuationCompression || spacedWesternWordFits
+ || (!precedingLineCanStretch
+ && offsetLeft + width - trailingShrinkability - hangingExtra - divideWidth <= divideWidth - offsetLeft))
+ && !precedingGlyphs.some((glyph) => glyph.glyphType === GlyphType.TAB)
+ && !glyphGroup.some((glyph) => glyph.glyphType === GlyphType.TAB)
+ ? getGlyphGroupShrinkability(precedingGlyphs) + getGlyphGroupShrinkability(glyphGroup) - (trailingAutoSpacing + leadingAutoSpacing) / 2
+ : trailingShrinkability;
+ return isBeyondDivideWidth(offsetLeft + width - shrinkability - hangingExtra, divideWidth, lineWrapTolerance);
}
export function layoutParagraph(
@@ -125,9 +248,11 @@ export function layoutParagraph(
paragraphConfig: IParagraphConfig,
isParagraphFirstShapedText: boolean,
breakPointType = BreakPointType.Normal,
- renderBullet = isParagraphFirstShapedText
+ renderBullet = isParagraphFirstShapedText,
+ startNewLine = false
) {
- if (isParagraphFirstShapedText) {
+ paragraphConfig.documentCompatibilityPolicy ??= sectionBreakConfig.documentCompatibilityPolicy;
+ if (isParagraphFirstShapedText || startNewLine) {
// elementIndex === 0 means the first character at the beginning of a paragraph, needs a new line to distinguish from the previous paragraph
if (renderBullet && paragraphConfig.bulletSkeleton) {
const { bulletSkeleton, paragraphStyle = {} } = paragraphConfig;
@@ -138,7 +263,7 @@ export function layoutParagraph(
const { snapToGrid = BooleanNumber.TRUE } = paragraphStyle;
const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);
- const bulletGlyph = createSkeletonBulletGlyph(glyphGroup[0], bulletSkeleton, charSpaceApply);
+ const bulletGlyph = createSkeletonBulletGlyph(glyphGroup[0], bulletSkeleton, charSpaceApply, paragraphConfig.documentCompatibilityPolicy ?? sectionBreakConfig.documentCompatibilityPolicy);
const paragraphProperties = bulletSkeleton.paragraphProperties || {};
const bulletParagraphStyle = {
...paragraphProperties,
@@ -152,10 +277,13 @@ export function layoutParagraph(
const hangingWidth = getNumberUnitValue(paragraphConfig.paragraphStyle.hanging, charSpaceApply);
if (hangingWidth > 0) {
- // Direct paragraph hanging is authored layout; the list default is only a minimum marker width.
- bulletGlyph.width = directParagraphHanging == null
- ? Math.max(bulletGlyph.width, hangingWidth)
- : hangingWidth;
+ // Word list-level indents are authored positions, not a minimum of two default tab stops.
+ const hasAuthoredHanging = directParagraphHanging != null ||
+ (isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy) &&
+ paragraphProperties.hanging != null);
+ bulletGlyph.width = hasAuthoredHanging
+ ? hangingWidth
+ : Math.max(bulletGlyph.width, hangingWidth);
}
_lineOperator(ctx, [bulletGlyph, ...glyphGroup], pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType);
@@ -176,7 +304,7 @@ export function layoutParagraph(
return [...pages];
}
-function isGlyphGroupEndWithWhiteSpaces(glyphGroup: IDocumentSkeletonGlyph[]) {
+function isGlyphGroupEndWithWhiteSpaces(glyphGroup: IDocumentSkeletonGlyph[], drawingML = false) {
if (glyphGroup.length <= 1) {
return false;
}
@@ -184,12 +312,13 @@ function isGlyphGroupEndWithWhiteSpaces(glyphGroup: IDocumentSkeletonGlyph[]) {
let isInWhiteSpace = false;
for (const g of glyphGroup) {
- if (g.content === DataStreamTreeTokenType.SPACE) {
+ if (g.content === DataStreamTreeTokenType.SPACE || (drawingML && g.content === '\u3000')) {
isInWhiteSpace = true;
}
if (isInWhiteSpace &&
- g.content !== DataStreamTreeTokenType.SPACE && g.content !== DataStreamTreeTokenType.PARAGRAPH &&
+ g.content !== DataStreamTreeTokenType.SPACE && !(drawingML && g.content === '\u3000') &&
+ g.content !== DataStreamTreeTokenType.PARAGRAPH &&
g.streamType !== DataStreamTreeTokenType.SECTION_BREAK && g.streamType !== DataStreamTreeTokenType.PAGE_BREAK) {
return false;
}
@@ -198,7 +327,7 @@ function isGlyphGroupEndWithWhiteSpaces(glyphGroup: IDocumentSkeletonGlyph[]) {
return isInWhiteSpace;
}
-function isGlyphGroupBeyondContentBox(glyphGroup: IDocumentSkeletonGlyph[], left: number, divideWidth: number) {
+function isGlyphGroupBeyondContentBox(glyphGroup: IDocumentSkeletonGlyph[], left: number, divideWidth: number, drawingML = false) {
if (glyphGroup.length <= 1) {
return false;
}
@@ -209,6 +338,7 @@ function isGlyphGroupBeyondContentBox(glyphGroup: IDocumentSkeletonGlyph[], left
for (const g of glyphGroup) {
if (
g.content === DataStreamTreeTokenType.SPACE ||
+ (drawingML && g.content === '\u3000') ||
g.content === DataStreamTreeTokenType.PARAGRAPH ||
g.streamType === DataStreamTreeTokenType.SECTION_BREAK
) {
@@ -296,158 +426,22 @@ function _divideOperator(
ctx.footnoteLayout?.updateReferenceGlyphs(lastPage, glyphGroup, sectionBreakConfig, paragraphConfig);
if (divideInfo) {
const { divide, isLast } = divideInfo;
- _adjustExplicitTabStop(divide, glyphGroup, paragraphConfig);
- const lastGlyph = divide?.glyphGroup?.[divide.glyphGroup.length - 1];
- const lastWidth = lastGlyph?.width || 0;
- const lastLeft = lastGlyph?.left || 0;
- const preOffsetLeft = lastWidth + lastLeft;
+ const fit = _fitGlyphsToDivide(ctx, divide, glyphGroup, sectionBreakConfig, paragraphConfig);
+ const { preOffsetLeft } = fit;
const { hyphenationZone } = sectionBreakConfig;
- const hangingPunctuation = paragraphConfig.paragraphStyle?.hangingPunctuation === BooleanNumber.TRUE;
- if (isGlyphGroupBeyondDivideWidth(glyphGroup, preOffsetLeft, divide.width, hangingPunctuation)) {
- if (
- divide?.glyphGroup.length === 0 &&
- glyphGroup.length > 0 &&
- glyphGroup[0].streamType === DataStreamTreeTokenType.CUSTOM_BLOCK
- ) {
- addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
- updateDivideInfo(divide, { breakType: breakPointType });
- return;
- }
-
- if (shouldKeepOverflowingTextOnLine(sectionBreakConfig)) {
- addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
- updateDivideInfo(divide, { breakType: breakPointType });
- return;
- }
-
- // width exceeds divide width
- updateDivideInfo(divide, {
- isFull: true,
- });
- const hyphenLineCount = _getConsecutiveHyphenLineCount(divideInfo.divide);
- const { consecutiveHyphenLimit = Number.POSITIVE_INFINITY } = sectionBreakConfig;
-
- // There are two main ways to deal with word or number strings exceeding divide width
- // 1. If you end with a line break(\r), you need to append a line break(\r) to the end of divide, even if it exceeds the divide width.
- // 2. In a blank line, if the English word or consecutive number exceeds the width of the divide, the English word and number string will be split, and some of them will be added to the previous line, and the rest will be placed in the new line.
- // There is a boundary case, that is, the width of the English character exceeds the width of the divide, and this character needs to be appended to the previous line.
- if (
- divideInfo.isLast &&
- glyphGroup.length === 1 &&
- (glyphGroup[0].content === DataStreamTreeTokenType.SPACE ||
- glyphGroup[0].content === DataStreamTreeTokenType.PARAGRAPH)
- ) {
- addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
- } else if (
- // If a line of text ends with consecutive spaces, the spaces should not be placed on the second line.
- divideInfo.isLast && !isGlyphGroupBeyondContentBox(glyphGroup, preOffsetLeft, divide.width) && isGlyphGroupEndWithWhiteSpaces(glyphGroup)
- ) {
- addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
- } else if (
- !isLast &&
- divide?.glyphGroup.length === 0 &&
- glyphGroup.length === 1 &&
- glyphGroup[0].streamType === DataStreamTreeTokenType.CUSTOM_BLOCK &&
- glyphGroup[0].width > divide.width
- ) {
- addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
- updateDivideInfo(divide, { breakType: breakPointType });
- } else if (!isLast && divide?.glyphGroup.length === 0) {
- // A wrap drawing can leave a sliver before another usable divide.
- // Preserve the shaped word and try the next divide instead of
- // forcing a single glyph into that sliver.
- _divideOperator(
- ctx,
- glyphGroup,
- pages,
- sectionBreakConfig,
- paragraphConfig,
- isParagraphFirstShapedText,
- breakPointType,
- defaultSpanMetrics
- );
- } else if (divide?.glyphGroup.length === 0) {
- const line = divide.parent!;
- const column = line.parent!;
- const section = column.parent!;
- const wordWidth = __getGlyphGroupWidth(glyphGroup);
- if (
- isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy!) &&
- wordWidth < column.width &&
- calculateLineTopByDrawings(line.lineHeight, line.top, lastPage, null, null, column.left, column.width, section.top, wordWidth - 0.001) > line.top
- ) {
- // Preserve the shaped word when the obstacle, rather than the
- // column, is too narrow. Normal long-word breaking still applies.
- _lineOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType, defaultSpanMetrics);
- return;
- }
- const sliceGlyphGroup: IDocumentSkeletonGlyph[] = [];
-
- while (glyphGroup.length) {
- sliceGlyphGroup.push(glyphGroup.shift()!);
-
- if (isGlyphGroupBeyondDivideWidth(sliceGlyphGroup, 0, divide.width, hangingPunctuation)) {
- // 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()!);
- }
- break;
- }
- }
-
- if (sliceGlyphGroup.length > 0) {
- addGlyphToDivide(divide, sliceGlyphGroup, preOffsetLeft);
- }
-
- if (glyphGroup.length) {
- // Only Divide in the first paragraph is the beginning of the paragraph
- _divideOperator(
- ctx,
- glyphGroup,
- pages,
- sectionBreakConfig,
- paragraphConfig,
- false,
-
- breakPointType,
- defaultSpanMetrics
- );
- }
- } else if (hyphenLineCount > consecutiveHyphenLimit) {
- const hyphenSliceGlyphGroup = _popHyphenSlice(divide);
-
- if (hyphenSliceGlyphGroup.length > 0) {
- updateDivideInfo(divide, {
- breakType: BreakPointType.Normal,
- });
-
- _divideOperator(ctx, hyphenSliceGlyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, BreakPointType.Hyphen);
- }
-
- _divideOperator(
- ctx,
- glyphGroup,
- pages,
- sectionBreakConfig,
- paragraphConfig,
- isParagraphFirstShapedText,
-
- breakPointType,
- defaultSpanMetrics
- );
- } else {
- _divideOperator(
- ctx,
- glyphGroup,
- pages,
- sectionBreakConfig,
- paragraphConfig,
- isParagraphFirstShapedText,
-
- breakPointType,
- defaultSpanMetrics
- );
- }
+ if (fit.beyondWidth) {
+ _appendOverflowingGlyphs(
+ ctx,
+ glyphGroup,
+ pages,
+ sectionBreakConfig,
+ paragraphConfig,
+ isParagraphFirstShapedText,
+ divideInfo,
+ fit,
+ breakPointType,
+ defaultSpanMetrics
+ );
} else if ( // Determine if first word slice appears inside the hyphenation zone.
isLast &&
hyphenationZone &&
@@ -472,200 +466,815 @@ function _divideOperator(
defaultSpanMetrics
);
} else {
- // w does not exceed divide width, add it to divide
- const currentLine = divide.parent;
- if (currentLine?.parent?.parent && ctx.footnoteLayout && glyphGroup.some((glyph) => glyph.noteId)) {
- const bodyBottom = currentLine.parent.parent.top + currentLine.top + currentLine.lineHeight;
- const bodyLimit = ctx.footnoteLayout.getBodyLimit(lastPage, pages, sectionBreakConfig, bodyBottom, glyphGroup);
- if (bodyBottom > bodyLimit + LINE_LAYOUT_OVERFLOW_TOLERANCE) {
- const column = currentLine.parent;
- const cachedGlyphs = __getGlyphGroupByLine(currentLine);
- column.lines.pop();
- const previousLine = column.lines[column.lines.length - 1];
- const previousBottom = column.parent!.top + (previousLine == null ? 0 : previousLine.top + previousLine.lineHeight);
- ctx.footnoteLayout.getBodyLimit(lastPage, pages, sectionBreakConfig, previousBottom);
- _pageOperator(ctx, [...cachedGlyphs, ...glyphGroup], pages, sectionBreakConfig, paragraphConfig, currentLine.paragraphStart, breakPointType, defaultSpanMetrics);
- return;
- }
- }
- const maxBox = __maxFontBoundingBoxByGlyphGroup(glyphGroup);
-
- if (currentLine?.parent && __isNullLine(currentLine) && __hasFlowGlyph(glyphGroup)) {
- const cachedGlyphs = __getGlyphGroupByLine(currentLine);
- if (cachedGlyphs.length > 0 && cachedGlyphs.every((glyph) => glyph.streamType === DataStreamTreeTokenType.PAGE_BREAK)) {
- // A skipped rendered-page hint has no font metrics. Let the first real text
- // establish its line, including normal font leading and available page height.
- currentLine.parent.lines.pop();
- _lineOperator(ctx, [...cachedGlyphs, ...glyphGroup], pages, sectionBreakConfig, paragraphConfig, currentLine.paragraphStart, breakPointType, defaultSpanMetrics);
- return;
- }
- }
+ _appendFittingGlyphs(
+ ctx,
+ glyphGroup,
+ pages,
+ sectionBreakConfig,
+ paragraphConfig,
+ isParagraphFirstShapedText,
+ divide,
+ preOffsetLeft,
+ breakPointType,
+ defaultSpanMetrics
+ );
+ }
+ } else {
+ _lineOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType, defaultSpanMetrics);
+ }
+}
- if (
- currentLine &&
- __isPositionedCustomBlockOnlyLine(__getGlyphGroupByLine(currentLine), paragraphConfig.paragraphNonInlineSkeDrawings) &&
- __hasFlowGlyph(glyphGroup)
- ) {
- for (const lineDivide of currentLine.divides) {
- updateDivideInfo(lineDivide, {
- isFull: true,
- });
- }
- _lineOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, false, breakPointType);
- return;
- }
+function _fitGlyphsToDivide(
+ ctx: ILayoutContext,
+ divide: IDocumentSkeletonDivide,
+ glyphGroup: IDocumentSkeletonGlyph[],
+ sectionBreakConfig: ISectionBreakConfig,
+ paragraphConfig: IParagraphConfig
+) {
+ const compressLineStart = paragraphConfig.paragraphStyle?.topLinePunct
+ ?? (isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy) ? BooleanNumber.FALSE : BooleanNumber.TRUE);
+ if (divide.glyphGroup.length === 0 && glyphGroup.length > 0 && compressLineStart === BooleanNumber.FALSE) {
+ // Set the same uncompressed width before fitting and before line-wide justification.
+ preserveLineStartPunctuationSpace(glyphGroup[0]);
+ }
+ const tabStops = getParagraphTabStops(ctx, sectionBreakConfig, paragraphConfig);
+ _adjustExplicitTabStop(divide, glyphGroup, paragraphConfig, tabStops);
+ const lastGlyph = divide?.glyphGroup?.[divide.glyphGroup.length - 1];
+ const lastWidth = lastGlyph?.width || 0;
+ const lastLeft = lastGlyph?.left || 0;
+ const preOffsetLeft = lastWidth + lastLeft;
+ _adjustIncomingTabStops(divide, glyphGroup, preOffsetLeft, sectionBreakConfig, paragraphConfig, tabStops);
+ const fitOffsetLeft = preOffsetLeft + getGlyphPairKerningAdjustment(lastGlyph, glyphGroup[0]) -
+ (lastGlyph?.kerningAdjustment ?? 0);
+ const drawingML = sectionBreakConfig.documentCompatibilityPolicy?.mode === 'drawingml';
+ const hangingPunctuation = paragraphConfig.paragraphStyle?.hangingPunctuation === BooleanNumber.TRUE;
+ // Word line fitting must not borrow the legacy 1–3px allowance in addition
+ // to punctuation hanging/compression; small overflows accumulate across lines.
+ const lineWrapTolerance = sectionBreakConfig.renderConfig?.lineWrapTolerance
+ ?? (drawingML || isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy) ? 0 : undefined);
+ const compression = sectionBreakConfig.characterSpacingControl ?? ctx.dataModel.documentStyle.characterSpacingControl;
+ const horizontalAlign = paragraphConfig.paragraphStyle?.horizontalAlign;
+ const westernLine = !glyphGroup.some((glyph) => cjk.hasCJKText(glyph.content))
+ && !divide.glyphGroup.some((glyph) => cjk.hasCJKText(glyph.content));
+ const preserveWordSpacing = isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)
+ && (horizontalAlign == null || horizontalAlign === HorizontalAlign.UNSPECIFIED || horizontalAlign === HorizontalAlign.LEFT
+ || horizontalAlign === HorizontalAlign.JUSTIFIED || horizontalAlign === HorizontalAlign.BOTH)
+ && preOffsetLeft + __getGlyphGroupWidth(glyphGroup) > divide.width
+ && westernLine;
+ const justifyWordSpacing = preserveWordSpacing
+ && (horizontalAlign === HorizontalAlign.JUSTIFIED || horizontalAlign === HorizontalAlign.BOTH);
+ // East Asian punctuation contracts before horizontal alignment, including
+ // centered and right-aligned cell text that would otherwise wrap.
+ const allowLineCompression = isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)
+ && compression !== characterSpacingControlType.doNotCompress
+ && (horizontalAlign === HorizontalAlign.LEFT || (!westernLine && (horizontalAlign === HorizontalAlign.CENTER || horizontalAlign === HorizontalAlign.RIGHT))
+ || horizontalAlign === HorizontalAlign.JUSTIFIED || horizontalAlign === HorizontalAlign.BOTH || horizontalAlign === HorizontalAlign.DISTRIBUTED);
+
+ const beyondWidth = isGlyphGroupBeyondDivideWidth(
+ glyphGroup,
+ fitOffsetLeft,
+ divide.width,
+ hangingPunctuation,
+ allowLineCompression || justifyWordSpacing ? divide.glyphGroup : undefined,
+ preserveWordSpacing,
+ lineWrapTolerance,
+ !isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy),
+ justifyWordSpacing
+ );
+ return {
+ preOffsetLeft,
+ fitOffsetLeft,
+ drawingML,
+ hangingPunctuation,
+ allowLineCompression,
+ preserveWordSpacing,
+ lineWrapTolerance,
+ beyondWidth,
+ };
+}
- if (
- currentLine &&
- maxBox &&
- !__isNullLine(currentLine) &&
- __hasFlowGlyph(__getGlyphGroupByLine(currentLine)) &&
- !__isZeroWidthNonFlowFloatingAnchorLine(glyphGroup, paragraphConfig.paragraphNonInlineSkeDrawings)
- ) {
- const { paragraphLineGapDefault, linePitch, lineSpacing, spacingRule, snapToGrid, gridType } =
- getLineHeightConfig(sectionBreakConfig, paragraphConfig);
- const { boundingBoxAscent, boundingBoxDescent } = maxBox;
- const spanLineHeight = boundingBoxAscent + boundingBoxDescent;
- const { contentHeight } = getLineHeightMetrics(
- spanLineHeight,
- paragraphLineGapDefault,
- linePitch,
- gridType,
- lineSpacing,
- spacingRule,
- snapToGrid,
- paragraphConfig.useWordStyleLineHeight
- );
+function _appendOverflowingGlyphs(
+ ctx: ILayoutContext,
+ glyphGroup: IDocumentSkeletonGlyph[],
+ pages: IDocumentSkeletonPage[],
+ sectionBreakConfig: ISectionBreakConfig,
+ paragraphConfig: IParagraphConfig,
+ isParagraphFirstShapedText: boolean,
+ divideInfo: NonNullable<ReturnType<typeof getLastNotFullDivideInfo>>,
+ fit: ReturnType<typeof _fitGlyphsToDivide>,
+ breakPointType: BreakPointType,
+ defaultSpanMetrics?: IDefaultSpanMetrics
+): void {
+ const lastPage = getLastPage(pages);
+ const { divide, isLast } = divideInfo;
+ const {
+ preOffsetLeft,
+ fitOffsetLeft,
+ drawingML,
+ hangingPunctuation,
+ allowLineCompression,
+ preserveWordSpacing,
+ lineWrapTolerance,
+ } = fit;
+ if (
+ divide?.glyphGroup.length === 0 &&
+ // A retained pagination marker must stay with the oversized picture;
+ // laying it out alone would reserve the picture's line height twice.
+ glyphGroup.find((glyph) => !__isIgnorableZeroSizeGlyph(glyph))?.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK
+ ) {
+ addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
+ updateDivideInfo(divide, { breakType: breakPointType });
+ return;
+ }
- if (contentHeight - currentLine.contentHeight > LINE_LAYOUT_OVERFLOW_TOLERANCE) {
- // If the height of the new content exceeds the height of the line it joins, for mixed text and graphics layout, the entire line needs to be recalculated according to the new height
- // If the height of the new content exceeds the height of the added row,
- // the entire row needs to be recalculated according to the new height
- // in order to handle the mixing of graphics and text
- const spanGroupCached = __getGlyphGroupByLine(currentLine);
- const spanGroupCachedLen = spanGroupCached.length;
- let newGlyphGroup = [];
- let startIndex = 1;
-
- if (spanGroupCachedLen > 2 && spanGroupCached[0].glyphType === GlyphType.LIST) {
- newGlyphGroup = [spanGroupCached[0], spanGroupCached[1]];
- startIndex = 2;
- } else {
- newGlyphGroup = [spanGroupCached[0]];
- }
- const column = currentLine.parent!;
-
- const { paragraphStart: lineIsStart } = column.lines.pop()!; // Delete the previous line and recalculate according to the maximum content height
-
- _lineOperator(
- ctx,
- newGlyphGroup,
- pages,
- sectionBreakConfig,
- paragraphConfig,
- lineIsStart,
-
- breakPointType,
- {
- lineHeight: boundingBoxAscent + boundingBoxDescent,
- hasInlineCustomBlock: glyphGroup.some((glyph) =>
- glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width !== 0
- ),
- }
- );
-
- for (let i = startIndex; i < spanGroupCached.length; i++) {
- // TODO: @jocs Here you may see non-breakpoints appearing at the end of the line.
- _divideOperator(
- ctx,
- [spanGroupCached[i]],
- pages,
- sectionBreakConfig,
- paragraphConfig,
- isParagraphFirstShapedText
- );
- }
+ if (shouldKeepOverflowingTextOnLine(sectionBreakConfig)) {
+ addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
+ updateDivideInfo(divide, { breakType: breakPointType });
+ return;
+ }
- _divideOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType);
+ // width exceeds divide width
+ updateDivideInfo(divide, {
+ isFull: true,
+ });
+ const hyphenLineCount = _getConsecutiveHyphenLineCount(divideInfo.divide);
+ const { consecutiveHyphenLimit = Number.POSITIVE_INFINITY } = sectionBreakConfig;
- return;
+ // There are two main ways to deal with word or number strings exceeding divide width
+ // 1. If you end with a line break(\r), you need to append a line break(\r) to the end of divide, even if it exceeds the divide width.
+ // 2. In a blank line, if the English word or consecutive number exceeds the width of the divide, the English word and number string will be split, and some of them will be added to the previous line, and the rest will be placed in the new line.
+ // There is a boundary case, that is, the width of the English character exceeds the width of the divide, and this character needs to be appended to the previous line.
+ if (
+ divideInfo.isLast &&
+ glyphGroup.length === 1 &&
+ (glyphGroup[0].content === DataStreamTreeTokenType.SPACE ||
+ (drawingML && glyphGroup[0].content === '\u3000') ||
+ glyphGroup[0].content === DataStreamTreeTokenType.PARAGRAPH)
+ ) {
+ addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
+ } else if (
+ // If a line of text ends with consecutive spaces, the spaces should not be placed on the second line.
+ divideInfo.isLast && !isGlyphGroupBeyondContentBox(glyphGroup, fitOffsetLeft, divide.width, drawingML) &&
+ isGlyphGroupEndWithWhiteSpaces(glyphGroup, drawingML)
+ ) {
+ addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
+ } else if (
+ !isLast &&
+ divide?.glyphGroup.length === 0 &&
+ glyphGroup.length === 1 &&
+ glyphGroup[0].streamType === DataStreamTreeTokenType.CUSTOM_BLOCK &&
+ glyphGroup[0].width > divide.width
+ ) {
+ addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
+ updateDivideInfo(divide, { breakType: breakPointType });
+ } else if (!isLast && divide?.glyphGroup.length === 0) {
+ // A wrap drawing can leave a sliver before another usable divide.
+ // Preserve the shaped word and try the next divide instead of
+ // forcing a single glyph into that sliver.
+ _divideOperator(
+ ctx,
+ glyphGroup,
+ pages,
+ sectionBreakConfig,
+ paragraphConfig,
+ isParagraphFirstShapedText,
+ breakPointType,
+ defaultSpanMetrics
+ );
+ } else if (divide?.glyphGroup.length === 0) {
+ const line = divide.parent!;
+ const column = line.parent!;
+ const section = column.parent!;
+ const wordWidth = __getGlyphGroupWidth(glyphGroup);
+ if (
+ isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy!) &&
+ wordWidth < column.width &&
+ calculateLineTopByDrawings(line.lineHeight, line.top, lastPage, null, null, column.left, column.width, section.top, wordWidth - 0.001) > line.top
+ ) {
+ // Preserve the shaped word when the obstacle, rather than the
+ // column, is too narrow. Normal long-word breaking still applies.
+ _lineOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType, defaultSpanMetrics);
+ return;
+ }
+ const sliceGlyphGroup: IDocumentSkeletonGlyph[] = [];
+
+ while (glyphGroup.length) {
+ sliceGlyphGroup.push(glyphGroup.shift()!);
+
+ if (isGlyphGroupBeyondDivideWidth(
+ sliceGlyphGroup,
+ 0,
+ divide.width,
+ hangingPunctuation,
+ allowLineCompression ? [] : undefined,
+ preserveWordSpacing,
+ lineWrapTolerance,
+ !isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)
+ )) {
+ // 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()!);
}
+ break;
}
- if (currentLine?.parent) {
- const anchorDrawings = __getZeroWidthNonFlowFloatingAnchorDrawings(glyphGroup, paragraphConfig.paragraphNonInlineSkeDrawings);
- if (anchorDrawings.length > 0) {
- const paragraphAnchorLeft = __getParagraphAnchorLeft(sectionBreakConfig, paragraphConfig, paragraphConfig.paragraphStyle?.indentStart);
- const drawings = __getDrawingPosition(
- ctx,
- currentLine.top,
- currentLine.lineHeight,
- currentLine.parent,
- true,
- paragraphConfig.pDrawingAnchor?.get(paragraphConfig.paragraphIndex)?.top,
- anchorDrawings,
- paragraphAnchorLeft,
- false
- );
- __updateDrawingPosition(currentLine.parent, drawings);
- addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
- updateDivideInfo(divide, { breakType: breakPointType });
- glyphGroup.length = 0;
- return;
- }
+ }
+
+ if (sliceGlyphGroup.length > 0) {
+ // An oversized first glyph still owns its paragraph terminator;
+ // moving the terminator alone would create a spurious blank line.
+ if (glyphGroup.every(__isStructuralTerminatorGlyph)) {
+ sliceGlyphGroup.push(...glyphGroup.splice(0));
}
+ addGlyphToDivide(divide, sliceGlyphGroup, preOffsetLeft);
+ }
+
+ if (glyphGroup.length) {
+ // Only Divide in the first paragraph is the beginning of the paragraph
+ _divideOperator(
+ ctx,
+ glyphGroup,
+ pages,
+ sectionBreakConfig,
+ paragraphConfig,
+ false,
+
+ breakPointType,
+ defaultSpanMetrics
+ );
+ }
+ } else if (hyphenLineCount > consecutiveHyphenLimit) {
+ const hyphenSliceGlyphGroup = _popHyphenSlice(divide);
+
+ if (hyphenSliceGlyphGroup.length > 0) {
+ updateDivideInfo(divide, {
+ breakType: BreakPointType.Normal,
+ });
+
+ _divideOperator(ctx, hyphenSliceGlyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, BreakPointType.Hyphen);
+ }
+
+ _divideOperator(
+ ctx,
+ glyphGroup,
+ pages,
+ sectionBreakConfig,
+ paragraphConfig,
+ isParagraphFirstShapedText,
+
+ breakPointType,
+ defaultSpanMetrics
+ );
+ } else {
+ _divideOperator(
+ ctx,
+ glyphGroup,
+ pages,
+ sectionBreakConfig,
+ paragraphConfig,
+ isParagraphFirstShapedText,
+
+ breakPointType,
+ defaultSpanMetrics
+ );
+ }
+}
+function _appendFittingGlyphs(
+ ctx: ILayoutContext,
+ glyphGroup: IDocumentSkeletonGlyph[],
+ pages: IDocumentSkeletonPage[],
+ sectionBreakConfig: ISectionBreakConfig,
+ paragraphConfig: IParagraphConfig,
+ isParagraphFirstShapedText: boolean,
+ divide: IDocumentSkeletonDivide,
+ preOffsetLeft: number,
+ breakPointType: BreakPointType,
+ defaultSpanMetrics?: IDefaultSpanMetrics
+): void {
+ const lastPage = getLastPage(pages);
+ const currentLine = divide.parent;
+ if (currentLine?.parent?.parent && ctx.footnoteLayout && glyphGroup.some((glyph) => glyph.noteId)) {
+ const bodyBottom = currentLine.parent.parent.top + currentLine.top + currentLine.lineHeight;
+ const bodyLimit = ctx.footnoteLayout.getBodyLimit(lastPage, pages, sectionBreakConfig, bodyBottom, glyphGroup);
+ if (bodyBottom > bodyLimit + LINE_LAYOUT_OVERFLOW_TOLERANCE) {
+ const column = currentLine.parent;
+ const cachedGlyphs = __getGlyphGroupByLine(currentLine);
+ column.lines.pop();
+ const previousLine = column.lines[column.lines.length - 1];
+ const previousBottom = column.parent!.top + (previousLine == null ? 0 : previousLine.top + previousLine.lineHeight);
+ ctx.footnoteLayout.getBodyLimit(lastPage, pages, sectionBreakConfig, previousBottom);
+ _pageOperator(ctx, [...cachedGlyphs, ...glyphGroup], pages, sectionBreakConfig, paragraphConfig, currentLine.paragraphStart, breakPointType, defaultSpanMetrics);
+ return;
+ }
+ }
+ const lineGlyphs = currentLine ? __getGlyphGroupByLine(currentLine) : [];
+ if (currentLine?.parent &&
+ isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy) &&
+ __isPositionedCustomBlockOnlyLine(lineGlyphs, paragraphConfig.paragraphNonInlineSkeDrawings) &&
+ glyphGroup.some((glyph) => glyph.streamType === DataStreamTreeTokenType.PARAGRAPH && glyph.bBox.ba + glyph.bBox.bd > 0) &&
+ ctx.viewModel.getSelfOrHeaderFooterViewModel(lastPage.segmentId).getParagraph(paragraphConfig.paragraphIndex) != null) {
+ // The mark can arrive after a heightless anchor fragment. Re-layout the
+ // complete paragraph so its real height also participates in pagination.
+ currentLine.parent.lines.pop();
+ _lineOperator(ctx, [...lineGlyphs, ...glyphGroup], pages, sectionBreakConfig, paragraphConfig, currentLine.paragraphStart, breakPointType);
+ return;
+ }
+
+ if (currentLine?.parent && __isNullLine(currentLine) && __hasFlowGlyph(glyphGroup)) {
+ const cachedGlyphs = __getGlyphGroupByLine(currentLine);
+ if (cachedGlyphs.length > 0 && cachedGlyphs.every((glyph) => glyph.streamType === DataStreamTreeTokenType.PAGE_BREAK)) {
+ // A skipped rendered-page hint has no font metrics. Let the first real text
+ // establish its line, including normal font leading and available page height.
+ currentLine.parent.lines.pop();
+ _lineOperator(ctx, [...cachedGlyphs, ...glyphGroup], pages, sectionBreakConfig, paragraphConfig, currentLine.paragraphStart, breakPointType, defaultSpanMetrics);
+ return;
+ }
+ }
+
+ if (
+ currentLine &&
+ __isPositionedCustomBlockOnlyLine(lineGlyphs, paragraphConfig.paragraphNonInlineSkeDrawings) &&
+ __hasFlowGlyph(glyphGroup)
+ ) {
+ for (const lineDivide of currentLine.divides) {
+ updateDivideInfo(lineDivide, {
+ isFull: true,
+ });
+ }
+ _lineOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, false, breakPointType);
+ return;
+ }
+
+ const reflowMetrics = currentLine
+ ? _getExpandedLineMetrics(currentLine, lineGlyphs, glyphGroup, sectionBreakConfig, paragraphConfig)
+ : undefined;
+ if (currentLine && reflowMetrics) {
+ // Rebuild the complete line with the incoming run's metrics.
+ const spanGroupCached = lineGlyphs;
+ const spanGroupCachedLen = spanGroupCached.length;
+ let newGlyphGroup = [];
+ let startIndex = 1;
+
+ if (spanGroupCachedLen > 2 && spanGroupCached[0].glyphType === GlyphType.LIST) {
+ newGlyphGroup = [spanGroupCached[0], spanGroupCached[1]];
+ startIndex = 2;
+ } else {
+ newGlyphGroup = [spanGroupCached[0]];
+ }
+ const column = currentLine.parent!;
+
+ const { paragraphStart: lineIsStart } = column.lines.pop()!; // Delete the previous line and recalculate according to the maximum content height
+
+ _lineOperator(
+ ctx,
+ newGlyphGroup,
+ pages,
+ sectionBreakConfig,
+ paragraphConfig,
+ lineIsStart,
+
+ breakPointType,
+ reflowMetrics
+ );
+
+ for (let i = startIndex; i < spanGroupCached.length; i++) {
+ // TODO: @jocs Here you may see non-breakpoints appearing at the end of the line.
+ _divideOperator(
+ ctx,
+ [spanGroupCached[i]],
+ pages,
+ sectionBreakConfig,
+ paragraphConfig,
+ isParagraphFirstShapedText,
+ BreakPointType.Normal,
+ reflowMetrics
+ );
+ }
+
+ // Replaying a zero-height page hint can rebuild the line again.
+ // Keep the complete mixed-run metrics throughout that replay.
+ _divideOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType, reflowMetrics);
+
+ return;
+ }
+
+ if (currentLine?.parent) {
+ const anchorDrawings = __getZeroWidthNonFlowFloatingAnchorDrawings(glyphGroup, paragraphConfig.paragraphNonInlineSkeDrawings);
+ if (anchorDrawings.length > 0) {
+ const paragraphAnchorLeft = __getParagraphAnchorLeft(sectionBreakConfig, paragraphConfig, paragraphConfig.paragraphStyle?.indentStart);
+ const drawings = __getDrawingPosition(
+ ctx,
+ currentLine.top,
+ currentLine.lineHeight,
+ currentLine.parent,
+ true,
+ paragraphConfig.pDrawingAnchor?.get(paragraphConfig.paragraphIndex)?.top,
+ anchorDrawings,
+ paragraphAnchorLeft,
+ false
+ );
+ __updateDrawingPosition(currentLine.parent, drawings);
addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
updateDivideInfo(divide, { breakType: breakPointType });
+ glyphGroup.length = 0;
+ return;
}
- } else {
- _lineOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType, defaultSpanMetrics);
}
+
+ addGlyphToDivide(divide, glyphGroup, preOffsetLeft);
+ updateDivideInfo(divide, { breakType: breakPointType });
+}
+
+function _getExpandedLineMetrics(
+ currentLine: IDocumentSkeletonLine,
+ lineGlyphs: IDocumentSkeletonGlyph[],
+ glyphGroup: IDocumentSkeletonGlyph[],
+ sectionBreakConfig: ISectionBreakConfig,
+ paragraphConfig: IParagraphConfig
+): IDefaultSpanMetrics | undefined {
+ if (__isNullLine(currentLine) || !__hasFlowGlyph(lineGlyphs)
+ || isNonFlowFloatingAnchor(glyphGroup, paragraphConfig.paragraphNonInlineSkeDrawings)) {
+ return;
+ }
+ const maxBox = getGlyphGroupFontBoundingBox(paragraphConfig.documentCompatibilityPolicy, lineGlyphs, glyphGroup);
+ const { paragraphLineGapDefault, linePitch, lineSpacing, spacingRule, snapToGrid, gridType } =
+ getLineHeightConfig(sectionBreakConfig, paragraphConfig);
+ const { boundingBoxAscent, boundingBoxDescent } = maxBox;
+ const { normalLineHeight: visibleNormalLineHeight, boundingBoxAscent: visibleAscent, boundingBoxDescent: visibleDescent } = getGlyphGroupFontBoundingBox(
+ paragraphConfig.documentCompatibilityPolicy,
+ lineGlyphs.filter((glyph) => !__isStructuralTerminatorGlyph(glyph)),
+ glyphGroup.filter((glyph) => !__isStructuralTerminatorGlyph(glyph))
+ );
+ const spanLineHeight = boundingBoxAscent + boundingBoxDescent;
+ const hasInlineCustomBlock = [lineGlyphs, glyphGroup].some((group) => group.some((glyph) =>
+ glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width !== 0
+ ));
+ const hasListGlyph = isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)
+ && [lineGlyphs, glyphGroup].some((group) => group.some((glyph) => glyph.glyphType === GlyphType.LIST));
+ const normalLineHeight = hasListGlyph
+ ? getListTextLineHeight(paragraphConfig.documentCompatibilityPolicy, lineGlyphs, glyphGroup)
+ : visibleNormalLineHeight;
+ const drawingMLLineHeight = getDrawingMLNominalLineHeight([...lineGlyphs, ...glyphGroup], sectionBreakConfig, hasInlineCustomBlock);
+ const { contentHeight, paddingTop, paddingBottom } = getLineHeightMetrics(
+ spanLineHeight,
+ paragraphLineGapDefault,
+ linePitch,
+ gridType,
+ lineSpacing,
+ spacingRule,
+ snapToGrid,
+ paragraphConfig.useWordStyleLineHeight,
+ !hasInlineCustomBlock && !hasListGlyph,
+ hasInlineCustomBlock && !isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)
+ ? undefined
+ : normalLineHeight || undefined,
+ false,
+ drawingMLLineHeight
+ );
+
+ // Extra font leading can change the line extent without changing its
+ // font box. Keep the existing font-box tolerance for paragraph marks.
+ const expandsFontLeading = spacingRule !== SpacingRule.EXACT && (normalLineHeight > spanLineHeight || hasInlineCustomBlock || hasListGlyph || drawingMLLineHeight != null) &&
+ contentHeight + paddingTop + paddingBottom - currentLine.contentHeight -
+ currentLine.paddingTop - currentLine.paddingBottom +
+ (currentLine.borderTopSpace ?? 0) + (currentLine.borderBottomSpace ?? 0) > 1e-6;
+ const paragraphEnd = (paragraphConfig.borderBottomSpace ?? 0) > 0 &&
+ (lineGlyphs.some((glyph) => glyph.streamType === DataStreamTreeTokenType.PARAGRAPH) ||
+ glyphGroup.some((glyph) => glyph.streamType === DataStreamTreeTokenType.PARAGRAPH));
+ const expandsBorder = paragraphEnd && (paragraphConfig.borderBottomSpace ?? 0) > (currentLine.borderBottomSpace ?? 0);
+ const expandsVisibleText = isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)
+ && visibleAscent + visibleDescent - currentLine.contentHeight > 1e-6;
+
+ if (contentHeight - currentLine.contentHeight > LINE_LAYOUT_OVERFLOW_TOLERANCE || expandsVisibleText || expandsFontLeading || expandsBorder) {
+ return {
+ lineHeight: boundingBoxAscent + boundingBoxDescent,
+ hasInlineCustomBlock,
+ hasListGlyph,
+ normalLineHeight: normalLineHeight || undefined,
+ drawingMLLineHeight,
+ paragraphEnd,
+ };
+ }
+}
+
+function getParagraphTabStops(
+ ctx: ILayoutContext,
+ sectionBreakConfig: ISectionBreakConfig,
+ paragraphConfig: IParagraphConfig
+): ITabStop[] | undefined {
+ const style = paragraphConfig.paragraphStyle;
+ const stops = style?.tabStops;
+ const noTabHangInd = ctx.dataModel.documentStyle.compatibilityFlags?.noTabHangInd;
+ if (!isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy) ||
+ noTabHangInd === BooleanNumber.TRUE || !style?.hanging?.v) {
+ return stops;
+ }
+ const { charSpace, defaultTabStop } = getCharSpaceConfig(sectionBreakConfig, paragraphConfig);
+ const step = getCharSpaceApply(charSpace, defaultTabStop, sectionBreakConfig.gridType, style.snapToGrid);
+ const hanging = getNumberUnitValue(style.hanging, step);
+ const offset = getNumberUnitValue(style.indentStart, step);
+ if (hanging <= 0 || !Number.isFinite(offset) || stops?.some((stop) => !stop.clear && stop.offset === offset)) {
+ return stops;
+ }
+ // Word treats the hanging-indent position as a custom stop, ahead of the default grid.
+ return [...(stops ?? []), { offset, alignment: TabStopAlignment.START }];
+}
+
+function _adjustIncomingTabStops(
+ divide: IDocumentSkeletonDivide,
+ glyphs: IDocumentSkeletonGlyph[],
+ offsetLeft: number,
+ sectionBreakConfig: ISectionBreakConfig,
+ paragraphConfig: IParagraphConfig,
+ tabStops = paragraphConfig.paragraphStyle?.tabStops
+): void {
+ if (!isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy) ||
+ !glyphs.some((glyph) => glyph.glyphType === GlyphType.TAB)) {
+ return;
+ }
+ const { charSpace, defaultTabStop } = getCharSpaceConfig(sectionBreakConfig, paragraphConfig);
+ const step = getCharSpaceApply(charSpace, defaultTabStop, sectionBreakConfig.gridType, paragraphConfig.paragraphStyle?.snapToGrid);
+ if (!Number.isFinite(step) || step <= 0) {
+ return;
+ }
+ let position = divide.left + divide.paddingLeft + offsetLeft;
+ for (const glyph of glyphs) {
+ const positionedWidth = glyph.ts?.positionedTab == null
+ ? undefined
+ : getPositionedTabWidth(divide, glyph, position - divide.left - divide.paddingLeft);
+ if (positionedWidth != null && positionedWidth > 0) {
+ glyph.width = positionedWidth;
+ glyph.bBox.width = positionedWidth;
+ } else if (glyph.glyphType === GlyphType.TAB && glyph.ts?.positionedTab == null) {
+ const stop = tabStops?.filter((stop) => !stop.clear && stop.offset > position)
+ .sort((left, right) => left.offset - right.offset)[0];
+ // Resolve before fitting: a provisional default-width tab can create a false line break.
+ if (stop) {
+ const followingWidth = glyph.tabAlignedTextWidth ?? 0;
+ let alignmentOffset = 0;
+ if (stop.alignment === TabStopAlignment.END) {
+ alignmentOffset = followingWidth;
+ } else if (stop.alignment === TabStopAlignment.CENTER) {
+ alignmentOffset = followingWidth / 2;
+ }
+ const width = Math.min(stop.offset, divide.left + divide.paddingLeft + divide.width)
+ - position - alignmentOffset;
+ if (width > 0) {
+ glyph.width = width;
+ glyph.tabLeader = stop.leader;
+ }
+ } else {
+ // Default stops are a grid measured from the column/cell origin, not fixed-width spaces.
+ glyph.width = (Math.floor(position / step) + 1) * step - position;
+ }
+ glyph.bBox.width = glyph.width;
+ }
+ position += glyph.width;
+ }
+}
+
+function getPositionedTabWidth(divide: IDocumentSkeletonDivide, tabGlyph: IDocumentSkeletonGlyph, offset: number): number | undefined {
+ const positionedTab = tabGlyph.ts?.positionedTab;
+ const line = divide.parent;
+ if (positionedTab == null || line?.parent == null) {
+ return;
+ }
+ const columnWidth = line.parent.width;
+ const start = positionedTab.relativeTo === 'indent' ? line.paragraphPaddingLeft ?? 0 : 0;
+ const end = columnWidth - (positionedTab.relativeTo === 'indent' ? line.paragraphPaddingRight ?? 0 : 0);
+ const followingWidth = tabGlyph.tabAlignedTextWidth ?? 0;
+ let target = start;
+ if (positionedTab.alignment === TabStopAlignment.END) {
+ target = end - followingWidth;
+ } else if (positionedTab.alignment === TabStopAlignment.CENTER) {
+ target = (start + end - followingWidth) / 2;
+ }
+ return target - divide.left - divide.paddingLeft - offset;
}
function _adjustExplicitTabStop(
divide: IDocumentSkeletonDivide,
followingGlyphs: IDocumentSkeletonGlyph[],
- paragraphConfig: IParagraphConfig
+ paragraphConfig: IParagraphConfig,
+ tabStops = paragraphConfig.paragraphStyle?.tabStops
): void {
- const tabGlyph = divide.glyphGroup[divide.glyphGroup.length - 1];
+ let tabIndex = divide.glyphGroup.length - 1;
+ while (tabIndex >= 0 && isCustomRangeMarker(divide.glyphGroup[tabIndex])) {
+ tabIndex -= 1;
+ }
+ const tabGlyph = divide.glyphGroup[tabIndex];
if (tabGlyph?.glyphType !== GlyphType.TAB) {
return;
}
+ const previousWidth = tabGlyph.width;
+
+ const positionedTab = tabGlyph.ts?.positionedTab;
+ if (positionedTab != null) {
+ const width = getPositionedTabWidth(divide, tabGlyph, tabGlyph.left);
+ if (width != null && width > 0) {
+ tabGlyph.width = width;
+ tabGlyph.bBox.width = width;
+ tabGlyph.tabLeader = positionedTab.leader;
+ shiftTrailingRangeMarkers(divide.glyphGroup, tabIndex, width - previousWidth);
+ }
+ return;
+ }
+
+ if (!tabStops?.length) {
+ return;
+ }
+
+ const origin = isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)
+ ? divide.left + divide.paddingLeft
+ : 0;
+ const tabLeft = origin + tabGlyph.left;
+ const tabStop = [...tabStops]
+ .sort((left, right) => left.offset - right.offset)
+ .find(({ offset, clear }) => !clear && offset > tabLeft);
+ if (!tabStop) {
+ return;
+ }
+
+ const followingWidth = tabGlyph.tabAlignedTextWidth
+ ?? followingGlyphs.reduce((width, glyph) => width + glyph.width, 0);
+
+ const alignmentOffset = tabStop.alignment === TabStopAlignment.END
+ ? followingWidth
+ : tabStop.alignment === TabStopAlignment.CENTER
+ ? followingWidth / 2
+ : 0;
+ const targetOffset = Math.min(tabStop.offset, origin + divide.width);
+ const width = targetOffset - tabLeft - alignmentOffset;
+ if (width <= 0) {
+ return;
+ }
+
+ tabGlyph.width = width;
+ tabGlyph.bBox.width = width;
+ tabGlyph.tabLeader = tabStop.leader;
+ shiftTrailingRangeMarkers(divide.glyphGroup, tabIndex, width - previousWidth);
+}
+
+function isCustomRangeMarker(glyph: IDocumentSkeletonGlyph | undefined): boolean {
+ return glyph?.width === 0 &&
+ (glyph.raw === DataStreamTreeTokenType.CUSTOM_RANGE_START || glyph.raw === DataStreamTreeTokenType.CUSTOM_RANGE_END);
+}
+
+function shiftTrailingRangeMarkers(glyphs: IDocumentSkeletonGlyph[], tabIndex: number, delta: number): void {
+ if (!delta) {
+ return;
+ }
+ for (let index = tabIndex + 1; index < glyphs.length; index += 1) {
+ glyphs[index].left += delta;
+ }
+}
+
+function getListTextLineHeight(
+ policy: IParagraphConfig['documentCompatibilityPolicy'],
+ ...groups: IDocumentSkeletonGlyph[][]
+): number {
+ // Word expands the line to fit the marker, but scales extra leading by the text font.
+ const metrics = getGlyphGroupFontBoundingBox(policy, ...groups.map((group) => group.filter((glyph) => glyph.glyphType !== GlyphType.LIST)));
+ return Math.max(metrics.normalLineHeight, metrics.boundingBoxAscent + metrics.boundingBoxDescent);
+}
+
+function _getStructuralLineFlags(
+ ctx: ILayoutContext,
+ glyphGroup: IDocumentSkeletonGlyph[],
+ lastPage: IDocumentSkeletonPage,
+ paragraphConfig: IParagraphConfig,
+ isParagraphFirstShapedText: boolean,
+ preLine: IDocumentSkeletonLine | undefined
+) {
+ const { paragraphStyle: originParagraphStyle = {}, paragraphNonInlineSkeDrawings, skeTablesInParagraph, paragraphIndex } = paragraphConfig;
+ // Floating objects do not consume a line, but their authored paragraph mark does.
+ // A temporary anchor fragment preceding text in the same paragraph has no such mark.
+ const hasAuthoredParagraphMark = isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy) &&
+ glyphGroup.some((glyph) => glyph.streamType === DataStreamTreeTokenType.PARAGRAPH && glyph.bBox.ba + glyph.bBox.bd > 0) &&
+ ctx.viewModel.getSelfOrHeaderFooterViewModel(lastPage.segmentId).getParagraph(paragraphIndex) != null;
+ const isZeroWidthNonFlowFloatingAnchorLine = !hasAuthoredParagraphMark &&
+ isNonFlowFloatingAnchor(glyphGroup, paragraphNonInlineSkeDrawings);
+ // Imported tables have a structural terminator in addition to any authored following paragraph.
+ const isStructuralTableAnchorLine = isParagraphFirstShapedText &&
+ isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy!) &&
+ (skeTablesInParagraph?.length ?? 0) > 0 &&
+ glyphGroup.length > 0 &&
+ glyphGroup.every(__isStructuralTerminatorGlyph) &&
+ ctx.viewModel.getSelfOrHeaderFooterViewModel(lastPage.segmentId).getParagraph(paragraphIndex) == null;
+ // A frame's table continuation is structural, but authored blank paragraphs
+ // elsewhere in the same frame still contribute their normal spacing.
+ const isEmptyFramedParagraph = isParagraphFirstShapedText &&
+ isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy!) &&
+ (originParagraphStyle.paragraphFrame === BooleanNumber.TRUE ||
+ (originParagraphStyle.paragraphFrame != null && typeof originParagraphStyle.paragraphFrame === 'object' &&
+ (skeTablesInParagraph?.length ?? 0) > 0)) &&
+ glyphGroup.length > 0 &&
+ glyphGroup.every(__isStructuralTerminatorGlyph);
+ // A standalone manual page boundary must not overflow as an empty line
+ // before the break is applied. Authored blank paragraphs remain normal lines.
+ const isStandalonePageBoundary = isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy) &&
+ !(lastPage.type === DocumentSkeletonPageType.CELL && preLine == null &&
+ glyphGroup.some((glyph) => __isStructuralTerminatorGlyph(glyph) && glyph.bBox.ba + glyph.bBox.bd > 0)) &&
+ paragraphConfig.bulletSkeleton == null &&
+ glyphGroup.some((glyph) => glyph.raw === DataStreamTreeTokenType.PAGE_BREAK) &&
+ glyphGroup.every((glyph) => glyph.raw === DataStreamTreeTokenType.PAGE_BREAK || __isStructuralTerminatorGlyph(glyph));
+ return { hasAuthoredParagraphMark, isZeroWidthNonFlowFloatingAnchorLine, isStructuralTableAnchorLine, isEmptyFramedParagraph, isStandalonePageBoundary };
+}
+
+function _isPositionedCustomBlockOnly(
+ glyphGroup: IDocumentSkeletonGlyph[],
+ paragraphNonInlineSkeDrawings: IParagraphConfig['paragraphNonInlineSkeDrawings'],
+ hasAuthoredParagraphMark: boolean
+): boolean {
+ return !hasAuthoredParagraphMark && glyphGroup.length > 0 &&
+ paragraphNonInlineSkeDrawings != null &&
+ paragraphNonInlineSkeDrawings.size > 0 &&
+ glyphGroup.every((glyph) => {
+ if (!glyph) {
+ return false;
+ }
- const tabStops = paragraphConfig.paragraphStyle?.tabStops;
- if (!tabStops?.length) {
- return;
- }
+ if (glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK) {
+ return [...paragraphNonInlineSkeDrawings.values()].some((drawing) => drawing.drawingId === glyph.drawingId);
+ }
- const tabStop = [...tabStops]
- .sort((left, right) => left.offset - right.offset)
- .find(({ offset }) => offset > tabGlyph.left);
- if (!tabStop) {
- return;
- }
+ return glyph.streamType === DataStreamTreeTokenType.PARAGRAPH || glyph.raw === DataStreamTreeTokenType.PARAGRAPH;
+ });
+}
- let followingWidth = 0;
- for (const glyph of followingGlyphs) {
- followingWidth += glyph.width;
- }
+function _shouldSuppressPageTopSpacing(
+ lastPage: IDocumentSkeletonPage,
+ column: IDocumentSkeletonColumn,
+ paragraphConfig: IParagraphConfig,
+ preLine: IDocumentSkeletonLine | undefined,
+ firstPageNumber: number,
+ startsSection: boolean
+): boolean {
+ return isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy!) &&
+ lastPage.pageNumber > firstPageNumber &&
+ !startsSection &&
+ lastPage.type !== DocumentSkeletonPageType.HEADER &&
+ lastPage.type !== DocumentSkeletonPageType.FOOTER &&
+ (!paragraphConfig.isInsideTable || lastPage.type === DocumentSkeletonPageType.CELL) &&
+ (preLine == null || (preLine.top === 0 && preLine.lineHeight === 0 &&
+ !__hasFlowGlyph(__getGlyphGroupByLine(preLine)))) &&
+ (column.parent?.top ?? 0) === 0;
+}
- const alignmentOffset = tabStop.alignment === TabStopAlignment.END
- ? followingWidth
- : tabStop.alignment === TabStopAlignment.CENTER
- ? followingWidth / 2
- : 0;
- const targetOffset = Math.min(tabStop.offset, divide.width);
- const width = targetOffset - tabGlyph.left - alignmentOffset;
- if (width <= 0) {
- return;
+function _collapseSectionBeforeSpacing(ctx: ILayoutContext, previousParagraphIndex: number, marginTop: number): number {
+ // Word collapses before-spacing against the preceding section's final paragraph.
+ for (let index = ctx.skeleton.pages.length - 1; index >= 0; index--) {
+ const previousPage = ctx.skeleton.pages[index];
+ const previousColumns = getLastSection(previousPage)?.columns ?? [];
+ const previousLine = previousColumns.slice().reverse().map(getLastLineByColumn).find((line) => line != null);
+ if (previousLine) {
+ return previousLine.paragraphIndex === previousParagraphIndex
+ ? Math.max(0, marginTop - previousLine.spaceBelowApply)
+ : marginTop;
+ }
}
+ return marginTop;
+}
- tabGlyph.width = width;
- tabGlyph.bBox.width = width;
- tabGlyph.tabLeader = tabStop.leader;
+function _snapPreviousParagraphLineToGrid(
+ preLine: IDocumentSkeletonLine | undefined,
+ paragraphConfig: IParagraphConfig,
+ lineConfig: ReturnType<typeof getLineHeightConfig>,
+ snapMultilineParagraphToWholeGrid: boolean
+) {
+ const { paragraphIndex } = paragraphConfig;
+ const { paragraphLineGapDefault, linePitch, gridType, lineSpacing, spacingRule, snapToGrid } = lineConfig;
+ if (snapMultilineParagraphToWholeGrid && preLine?.paragraphIndex === paragraphIndex) {
+ const preLineGlyphs = __getGlyphGroupByLine(preLine);
+ const preLineHasInlineCustomBlock = preLineGlyphs.some(
+ (glyph) => glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width !== 0
+ );
+ if (__hasFlowGlyph(preLineGlyphs) && !preLineHasInlineCustomBlock) {
+ const preLineMetrics = getLineHeightMetrics(
+ preLine.contentHeight,
+ paragraphLineGapDefault,
+ linePitch,
+ gridType,
+ lineSpacing,
+ spacingRule,
+ snapToGrid,
+ paragraphConfig.useWordStyleLineHeight,
+ true,
+ undefined,
+ true
+ );
+ const heightDelta = preLineMetrics.lineSpacingApply -
+ (preLine.paddingTop + preLine.contentHeight + preLine.paddingBottom);
+ if (heightDelta > LINE_LAYOUT_OVERFLOW_TOLERANCE) {
+ preLine.paddingTop += heightDelta / 2;
+ preLine.paddingBottom += heightDelta / 2;
+ preLine.lineHeight += heightDelta;
+ }
+ }
+ }
}
-function _getParagraphLineMetrics(
+function _getParagraphContentMetrics(
ctx: ILayoutContext,
glyphGroup: IDocumentSkeletonGlyph[],
lastPage: IDocumentSkeletonPage,
@@ -676,22 +1285,28 @@ function _getParagraphLineMetrics(
defaultSpanMetrics?: IDefaultSpanMetrics
) {
const preLine = getLastLineByColumn(column);
- const ascent = Math.max(...glyphGroup.map((glyph) => glyph.bBox.ba));
- const descent = Math.max(...glyphGroup.map((glyph) => glyph.bBox.bd));
- const glyphLineHeight = defaultSpanMetrics?.lineHeight || (ascent + descent);
- const normalLineHeight = Math.max(...glyphGroup.map((glyph) => glyph.bBox.normalLineHeight ?? 0)) || undefined;
+
+ const { boundingBoxAscent, boundingBoxDescent, normalLineHeight: glyphNormalLineHeight } = getGlyphGroupFontBoundingBox(
+ paragraphConfig.documentCompatibilityPolicy,
+ glyphGroup
+ );
+ const glyphLineHeight = defaultSpanMetrics?.lineHeight || (boundingBoxAscent + boundingBoxDescent);
+ const hasListGlyph = isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)
+ && (defaultSpanMetrics?.hasListGlyph || glyphGroup.some((glyph) => glyph.glyphType === GlyphType.LIST));
+ const normalLineHeight = Math.max(
+ defaultSpanMetrics?.normalLineHeight ?? 0,
+ hasListGlyph ? getListTextLineHeight(paragraphConfig.documentCompatibilityPolicy, glyphGroup) : glyphNormalLineHeight
+ ) || undefined;
+ const ascent = boundingBoxAscent;
+ const descent = boundingBoxDescent;
const {
paragraphStyle: originParagraphStyle = {},
paragraphNonInlineSkeDrawings,
- skeTablesInParagraph,
paragraphIndex,
} = paragraphConfig;
- const isZeroWidthNonFlowFloatingAnchorLine = __isZeroWidthNonFlowFloatingAnchorLine(glyphGroup, paragraphNonInlineSkeDrawings);
- const isSyntheticTableAnchorLine = isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy!) &&
- skeTablesInParagraph?.some(({ table }) => table.tableSource.textWrap === TableTextWrapType.NONE) === true &&
- ctx.viewModel.getSelfOrHeaderFooterViewModel(lastPage.segmentId).getParagraph(paragraphIndex) == null &&
- glyphGroup.every((glyph) => glyph.streamType === DataStreamTreeTokenType.PARAGRAPH || glyph.streamType === DataStreamTreeTokenType.SECTION_BREAK);
+ const { hasAuthoredParagraphMark, isZeroWidthNonFlowFloatingAnchorLine, isStructuralTableAnchorLine, isEmptyFramedParagraph, isStandalonePageBoundary } =
+ _getStructuralLineFlags(ctx, glyphGroup, lastPage, paragraphConfig, isParagraphFirstShapedText, preLine);
const { namedStyleType } = originParagraphStyle;
const namedStyle = namedStyleType !== undefined ? NAMED_STYLE_SPACE_MAP[namedStyleType] : null;
const paragraphStyle = {
@@ -723,20 +1338,9 @@ function _getParagraphLineMetrics(
!hasInlineCustomBlock &&
reachesNextDocumentGridLine(lineSpacing, getNumberUnitValue(spaceBelow, lineSpacing), linePitch) &&
isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy!);
- const positionedCustomBlockOnly = glyphGroup.length > 0 &&
- paragraphNonInlineSkeDrawings != null &&
- paragraphNonInlineSkeDrawings.size > 0 &&
- glyphGroup.every((glyph) => {
- if (!glyph) {
- return false;
- }
-
- if (glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK) {
- return [...paragraphNonInlineSkeDrawings.values()].some((drawing) => drawing.drawingId === glyph.drawingId);
- }
-
- return glyph.streamType === DataStreamTreeTokenType.PARAGRAPH || glyph.raw === DataStreamTreeTokenType.PARAGRAPH;
- });
+ const positionedCustomBlockOnly = _isPositionedCustomBlockOnly(glyphGroup, paragraphNonInlineSkeDrawings, hasAuthoredParagraphMark);
+ const drawingMLLineHeight = defaultSpanMetrics?.drawingMLLineHeight ??
+ getDrawingMLNominalLineHeight(glyphGroup, sectionBreakConfig, hasInlineCustomBlock);
let { paddingTop, paddingBottom, contentHeight, lineSpacingApply } = getLineHeightMetrics(
glyphLineHeight,
paragraphLineGapDefault,
@@ -746,40 +1350,42 @@ function _getParagraphLineMetrics(
spacingRule,
snapToGrid,
paragraphConfig.useWordStyleLineHeight,
- !hasInlineCustomBlock,
- normalLineHeight,
- snapMultilineParagraphToWholeGrid
+ !hasInlineCustomBlock && !hasListGlyph,
+ hasInlineCustomBlock && !isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)
+ ? undefined
+ : normalLineHeight,
+ snapMultilineParagraphToWholeGrid || (
+ hasInlineCustomBlock && isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy!)
+ ),
+ drawingMLLineHeight
);
-
- if (snapMultilineParagraphToWholeGrid && preLine?.paragraphIndex === paragraphIndex) {
- const preLineGlyphs = __getGlyphGroupByLine(preLine);
- const preLineHasInlineCustomBlock = preLineGlyphs.some(
- (glyph) => glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width !== 0
- );
- if (__hasFlowGlyph(preLineGlyphs) && !preLineHasInlineCustomBlock) {
- const preLineMetrics = getLineHeightMetrics(
- preLine.contentHeight,
- paragraphLineGapDefault,
- linePitch,
- gridType,
- lineSpacing,
- spacingRule,
- snapToGrid,
- paragraphConfig.useWordStyleLineHeight,
- true,
- undefined,
- true
- );
- const heightDelta = preLineMetrics.lineSpacingApply -
- (preLine.paddingTop + preLine.contentHeight + preLine.paddingBottom);
- if (heightDelta > LINE_LAYOUT_OVERFLOW_TOLERANCE) {
- preLine.paddingTop += heightDelta / 2;
- preLine.paddingBottom += heightDelta / 2;
- preLine.lineHeight += heightDelta;
- }
- }
+ const wordAutoLeading = isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)
+ && spacingRule === SpacingRule.AUTO && lineSpacing > 1 && !hasInlineCustomBlock
+ && (snapToGrid === BooleanNumber.FALSE || (gridType !== GridType.LINES && gridType !== GridType.LINES_AND_CHARS))
+ ? Math.max(0, lineSpacingApply - contentHeight)
+ : 0;
+ if (wordAutoLeading > 0) {
+ // Word adds multiple-line leading below the font box, not above the first baseline.
+ paddingTop = 0;
+ paddingBottom = wordAutoLeading;
+ }
+ const drawingMLBaselineHeight = !positionedCustomBlockOnly && !isZeroWidthNonFlowFloatingAnchorLine &&
+ drawingMLLineHeight != null && (spacingRule === SpacingRule.EXACT || (spacingRule === SpacingRule.AUTO && lineSpacing > 1)) &&
+ (snapToGrid === BooleanNumber.FALSE || (gridType !== GridType.LINES && gridType !== GridType.LINES_AND_CHARS))
+ ? lineSpacingApply
+ : undefined;
+ if (drawingMLBaselineHeight != null) {
+ paddingTop = getDrawingMLLineBaseline(drawingMLBaselineHeight, ascent, descent) - ascent;
+ paddingBottom = lineSpacingApply - contentHeight - paddingTop;
}
+ _snapPreviousParagraphLineToGrid(
+ preLine,
+ paragraphConfig,
+ getLineHeightConfig(sectionBreakConfig, paragraphConfig),
+ snapMultilineParagraphToWholeGrid
+ );
+
if (positionedCustomBlockOnly) {
paddingTop = 0;
paddingBottom = 0;
@@ -787,25 +1393,108 @@ function _getParagraphLineMetrics(
lineSpacingApply = 0.01;
}
- let { marginTop, spaceBelowApply } = __getParagraphSpace(
- ctx,
- lineSpacingApply,
+ return {
+ preLine,
+ paragraphIndex,
+ paragraphStyle,
spaceAbove,
spaceBelow,
+ spacingRule,
+ gridType,
+ snapToGrid,
+ hasInlineCustomBlock,
+ positionedCustomBlockOnly,
+ drawingMLLineHeight,
+ drawingMLBaselineHeight,
+ isZeroWidthNonFlowFloatingAnchorLine,
+ isStructuralTableAnchorLine,
+ isEmptyFramedParagraph,
+ isStandalonePageBoundary,
+ paddingTop,
+ paddingBottom,
+ contentHeight,
+ lineSpacingApply,
+ wordAutoLeading,
+ };
+}
+
+function _getParagraphLineMetrics(
+ ctx: ILayoutContext,
+ glyphGroup: IDocumentSkeletonGlyph[],
+ lastPage: IDocumentSkeletonPage,
+ column: IDocumentSkeletonColumn,
+ sectionBreakConfig: ISectionBreakConfig,
+ paragraphConfig: IParagraphConfig,
+ isParagraphFirstShapedText: boolean,
+ defaultSpanMetrics?: IDefaultSpanMetrics
+) {
+ const metrics = _getParagraphContentMetrics(
+ ctx,
+ glyphGroup,
+ lastPage,
+ column,
+ sectionBreakConfig,
+ paragraphConfig,
isParagraphFirstShapedText,
- preLine,
- isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy!) &&
- preLine == null &&
- (column.parent?.top ?? 0) === 0
+ defaultSpanMetrics
);
+ const {
+ preLine,
+ paragraphIndex,
+ paragraphStyle,
+ spaceAbove,
+ spaceBelow,
+ spacingRule,
+ gridType,
+ snapToGrid,
+ hasInlineCustomBlock,
+ positionedCustomBlockOnly,
+ drawingMLLineHeight,
+ drawingMLBaselineHeight,
+ isZeroWidthNonFlowFloatingAnchorLine,
+ isStructuralTableAnchorLine,
+ isEmptyFramedParagraph,
+ isStandalonePageBoundary,
+ wordAutoLeading,
+ } = metrics;
+ let { paddingTop, paddingBottom, contentHeight, lineSpacingApply } = metrics;
+
+ const isHiddenParagraph = isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy) &&
+ glyphGroup.length > 0 && glyphGroup.every((glyph) => glyph.ts?.hidden === true);
+ const suppressCellAutoSpaceAbove = lastPage.type === DocumentSkeletonPageType.CELL && preLine == null &&
+ isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy) &&
+ paragraphStyle.beforeAutoSpacing === BooleanNumber.TRUE;
+ const firstPageNumber = lastPage.type === DocumentSkeletonPageType.BODY ? sectionBreakConfig.pageNumberStart ?? 1 : 1;
+ const startingSection = lastPage.type === DocumentSkeletonPageType.BODY && preLine == null
+ ? ctx.viewModel.getChildren().find((section, index) => index > 0 && section.children[0]?.endIndex === paragraphIndex)
+ : undefined;
+ let { marginTop, spaceBelowApply } = isHiddenParagraph
+ ? { marginTop: 0, spaceBelowApply: preLine?.spaceBelowApply ?? 0 }
+ : __getParagraphSpace(
+ sectionBreakConfig.documentCompatibilityPolicy?.mode === 'drawingml',
+ lineSpacingApply,
+ suppressCellAutoSpaceAbove ? undefined : spaceAbove,
+ spaceBelow,
+ isParagraphFirstShapedText,
+ preLine,
+ _shouldSuppressPageTopSpacing(lastPage, column, paragraphConfig, preLine, firstPageNumber, startingSection != null),
+ drawingMLLineHeight
+ );
+
+ if (startingSection && marginTop > 0 && isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)) {
+ marginTop = _collapseSectionBeforeSpacing(ctx, startingSection.children[0].startIndex - 2, marginTop);
+ }
if (positionedCustomBlockOnly) {
spaceBelowApply = 0;
}
- // A table's structural terminator has no Word paragraph. Keep its glyph and
- // character position without adding a blank line after the table.
- if (isZeroWidthNonFlowFloatingAnchorLine || isSyntheticTableAnchorLine) {
+ const isHiddenCellEndMark = lastPage.type === DocumentSkeletonPageType.CELL &&
+ isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy) &&
+ sectionBreakConfig.cellHiddenEndMarkIndex === paragraphIndex &&
+ paragraphConfig.bulletSkeleton == null &&
+ glyphGroup.length > 0 && glyphGroup.every(__isStructuralTerminatorGlyph);
+ if (isZeroWidthNonFlowFloatingAnchorLine || isStructuralTableAnchorLine || isEmptyFramedParagraph || isStandalonePageBoundary || isHiddenCellEndMark) {
paddingTop = 0;
paddingBottom = 0;
contentHeight = 0;
@@ -814,17 +1503,42 @@ function _getParagraphLineMetrics(
spaceBelowApply = 0;
}
+ if (isHiddenParagraph) {
+ // Hidden paragraph marks do not reserve fixed/minimum line spacing.
+ // Carry the preceding visible paragraph's spacing across hidden content.
+ paddingTop = 0;
+ paddingBottom = 0;
+ contentHeight = 0;
+ lineSpacingApply = 0;
+ }
+
+ const firstFlowLine = isParagraphFirstShapedText ||
+ (preLine?.paragraphStart && preLine.paragraphIndex === paragraphIndex && preLine.lineHeight === 0);
+ const borderTopSpace = lineSpacingApply > 0.01 && firstFlowLine ? paragraphConfig.borderTopSpace ?? 0 : 0;
+ const paragraphEnd = (paragraphConfig.borderBottomSpace ?? 0) > 0 &&
+ (defaultSpanMetrics?.paragraphEnd || glyphGroup.some((glyph) => glyph.streamType === DataStreamTreeTokenType.PARAGRAPH));
+ const borderBottomSpace = lineSpacingApply > 0.01 && paragraphEnd ? paragraphConfig.borderBottomSpace ?? 0 : 0;
+ paddingTop += borderTopSpace;
+ paddingBottom += borderBottomSpace;
+
return {
paragraphStyle,
+ spacingRule,
+ drawingMLLineHeight,
+ drawingMLBaselineHeight,
gridType,
snapToGrid,
hasInlineCustomBlock,
positionedCustomBlockOnly,
+ isStandalonePageBoundary,
paddingTop,
paddingBottom,
contentHeight,
marginTop,
spaceBelowApply,
+ borderTopSpace,
+ borderBottomSpace,
+ wordAutoLeading: Math.min(wordAutoLeading, Math.max(0, paddingBottom - borderBottomSpace)),
};
}
@@ -974,6 +1688,8 @@ function _lineOperator(
const preLine = getLastLineByColumn(column);
+ const previousLineHeight = preLine?.lineHeight;
+ const previousLineMarginBottom = preLine?.marginBottom;
const {
paragraphNonInlineSkeDrawings,
skeTablesInParagraph,
@@ -984,15 +1700,22 @@ function _lineOperator(
} = paragraphConfig;
const {
paragraphStyle,
+ spacingRule,
+ drawingMLLineHeight,
+ drawingMLBaselineHeight,
gridType,
snapToGrid,
hasInlineCustomBlock,
positionedCustomBlockOnly,
+ isStandalonePageBoundary,
paddingTop,
paddingBottom,
contentHeight,
marginTop,
spaceBelowApply,
+ borderTopSpace,
+ borderBottomSpace,
+ wordAutoLeading,
} = _getParagraphLineMetrics(ctx, glyphGroup, lastPage, column, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, defaultSpanMetrics);
const { indentFirstLine, hanging, indentStart, indentEnd } = paragraphStyle;
@@ -1074,8 +1797,19 @@ function _lineOperator(
glyphGroup
);
const availableSectionHeight = footnoteBodyLimit == null ? section.height : Math.min(section.height, footnoteBodyLimit - section.top);
+ // An authored empty cell paragraph is spacing content. Its after-spacing
+ // must fit with the paragraph mark, rather than disappearing at the page edge.
+ const emptyCellParagraphSpace = lastPage.type === DocumentSkeletonPageType.CELL &&
+ isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy) &&
+ isParagraphFirstShapedText && glyphGroup.length > 0 &&
+ glyphGroup.every((glyph) => glyph.streamType === DataStreamTreeTokenType.PARAGRAPH)
+ ? Math.max(0, spaceBelowApply)
+ : 0;
+ // Blank multiple-line leading can hang below the last body line. Keep cell
+ // height and painted paragraph borders inside their full layout extent.
+ const trailingLeading = lastPage.type === DocumentSkeletonPageType.BODY && borderBottomSpace === 0 ? wordAutoLeading : 0;
const lineOverflowsSection = !clipsSameParagraphInlineDrawing &&
- lineHeight + newLineTop - availableSectionHeight > LINE_LAYOUT_OVERFLOW_TOLERANCE;
+ lineHeight - trailingLeading + emptyCellParagraphSpace + newLineTop - availableSectionHeight > LINE_LAYOUT_OVERFLOW_TOLERANCE;
if (
(lineOverflowsSection &&
@@ -1083,8 +1817,20 @@ function _lineOperator(
lastPage.sections.length > 0) ||
needOpenNewPageByTableLayout
) {
- // Line height exceeds column height, and there is more than one line in the column, and there is more than one section;
- // console.log('_lineOperator', { glyphGroup, pages, lineHeight, newLineTop, sectionHeight: section.height, lastPage });
+ // Cell after-spacing contributes to the fragment's height when it fits.
+ // Never let a trial next paragraph inflate the fragment beyond its capacity.
+ const keepCellAfterSpacing = lastPage.type === DocumentSkeletonPageType.CELL && preLine != null &&
+ preLine.top + preLine.lineHeight <= section.height + LINE_LAYOUT_OVERFLOW_TOLERANCE;
+ if (!keepCellAfterSpacing && preLine && previousLineHeight != null &&
+ isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)) {
+ preLine.lineHeight = previousLineHeight;
+ preLine.marginBottom = previousLineMarginBottom ?? 0;
+ }
+ // A provisional floating-only line may have recorded this paragraph on
+ // the old page before its real mark made the complete first line overflow.
+ if (isParagraphFirstShapedText) {
+ pDrawingAnchor?.delete(paragraphIndex);
+ }
setColumnFullState(column, true);
_columnOperator(
ctx,
@@ -1150,13 +1896,28 @@ function _lineOperator(
column.left,
section.top
);
+ if (drawingMLBaselineHeight != null) {
+ newLine.drawingMLBaselineHeight = drawingMLBaselineHeight;
+ if (spacingRule === SpacingRule.AUTO) {
+ newLine.drawingMLNormalLineHeight = drawingMLLineHeight;
+ }
+ }
column.lines.push(newLine);
newLine.parent = column;
newLine.paragraphPaddingLeft = paragraphPaddingLeft;
newLine.paragraphPaddingRight = paragraphPaddingRight;
+ if (borderTopSpace > 0) {
+ newLine.borderTopSpace = borderTopSpace;
+ }
+ if (borderBottomSpace > 0) {
+ newLine.borderBottomSpace = borderBottomSpace;
+ }
const blockAnchorTop = deferredTopBottomAnchorDrawings.length > 0 ? newLineTop : lineTop;
- createAndUpdateBlockAnchor(paragraphIndex, newLine, blockAnchorTop, pDrawingAnchor);
+ // A leading page break is not the paragraph's content anchor on the destination page.
+ if (!isStandalonePageBoundary) {
+ createAndUpdateBlockAnchor(paragraphIndex, newLine, blockAnchorTop, pDrawingAnchor);
+ }
if (deferredTopBottomAnchorDrawings.length > 0) {
__updateAndPositionDrawings(ctx, newLineTop, lineHeight, column, deferredTopBottomAnchorDrawings, paragraphConfig.paragraphIndex, isParagraphFirstShapedText, blockAnchorTop, paragraphAnchorLeft, false, true);
__updateTopBottomCustomBlockFlowBottom(paragraphConfig, deferredTopBottomAnchorDrawings, section.top);
@@ -1230,6 +1991,10 @@ function __updateAndPositionDrawings(
angle,
behindDoc: drawingOrigin.behindDoc,
layoutType: drawingOrigin.layoutType,
+ effectExtent: drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_SQUARE ||
+ drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM
+ ? drawingOrigin.effectExtent
+ : undefined,
type: FloatObjectType.IMAGE,
positionV,
};
@@ -1298,11 +2063,22 @@ function __getWrapTablePosition(
const { tableSource, width, height } = table;
const { positionH, positionV } = tableSource.position;
- const horizontalPosition = getPositionHorizon(positionH, column, page, width, isPageBreak);
- // Tables render from the body origin; page/margin anchors return page coordinates.
- const pageRelative = positionH.relativeFrom === ObjectRelativeFromH.PAGE || positionH.relativeFrom === ObjectRelativeFromH.MARGIN;
- const left = horizontalPosition == null ? 0 : horizontalPosition - (pageRelative ? page.marginLeft : 0);
- const top = getPositionVertical(
+ // An omitted table offset starts at its anchor, not at the physical page edge.
+ const horizontalPosition = positionH.align == null && positionH.posOffset == null && positionH.percent == null
+ ? { ...positionH, posOffset: 0 }
+ : positionH;
+ // Page and margin anchors use page coordinates; table skeletons use the content origin.
+ const horizontalOrigin = positionH.relativeFrom === ObjectRelativeFromH.PAGE ||
+ positionH.relativeFrom === ObjectRelativeFromH.MARGIN
+ ? page.marginLeft
+ : 0;
+ const computedLeft = (getPositionHorizon(horizontalPosition, column, page, width, isPageBreak) ?? 0) - horizontalOrigin;
+ // Word keeps an oversized, aligned nested table at the cell's content start.
+ // Explicit offsets still allow authored positioning outside that cell.
+ const left = page.type === DocumentSkeletonPageType.CELL && positionH.align != null
+ ? Math.max(0, computedLeft)
+ : computedLeft;
+ const computedTop = getPositionVertical(
positionV,
page,
sectionTop + lineTop,
@@ -1311,6 +2087,12 @@ function __getWrapTablePosition(
drawingAnchorTop == null ? undefined : sectionTop + drawingAnchorTop,
isPageBreak
) ?? 0;
+ const top =
+ page.type === DocumentSkeletonPageType.CELL &&
+ (positionV.relativeFrom === ObjectRelativeFromV.PARAGRAPH ||
+ positionV.relativeFrom === ObjectRelativeFromV.LINE)
+ ? Math.max(0, computedTop)
+ : computedTop;
return { left, top };
}
@@ -1353,6 +2135,33 @@ function __avoidFlowAffectingDrawingsForTable(
}
}
+function __avoidNonOverlappingFloatingTables(
+ table: IDocumentSkeletonTable,
+ page: IDocumentSkeletonPage
+) {
+ for (const floatingTable of page.skeTables.values()) {
+ if (
+ floatingTable.tableSource?.textWrap !== TableTextWrapType.WRAP ||
+ floatingTable.tableSource.overlap !== BooleanNumber.FALSE
+ ) {
+ continue;
+ }
+
+ const tableRight = table.left + table.width;
+ const floatingTableRight = floatingTable.left + floatingTable.width;
+ if (table.left >= floatingTableRight || tableRight <= floatingTable.left) {
+ continue;
+ }
+
+ table.top = Math.max(
+ table.top,
+ floatingTable.top +
+ floatingTable.height +
+ (floatingTable.tableSource.dist?.distB ?? 0)
+ );
+ }
+}
+
function _updateAndPositionTable(
ctx: ILayoutContext,
lineTop: number,
@@ -1386,6 +2195,7 @@ function _updateAndPositionTable(
table.top = section.top + lineTop;
table.left = column.left + getTableLeft(column.width, table.width, tableSource.align, tableSource.indent);
__avoidFlowAffectingDrawingsForTable(table, page, column);
+ __avoidNonOverlappingFloatingTables(table, page);
break;
}
case TableTextWrapType.WRAP: {
@@ -1423,26 +2233,59 @@ function _updateAndPositionTable(
}
}
+ const verticalPosition = tableSource.position?.positionV;
+ const usesPhysicalPageBounds = tableSource.textWrap === TableTextWrapType.WRAP &&
+ verticalPosition?.relativeFrom === ObjectRelativeFromV.PAGE &&
+ (verticalPosition.posOffset != null || verticalPosition.align != null || verticalPosition.percent != null) &&
+ top < 0;
+ const fitsPhysicalPage = usesPhysicalPageBounds &&
+ top + height <= page.pageHeight - page.marginTop + LINE_LAYOUT_OVERFLOW_TOLERANCE;
+ const wordCompatibilityMode = Number(ctx.dataModel?.documentStyle.compatibilitySettings?.compatibilityMode);
+ // Before Word 2013, floating tables remain intact even when they extend
+ // beyond the page. Inline tables and explicitly authored breaks still paginate.
+ const legacyFloatingTable = tableSource.textWrap === TableTextWrapType.WRAP &&
+ wordCompatibilityMode >= 11 && wordCompatibilityMode < 15;
if (
- (localTop + height > section.height || table.hasPageBreak === true) &&
+ (tableSource.textWrap === TableTextWrapType.NONE ||
+ (page.type === DocumentSkeletonPageType.BODY &&
+ isTraditionalDocumentCompatibility(sectionBreakConfig.documentCompatibilityPolicy))) &&
+ ((localTop + height > section.height && !fitsPhysicalPage && !legacyFloatingTable) || table.hasPageBreak === true) &&
firstUnPositionedTable.isSlideTable === false
) {
+ if (tableSource.textWrap === TableTextWrapType.WRAP &&
+ (verticalPosition?.relativeFrom === ObjectRelativeFromV.PARAGRAPH ||
+ verticalPosition?.relativeFrom === ObjectRelativeFromV.LINE) &&
+ table.hasPageBreak !== true && column.lines.length > 0) {
+ const nextPosition = __getWrapTablePosition(table, column, 0, lineHeight, 0);
+ // A text-anchored float that fits a fresh column moves with its anchor;
+ // only oversized floats need the row-slicing path below.
+ if (nextPosition != null && nextPosition.top - section.top + height <= section.height + LINE_LAYOUT_OVERFLOW_TOLERANCE) {
+ return true;
+ }
+ }
// Need split table.
skeTablesInParagraph.pop();
- const availableHeight = section.height - localTop;
+ // A page-edge float can occupy the margins, including when its content
+ // requires slicing. Its first slice must use the same bounds as an intact float.
+ const availableHeight = usesPhysicalPageBounds
+ ? page.pageHeight - page.marginTop - top
+ : section.height - localTop;
+ const tableLayoutPage = usesPhysicalPageBounds ? { ...page, marginTop: 0, marginBottom: 0 } : page;
// TODO: handle nested table.
const { segmentId } = page;
const viewModel = ctx.viewModel.getSelfOrHeaderFooterViewModel(segmentId);
const tableNode = firstUnPositionedTable.tableNode;
- rollbackListCache(ctx.skeletonResourceReference.skeListLevel!, tableNode);
+ // Slicing reuses the measured paragraphs and their bullet cache. Keep the
+ // corresponding list counters so numbering also continues after the table.
+ cachePrecomputedTableSkeleton(ctx, tableNode, table);
const {
fromCurrentPage,
skeTables,
} = createTableSkeletons(
ctx,
- page,
+ tableLayoutPage,
viewModel,
tableNode,
sectionBreakConfig,
@@ -1487,6 +2330,20 @@ function _updateAndPositionTable(
ctx.footnoteLayout?.getTableBodyLimit(page, pages, sectionBreakConfig, table);
firstUnPositionedTable.hasPositioned = true;
+ if (
+ tableSource.textWrap === TableTextWrapType.WRAP &&
+ tableSource.overlap === BooleanNumber.FALSE &&
+ top + height >= section.top + section.height
+ ) {
+ const nextParagraphEnd = ctx.viewModel.getBody()?.dataStream.indexOf(
+ DataStreamTreeTokenType.PARAGRAPH,
+ paragraphIndex + 1
+ );
+ if (nextParagraphEnd != null && nextParagraphEnd >= 0) {
+ ctx.paragraphsOpenNewPage.add(nextParagraphEnd);
+ }
+ }
+
const isLastTable = firstUnPositionedTable === skeTablesInParagraph[skeTablesInParagraph.length - 1];
return !isLastTable;
@@ -1529,10 +2386,10 @@ function __updateTopBottomCustomBlockFlowBottom(
}
}
-function __isZeroWidthNonFlowFloatingAnchorLine(
+export function isNonFlowFloatingAnchor(
glyphGroup: IDocumentSkeletonGlyph[],
paragraphNonInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>
-) {
+): boolean {
return __getZeroWidthNonFlowFloatingAnchorDrawings(glyphGroup, paragraphNonInlineSkeDrawings).length > 0;
}
@@ -1763,7 +2620,9 @@ function checkRelativeDrawingNeedRePosition(ctx: ILayoutContext, floatObject: IF
export const __testing = {
reLayoutCheck: _reLayoutCheck,
+ getWrapTablePosition: __getWrapTablePosition,
avoidFlowAffectingDrawingsForTable: __avoidFlowAffectingDrawingsForTable,
+ avoidNonOverlappingFloatingTables: __avoidNonOverlappingFloatingTables,
isGlyphGroupBeyondDivideWidth,
checkPageBreak: __checkPageBreak,
updateAndPositionTable: _updateAndPositionTable,
@@ -1807,7 +2666,9 @@ function _pageOperator(
ctx,
sectionBreakConfig,
{ skeHeaders, skeFooters },
- curSkeletonPage?.pageNumber + 1
+ curSkeletonPage.pageNumber + 1,
+ undefined,
+ curSkeletonPage
);
nextPage.isNaturalPageOverflow = true;
pages.push(nextPage);
@@ -1850,29 +2711,35 @@ function __getIndentPadding(
}
function __getParagraphSpace(
- ctx: ILayoutContext,
+ isDrawingML: boolean,
lineSpacing: number = 0,
spaceAbove: Nullable<INumberUnit>,
spaceBelow: Nullable<INumberUnit>,
isParagraphFirstShapedText: boolean,
preLine?: IDocumentSkeletonLine,
- suppressSpaceAbove = false
+ suppressSpaceAbove = false,
+ drawingMLLineHeight?: number
) {
// Unable to read the paragraph information from the previous line,
// So add the spaceBelowApply information to each line when creating a new line.
// `SpaceBelowApply` will not participate in the current line height calculation.
- const spaceBelowApply = getNumberUnitValue(spaceBelow, lineSpacing);
+ const spaceBelowApply = getParagraphSpaceValue(spaceBelow, lineSpacing, drawingMLLineHeight);
if (isParagraphFirstShapedText) {
- let marginTop = suppressSpaceAbove ? 0 : getNumberUnitValue(spaceAbove, lineSpacing);
+ let marginTop = suppressSpaceAbove ? 0 : getParagraphSpaceValue(spaceAbove, lineSpacing, drawingMLLineHeight);
if (preLine) {
const { spaceBelowApply: preSpaceBelowApply } = preLine;
- if (marginTop < preSpaceBelowApply) {
+ if (isDrawingML) {
+ // DrawingML adds adjacent paragraph spacing; Word collapses it to the larger value.
+ marginTop += preSpaceBelowApply;
+ } else if (marginTop < preSpaceBelowApply) {
const maxValue = Math.max(preSpaceBelowApply, marginTop);
// spaceBelow and spaceAbove compare the size, the larger one takes effect
// 17.3.1.33 spacing (Spacing Between Lines and Above/Below Paragraph)
- preLine.lineHeight += maxValue;
+ // Reflowing the following line can visit this paragraph boundary
+ // again. Replace the applied spacing instead of accumulating it.
+ preLine.lineHeight += maxValue - (preLine.marginBottom ?? 0);
setLineMarginBottom(preLine, maxValue);
// Remove the marginTop of the current line.
marginTop = 0;
@@ -1890,6 +2757,13 @@ function __getParagraphSpace(
};
}
+function getParagraphSpaceValue(value: Nullable<INumberUnit>, lineSpacing: number, drawingMLLineHeight?: number): number {
+ // DrawingML paragraph percentages use a normal line, independent of the paragraph's line spacing.
+ const relativeToNormalLine = drawingMLLineHeight != null &&
+ (value?.u === NumberUnitType.LINE || value?.u === NumberUnitType.PERCENT);
+ return getNumberUnitValue(value, relativeToNormalLine ? drawingMLLineHeight : lineSpacing);
+}
+
function __getParagraphAnchorLeft(
sectionBreakConfig: ISectionBreakConfig,
paragraphConfig: IParagraphConfig,
@@ -1909,6 +2783,24 @@ function __getParagraphAnchorLeft(
return getNumberUnitValue(paragraphConfig.docxFallbackAnchorLeft, charSpaceApply);
}
+function getDrawingMLNominalLineHeight(
+ glyphGroup: IDocumentSkeletonGlyph[],
+ sectionBreakConfig: ISectionBreakConfig,
+ hasInlineCustomBlock = false
+): number | undefined {
+ if (sectionBreakConfig.documentCompatibilityPolicy?.mode !== 'drawingml' || hasInlineCustomBlock ||
+ glyphGroup.some((glyph) => glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width !== 0)) {
+ return undefined;
+ }
+ const textGlyphs = glyphGroup.filter((glyph) =>
+ glyph.content && glyph.streamType !== DataStreamTreeTokenType.PARAGRAPH && glyph.glyphType !== GlyphType.LIST
+ );
+ const fontSize = Math.max(0, ...(textGlyphs.length ? textGlyphs : glyphGroup)
+ .map((glyph) => glyph.fontStyle?.originFontSize ?? 0)
+ .filter((size) => Number.isFinite(size) && size > 0));
+ return getNominalFontLineHeight(fontSize, sectionBreakConfig.documentCompatibilityPolicy);
+}
+
export function getLineHeightMetrics(
glyphLineHeight: number,
paragraphLineGapDefault: number,
@@ -1920,9 +2812,24 @@ export function getLineHeightMetrics(
useWordStyleLineHeight = true,
scaleAutoLineSpacingByGlyphHeight = true,
normalLineHeight?: number,
- snapAutoLineSpacingToWholeGridLines = false
+ snapAutoLineSpacingToWholeGridLines = false,
+ drawingMLLineHeight?: number
) {
const usesLineGridType = gridType === GridType.LINES || gridType === GridType.LINES_AND_CHARS;
+ const hasNoLineGrid = !usesLineGridType || snapToGrid === BooleanNumber.FALSE;
+ if (hasNoLineGrid && ((!useWordStyleLineHeight && spacingRule === SpacingRule.EXACT) ||
+ (drawingMLLineHeight != null && spacingRule === SpacingRule.AUTO))) {
+ const lineSpacingApply = spacingRule === SpacingRule.EXACT
+ ? scaleAutoLineSpacingByGlyphHeight ? lineSpacing : Math.max(lineSpacing, glyphLineHeight)
+ : lineSpacing * drawingMLLineHeight!;
+ const padding = (lineSpacingApply - glyphLineHeight) / 2;
+ return {
+ paddingTop: padding,
+ paddingBottom: padding,
+ contentHeight: glyphLineHeight,
+ lineSpacingApply,
+ };
+ }
if (!useWordStyleLineHeight) {
let paddingTop = paragraphLineGapDefault;
let paddingBottom = paragraphLineGapDefault;
@@ -1972,18 +2879,20 @@ export function getLineHeightMetrics(
&& usesLineGridType;
if (spacingRule === SpacingRule.AUTO) {
+ // Inline objects keep their physical extent, but adjacent text still
+ // contributes the paragraph's additional multiple-line leading.
const gridLineSpacing = snapAutoLineSpacingToWholeGridLines
? Math.ceil(lineSpacing - 1e-6) * linePitch
: lineSpacing * linePitch;
let lineSpacingApply = usesDocumentGrid
- ? scaleAutoLineSpacingByGlyphHeight
+ ? scaleAutoLineSpacingByGlyphHeight || snapAutoLineSpacingToWholeGridLines
? glyphLineHeight > gridLineSpacing + 1e-6
? Math.ceil((glyphLineHeight - 1e-6) / linePitch) * linePitch
: gridLineSpacing
: Math.max(glyphLineHeight, gridLineSpacing)
: scaleAutoLineSpacingByGlyphHeight
? lineSpacing * Math.max(glyphLineHeight, normalLineHeight ?? 0)
- : glyphLineHeight;
+ : glyphLineHeight + Math.max(0, lineSpacing - 1) * (normalLineHeight ?? 0);
if (
!usesDocumentGrid
&& scaleAutoLineSpacingByGlyphHeight
@@ -2004,7 +2913,7 @@ export function getLineHeightMetrics(
}
if (spacingRule === SpacingRule.AT_LEAST) {
- const lineSpacingApply = Math.max(lineSpacing, glyphLineHeight);
+ const lineSpacingApply = Math.max(lineSpacing, glyphLineHeight, normalLineHeight ?? 0);
const padding = (lineSpacingApply - glyphLineHeight) / 2;
return {
@@ -2015,9 +2924,8 @@ export function getLineHeightMetrics(
};
}
- let exactLineSpacingApply = snapToGrid === BooleanNumber.TRUE && usesLineGridType
- ? Math.max(lineSpacing, linePitch)
- : lineSpacing;
+ // An explicit Word EXACT line box overrides the document grid pitch.
+ let exactLineSpacingApply = lineSpacing;
if (!scaleAutoLineSpacingByGlyphHeight) {
exactLineSpacingApply = Math.max(exactLineSpacingApply, glyphLineHeight);
}
@@ -2039,7 +2947,8 @@ export function updateInlineDrawingPosition(
paragraphInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>,
unitId = '',
blockAnchorTop?: number,
- paragraphNonInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>
+ paragraphNonInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>,
+ documentCompatibilityPolicy?: IParagraphConfig['documentCompatibilityPolicy']
) {
const column = line.parent;
const section = column?.parent;
@@ -2055,6 +2964,10 @@ export function updateInlineDrawingPosition(
const { top, lineHeight, marginBottom = 0 } = line;
const sectionTop = section?.top ?? 0;
const lineTop = sectionTop + top;
+ const baseline = isTraditionalDocumentCompatibility(documentCompatibilityPolicy)
+ ? lineTop + line.marginTop + line.paddingTop +
+ getGlyphGroupFontBoundingBox(documentCompatibilityPolicy, ...line.divides.map((divide) => divide.glyphGroup)).boundingBoxAscent
+ : undefined;
for (const divide of line.divides) {
for (const glyph of divide.glyphGroup) {
@@ -2090,9 +3003,12 @@ export function updateInlineDrawingPosition(
});
const drawingWidth = viewport?.width ?? width;
const drawingHeight = viewport?.height ?? height;
+ const extent = drawingOrigin.effectExtent;
+ const effectOffsetX = ((extent?.left ?? 0) - (extent?.right ?? 0)) / 2;
+ const effectOffsetY = ((extent?.top ?? 0) - (extent?.bottom ?? 0)) / 2;
drawing.aLeft = viewport
- ? blockLeft + (viewport.offsetLeft ?? 0)
- : blockLeft + 0.5 * glyph.width - 0.5 * drawingWidth || 0;
+ ? blockLeft + (viewport.offsetLeft ?? 0) + (extent?.left ?? 0)
+ : blockLeft + 0.5 * glyph.width - 0.5 * drawingWidth + effectOffsetX || 0;
if (glyph.width > divide.width) {
for (const positionedDrawing of paragraphNonInlineSkeDrawings?.values() ?? []) {
const positionedOrigin = positionedDrawing.drawingOrigin;
@@ -2123,7 +3039,10 @@ export function updateInlineDrawingPosition(
}
drawing.width = drawingWidth;
drawing.height = drawingHeight;
- drawing.aTop = lineTop + lineHeight - 0.5 * glyphHeight - 0.5 * drawingHeight - marginBottom;
+ // Inline pictures sit on the text baseline, not below its descenders or leading.
+ drawing.aTop = baseline == null
+ ? lineTop + lineHeight - 0.5 * glyphHeight - 0.5 * drawingHeight - marginBottom + effectOffsetY
+ : baseline - glyph.bBox.ba + 0.5 * (glyphHeight - drawingHeight) + effectOffsetY;
drawing.angle = angle;
drawing.customBlockRenderViewport = viewport
? {
@@ -2206,6 +3125,13 @@ function __getDrawingPosition(
const drawingHeight = viewport?.height ?? fallbackHeight;
let aLeft = getPositionHorizon(positionH, column, page, drawingWidth, isPageBreak) ?? 0;
+ if (
+ ctx.dataModel.documentStyle.documentFlavor === DocumentFlavor.TRADITIONAL &&
+ (positionH.relativeFrom === ObjectRelativeFromH.PAGE || positionH.relativeFrom === ObjectRelativeFromH.MARGIN)
+ ) {
+ // Floating drawings and text wrapping share the content origin, not the physical page edge.
+ aLeft -= page.marginLeft;
+ }
if (
positionH.relativeFrom === ObjectRelativeFromH.COLUMN &&
blockAnchorLeft > 0
@@ -2329,36 +3255,23 @@ function __checkPageBreak(column: IDocumentSkeletonColumn) {
return true;
}
-function __getGlyphGroupWidth(glyphGroup: IDocumentSkeletonGlyph[]) {
+function __getGlyphGroupWidth(glyphGroup: IDocumentSkeletonGlyph[], includeParagraphMark = false) {
+ applyGlyphKerning(glyphGroup);
const glyphGroupLen = glyphGroup.length;
let width = 0;
for (let i = 0; i < glyphGroupLen; i++) {
const glyph = glyphGroup[i];
+ // Word end marks do not consume line width. Other hosts may request a visible advance.
+ if (glyph.streamType === DataStreamTreeTokenType.SECTION_BREAK ||
+ (!includeParagraphMark && glyph.content === DataStreamTreeTokenType.PARAGRAPH)) {
+ continue;
+ }
width += glyph.width;
}
return width;
}
-function __maxFontBoundingBoxByGlyphGroup(glyphGroup: IDocumentSkeletonGlyph[]) {
- const glyphGroupLen = glyphGroup.length;
- let height = Number.NEGATIVE_INFINITY;
- let maxBox;
-
- for (let i = 0; i < glyphGroupLen; i++) {
- const glyph = glyphGroup[i];
- const { ba: boundingBoxAscent, bd: boundingBoxDescent } = glyph.bBox;
-
- if (height < boundingBoxAscent + boundingBoxDescent) {
- maxBox = { boundingBoxAscent, boundingBoxDescent };
- }
-
- height = boundingBoxAscent + boundingBoxDescent;
- }
-
- return maxBox;
-}
-
function __getGlyphGroupByLine({ divides }: IDocumentSkeletonLine) {
return divides.flatMap((divide) => divide.glyphGroup);
}
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.ts
index 07ca92b659..ab1b609a52 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.ts
@@ -23,16 +23,34 @@ import type {
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 { DataStreamTreeTokenType, HorizontalAlign, WrapStrategy } from '@univerjs/core';
+import {
+ BooleanNumber,
+ characterSpacingControlType,
+ DataStreamTreeTokenType,
+ HorizontalAlign,
+ resolveDocumentParagraphStyle,
+ SpacingRule,
+ WrapStrategy,
+} from '@univerjs/core';
import { cjk } from '../../../../../basics/cjk-regexp';
import {
isCjkLeftAlignedPunctuation,
isCjkRightAlignedPunctuation,
} from '../../../../../basics/tools';
+import { getDocumentCompatibilityPolicy, isTraditionalDocumentCompatibility } from '../../../document-compatibility';
import { BreakPointType } from '../../line-breaker/break';
import { isLetter } from '../../line-breaker/enhancers/utils';
-import { createHyphenDashGlyph, glyphShrinkLeft, glyphShrinkRight, setGlyphGroupLeft } from '../../model/glyph';
-import { getFontConfigFromLastGlyph, getGlyphGroupWidth } from '../../tools';
+import {
+ createHyphenDashGlyph,
+ getGlyphGroupFontBoundingBox,
+ getGlyphGroupShrinkability,
+ getGlyphGroupStretchability,
+ glyphShrinkLeft,
+ glyphShrinkRight,
+ removeGlyphAutoSpacing,
+ setGlyphGroupLeft,
+} from '../../model/glyph';
+import { getFontConfigFromLastGlyph, getGlyphGroupWidth, isParagraphEnd } from '../../tools';
// How much a character should hang into the end margin.
// For more discussion, see:
@@ -65,32 +83,6 @@ function overhang(c: string): number {
}
}
-function getDivideShrinkability(divide: IDocumentSkeletonDivide): number {
- const { glyphGroup } = divide;
- let shrinkability = 0;
-
- for (const glyph of glyphGroup) {
- const [left, right] = glyph.adjustability.shrinkability;
-
- shrinkability += left + right;
- }
-
- return shrinkability;
-}
-
-function getDivideStretchability(divide: IDocumentSkeletonDivide): number {
- const { glyphGroup } = divide;
- let stretchability = 0;
-
- for (const glyph of glyphGroup) {
- const [left, right] = glyph.adjustability.stretchability;
-
- stretchability += left + right;
- }
-
- return stretchability;
-}
-
function getJustifiables(divide: IDocumentSkeletonDivide): number {
const justifiables = divide.glyphGroup.filter((glyph) => glyph.isJustifiable).length;
const lastGlyph = divide.glyphGroup[divide.glyphGroup.length - 1];
@@ -104,6 +96,7 @@ function getJustifiables(divide: IDocumentSkeletonDivide): number {
}
function adjustGlyphsInDivide(divide: IDocumentSkeletonDivide, justificationRatio: number, extraJustification: number) {
+ const lastGlyph = divide.glyphGroup[divide.glyphGroup.length - 1];
for (const glyph of divide.glyphGroup) {
const adjustabilityLeft = justificationRatio < 0
? glyph.adjustability.shrinkability[0]
@@ -115,7 +108,7 @@ function adjustGlyphsInDivide(divide: IDocumentSkeletonDivide, justificationRati
const justificationLeft = adjustabilityLeft * justificationRatio;
let justificationRight = adjustabilityRight * justificationRatio;
- if (glyph.isJustifiable) {
+ if (glyph.isJustifiable && (glyph !== lastGlyph || !cjk.hasCJK(glyph.content))) {
justificationRight += extraJustification;
}
@@ -186,10 +179,34 @@ function getGlyphGroupInkBounds(divide: IDocumentSkeletonDivide): { left: number
return { left, right };
}
+function getAlignmentDivide(divide: IDocumentSkeletonDivide): IDocumentSkeletonDivide {
+ const { glyphGroup } = divide;
+ let end = glyphGroup.length;
+ let hasTrailingSpace = false;
+ while (end > 0) {
+ const glyph = glyphGroup[end - 1];
+ if (/^[ \u3000]+$/.test(glyph.content)) {
+ hasTrailingSpace = true;
+ } else if (glyph.width !== 0 || !['', '\r', '\n', '\u2028'].includes(glyph.content)) {
+ break;
+ }
+ end--;
+ }
+
+ // Office hangs breakable spaces outside alignment, but retains tabs and
+ // nonbreaking spaces. Share glyphs without removing editable source positions.
+ return hasTrailingSpace ? { ...divide, glyphGroup: glyphGroup.slice(0, end) } : divide;
+}
+
function horizontalAlignHandler(
line: IDocumentSkeletonLine,
horizontalAlign: HorizontalAlign,
- allowOverflowHorizontalOffset = false
+ allowOverflowHorizontalOffset = false,
+ hangingCjkPunctuation = false,
+ excludeTrailingSpaces = false,
+ preserveWordSpacing = false,
+ isDrawingML = false,
+ compressAlignedOverflow = false
) {
const { divides } = line;
@@ -203,43 +220,56 @@ function horizontalAlignHandler(
continue;
}
- let glyphGroupWidth = getGlyphGroupWidth(divide);
+ removeGlyphAutoSpacing(divide.glyphGroup[divide.glyphGroup.length - 1], 1);
+ const alignmentDivide = isDrawingML || preserveWordSpacing ? getAlignmentDivide(divide) : divide;
+ let glyphGroupWidth = getGlyphGroupWidth(alignmentDivide);
- divide.glyphGroupWidth = glyphGroupWidth;
+ divide.glyphGroupWidth = getGlyphGroupWidth(divide);
if (width === Number.POSITIVE_INFINITY) {
continue;
}
- if (divide.isFull) {
+ const justifiedWords = preserveWordSpacing
+ && (horizontalAlign === HorizontalAlign.JUSTIFIED || horizontalAlign === HorizontalAlign.BOTH);
+ const compressedAlignedText = compressAlignedOverflow && alignmentDivide.glyphGroup.some((glyph) => cjk.hasCJKText(glyph.content));
+ if ((divide.isFull || ((justifiedWords || compressedAlignedText) && glyphGroupWidth > width)) && alignmentDivide.glyphGroup.length > 0) {
let remaining = width - glyphGroupWidth;
// Handle hanging punctuation to the right.
// TODO: @jocs Handle hanging punctuation to the left if text dir is RTL.
- if (divide.glyphGroup.length > 1) {
- const lastGlyph = divide.glyphGroup[divide.glyphGroup.length - 1];
- const amount = overhang(lastGlyph.content) * lastGlyph.width;
-
- remaining += amount;
+ if (alignmentDivide.glyphGroup.length > 1) {
+ const lastGlyph = alignmentDivide.glyphGroup[alignmentDivide.glyphGroup.length - 1];
+ // A no-compression line can already contain a full CJK punctuation
+ // glyph outside its text extent. Do not compress it back inside.
+ const amount = hangingCjkPunctuation && glyphGroupWidth > width && isCjkLeftAlignedPunctuation(lastGlyph.content)
+ ? lastGlyph.width
+ : overhang(lastGlyph.content) * lastGlyph.width;
+
+ remaining += preserveWordSpacing && !hangingCjkPunctuation ? 0 : amount;
}
let justificationRatio = 0;
let extraJustification = 0;
- const shrink = getDivideShrinkability(divide);
- const stretch = getDivideStretchability(divide);
+ const shrink = getGlyphGroupShrinkability(alignmentDivide.glyphGroup);
+ const stretch = getGlyphGroupStretchability(alignmentDivide.glyphGroup);
- if (remaining < 0 && shrink > 0) {
+ if (remaining < 0 && shrink > 0 && (!preserveWordSpacing
+ || horizontalAlign === HorizontalAlign.JUSTIFIED || horizontalAlign === HorizontalAlign.BOTH)) {
// Attempt to reduce the length of the line, using shrinkability.
justificationRatio = Math.max(remaining / shrink, -1.0);
remaining = Math.min(remaining + shrink, 0);
- } else if (horizontalAlign === HorizontalAlign.JUSTIFIED) {
+ } else if (
+ (horizontalAlign === HorizontalAlign.JUSTIFIED || horizontalAlign === HorizontalAlign.BOTH) &&
+ !(i === divides.length - 1 && isParagraphEnd(line))
+ ) {
// Attempt to increase the length of the line, using stretchability.
if (stretch > 0) {
justificationRatio = Math.min(remaining / stretch, 1.0);
remaining = Math.max(remaining - stretch, 0);
}
- const justifiables = getJustifiables(divide);
+ const justifiables = getJustifiables(alignmentDivide);
if (justifiables > 0 && remaining > 0) {
extraJustification = remaining / justifiables;
@@ -250,19 +280,25 @@ function horizontalAlignHandler(
if (justificationRatio !== 0 || extraJustification !== 0) {
// Extrude or stretch row so that they fit within a specified width,
// or they can be squeezed or stretched to justify the row.
- adjustGlyphsInDivide(divide, justificationRatio, extraJustification);
+ adjustGlyphsInDivide(alignmentDivide, justificationRatio, extraJustification);
+ if (alignmentDivide !== divide) {
+ setGlyphGroupLeft(divide.glyphGroup);
+ }
// Recalculate the glyph group width, because we adjust the width and xOffset of glyphs.
- glyphGroupWidth = getGlyphGroupWidth(divide);
- divide.glyphGroupWidth = glyphGroupWidth;
+ glyphGroupWidth = getGlyphGroupWidth(alignmentDivide);
+ divide.glyphGroupWidth = getGlyphGroupWidth(divide);
}
}
- const inkBounds = allowOverflowHorizontalOffset ? getGlyphGroupInkBounds(divide) : null;
+ const inkBounds = allowOverflowHorizontalOffset ? getGlyphGroupInkBounds(alignmentDivide) : null;
+ const alignmentWidth = excludeTrailingSpaces ? getGlyphGroupWidth(divide, true) : glyphGroupWidth;
if (horizontalAlign === HorizontalAlign.DISTRIBUTED) {
- if (distributeGlyphsInDivide(divide)) {
- glyphGroupWidth = getGlyphGroupWidth(divide);
- divide.glyphGroupWidth = glyphGroupWidth;
+ if (distributeGlyphsInDivide(alignmentDivide)) {
+ if (alignmentDivide !== divide) {
+ setGlyphGroupLeft(divide.glyphGroup);
+ }
+ divide.glyphGroupWidth = getGlyphGroupWidth(divide);
}
divide.paddingLeft = 0;
} else if (horizontalAlign === HorizontalAlign.CENTER && inkBounds) {
@@ -270,9 +306,9 @@ function horizontalAlignHandler(
} else if (horizontalAlign === HorizontalAlign.RIGHT && inkBounds) {
divide.paddingLeft = width - inkBounds.right;
} else if (horizontalAlign === HorizontalAlign.CENTER) {
- divide.paddingLeft = (width - glyphGroupWidth) / 2;
+ divide.paddingLeft = (width - alignmentWidth) / 2;
} else if (horizontalAlign === HorizontalAlign.RIGHT) {
- divide.paddingLeft = width - glyphGroupWidth;
+ divide.paddingLeft = width - alignmentWidth;
}
if (!allowOverflowHorizontalOffset) {
@@ -282,30 +318,10 @@ function horizontalAlignHandler(
}
}
-// If the last glyph is a CJK character adjusted by [`addCJKLatinSpacing`],
-// restore the original width.
-function restoreLastCJKGlyphWidth(line: IDocumentSkeletonLine) {
- for (const divide of line.divides) {
- const lastGlyph = divide.glyphGroup[divide.glyphGroup.length - 1];
-
- if (
- lastGlyph &&
- divide.isFull &&
- cjk.hasCJKText(lastGlyph.content) &&
- lastGlyph.width - lastGlyph.xOffset > lastGlyph.bBox.width
- ) {
- const shrinkAmount = lastGlyph.width - lastGlyph.xOffset - lastGlyph.bBox.width;
-
- lastGlyph.width -= shrinkAmount;
- lastGlyph.adjustability.shrinkability[1] = 0;
- }
- }
-}
-
// If the first or last glyph is a CJK punctuation, we want to shrink it.
// See Requirements for Chinese Text Layout, Section 3.1.6.3
// Compression of punctuation marks at line start or line end
-function shrinkStartAndEndCJKPunctuation(line: IDocumentSkeletonLine) {
+function shrinkStartAndEndCJKPunctuation(line: IDocumentSkeletonLine, preserveEndSpace = false) {
for (const divide of line.divides) {
const glyphGroupLength = divide.glyphGroup.length;
if (glyphGroupLength < 2) {
@@ -321,7 +337,7 @@ function shrinkStartAndEndCJKPunctuation(line: IDocumentSkeletonLine) {
glyphShrinkLeft(firstGlyph, shrinkAmount);
}
- if (isCjkLeftAlignedPunctuation(lastGlyph.content)) {
+ if (!preserveEndSpace && isCjkLeftAlignedPunctuation(lastGlyph.content)) {
const shrinkAmount = lastGlyph.adjustability.shrinkability[1];
glyphShrinkRight(lastGlyph, shrinkAmount);
@@ -370,6 +386,21 @@ export function lineAdjustment(
const { paragraphStyle = {} } = paragraph;
const { horizontalAlign = HorizontalAlign.UNSPECIFIED } = paragraphStyle;
+ const snapshot = viewModel.getSnapshot();
+ const documentStyle = snapshot.documentStyle;
+ const policy = sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy(documentStyle.documentFlavor);
+ const traditional = isTraditionalDocumentCompatibility(policy);
+ const excludeTrailingSpaces = traditional && (horizontalAlign === HorizontalAlign.CENTER || horizontalAlign === HorizontalAlign.RIGHT);
+ // Fitting can borrow punctuation space even on the terminal line of an
+ // aligned paragraph. Apply that contraction before computing its offset.
+ const compressAlignedOverflow = excludeTrailingSpaces
+ && (sectionBreakConfig.characterSpacingControl ?? documentStyle.characterSpacingControl) !== characterSpacingControlType.doNotCompress;
+ const resolvedParagraphStyle = resolveDocumentParagraphStyle(documentStyle, paragraphStyle, {
+ styles: snapshot.styles,
+ paragraphStyleId: paragraph.styleId,
+ });
+ const hangingCjkPunctuation = traditional && (sectionBreakConfig.characterSpacingControl ?? documentStyle.characterSpacingControl) === characterSpacingControlType.doNotCompress
+ && resolvedParagraphStyle.hangingPunctuation === BooleanNumber.TRUE;
for (const page of pages) {
for (const section of page.sections) {
for (const column of section.columns) {
@@ -389,10 +420,22 @@ export function lineAdjustment(
}
for (let index = low; index < lines.length && lines[index].paragraphIndex === paragraph.startIndex; index++) {
const line = lines[index];
- shrinkStartAndEndCJKPunctuation(line);
- restoreLastCJKGlyphWidth(line);
+ if (traditional && resolvedParagraphStyle.spacingRule === SpacingRule.EXACT && line.contentHeight > 0.01 &&
+ !line.divides.some((divide) => divide.glyphGroup.some((glyph) => glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width > 0))) {
+ // Word places text at 80% of the exact line box, independent of font ascent.
+ // Keep the line box unchanged so pagination and following objects do not move.
+ const lineBoxHeight = line.paddingTop + line.contentHeight + line.paddingBottom;
+ const { boundingBoxAscent } = getGlyphGroupFontBoundingBox(policy, ...line.divides.map((divide) => divide.glyphGroup));
+ line.paddingTop = lineBoxHeight * 0.8 - boundingBoxAscent;
+ line.paddingBottom = lineBoxHeight - line.contentHeight - line.paddingTop;
+ }
+ shrinkStartAndEndCJKPunctuation(line, hangingCjkPunctuation);
addHyphenDash(line, viewModel, paragraphNode, sectionBreakConfig, paragraphStyle);
- horizontalAlignHandler(line, horizontalAlign, shouldAllowOverflowHorizontalOffset(sectionBreakConfig));
+ const preserveWordSpacing = traditional
+ && (horizontalAlign === HorizontalAlign.UNSPECIFIED || horizontalAlign === HorizontalAlign.LEFT
+ || horizontalAlign === HorizontalAlign.JUSTIFIED || horizontalAlign === HorizontalAlign.BOTH)
+ && !line.divides.some((divide) => divide.glyphGroup.some((glyph) => cjk.hasCJKText(glyph.content)));
+ horizontalAlignHandler(line, horizontalAlign, shouldAllowOverflowHorizontalOffset(sectionBreakConfig), hangingCjkPunctuation, excludeTrailingSpaces, preserveWordSpacing, sectionBreakConfig.documentCompatibilityPolicy?.mode === 'drawingml', compressAlignedOverflow);
}
}
}
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts
index 5500f426ab..3d0776dadb 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts
@@ -43,21 +43,23 @@ import type { ILayoutContext } from '../../tools';
import type { IShapedText } from './shaping';
import {
BooleanNumber,
+ DataStreamTreeNodeType,
DataStreamTreeTokenType,
DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING,
DocumentBlockRangeType,
DocxBreakType,
PositionedObjectLayoutType,
resolveDocumentParagraphStyle,
+ TableTextWrapType,
} from '@univerjs/core';
-import { BreakType, GlyphType } from '../../../../../basics/i-document-skeleton-cached';
+import { BreakType, DocumentSkeletonPageType, GlyphType } from '../../../../../basics/i-document-skeleton-cached';
import { getDocumentCompatibilityPolicy, isTraditionalDocumentCompatibility } from '../../../document-compatibility';
import { BreakPointType } from '../../line-breaker/break';
import { createSkeletonPage } from '../../model/page';
import { setColumnFullState } from '../../model/section';
-import { getLastNotFullColumnInfo, getLastSection, hasSameParagraphBorderSet, isBlankColumn } from '../../tools';
+import { getFontCreateConfig, getLastNotFullColumnInfo, getLastSection, getNumberUnitValue, hasSameParagraphBorderSet, isBlankColumn } from '../../tools';
import { dealWithBullet } from './bullet';
-import { layoutParagraph } from './layout-ruler';
+import { isNonFlowFloatingAnchor, layoutParagraph } from './layout-ruler';
const BLOCK_LAYOUT_OUTER_SPACING_MAP = new Map([
[DocumentBlockRangeType.CALLOUT, 34],
@@ -74,30 +76,6 @@ function _isRenderedPageBreak(viewModel: DocumentViewModel, absoluteIndex: numbe
return viewModel.getBody?.()?.renderedPageBreaks?.includes(absoluteIndex) === true;
}
-function _hasReachedRenderedPageBreak(
- viewModel: DocumentViewModel,
- absoluteIndex: number,
- currentPage: IDocumentSkeletonPage
-): boolean {
- const body = viewModel.getBody?.();
- const renderedBreakIndex = body?.renderedPageBreaks?.indexOf(absoluteIndex) ?? -1;
- if (renderedBreakIndex < 0) {
- return false;
- }
-
- // Page-number restarts make the visible page number different from the physical page ordinal.
- // Keep the conservative boundary behavior until the skeleton exposes a physical page index.
- const hasPageNumberRestart = body?.sectionBreaks?.some(
- (sectionBreak) => sectionBreak.startIndex <= absoluteIndex && sectionBreak.pageNumberStart != null
- ) === true;
- if (hasPageNumberRestart) {
- return false;
- }
-
- const targetPageNumber = currentPage.pageNumberStart + renderedBreakIndex + 1;
- return currentPage.pageNumber >= targetPageNumber;
-}
-
function _isInsideFlowTable(viewModel: DocumentViewModel, absoluteIndex: number): boolean {
return viewModel.getBody?.()?.tables?.some(
(table) => table.startIndex <= absoluteIndex && absoluteIndex < table.endIndex
@@ -549,13 +527,14 @@ function _hasOnlyExplicitPageBoundaryMarkers(page: IDocumentSkeletonPage): boole
);
}
-function _lineSpanHeight(lines: IParagraphLineRef['line'][]): number {
+function _lineSpanHeight(lines: IParagraphLineRef['line'][], includeAfterSpacing = true): number {
if (lines.length === 0) {
return 0;
}
const firstTop = Math.min(...lines.map((line) => line.top));
+ // The next paragraph may already have collapsed after-spacing into this line's height.
return Math.max(...lines.map((line) =>
- line.top + line.lineHeight + Math.max(0, line.spaceBelowApply ?? 0)
+ line.top + line.lineHeight + (includeAfterSpacing ? Math.max(0, (line.spaceBelowApply ?? 0) - (line.marginBottom ?? 0)) : 0)
)) - firstTop;
}
@@ -574,14 +553,41 @@ function _prependLines(
sourceColumn: IDocumentSkeletonColumn,
targetColumn: IDocumentSkeletonColumn,
lines: IParagraphLineRef['line'][],
- validateMove?: () => boolean
+ validateMove?: () => boolean,
+ targetSpaceAbove = 0
): number {
if (lines.length === 0 || lines.some((line) => !sourceColumn.lines.includes(line))) {
return 0;
}
- const movedHeight = _lineSpanHeight(lines);
+ // Relocating lines within the same paragraph must not turn its cached
+ // after-spacing into an extra gap at the join with the continuation.
+ const continuesParagraph = lines[lines.length - 1].paragraphIndex === targetColumn.lines[0]?.paragraphIndex;
+ const firstLine = lines[0];
+ const targetPage = targetColumn.parent?.parent;
+ // Traditional keep/widow moves must apply the same page-top spacing rule as fresh layout.
+ const sourcePage = sourceColumn.parent?.parent;
+ const suppressedBefore = targetPage != null && sourcePage != null && targetPage !== sourcePage &&
+ targetPage.type !== DocumentSkeletonPageType.HEADER && targetPage.type !== DocumentSkeletonPageType.FOOTER &&
+ targetColumn.parent?.top === 0 && firstLine.paragraphStart
+ ? Math.max(0, firstLine.marginTop)
+ : 0;
+ const lastLine = lines[lines.length - 1];
+ const targetFirstLine = targetColumn.lines[0];
+ // The old page-top paragraph now follows the moved heading. Restore its
+ // resolved before-spacing, collapsed with the heading's after-spacing.
+ const restoredGap = !continuesParagraph && targetFirstLine != null
+ ? Math.max(lastLine.spaceBelowApply ?? 0, targetSpaceAbove) -
+ (lastLine.spaceBelowApply ?? 0) - targetFirstLine.marginTop
+ : 0;
+ const movedHeight = _lineSpanHeight(lines, !continuesParagraph) - suppressedBefore + restoredGap;
const targetHeight = targetColumn.parent?.height ?? Number.POSITIVE_INFINITY;
- if (movedHeight + _columnUsedHeight(targetColumn) > targetHeight) {
+ const targetTables = [...(targetPage?.skeTables.values() ?? [])].filter((table) =>
+ table.tableSource?.textWrap === TableTextWrapType.NONE);
+ const targetTableBottom = targetTables.reduce((bottom, table) => Math.max(
+ bottom,
+ table.top + table.height - (targetColumn.parent?.top ?? 0)
+ ), 0);
+ if (movedHeight + Math.max(_columnUsedHeight(targetColumn), targetTableBottom) > targetHeight) {
return 0;
}
@@ -589,16 +595,23 @@ function _prependLines(
const targetLines = targetColumn.lines.slice();
const originalTops = validateMove ? new Map([...sourceLines, ...targetLines].map((line) => [line, line.top])) : undefined;
const sourceWasFull = sourceColumn.isFull;
+ const firstLineHeight = firstLine.lineHeight;
+ const firstLineMarginTop = firstLine.marginTop;
const firstTop = Math.min(...lines.map((line) => line.top));
- const moved = lines.map((line) => {
- line.top -= firstTop;
+ const moved = lines.map((line, index) => {
+ line.top -= firstTop + (index === 0 ? 0 : suppressedBefore);
return line;
});
+ firstLine.marginTop -= suppressedBefore;
+ firstLine.lineHeight -= suppressedBefore;
const movedSet = new Set(moved);
sourceColumn.lines = sourceColumn.lines.filter((line) => !movedSet.has(line));
for (const line of targetColumn.lines) {
line.top += movedHeight;
}
+ for (const table of targetTables) {
+ table.top += movedHeight;
+ }
targetColumn.lines.unshift(...moved);
sourceColumn.isFull = false;
_reindexColumnLines(sourceColumn);
@@ -607,9 +620,14 @@ function _prependLines(
sourceColumn.lines = sourceLines;
targetColumn.lines = targetLines;
sourceColumn.isFull = sourceWasFull;
+ firstLine.marginTop = firstLineMarginTop;
+ firstLine.lineHeight = firstLineHeight;
originalTops?.forEach((top, line) => {
line.top = top;
});
+ for (const table of targetTables) {
+ table.top -= movedHeight;
+ }
_reindexColumnLines(sourceColumn);
_reindexColumnLines(targetColumn);
validateMove();
@@ -618,12 +636,19 @@ function _prependLines(
return moved.length;
}
-function _hasExplicitStructuralBreak(shapedTextList: IShapedText[], viewModel: DocumentViewModel, startIndex: number): boolean {
+function _hasExplicitStructuralBreak(
+ shapedTextList: IShapedText[],
+ viewModel: DocumentViewModel,
+ startIndex: number,
+ traditionalPagination: boolean
+): boolean {
let offset = startIndex;
return shapedTextList.some(({ text, glyphs }) => {
offset += _glyphCount(glyphs);
- return (_endsWithToken(text, glyphs, DataStreamTreeTokenType.PAGE_BREAK) && !_isRenderedPageBreak(viewModel, offset - 1)) ||
- _endsWithToken(text, glyphs, DataStreamTreeTokenType.COLUMN_BREAK);
+ return (_endsWithToken(text, glyphs, DataStreamTreeTokenType.PAGE_BREAK) &&
+ (!traditionalPagination || !_isRenderedPageBreak(viewModel, offset - 1))) ||
+ (_endsWithToken(text, glyphs, DataStreamTreeTokenType.COLUMN_BREAK) &&
+ (!traditionalPagination || _isMarkedColumnBreak(viewModel, offset - 1)));
});
}
@@ -694,6 +719,15 @@ function _applyKeepNext(
return 0;
}
+ // A heading already followed by the first table slice has satisfied keep-next.
+ // Moving it again for a continuation would separate it from that first slice.
+ const sourceTail = sourceColumn.lines[sourceColumn.lines.length - 1];
+ if (sourceTail && [...originalPage.skeTables.values()].some((table) =>
+ table.tableSource?.textWrap === TableTextWrapType.NONE &&
+ table.top + table.height > sourceSection.top + sourceTail.top + sourceTail.lineHeight)) {
+ return 0;
+ }
+
let start = sourceColumn.lines.length;
let scannedParagraphs = 0;
while (start > 0 && scannedParagraphs < MAX_KEEP_NEXT_LOOKAHEAD) {
@@ -723,7 +757,12 @@ function _applyKeepNext(
if (start === sourceColumn.lines.length) {
return 0;
}
- const movedLineCount = _prependLines(sourceColumn, targetColumn, sourceColumn.lines.slice(start), validateMove);
+ const targetFirstLine = targetColumn.lines[0];
+ const targetSpaceAbove = getNumberUnitValue(
+ paragraphConfigCache.get(targetFirstLine.paragraphIndex)?.paragraphStyle?.spaceAbove,
+ targetFirstLine.paddingTop + targetFirstLine.contentHeight + targetFirstLine.paddingBottom
+ );
+ const movedLineCount = _prependLines(sourceColumn, targetColumn, sourceColumn.lines.slice(start), validateMove, targetSpaceAbove);
if (metrics && movedLineCount > 0) {
metrics.retryCount += 1;
metrics.movedLineCount += movedLineCount;
@@ -784,6 +823,124 @@ interface IPreparedLineBreaking {
segmentParagraphCache: Map<number, IParagraphConfig>;
}
+function _hasSameParagraphStyle(paragraph: IParagraph, adjacent: IParagraph | undefined): boolean {
+ if (adjacent == null || paragraph.styleId !== adjacent.styleId) {
+ return false;
+ }
+ return paragraph.styleId != null ||
+ paragraph.paragraphStyle?.namedStyleType === adjacent.paragraphStyle?.namedStyleType;
+}
+
+function _applyContextualParagraphSpacing(
+ viewModel: DocumentViewModel,
+ paragraph: IParagraph,
+ paragraphNode: DataStreamTreeNode,
+ nextParagraphNode: DataStreamTreeNode | undefined,
+ resolvedParagraphStyle: IParagraphStyle,
+ documentCompatibilityPolicy: IDocumentCompatibilityPolicy
+): void {
+ const { endIndex, children } = paragraphNode;
+ if (isTraditionalDocumentCompatibility(documentCompatibilityPolicy) &&
+ resolvedParagraphStyle.contextualSpacing === BooleanNumber.TRUE && children.length === 0) {
+ // Contextual spacing suppresses each paragraph's own spacing, not its neighbour's.
+ // A following flow table contributes its first cell paragraph to Word's
+ // same-style comparison; unrelated cells and floating tables do not.
+ const previousParagraph = viewModel.getParagraph(paragraphNode.startIndex - 1);
+ if (_hasSameParagraphStyle(paragraph, previousParagraph)) {
+ resolvedParagraphStyle.spaceAbove = { v: 0 };
+ }
+ let nextTextNode = nextParagraphNode;
+ const nextTable = nextParagraphNode?.children[0];
+ if (nextTable?.nodeType === DataStreamTreeNodeType.TABLE &&
+ viewModel.getTableByStartIndex(nextTable.startIndex)?.tableSource.textWrap === TableTextWrapType.NONE) {
+ while (nextTextNode?.children.length) {
+ nextTextNode = nextTextNode.children[0];
+ }
+ }
+ if (nextParagraphNode?.startIndex === endIndex + 1 && nextTextNode?.nodeType === DataStreamTreeNodeType.PARAGRAPH && nextTextNode.children.length === 0 &&
+ _hasSameParagraphStyle(paragraph, viewModel.getParagraph(nextTextNode.endIndex))) {
+ resolvedParagraphStyle.spaceBelow = { v: 0 };
+ }
+ }
+}
+
+function _getParagraphBorderSpacing(
+ viewModel: DocumentViewModel,
+ paragraphNode: DataStreamTreeNode,
+ nextParagraphNode: DataStreamTreeNode | undefined,
+ resolvedParagraphStyle: IParagraphStyle,
+ documentCompatibilityPolicy: IDocumentCompatibilityPolicy
+): Pick<IParagraphConfig, 'borderTopSpace' | 'borderBottomSpace'> {
+ const documentSnapshot = viewModel.getSnapshot?.();
+ const documentStyle = documentSnapshot?.documentStyle;
+ const body = viewModel.getBody?.() ?? null;
+ const shouldApplyDocumentDefaults = documentCompatibilityPolicy.applyDocumentDefaultParagraphStyle;
+ const borderTop = resolvedParagraphStyle.borderTop;
+ const borderBottom = resolvedParagraphStyle.borderBottom;
+ const borderBetween = resolvedParagraphStyle.borderBetween;
+ const traditionalBorders = isTraditionalDocumentCompatibility(documentCompatibilityPolicy);
+ const nextParagraph = (borderBetween || (traditionalBorders && borderBottom)) && nextParagraphNode
+ ? viewModel.getParagraph(nextParagraphNode.endIndex)
+ : undefined;
+ const nextParagraphStyle = nextParagraph == null
+ ? undefined
+ : _applyBlockRangeLayoutParagraphStyle(
+ body,
+ nextParagraph,
+ nextParagraph.paragraphStyle ?? {},
+ documentStyle,
+ shouldApplyDocumentDefaults,
+ documentSnapshot?.styles,
+ nextParagraph.styleId
+ );
+
+ if (borderTop && !traditionalBorders) {
+ _withMinSpacing(
+ resolvedParagraphStyle,
+ 'spaceAbove',
+ Math.max(0, borderTop.padding ?? 0) + Math.max(0, borderTop.width ?? 1) / 2
+ );
+ }
+
+ const matchingNextBorder = nextParagraphStyle &&
+ hasSameParagraphBorderSet(resolvedParagraphStyle, nextParagraphStyle);
+ const bottomBorder = matchingNextBorder && (traditionalBorders || borderBetween)
+ ? borderBetween
+ : borderBottom;
+ const bottomBorderClearance = bottomBorder
+ ? Math.max(0, bottomBorder.padding ?? 0) + Math.max(0, bottomBorder.width ?? 1) / 2
+ : 0;
+ if (bottomBorderClearance > 0 && !traditionalBorders) {
+ // Keep the stroke inside the paragraph's post-text region when spaceBelow is smaller.
+ _withMinSpacing(resolvedParagraphStyle, 'spaceBelow', bottomBorderClearance);
+ }
+
+ const previousBorderParagraph = traditionalBorders && borderTop
+ ? viewModel.getParagraph(paragraphNode.startIndex - 1)
+ : undefined;
+ const previousParagraphStyle = previousBorderParagraph == null
+ ? undefined
+ : _applyBlockRangeLayoutParagraphStyle(
+ body,
+ previousBorderParagraph,
+ previousBorderParagraph.paragraphStyle ?? {},
+ documentStyle,
+ shouldApplyDocumentDefaults,
+ documentSnapshot?.styles,
+ previousBorderParagraph.styleId
+ );
+ const topBorderClearance = borderTop && (borderTop.width ?? 1) > 0 &&
+ (!previousParagraphStyle || !hasSameParagraphBorderSet(previousParagraphStyle, resolvedParagraphStyle))
+ ? Math.max(0, borderTop.padding ?? 0) + Math.max(0, borderTop.width ?? 1)
+ : 0;
+ return {
+ borderTopSpace: traditionalBorders ? topBorderClearance : undefined,
+ borderBottomSpace: traditionalBorders && bottomBorder && (bottomBorder.width ?? 1) > 0
+ ? Math.max(0, bottomBorder.padding ?? 0) + Math.max(0, bottomBorder.width ?? 1)
+ : undefined,
+ };
+}
+
function _prepareLineBreaking(
ctx: ILayoutContext,
viewModel: DocumentViewModel,
@@ -802,11 +959,15 @@ function _prepareLineBreaking(
const { endIndex, blocks = [], children } = paragraphNode;
const { segmentId } = curPage;
const paragraph = viewModel.getParagraph(endIndex) || { startIndex: 0, paragraphId: 'para_render_fallback' };
- const { paragraphStyle = {}, bullet } = paragraph;
+ const { paragraphStyle = {} } = paragraph;
const documentSnapshot = viewModel.getSnapshot?.();
const documentStyle = documentSnapshot?.documentStyle;
const documentCompatibilityPolicy = sectionBreakConfig.documentCompatibilityPolicy ??
getDocumentCompatibilityPolicy(documentStyle?.documentFlavor);
+ // Keep list membership in the model; a page-break-only paragraph has no displayed item.
+ const bullet = isTraditionalDocumentCompatibility(documentCompatibilityPolicy) && /^\f+\r?$/.test(paragraphNode.content ?? '')
+ ? undefined
+ : paragraph.bullet;
const shouldApplyDocumentDefaults = documentCompatibilityPolicy.applyDocumentDefaultParagraphStyle;
const useWordStyleLineHeight = documentCompatibilityPolicy.useWordStyleLineHeight;
const { skeHeaders, skeFooters, skeListLevel, drawingAnchor } = skeletonResourceReference;
@@ -831,49 +992,16 @@ function _prepareLineBreaking(
documentSnapshot?.styles,
paragraph.styleId
);
- const borderTop = resolvedParagraphStyle.borderTop;
- const borderBottom = resolvedParagraphStyle.borderBottom;
- const borderBetween = resolvedParagraphStyle.borderBetween;
- const nextParagraph = borderBetween && nextParagraphNode
- ? viewModel.getParagraph(nextParagraphNode.endIndex)
- : undefined;
- const nextParagraphStyle = nextParagraph == null
- ? undefined
- : _applyBlockRangeLayoutParagraphStyle(
- body,
- nextParagraph,
- nextParagraph.paragraphStyle ?? {},
- documentStyle,
- shouldApplyDocumentDefaults,
- documentSnapshot?.styles,
- nextParagraph.styleId
- );
-
- if (borderTop) {
- _withMinSpacing(
- resolvedParagraphStyle,
- 'spaceAbove',
- Math.max(0, borderTop.padding ?? 0) + Math.max(0, borderTop.width ?? 1) / 2
- );
- }
-
- const bottomBorder = borderBetween && nextParagraphStyle &&
- hasSameParagraphBorderSet(resolvedParagraphStyle, nextParagraphStyle)
- ? borderBetween
- : borderBottom;
- const bottomBorderClearance = bottomBorder
- ? Math.max(0, bottomBorder.padding ?? 0) + Math.max(0, bottomBorder.width ?? 1) / 2
- : 0;
- if (bottomBorderClearance > 0) {
- // Keep the stroke inside the paragraph's post-text region when spaceBelow is smaller.
- _withMinSpacing(resolvedParagraphStyle, 'spaceBelow', bottomBorderClearance);
- }
+ _applyContextualParagraphSpacing(viewModel, paragraph, paragraphNode, nextParagraphNode, resolvedParagraphStyle, documentCompatibilityPolicy);
+ const borderSpacing = _getParagraphBorderSpacing(viewModel, paragraphNode, nextParagraphNode, resolvedParagraphStyle, documentCompatibilityPolicy);
const paragraphConfig: IParagraphConfig = {
paragraphIndex: endIndex,
isInsideTable: _isInsideFlowTable(viewModel, endIndex),
documentCompatibilityPolicy,
paragraphStyle: resolvedParagraphStyle,
+ // Word border distances occupy space in addition to collapsed paragraph spacing.
+ ...borderSpacing,
docxFallbackAnchorLeft: _getFollowingIndentedParagraphAnchorLeft(
viewModel,
paragraph,
@@ -912,7 +1040,17 @@ function _prepareLineBreaking(
paragraphConfig.bulletSkeleton = bulletSkeleton;
} else {
const listLevelAncestors = _getListLevelAncestors(bullet, skeListLevel); // Get the cache of all levels of the list
- const bulletSkeleton = dealWithBullet(bullet, lists, listLevelAncestors, localeService); // Generate bullet
+ const markerTextStyle = bullet && isTraditionalDocumentCompatibility(documentCompatibilityPolicy)
+ ? {
+ ...getFontCreateConfig(endIndex - paragraphNode.contentStartIndex, viewModel, paragraphNode, sectionBreakConfig, {
+ ...paragraph,
+ paragraphStyle: resolvedParagraphStyle,
+ }).textStyle,
+ // Explicit list formatting below may underline the marker; paragraph-mark formatting may not.
+ ul: { s: BooleanNumber.FALSE },
+ }
+ : undefined;
+ const bulletSkeleton = dealWithBullet(bullet, lists, listLevelAncestors, localeService, false, markerTextStyle);
_updateListLevelAncestors(paragraph, bullet, bulletSkeleton, skeListLevel, lists); // Update the latest level cache list
@@ -960,7 +1098,6 @@ interface ILayoutShapedTextsParams {
viewModel: DocumentViewModel;
shapedTextList: IShapedText[];
allPages: IDocumentSkeletonPage[];
- curPage: IDocumentSkeletonPage;
paragraphNode: DataStreamTreeNode;
sectionBreakConfig: ISectionBreakConfig;
paragraphConfig: IParagraphConfig;
@@ -998,7 +1135,6 @@ function _layoutShapedTexts({
viewModel,
shapedTextList,
allPages: initialPages,
- curPage,
paragraphNode,
sectionBreakConfig,
paragraphConfig,
@@ -1013,11 +1149,12 @@ function _layoutShapedTexts({
let allPages = initialPages;
let isParagraphFirstShapedText = true; // First shaped text
let renderParagraphBullet = true;
+ let startNewLine = false;
let shapedTextOffset = 0;
- let renderedPageBreakAnchorPage = curPage;
+ let deferredRenderedMarkers: IDocumentSkeletonGlyph[] = [];
const retainedBreaks = ctx.footnoteLayout?.getReferencePageBreaks(paragraphNode.endIndex);
const referencePageBreaks = retainedBreaks
- ? new Set(retainedBreaks.map((offset) => offset - paragraphNode.startIndex))
+ ? new Set(retainedBreaks.map((offset) => offset - paragraphNode.contentStartIndex))
: undefined;
const mergedShapedTextList = _mergeAdjacentCustomBlockShapedTexts(
_splitAtReferencePageBreaks(shapedTextList, referencePageBreaks),
@@ -1026,104 +1163,129 @@ function _layoutShapedTexts({
for (let shapedIndex = 0; shapedIndex < mergedShapedTextList.length; shapedIndex++) {
const { text, glyphs, breakPointType } = mergedShapedTextList[shapedIndex];
- let layoutGlyphs = glyphs;
- const textStartIndex = paragraphNode.startIndex + shapedTextOffset;
+ const textStartIndex = paragraphNode.contentStartIndex + shapedTextOffset;
const lastPage = allPages[allPages.length - 1];
if (referencePageBreaks?.has(shapedTextOffset) && _hasPageContent(lastPage)) {
allPages.push(createSkeletonPage(ctx, sectionBreakConfig, skeletonResourceReference, _getNextPageNumber(lastPage)));
}
const textGlyphCount = _glyphCount(glyphs);
const textEndIndex = textStartIndex + textGlyphCount;
- const pushPending = (layoutBreakPointType = breakPointType) => {
- if (layoutGlyphs.length === 0) {
+ const pushPending = (pendingGlyphs = glyphs, layoutBreakPointType = breakPointType) => {
+ if (pendingGlyphs.length === 0) {
return;
}
+ if (deferredRenderedMarkers.length > 0) {
+ pendingGlyphs = [...deferredRenderedMarkers, ...pendingGlyphs];
+ deferredRenderedMarkers = [];
+ }
syncActiveParagraphDrawings(
- layoutGlyphs,
+ pendingGlyphs,
paragraphNonInlineSkeDrawings,
paragraphInlineSkeDrawings,
paragraphNonInlineSkeDrawingsByBlockId,
paragraphInlineSkeDrawingsByBlockId
);
+ const nonFlowAnchor = isNonFlowFloatingAnchor(pendingGlyphs, paragraphNonInlineSkeDrawings);
+ const preserveParagraphStart = nonFlowAnchor && mergedShapedTextList.slice(shapedIndex + 1)
+ .some(({ glyphs }) => glyphs.some((glyph) => glyph.width > 0 &&
+ glyph.streamType !== DataStreamTreeTokenType.PARAGRAPH &&
+ glyph.streamType !== DataStreamTreeTokenType.SECTION_BREAK &&
+ glyph.streamType !== DataStreamTreeTokenType.DOCS_END));
allPages = layoutParagraph(
ctx,
- layoutGlyphs,
+ pendingGlyphs,
allPages,
sectionBreakConfig,
paragraphConfig,
- isParagraphFirstShapedText || hasOnlyFloatingCustomBlockGlyphs(glyphs, paragraphNonInlineSkeDrawingsByBlockId),
+ isParagraphFirstShapedText || (!nonFlowAnchor && hasOnlyFloatingCustomBlockGlyphs(pendingGlyphs, paragraphNonInlineSkeDrawingsByBlockId)),
layoutBreakPointType,
- renderParagraphBullet
+ renderParagraphBullet && !preserveParagraphStart,
+ startNewLine
);
- isParagraphFirstShapedText = false;
- renderParagraphBullet = false;
+ // Zero-height drawing anchors do not consume the visible first line.
+ if (!preserveParagraphStart) {
+ isParagraphFirstShapedText = false;
+ renderParagraphBullet = false;
+ }
+ startNewLine = false;
};
if (_endsWithToken(text, glyphs, DataStreamTreeTokenType.PAGE_BREAK)) {
const isRenderedPageBreak =
traditionalPagination && _isRenderedPageBreak(viewModel, textEndIndex - 1);
- if (
- traditionalPagination && !isRenderedPageBreak &&
- viewModel.getDataModel().documentStyle.splitPageBreakAndParagraphMark !== BooleanNumber.TRUE
- ) {
- const trailingGlyphs = mergedShapedTextList.slice(shapedIndex + 1).flatMap((item) => item.glyphs);
- if (
- trailingGlyphs.some((glyph) => glyph.raw === DataStreamTreeTokenType.PARAGRAPH) &&
- trailingGlyphs.every((glyph) =>
- glyph.raw === DataStreamTreeTokenType.PARAGRAPH || glyph.raw === DataStreamTreeTokenType.SECTION_BREAK
- )
- ) {
- // Word keeps the paragraph terminator on the break's line when no run content follows it.
- // Retain its source offset and font style without making an empty line on the next page.
- // A leading cell break does not advance a page, so its real paragraph still occupies height.
- const retainParagraphHeight = _isInsideFlowTable(viewModel, textEndIndex - 1) &&
- !_hasPageContent(allPages[allPages.length - 1]) &&
- glyphs.every((glyph) => glyph.raw === DataStreamTreeTokenType.PAGE_BREAK);
- layoutGlyphs = [...glyphs, ...trailingGlyphs.map((glyph) => retainParagraphHeight
- ? glyph
- : ({
- ...glyph,
- width: 0,
- bBox: { ...glyph.bBox, width: 0, ba: 0, bd: 0, aba: 0, abd: 0, normalLineHeight: 0 },
- }))];
- shapedTextOffset += _glyphCount(trailingGlyphs);
- shapedIndex = mergedShapedTextList.length - 1;
+ if (isRenderedPageBreak) {
+ // Cached pagination is round-trip metadata, not an authored line/page break.
+ // Keep its stream position for selections without reserving a line of its own.
+ if (textGlyphCount > 1) {
+ pushPending(glyphs, BreakPointType.Normal);
+ } else {
+ deferredRenderedMarkers.push(...glyphs);
+ }
+ shapedTextOffset += textGlyphCount;
+ continue;
+ }
+ let terminalParagraphGlyphs: IDocumentSkeletonGlyph[] | null = null;
+ if (traditionalPagination &&
+ viewModel.getDataModel().documentStyle.splitPageBreakAndParagraphMark !== BooleanNumber.TRUE) {
+ const trailingGlyphs: IDocumentSkeletonGlyph[] = [];
+ for (let index = shapedIndex + 1; index < mergedShapedTextList.length; index++) {
+ const tail = mergedShapedTextList[index];
+ if (index === mergedShapedTextList.length - 1 &&
+ _endsWithToken(tail.text, tail.glyphs, DataStreamTreeTokenType.PARAGRAPH) &&
+ (tail.glyphs.every(({ raw }) => raw === DataStreamTreeTokenType.PARAGRAPH || raw === DataStreamTreeTokenType.SECTION_BREAK) ||
+ isNonFlowFloatingAnchor(tail.glyphs, paragraphNonInlineSkeDrawingsByBlockId))) {
+ terminalParagraphGlyphs = [...trailingGlyphs, ...tail.glyphs];
+ break;
+ }
+ if (!isNonFlowFloatingAnchor(tail.glyphs, paragraphNonInlineSkeDrawingsByBlockId)) {
+ break;
+ }
+ trailingGlyphs.push(...tail.glyphs);
}
}
- pushPending(isRenderedPageBreak ? BreakPointType.Normal : breakPointType);
+ // A terminal mark and its non-flow pictures belong to the manual-break
+ // paragraph, not an otherwise empty continuation on the next page.
+ if (terminalParagraphGlyphs?.some((glyph) => glyph.drawingId != null)) {
+ pushPending(glyphs);
+ pushPending(terminalParagraphGlyphs);
+ } else {
+ const retainParagraphHeight = _isInsideFlowTable(viewModel, textEndIndex - 1) &&
+ !_hasPageContent(allPages[allPages.length - 1]) &&
+ glyphs.every((glyph) => glyph.raw === DataStreamTreeTokenType.PAGE_BREAK);
+ const terminalGlyphs = terminalParagraphGlyphs?.map((glyph) => retainParagraphHeight
+ ? glyph
+ : ({
+ ...glyph,
+ width: 0,
+ bBox: { ...glyph.bBox, width: 0, ba: 0, bd: 0, aba: 0, abd: 0, normalLineHeight: 0 },
+ }));
+ pushPending(terminalGlyphs ? [...glyphs, ...terminalGlyphs] : glyphs);
+ }
+ if (terminalParagraphGlyphs) {
+ shapedIndex = mergedShapedTextList.length - 1;
+ shapedTextOffset += _glyphCount(terminalParagraphGlyphs);
+ }
const currentPage = allPages[allPages.length - 1];
- const naturallyAdvancedInsideTable =
- isRenderedPageBreak &&
- _isInsideFlowTable(viewModel, textEndIndex - 1) &&
- currentPage.isNaturalPageOverflow === true;
- const alreadyAdvancedNaturally =
- isRenderedPageBreak &&
- (
- currentPage !== renderedPageBreakAnchorPage ||
- naturallyAdvancedInsideTable ||
- _hasReachedRenderedPageBreak(viewModel, textEndIndex - 1, currentPage)
- );
- if (
- !alreadyAdvancedNaturally &&
- _hasPageContent(currentPage) &&
- !_hasOnlyExplicitPageBoundaryMarkers(currentPage)
- ) {
+ const preserveAuthoredBlankPage = traditionalPagination && !_isInsideFlowTable(viewModel, textEndIndex - 1);
+ if (_hasPageContent(currentPage) &&
+ (preserveAuthoredBlankPage || !_hasOnlyExplicitPageBoundaryMarkers(currentPage))) {
const nextPage = createSkeletonPage(
ctx,
sectionBreakConfig,
skeletonResourceReference,
_getNextPageNumber(currentPage),
- BreakType.PAGE
+ BreakType.PAGE,
+ currentPage
);
nextPage.isExplicitPageBreak = true;
allPages.push(nextPage);
}
- renderedPageBreakAnchorPage = allPages[allPages.length - 1];
paragraphNonInlineSkeDrawings.clear();
- isParagraphFirstShapedText = allPages[allPages.length - 1] !== currentPage || !isRenderedPageBreak;
+ isParagraphFirstShapedText = true;
+ startNewLine = true;
shapedTextOffset += textGlyphCount;
continue;
} else if (
@@ -1155,7 +1317,8 @@ function _layoutShapedTexts({
sectionBreakConfig,
skeletonResourceReference,
_getNextPageNumber(lastPage),
- BreakType.COLUMN
+ BreakType.COLUMN,
+ lastPage
)
);
}
@@ -1166,7 +1329,8 @@ function _layoutShapedTexts({
sectionBreakConfig,
skeletonResourceReference,
_getNextPageNumber(lastPage),
- BreakType.COLUMN
+ BreakType.COLUMN,
+ lastPage
)
);
}
@@ -1211,6 +1375,13 @@ function _applyPaginationConstraints({
sectionBreakConfig,
}: IApplyPaginationConstraintsParams): void {
let moved = false;
+ const wordCompatibilityMode = Number(ctx.dataModel?.documentStyle.compatibilitySettings?.compatibilityMode);
+ // Before Word 2013, splittable table cells ignore paragraph keep-lines and
+ // widow control. Preserve the authored properties for body layout/export.
+ const legacyCell = curPage.type === DocumentSkeletonPageType.CELL &&
+ wordCompatibilityMode >= 11 && wordCompatibilityMode < 15;
+ const keepLines = !legacyCell && resolvedParagraphStyle.keepLines === BooleanNumber.TRUE;
+ const widowControl = !legacyCell && resolvedParagraphStyle.widowControl === BooleanNumber.TRUE;
const validateMove = ctx.footnoteLayout ? () => ctx.footnoteLayout!.reconcilePages(allPages, sectionBreakConfig) : undefined;
const needsPaginationCheckpoint =
forcePageBreakBefore ||
@@ -1219,11 +1390,11 @@ function _applyPaginationConstraints({
tableSkeleton == null &&
paragraphNonInlineSkeDrawingsByBlockId.size === 0 &&
(
- resolvedParagraphStyle.keepLines === BooleanNumber.TRUE ||
+ keepLines ||
(
allPages.length > 1 &&
(
- resolvedParagraphStyle.widowControl === BooleanNumber.TRUE ||
+ widowControl ||
segmentParagraphCache.size > 1
)
)
@@ -1240,16 +1411,16 @@ function _applyPaginationConstraints({
if (traditionalPagination &&
!explicitStructuralBreak &&
!forcePageBreakBefore &&
- tableSkeleton == null &&
paragraphNonInlineSkeDrawingsByBlockId.size === 0) {
// Apply Word-compatible soft constraints from strongest to weakest.
// Each helper only relocates already-shaped local lines and remains bounded.
- if (resolvedParagraphStyle.keepLines === BooleanNumber.TRUE &&
+ if (tableSkeleton == null && keepLines &&
_applyKeepLines(allPages, endIndex, ctx.paginationMetrics, validateMove) > 0) {
moved = true;
ctx.paragraphsOpenNewPage.add(endIndex);
}
- const keepNextMoved = allPages.length > 1
+ const keepNextMoved = allPages.length > 1 &&
+ (tableSkeleton == null || tableSkeleton.tableSource?.textWrap === TableTextWrapType.NONE)
? _applyKeepNext(allPages, curPage, endIndex, segmentParagraphCache, ctx.paginationMetrics, validateMove)
: 0;
if (keepNextMoved > 0) {
@@ -1258,8 +1429,8 @@ function _applyPaginationConstraints({
}
let widowMoved = 0;
if (
- allPages.length > 1 &&
- resolvedParagraphStyle.widowControl === BooleanNumber.TRUE
+ tableSkeleton == null && allPages.length > 1 &&
+ widowControl
) {
widowMoved = _applyWidowControl(allPages, endIndex, ctx.paginationMetrics, validateMove);
}
@@ -1309,7 +1480,7 @@ export function lineBreaking(
nextParagraphNode
);
const traditionalPagination = isTraditionalDocumentCompatibility(documentCompatibilityPolicy);
- const explicitStructuralBreak = _hasExplicitStructuralBreak(shapedTextList, viewModel, paragraphNode.startIndex);
+ const explicitStructuralBreak = _hasExplicitStructuralBreak(shapedTextList, viewModel, paragraphNode.contentStartIndex, traditionalPagination);
const forcePageBreakBefore =
traditionalPagination &&
(resolvedParagraphStyle.pageBreakBefore === BooleanNumber.TRUE || tablePageBreakBefore) &&
@@ -1323,7 +1494,8 @@ export function lineBreaking(
sectionBreakConfig,
ctx.skeletonResourceReference,
_getNextPageNumber(curPage),
- BreakType.PAGE
+ BreakType.PAGE,
+ curPage
);
nextPage.isExplicitPageBreak = true;
allPages.push(nextPage);
@@ -1335,7 +1507,6 @@ export function lineBreaking(
viewModel,
shapedTextList,
allPages,
- curPage,
paragraphNode,
sectionBreakConfig,
paragraphConfig,
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts
index 8b17d0e4d0..b970a18357 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
@@ -24,13 +24,17 @@ import type { ILayoutContext } from '../../tools';
import {
BaselineOffset,
BooleanNumber,
+ characterSpacingControlType,
DataStreamTreeTokenType,
+ DocxBreakType,
GridType,
PositionedObjectLayoutType,
+ resolveDocumentParagraphStyle,
} from '@univerjs/core';
import { cjk } from '../../../../../basics/cjk-regexp';
import { GlyphType } from '../../../../../basics/i-document-skeleton-cached';
import {
+ getFirstGrapheme,
getFontStyleString,
hasArabic,
hasThai,
@@ -38,6 +42,7 @@ import {
startWithEmoji,
} from '../../../../../basics/tools';
import { getDocsCustomBlockRenderViewport } from '../../../custom-block-render-viewport';
+import { getDocumentCompatibilityPolicy, isTraditionalDocumentCompatibility } from '../../../document-compatibility';
import { Lang } from '../../hyphenation/lang';
import { BreakPointType } from '../../line-breaker/break';
import { LineBreakerHyphenEnhancer } from '../../line-breaker/enhancers/hyphen-enhancer';
@@ -68,7 +73,7 @@ import { ArabicHandler, emojiHandler, otherHandler, ThaiHandler, TibetanHandler
// Now we apply consecutive punctuation adjustment, specified in Chinese Layout
// Requirements, section 3.1.6.1 Punctuation Adjustment Space, and Japanese Layout
// Requirements, section 3.1 Line Composition Rules for Punctuation Marks
-function punctuationSpaceAdjustment(shapedGlyphs: IDocumentSkeletonGlyph[]) {
+function punctuationSpaceAdjustment(shapedGlyphs: IDocumentSkeletonGlyph[], includeEastAsianQuotes = false) {
const len = shapedGlyphs.length;
for (let i = 0; i < len - 1; i++) {
const curGlyph = shapedGlyphs[i];
@@ -77,8 +82,8 @@ function punctuationSpaceAdjustment(shapedGlyphs: IDocumentSkeletonGlyph[]) {
const delta = width / 2;
if (
- cjk.hasCJKPunctuation(content) &&
- cjk.hasCJKPunctuation(nextGlyph.content) &&
+ (cjk.hasCJKPunctuation(content) || (includeEastAsianQuotes && /^[“”‘’]$/.test(content))) &&
+ (cjk.hasCJKPunctuation(nextGlyph.content) || (includeEastAsianQuotes && /^[“”‘’]$/.test(nextGlyph.content))) &&
curGlyph.adjustability.shrinkability[1] + nextGlyph.adjustability.shrinkability[0] >= delta
) {
const leftDelta = Math.min(curGlyph.adjustability.shrinkability[1], delta);
@@ -101,19 +106,24 @@ function addCJKLatinSpacing(shapedTextList: IShapedText[]) {
for (let i = 0; i < len; i++) {
const curGlyph = shapedGlyphs[i];
const nextGlyph = i < len - 1 ? shapedGlyphs[i + 1] : null;
- const { width } = curGlyph;
+ // Automatic mixed-script spacing is based on the character, not its explicit tracking interval.
+ const width = curGlyph.ts?.sc && Number.isFinite(curGlyph.ts.sc) ? curGlyph.bBox.width : curGlyph.width;
// Case 1: CJ followed by a Latin character.
if (cjk.hasCJKText(curGlyph.content) && nextGlyph && LATIN_REG.test(nextGlyph.content)) {
+ curGlyph.autoSpacing = [0, width / 4];
curGlyph.width += width / 4;
curGlyph.adjustability.shrinkability[1] += width / 8;
+ curGlyph.adjustability.stretchability[1] += width / 8;
}
// Case 2: Latin followed by a CJ character.
if (cjk.hasCJKText(curGlyph.content) && prevGlyph && LATIN_REG.test(prevGlyph.content)) {
+ curGlyph.autoSpacing = [width / 4, curGlyph.autoSpacing?.[1] ?? 0];
curGlyph.width += width / 4;
curGlyph.xOffset += width / 4;
curGlyph.adjustability.shrinkability[0] += width / 8;
+ curGlyph.adjustability.stretchability[0] += width / 8;
}
prevGlyph = curGlyph;
@@ -146,7 +156,7 @@ function collectMeasuredWholeEntityRanges(
paragraphNode: DataStreamTreeNode
): ICustomRangeForInterceptor[] {
const ranges: ICustomRangeForInterceptor[] = [];
- const contentStartIndex = paragraphNode.startIndex;
+ const contentStartIndex = paragraphNode.contentStartIndex;
const contentEndIndex = contentStartIndex + content.length - 1;
const customRanges = viewModel.getBody()?.customRanges ?? [];
@@ -182,8 +192,8 @@ function createMeasuredWholeEntityGlyph(
sectionBreakConfig: ISectionBreakConfig,
paragraph: IParagraph
): IDocumentSkeletonGlyph | undefined {
- const relativeStartIndex = range.startIndex - paragraphNode.startIndex;
- const relativeEndIndex = range.endIndex - paragraphNode.startIndex + 1;
+ const relativeStartIndex = range.startIndex - paragraphNode.contentStartIndex;
+ const relativeEndIndex = range.endIndex - paragraphNode.contentStartIndex + 1;
const raw = content.slice(relativeStartIndex, relativeEndIndex);
const config = getFontCreateConfig(relativeStartIndex, viewModel, paragraphNode, sectionBreakConfig, paragraph);
const metrics = getCustomRangeGlyphMetricsFromRange(range, config);
@@ -196,6 +206,9 @@ function createMeasuredWholeEntityGlyph(
}
function getShapedGlyphText(glyph: IDocumentSkeletonGlyph): string {
+ if (glyph.ts?.hidden === true) {
+ return '';
+ }
if (
glyph.glyphType === GlyphType.PLACEHOLDER &&
glyph.streamType === DataStreamTreeTokenType.LETTER &&
@@ -207,37 +220,169 @@ function getShapedGlyphText(glyph: IDocumentSkeletonGlyph): string {
return glyph.content;
}
-export function shaping(
+function createShapedCustomBlockGlyph(
+ i: number,
+ char: string,
+ viewModel: DocumentViewModel,
+ paragraphNode: DataStreamTreeNode,
+ sectionBreakConfig: ISectionBreakConfig,
+ paragraph: IParagraph
+): IDocumentSkeletonGlyph {
+ const { drawings = {} } = sectionBreakConfig;
+ const config = getFontCreateConfig(i, viewModel, paragraphNode, sectionBreakConfig, paragraph);
+ let newGlyph: Nullable<IDocumentSkeletonGlyph> = null;
+ const customBlock = viewModel.getCustomBlockWithoutSetCurrentIndex(paragraphNode.contentStartIndex + i);
+
+ if (customBlock != null) {
+ const { blockId } = customBlock;
+ const drawingOrigin = drawings[blockId];
+ if (drawingOrigin?.layoutType === PositionedObjectLayoutType.INLINE) {
+ const { angle } = drawingOrigin.docTransform;
+ const { width = 0, height = 0 } = drawingOrigin.docTransform.size;
+ const top = 0;
+ const left = 0;
+ const viewport = getDocsCustomBlockRenderViewport(
+ viewModel.getDataModel().getUnitId?.() ?? '',
+ drawingOrigin.drawingId,
+ {
+ fallbackHeight: height,
+ fallbackWidth: width,
+ }
+ );
+
+ const boundingBox = getBoundingBox(angle, left, viewport?.width ?? width, top, viewport?.height ?? height);
+ const extent = drawingOrigin.effectExtent;
+ newGlyph = createSkeletonCustomBlockGlyph(
+ config,
+ (viewport?.layoutWidth ?? boundingBox.width ?? 0) + (extent?.left ?? 0) + (extent?.right ?? 0),
+ (boundingBox.height ?? 0) + (extent?.top ?? 0),
+ drawingOrigin.drawingId
+ );
+ newGlyph.bBox.bd = extent?.bottom ?? 0;
+ } else if (drawingOrigin != null) {
+ newGlyph = createSkeletonCustomBlockGlyph(config, 0, 0, drawingOrigin.drawingId);
+ }
+ }
+
+ if (newGlyph == null) {
+ newGlyph = createSkeletonLetterGlyph(char, config);
+ }
+ return newGlyph;
+}
+
+function createWhitespaceGlyph(
+ char: string,
+ config: ReturnType<typeof getFontCreateConfig>,
+ i: number,
+ viewModel: DocumentViewModel,
+ paragraphNode: DataStreamTreeNode,
+ sectionBreakConfig: ISectionBreakConfig,
+ snapToGrid: BooleanNumber,
+ traditionalLayout: boolean
+): IDocumentSkeletonGlyph {
+ const { gridType = GridType.LINES, charSpace = 0, defaultTabStop = 10.5 } = sectionBreakConfig;
+ let newGlyph: IDocumentSkeletonGlyph;
+ if (char === DataStreamTreeTokenType.TAB) {
+ const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);
+ newGlyph = createSkeletonTabGlyph(config, charSpaceApply);
+ } else if (char === DataStreamTreeTokenType.PARAGRAPH) {
+ const zeroWidthParagraphBreak = sectionBreakConfig.renderConfig?.zeroWidthParagraphBreak;
+
+ if (zeroWidthParagraphBreak === BooleanNumber.TRUE) {
+ newGlyph = createSkeletonLetterGlyph(char, config, 0);
+ } else {
+ const defaultWidth = zeroWidthParagraphBreak == null && sectionBreakConfig.documentCompatibilityPolicy?.mode === 'drawingml'
+ ? 0
+ : undefined;
+ newGlyph = createSkeletonLetterGlyph(
+ char,
+ config,
+ getCustomRangeGlyphMetrics(i, viewModel, paragraphNode, config) ?? defaultWidth
+ );
+ }
+ } else {
+ const content = paragraphNode.content ?? '';
+ const balanceSpaceWidth = char === ' ' && config.balanceSingleByteDoubleByteWidth === BooleanNumber.TRUE &&
+ (i === 0 || i + 1 === content.length || /\s/.test(content[i - 1]) || /\s/.test(content[i + 1]));
+ newGlyph = createSkeletonLetterGlyph(char, balanceSpaceWidth ? { ...config, balanceSpaceWidth } : config);
+ }
+ if (traditionalLayout && char === DataStreamTreeTokenType.COLUMN_BREAK &&
+ viewModel.getCustomRange(paragraphNode.contentStartIndex + i)?.properties?.breakType !== DocxBreakType.COLUMN) {
+ // DOCX soft breaks are widthless, but an authored blank line still has font height.
+ newGlyph.bBox = { ...createSkeletonLetterGlyph(' ', config, 0).bBox, width: 0 };
+ }
+
+ if (char === DataStreamTreeTokenType.PARAGRAPH &&
+ sectionBreakConfig.cellHiddenEndMarkIndex === paragraphNode.endIndex &&
+ isTraditionalDocumentCompatibility(sectionBreakConfig.documentCompatibilityPolicy)) {
+ newGlyph.bBox.ba = 0;
+ newGlyph.bBox.bd = 0;
+ newGlyph.bBox.normalLineHeight = 0;
+ }
+ return newGlyph;
+}
+
+function createNoteGlyph(
+ ctx: ILayoutContext,
+ index: number,
+ viewModel: DocumentViewModel,
+ paragraphNode: DataStreamTreeNode,
+ sectionBreakConfig: ISectionBreakConfig,
+ paragraph: IParagraph
+): IDocumentSkeletonGlyph | undefined {
+ const offset = paragraphNode.contentStartIndex + index;
+ const fieldType = viewModel.getCustomRangeRaw(offset)?.properties?.fieldType;
+ if (fieldType === 'FOOTNOTE_SEPARATOR' || fieldType === 'FOOTNOTE_CONTINUATION_SEPARATOR') {
+ const config = getFontCreateConfig(index, viewModel, paragraphNode, sectionBreakConfig, paragraph);
+ const textWidth = Math.max(0, (sectionBreakConfig.pageSize?.width ?? 192) -
+ (sectionBreakConfig.marginLeft ?? 0) - (sectionBreakConfig.marginRight ?? 0));
+ const width = fieldType === 'FOOTNOTE_SEPARATOR' ? Math.min(192, textWidth) : textWidth;
+ const glyph = createSkeletonLetterGlyph(' ', config, width);
+ glyph.raw = '\uFFFC';
+ glyph.noteSeparator = true;
+ return glyph;
+ }
+
+ const note = viewModel === ctx.viewModel ? ctx.noteReferences?.get(offset) : undefined;
+ if (!note) {
+ return undefined;
+ }
+ const config = getFontCreateConfig(index, viewModel, paragraphNode, sectionBreakConfig, paragraph);
+ const glyph = createSkeletonLetterGlyph(note.label, config);
+ glyph.raw = '\uFFFC';
+ glyph.count = 1;
+ glyph.noteId = note.noteId;
+ return glyph;
+}
+
+function getScriptHandler(source: string, char: string): typeof otherHandler {
+ if (startWithEmoji(source)) {
+ return emojiHandler;
+ }
+ if (hasArabic(char)) {
+ return ArabicHandler;
+ }
+ if (hasTibetan(char)) {
+ return TibetanHandler;
+ }
+ if (hasThai(char)) {
+ return ThaiHandler;
+ }
+ return otherHandler;
+}
+
+function createShapingLineBreaker(
ctx: ILayoutContext,
content: string,
viewModel: DocumentViewModel,
paragraphNode: DataStreamTreeNode,
- sectionBreakConfig: ISectionBreakConfig
-): IShapedText[] {
- const {
- gridType = GridType.LINES,
- charSpace = 0,
- defaultTabStop = 10.5,
- drawings = {},
- } = sectionBreakConfig;
- const shapedTextList: IShapedText[] = [];
+ sectionBreakConfig: ISectionBreakConfig,
+ paragraph: IParagraph,
+ traditionalLayout: boolean,
+ measuredWholeEntityRanges: ICustomRangeForInterceptor[]
+): IBreakPoints {
const lineBreaker = new LineBreaker(content);
- const { endIndex } = paragraphNode;
- const paragraph = viewModel.getParagraph(endIndex) || { startIndex: 0, paragraphId: 'para_render_fallback' };
const { paragraphStyle = {} } = paragraph;
- const { snapToGrid = BooleanNumber.TRUE } = paragraphStyle;
- const measuredWholeEntityRanges = collectMeasuredWholeEntityRanges(content, viewModel, paragraphNode);
- const measuredWholeEntityRangeByStart = new Map(measuredWholeEntityRanges.map((range) => [
- range.startIndex - paragraphNode.startIndex,
- range,
- ]));
- const measuredWholeEntityRangeStarts = measuredWholeEntityRanges.map(
- (range) => range.startIndex - paragraphNode.startIndex
- );
- let measuredWholeEntityRangeIndex = 0;
- let last = 0;
- let bk;
-
const { hyphen } = ctx;
// Add custom extension for linebreak.
@@ -246,8 +391,29 @@ export function shaping(
if (cjk.hasCJKText(content)) {
eastAsianQuoteLineBreakExtension(lineBreaker);
}
+ if (traditionalLayout) {
+ // Word permits a signed value after CJK text or a list separator to
+ // start a line; the Unicode default joins the entire numeric list.
+ lineBreaker.addRule('break_before_cjk_signed_value', (codePoint, previous) => {
+ return (codePoint === 0x2B || codePoint === 0x2D) && previous != null
+ && (previous === 0x3001 || previous === 0xFF0C || cjk.hasCJKText(String.fromCodePoint(previous)));
+ });
+ if ((sectionBreakConfig.characterSpacingControl ?? ctx.dataModel.documentStyle.characterSpacingControl)
+ === characterSpacingControlType.doNotCompress) {
+ // With uncompressed punctuation, Word also permits a numeric hyphen
+ // to end the line. A plus sign remains attached to its number.
+ lineBreaker.addRule('break_after_uncompressed_numeric_hyphen', (codePoint, previous) => {
+ return previous === 0x2D && codePoint >= 0x30 && codePoint <= 0x39;
+ });
+ }
+ }
- let breaker: IBreakPoints = new LineBreakerLinkEnhancer(lineBreaker);
+ 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 lang = getHyphenationLanguage(ctx, content, paragraphStyle, sectionBreakConfig);
const doNotHyphenateCaps = sectionBreakConfig.doNotHyphenateCaps === BooleanNumber.TRUE;
@@ -262,30 +428,150 @@ export function shaping(
hyphen.loadPattern(lang).catch((error: unknown) => console.error(error));
}
}
- breaker = new LineBreakerWholeEntityEnhancer(
+ return new LineBreakerWholeEntityEnhancer(
breaker,
measuredWholeEntityRanges,
- paragraphNode.startIndex
+ paragraphNode.contentStartIndex
);
+}
- // eslint-disable-next-line no-cond-assign
- while ((bk = breaker.nextBreakPoint())) {
+function createNoteLabelGlyph(
+ ctx: ILayoutContext,
+ viewModel: DocumentViewModel,
+ paragraphNode: DataStreamTreeNode,
+ sectionBreakConfig: ISectionBreakConfig,
+ paragraph: IParagraph
+): IDocumentSkeletonGlyph | undefined {
+ if (ctx.noteLabel != null && viewModel === ctx.viewModel &&
+ paragraphNode.endIndex === viewModel.getBody()?.paragraphs?.[0]?.startIndex) {
+ const config = getFontCreateConfig(0, viewModel, paragraphNode, sectionBreakConfig, paragraph);
+ const textStyle = { ...config.textStyle, va: BaselineOffset.SUPERSCRIPT, ...ctx.noteReferenceTextStyle };
+ const marker = createSkeletonLetterGlyph(ctx.noteLabel, {
+ ...config,
+ textStyle,
+ fontStyle: getFontStyleString({ ...textStyle, ff: [textStyle.ff, textStyle.eastAsiaFontFamily].filter(Boolean).join(', ') }),
+ });
+ marker.raw = '';
+ marker.count = 0;
+ return marker;
+ }
+}
+
+function appendShapedText(
+ shapedTextList: IShapedText[],
+ shapedGlyphs: IDocumentSkeletonGlyph[],
+ breakPointType: BreakPointType
+): void {
+ const shapedGlyphsList: IDocumentSkeletonGlyph[][] = [[]];
+
+ for (let i = 0; i < shapedGlyphs.length; i++) {
+ const lastList = shapedGlyphsList[shapedGlyphsList.length - 1];
+ const glyph = shapedGlyphs[i];
+
+ // Inline Custom Block can open a new line.
+ if (glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width !== 0) {
+ if (lastList.length === 0) {
+ shapedGlyphsList.pop();
+ }
+ shapedGlyphsList.push([glyph]);
+ } else {
+ lastList.push(glyph);
+ }
+ }
+
+ const lastShapedGlyphs = shapedGlyphsList[shapedGlyphsList.length - 1];
+
+ for (const shapedGlyphs of shapedGlyphsList) {
+ const word = shapedGlyphs.map(getShapedGlyphText).join('');
+
+ shapedTextList.push({
+ text: word,
+ glyphs: shapedGlyphs,
+ breakPointType: shapedGlyphs === lastShapedGlyphs ? breakPointType : BreakPointType.Normal,
+ });
+ }
+}
+
+function setTabAlignedTextWidths(shapedTextList: IShapedText[]): void {
+ // Alignment tabs measure the entire following field, not just the next word-break slice.
+ let tabAlignedTextWidth = 0;
+ for (let index = shapedTextList.length - 1; index >= 0; index--) {
+ const glyphs = shapedTextList[index].glyphs;
+ for (let glyphIndex = glyphs.length - 1; glyphIndex >= 0; glyphIndex--) {
+ const glyph = glyphs[glyphIndex];
+ if (glyph.glyphType === GlyphType.TAB) {
+ glyph.tabAlignedTextWidth = tabAlignedTextWidth;
+ tabAlignedTextWidth = 0;
+ } else if (glyph.streamType === DataStreamTreeTokenType.PARAGRAPH || glyph.content === '\v') {
+ tabAlignedTextWidth = 0;
+ } else {
+ tabAlignedTextWidth += glyph.width;
+ }
+ }
+ }
+}
+
+export function shaping(
+ ctx: ILayoutContext,
+ content: string,
+ viewModel: DocumentViewModel,
+ paragraphNode: DataStreamTreeNode,
+ sectionBreakConfig: ISectionBreakConfig
+): IShapedText[] {
+ const shapedTextList: IShapedText[] = [];
+ const traditionalLayout = isTraditionalDocumentCompatibility(
+ sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy(ctx.dataModel.documentStyle.documentFlavor)
+ );
+ const fixedPunctuationPairs = traditionalLayout
+ && (sectionBreakConfig.characterSpacingControl ?? ctx.dataModel.documentStyle.characterSpacingControl)
+ === characterSpacingControlType.doNotCompress;
+ const { endIndex } = paragraphNode;
+ const paragraph = viewModel.getParagraph(endIndex) || { startIndex: 0, paragraphId: 'para_render_fallback' };
+ const { paragraphStyle = {} } = paragraph;
+ const { snapToGrid = BooleanNumber.TRUE } = paragraphStyle;
+ const measuredWholeEntityRanges = collectMeasuredWholeEntityRanges(content, viewModel, paragraphNode);
+ const measuredWholeEntityRangeByStart = new Map(measuredWholeEntityRanges.map((range) => [
+ range.startIndex - paragraphNode.contentStartIndex,
+ range,
+ ]));
+ const measuredWholeEntityRangeStarts = measuredWholeEntityRanges.map(
+ (range) => range.startIndex - paragraphNode.contentStartIndex
+ );
+ let measuredWholeEntityRangeIndex = 0;
+ let last = 0;
+
+ const breaker = createShapingLineBreaker(
+ ctx,
+ content,
+ viewModel,
+ paragraphNode,
+ sectionBreakConfig,
+ paragraph,
+ traditionalLayout,
+ measuredWholeEntityRanges
+ );
+
+ for (let bk = breaker.nextBreakPoint(); bk; bk = breaker.nextBreakPoint()) {
+ // Word treats a spaced ellipsis like closing punctuation, keeping the preceding word with it.
+ if (traditionalLayout && bk.type === BreakPointType.Normal
+ && content[bk.position] === '…' && content[bk.position - 1] === ' ') {
+ continue;
+ }
+ // 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
+ && /[a-z]\/[a-z]/i.test(content.slice(bk.position - 2, bk.position + 1))) {
+ continue;
+ }
// get the string between the last break and this one
const word = content.slice(last, bk.position);
const shapedGlyphs: IDocumentSkeletonGlyph[] = [];
- if (last === 0 && ctx.noteLabel != null && viewModel === ctx.viewModel &&
- paragraphNode.endIndex === viewModel.getBody()?.paragraphs?.[0]?.startIndex) {
- const config = getFontCreateConfig(0, viewModel, paragraphNode, sectionBreakConfig, paragraph);
- const textStyle = { ...config.textStyle, va: BaselineOffset.SUPERSCRIPT, ...ctx.noteReferenceTextStyle };
- const marker = createSkeletonLetterGlyph(ctx.noteLabel, {
- ...config,
- textStyle,
- fontStyle: getFontStyleString({ ...textStyle, ff: [textStyle.ff, textStyle.eastAsiaFontFamily].filter(Boolean).join(', ') }),
- });
- marker.raw = '';
- marker.count = 0;
- shapedGlyphs.push(marker);
+ if (last === 0) {
+ const marker = createNoteLabelGlyph(ctx, viewModel, paragraphNode, sectionBreakConfig, paragraph);
+ if (marker) {
+ shapedGlyphs.push(marker);
+ }
}
let src = word;
@@ -298,7 +584,7 @@ export function shaping(
measuredWholeEntityRangeIndex++;
}
- const char = src.match(/^[\s\S]/gu)?.[0];
+ let char = src.match(/^[\s\S]/gu)?.[0];
if (char == null) {
break;
@@ -325,158 +611,36 @@ export function shaping(
measuredWholeEntityRangeIndex++;
}
- const fieldType = char === '\uFFFC'
- ? viewModel.getCustomRangeRaw(paragraphNode.startIndex + i)?.properties?.fieldType
- : undefined;
- const isSeparator = fieldType === 'FOOTNOTE_SEPARATOR' || fieldType === 'FOOTNOTE_CONTINUATION_SEPARATOR';
- const note = viewModel === ctx.viewModel && char === '\uFFFC'
- ? ctx.noteReferences?.get(paragraphNode.startIndex + i)
+ const noteGlyph = char === '\uFFFC'
+ ? createNoteGlyph(ctx, i, viewModel, paragraphNode, sectionBreakConfig, paragraph)
: undefined;
- if (isSeparator) {
- const config = getFontCreateConfig(i, viewModel, paragraphNode, sectionBreakConfig, paragraph);
- const textWidth = Math.max(0, (sectionBreakConfig.pageSize?.width ?? 192) -
- (sectionBreakConfig.marginLeft ?? 0) - (sectionBreakConfig.marginRight ?? 0));
- const width = fieldType === 'FOOTNOTE_SEPARATOR' ? Math.min(192, textWidth) : textWidth;
- const glyph = createSkeletonLetterGlyph(' ', config, width);
- glyph.raw = '\uFFFC';
- glyph.noteSeparator = true;
- shapedGlyphs.push(glyph);
- i++;
- src = src.substring(1);
- } else if (note) {
- const config = getFontCreateConfig(i, viewModel, paragraphNode, sectionBreakConfig, paragraph);
- const glyph = createSkeletonLetterGlyph(note.label, config);
- glyph.raw = '\uFFFC';
- glyph.count = 1;
- glyph.noteId = note.noteId;
- shapedGlyphs.push(glyph);
+ if (noteGlyph) {
+ shapedGlyphs.push(noteGlyph);
i++;
src = src.substring(1);
} else if (char === DataStreamTreeTokenType.CUSTOM_BLOCK) {
- const config = getFontCreateConfig(i, viewModel, paragraphNode, sectionBreakConfig, paragraph);
- let newGlyph: Nullable<IDocumentSkeletonGlyph> = null;
- const customBlock = viewModel.getCustomBlockWithoutSetCurrentIndex(paragraphNode.startIndex + i);
-
- if (customBlock != null) {
- const { blockId } = customBlock;
- const drawingOrigin = drawings[blockId];
- if (drawingOrigin?.layoutType === PositionedObjectLayoutType.INLINE) {
- const { angle } = drawingOrigin.docTransform;
- const { width = 0, height = 0 } = drawingOrigin.docTransform.size;
- const top = 0;
- const left = 0;
- const boundingBox = getBoundingBox(angle, left, width, top, height);
- const viewport = getDocsCustomBlockRenderViewport(
- viewModel.getDataModel().getUnitId?.() ?? '',
- drawingOrigin.drawingId,
- {
- fallbackHeight: boundingBox.height ?? 0,
- fallbackWidth: boundingBox.width ?? 0,
- }
- );
-
- newGlyph = createSkeletonCustomBlockGlyph(
- config,
- viewport?.layoutWidth ?? viewport?.width ?? boundingBox.width,
- viewport?.height ?? boundingBox.height,
- drawingOrigin.drawingId
- );
- } else if (drawingOrigin != null) {
- newGlyph = createSkeletonCustomBlockGlyph(config, 0, 0, drawingOrigin.drawingId);
- }
- }
-
- if (newGlyph == null) {
- newGlyph = createSkeletonLetterGlyph(char, config);
- }
+ const newGlyph = createShapedCustomBlockGlyph(i, char, viewModel, paragraphNode, sectionBreakConfig, paragraph);
shapedGlyphs.push(newGlyph);
i += char.length;
src = src.substring(char.length);
} else if (/\s/.test(char) || cjk.hasCJK(char)) {
const config = getFontCreateConfig(i, viewModel, paragraphNode, sectionBreakConfig, paragraph);
- let newGlyph: Nullable<IDocumentSkeletonGlyph> = null;
-
- if (char === DataStreamTreeTokenType.TAB) {
- const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);
- newGlyph = createSkeletonTabGlyph(config, charSpaceApply);
- } else if (char === DataStreamTreeTokenType.PARAGRAPH) {
- const zeroWidthParagraphBreak = sectionBreakConfig.renderConfig?.zeroWidthParagraphBreak;
-
- if (zeroWidthParagraphBreak === BooleanNumber.TRUE) {
- newGlyph = createSkeletonLetterGlyph(char, config, 0);
- } else {
- newGlyph = createSkeletonLetterGlyph(
- char,
- config,
- getCustomRangeGlyphMetrics(i, viewModel, paragraphNode, config)
- );
- }
- } else {
- newGlyph = createSkeletonLetterGlyph(char, config);
+ if (config.textStyle.sc && cjk.hasCJK(char)) {
+ char = getFirstGrapheme(src) ?? char;
}
+ const newGlyph = createWhitespaceGlyph(char, config, i, viewModel, paragraphNode, sectionBreakConfig, snapToGrid, traditionalLayout);
shapedGlyphs.push(newGlyph);
i += char.length;
src = src.substring(char.length);
- } else if (startWithEmoji(src)) {
- const { step, glyphGroup } = emojiHandler(
- i,
- src,
- viewModel,
- paragraphNode,
- sectionBreakConfig,
- paragraph
- );
- shapedGlyphs.push(...glyphGroup);
- i += step;
-
- src = src.substring(step);
- } else if (hasArabic(char)) {
- const { step, glyphGroup } = ArabicHandler(
- i,
- src,
- viewModel,
- paragraphNode,
- sectionBreakConfig,
- paragraph
- );
- shapedGlyphs.push(...glyphGroup);
- i += step;
-
- src = src.substring(step);
- } else if (hasTibetan(char)) {
- const { step, glyphGroup } = TibetanHandler(
- i,
- src,
- viewModel,
- paragraphNode,
- sectionBreakConfig,
- paragraph
- );
- shapedGlyphs.push(...glyphGroup);
- i += step;
-
- src = src.substring(step);
- } else if (hasThai(char)) {
- const { step, glyphGroup } = ThaiHandler(
- i,
- src,
- viewModel,
- paragraphNode,
- sectionBreakConfig,
- paragraph
- );
- shapedGlyphs.push(...glyphGroup);
- i += step;
-
- src = src.substring(step);
} else {
+ const handler = getScriptHandler(src, char);
const nextMeasuredRangeStart = measuredWholeEntityRangeStarts[measuredWholeEntityRangeIndex];
- const sourceBeforeMeasuredRange = nextMeasuredRangeStart == null
+ const sourceBeforeMeasuredRange = handler !== otherHandler || nextMeasuredRangeStart == null
? src
: src.slice(0, nextMeasuredRangeStart - i);
- const { step, glyphGroup } = otherHandler(
+ const { step, glyphGroup } = handler(
i,
sourceBeforeMeasuredRange,
viewModel,
@@ -491,43 +655,24 @@ export function shaping(
}
}
- // Continuous punctuation space adjustment.
- punctuationSpaceAdjustment(shapedGlyphs);
-
- const shapedGlyphsList: IDocumentSkeletonGlyph[][] = [[]];
-
- for (let i = 0; i < shapedGlyphs.length; i++) {
- const lastList = shapedGlyphsList[shapedGlyphsList.length - 1];
- const glyph = shapedGlyphs[i];
-
- // Inline Custom Block can open a new line.
- if (glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width !== 0) {
- if (lastList.length === 0) {
- shapedGlyphsList.pop();
- }
- shapedGlyphsList.push([glyph]);
- } else {
- lastList.push(glyph);
- }
+ // With line compression enabled, Word resolves spacing for the whole line.
+ // doNotCompress still retains fixed adjacent-punctuation spacing, including
+ // East Asian quote/bracket pairs, independently of line justification.
+ if (!traditionalLayout || fixedPunctuationPairs) {
+ punctuationSpaceAdjustment(shapedGlyphs, fixedPunctuationPairs);
}
- const lastShapedGlyphs = shapedGlyphsList[shapedGlyphsList.length - 1];
-
- for (const shapedGlyphs of shapedGlyphsList) {
- const word = shapedGlyphs.map(getShapedGlyphText).join('');
-
- shapedTextList.push({
- text: word,
- glyphs: shapedGlyphs,
- breakPointType: shapedGlyphs === lastShapedGlyphs ? bk.type : BreakPointType.Normal,
- });
- }
+ appendShapedText(shapedTextList, shapedGlyphs, bk.type);
last = bk.position;
}
- // Add some spacing between Han characters and western characters.
- addCJKLatinSpacing(shapedTextList);
+ // Preserve the legacy default, but honor documents that explicitly disable mixed-script spacing.
+ if (sectionBreakConfig.spaceWidthEastAsian !== BooleanNumber.FALSE) {
+ addCJKLatinSpacing(shapedTextList);
+ }
+
+ setTabAlignedTextWidths(shapedTextList);
return shapedTextList;
}
diff --git a/packages/engine-render/src/components/docs/layout/block/section.ts b/packages/engine-render/src/components/docs/layout/block/section.ts
index 4f67e5d3ad..1f06a32aa0 100644
--- a/packages/engine-render/src/components/docs/layout/block/section.ts
+++ b/packages/engine-render/src/components/docs/layout/block/section.ts
@@ -87,7 +87,9 @@ export function dealWithSection(
ctx,
sectionBreakConfig,
ctx.skeletonResourceReference,
- currentPageCache.pageNumber + 1
+ currentPageCache.pageNumber + 1,
+ undefined,
+ currentPageCache
);
}
skeletonPages = dealWidthParagraph(
diff --git a/packages/engine-render/src/components/docs/layout/block/table.ts b/packages/engine-render/src/components/docs/layout/block/table.ts
index 38ad30c291..279e96df3e 100644
--- a/packages/engine-render/src/components/docs/layout/block/table.ts
+++ b/packages/engine-render/src/components/docs/layout/block/table.ts
@@ -27,20 +27,33 @@ import type { DocumentViewModel } from '../../view-model/document-view-model';
import type { DocumentFootnoteLayout } from '../footnote-layout';
import type { ICellSkeletonBuildState } from '../model/page';
import type { ILayoutContext } from '../tools';
-import { BooleanNumber, TableAlignmentType, TableRowHeightRule, VerticalAlignmentType } from '@univerjs/core';
+import {
+ BooleanNumber,
+ DataStreamTreeTokenType,
+ NumberUnitType,
+ ObjectRelativeFromV,
+ PositionedObjectLayoutType,
+ SpacingRule,
+ TableAlignmentType,
+ TableRowHeightRule,
+ TableSizeType,
+ VerticalAlignmentType,
+} from '@univerjs/core';
import { DocumentSkeletonPageType } from '../../../../basics/i-document-skeleton-cached';
import { getDocumentCompatibilityPolicy, isTraditionalDocumentCompatibility } from '../../document-compatibility';
import {
createNullCellPage,
createSkeletonCellPages,
+ getRowBorderInset,
startSkeletonCellPagesBuild,
stepSkeletonCellPagesBuild,
} from '../model/page';
-const precomputedTableSkeletons = new WeakMap<ILayoutContext, Map<number, IDocumentSkeletonTable>>();
+// Body, header and footer streams can share both table IDs and character offsets.
+const precomputedTableSkeletons = new WeakMap<ILayoutContext, WeakMap<DataStreamTreeNode, IDocumentSkeletonTable>>();
const precomputedSlicedTableSkeletons = new WeakMap<
ILayoutContext,
- Map<number, { availableHeight: number; result: ISlicedTableSkeletonParams }>
+ WeakMap<DataStreamTreeNode, { availableHeight: number; result: ISlicedTableSkeletonParams }>
>();
export interface ITableSkeletonBuildState {
@@ -60,6 +73,7 @@ export interface ITableSkeletonBuildState {
currentColumnIndex: number;
currentRowLeft: number;
currentRowHeight: number;
+ mergedCellContentHeights: Map<string, number>;
currentCellBuild: Nullable<ICellSkeletonBuildState>;
}
@@ -70,11 +84,16 @@ export function startTableSkeletonBuild(
tableNode: DataStreamTreeNode,
sectionBreakConfig: ISectionBreakConfig
): Nullable<ITableSkeletonBuildState> {
- const table = viewModel.getTableByStartIndex(tableNode.startIndex)?.tableSource;
- if (table == null) {
+ const tableSource = viewModel.getTableByStartIndex(tableNode.startIndex)?.tableSource;
+ if (tableSource == null) {
console.warn(`Table not found when creating table skeleton at index ${tableNode.startIndex}`);
return null;
}
+ const table = resolveTableLayoutColumns(
+ tableSource,
+ getTableAvailableWidth(curPage),
+ isTraditionalDocumentCompatibility(sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy())
+ );
return {
ctx,
@@ -93,6 +112,7 @@ export function startTableSkeletonBuild(
currentColumnIndex: 0,
currentRowLeft: 0,
currentRowHeight: 0,
+ mergedCellContentHeights: new Map(),
currentCellBuild: null,
};
}
@@ -124,15 +144,15 @@ export function stepTableSkeletonBuild(state: ITableSkeletonBuildState): boolean
export function cachePrecomputedTableSkeleton(
ctx: ILayoutContext,
- tableStartIndex: number,
+ tableNode: DataStreamTreeNode,
tableSkeleton: IDocumentSkeletonTable
): void {
let cache = precomputedTableSkeletons.get(ctx);
if (cache == null) {
- cache = new Map();
+ cache = new WeakMap();
precomputedTableSkeletons.set(ctx, cache);
}
- cache.set(tableStartIndex, tableSkeleton);
+ cache.set(tableNode, tableSkeleton);
}
export function createTableSkeleton(
@@ -142,7 +162,7 @@ export function createTableSkeleton(
tableNode: DataStreamTreeNode,
sectionBreakConfig: ISectionBreakConfig
): Nullable<IDocumentSkeletonTable> {
- const cached = precomputedTableSkeletons.get(ctx)?.get(tableNode.startIndex);
+ const cached = precomputedTableSkeletons.get(ctx)?.get(tableNode);
if (cached != null) {
return cached;
}
@@ -158,6 +178,17 @@ export function createTableSkeleton(
return state.tableSkeleton;
}
+function getOmittedGridWidth(table: ITable, row: number, edge: 'before' | 'after'): number {
+ const count = Math.max(0, edge === 'before' ? table.tableRows[row].gridBefore ?? 0 : table.tableRows[row].gridAfter ?? 0);
+ if (count === 0) {
+ return 0;
+ }
+ const columns = edge === 'before'
+ ? table.tableColumns.slice(0, count)
+ : table.tableColumns.slice(Math.max(0, table.tableColumns.length - count));
+ return columns.reduce((width, column) => width + column.size.width.v, 0);
+}
+
function _startUnslicedTableRow(state: ITableSkeletonBuildState, rowNode: DataStreamTreeNode): void {
const { table, tableSkeleton } = state;
const { startIndex, endIndex } = rowNode;
@@ -168,7 +199,7 @@ function _startUnslicedTableRow(state: ITableSkeletonBuildState, rowNode: DataSt
state.currentRowNode = rowNode;
state.currentRowSkeleton = rowSkeleton;
state.currentColumnIndex = 0;
- state.currentRowLeft = 0;
+ state.currentRowLeft = getOmittedGridWidth(table, row, 'before');
state.currentRowHeight = 0;
}
@@ -240,7 +271,9 @@ function _appendUnslicedCell(state: ITableSkeletonBuildState, cellPageSkeletons:
}
const pageHeight = getCellPagesLayoutHeight(
cellPageSkeletons,
- state.curPage.type === DocumentSkeletonPageType.CELL
+ state.curPage.type === DocumentSkeletonPageType.CELL,
+ state.viewModel,
+ state.table.tableRows[row]
);
cellPageSkeleton.left = state.currentRowLeft;
if (shouldAdvanceTableCellLeft(state.table, row, col)) {
@@ -248,7 +281,12 @@ function _appendUnslicedCell(state: ITableSkeletonBuildState, cellPageSkeletons:
}
cellPageSkeleton.parent = rowSkeleton;
rowSkeleton.cells.push(cellPageSkeleton);
- state.currentRowHeight = Math.max(state.currentRowHeight, pageHeight);
+ const rowSpan = state.table.tableRows[row].tableCells[col].rowSpan ?? 1;
+ if (rowSpan > 1) {
+ state.mergedCellContentHeights.set(`${row}:${col}`, pageHeight);
+ } else {
+ state.currentRowHeight = Math.max(state.currentRowHeight, pageHeight);
+ }
}
function _finishUnslicedTableRow(state: ITableSkeletonBuildState): void {
@@ -258,7 +296,10 @@ function _finishUnslicedTableRow(state: ITableSkeletonBuildState): void {
let rowHeight = state.currentRowHeight;
if (hRule === TableRowHeightRule.AT_LEAST) {
- rowHeight = Math.max(rowHeight, val.v);
+ const traditional = isTraditionalDocumentCompatibility(
+ state.sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy()
+ );
+ rowHeight = Math.max(rowHeight, getRowMinimumHeight(state.table, state.rowIndex, traditional));
} else if (hRule === TableRowHeightRule.EXACT) {
rowHeight = val.v;
}
@@ -270,7 +311,7 @@ function _finishUnslicedTableRow(state: ITableSkeletonBuildState): void {
rowSkeleton.height = rowHeight;
rowSkeleton.top = state.rowTop;
state.rowTop += rowHeight;
- state.tableWidth = Math.max(state.tableWidth, state.currentRowLeft);
+ state.tableWidth = Math.max(state.tableWidth, state.currentRowLeft + getOmittedGridWidth(state.table, state.rowIndex, 'after'));
state.rowIndex++;
state.currentRowNode = null;
state.currentRowSkeleton = null;
@@ -280,15 +321,20 @@ function _finishUnslicedTableRow(state: ITableSkeletonBuildState): void {
function _finishTableSkeletonBuild(state: ITableSkeletonBuildState): void {
const { curPage, table, tableSkeleton } = state;
+ applyMergedCellContentHeights(tableSkeleton, state.mergedCellContentHeights);
tableSkeleton.width = state.tableWidth;
- tableSkeleton.height = state.rowTop;
- const mergedRowHeightsChanged = isTraditionalDocumentCompatibility(state.sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy()) &&
+ tableSkeleton.height = tableSkeleton.rows.reduce((height, row) => {
+ row.top = height;
+ return height + row.height;
+ }, 0);
+ if (isTraditionalDocumentCompatibility(state.sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy())) {
resolveMergedRowHeights(tableSkeleton);
+ }
applyMergedCellSpanHeights(tableSkeleton);
- if (mergedRowHeightsChanged) {
- for (const row of tableSkeleton.rows) {
- _verticalAlignInCell(row, table.tableRows[row.index]);
- }
+ applyTableOuterBorderSpacing(tableSkeleton, state.sectionBreakConfig);
+
+ for (const rowSkeleton of tableSkeleton.rows) {
+ _verticalAlignInCell(rowSkeleton, table.tableRows[rowSkeleton.index]);
}
const { pageWidth, marginLeft = 0, marginRight = 0 } = curPage;
@@ -301,32 +347,138 @@ function _finishTableSkeletonBuild(state: ITableSkeletonBuildState): void {
state.complete = true;
}
-function getCellPagesLayoutHeight(pages: IDocumentSkeletonPage[], includeContinuations: boolean): number {
- const measuredPages = includeContinuations ? pages : pages.slice(0, 1);
- return measuredPages.reduce((total, page) => {
- const { marginTop = 0, marginBottom = 0 } = page;
- return total + page.height + marginTop + marginBottom;
- }, 0);
+function applyMergedCellContentHeights(
+ tableSkeleton: IDocumentSkeletonTable,
+ mergedCellContentHeights: Map<string, number>
+): void {
+ for (const [cellKey, contentHeight] of mergedCellContentHeights) {
+ const [rowIndex, columnIndex] = cellKey.split(':').map(Number);
+ const rowSpan =
+ tableSkeleton.tableSource?.tableRows[rowIndex]?.tableCells[columnIndex]?.rowSpan ?? 1;
+ const spannedRows = tableSkeleton.rows.slice(rowIndex, rowIndex + rowSpan);
+ const spanHeight = spannedRows.reduce((height, row) => height + row.height, 0);
+ const lastRow = spannedRows[spannedRows.length - 1];
+
+ if (lastRow != null && contentHeight > spanHeight) {
+ lastRow.height += contentHeight - spanHeight;
+ }
+ }
+
+ for (const rowSkeleton of tableSkeleton.rows) {
+ for (const cellPageSkeleton of rowSkeleton.cells) {
+ cellPageSkeleton.pageHeight = rowSkeleton.height;
+ }
+ }
}
-export function rollbackListCache(listLevel: Map<string, IParagraphList[][]>, table: DataStreamTreeNode) {
+function rollbackListCache(listLevel: Map<string, IParagraphList[][]>, table: DataStreamTreeNode): void {
const { startIndex, endIndex } = table;
-
for (const paragraphLists of listLevel.values()) {
for (const paragraphList of paragraphLists) {
if (paragraphList == null) {
continue;
}
-
- const paragraphListIndex = paragraphList.findIndex((p) => p.paragraph.startIndex > startIndex && p.paragraph.startIndex < endIndex);
-
- if (paragraphListIndex > -1) {
- paragraphList.splice(paragraphListIndex);
+ const index = paragraphList.findIndex((item) => item.paragraph.startIndex > startIndex && item.paragraph.startIndex < endIndex);
+ if (index > -1) {
+ paragraphList.splice(index);
}
}
}
}
+function getTableBorderHeight(firstRow: ITableRow, lastRow: ITableRow, traditional: boolean): number {
+ return traditional ? getRowBorderInset(firstRow, 'borderTop', true) + getRowBorderInset(lastRow, 'borderBottom', true) : 0;
+}
+
+function getRowMinimumHeight(table: ITable, index: number, traditional: boolean): number {
+ const row = table.tableRows[index];
+ const minimum = row.trHeight.val.v;
+ if (!traditional || minimum <= 0) {
+ return minimum;
+ }
+ // Word's authored minimum excludes the collapsed row-border insets. Content
+ // measurement already contains them, so add them only to the minimum branch.
+ const previous = table.tableRows[index - 1];
+ const next = table.tableRows[index + 1];
+ const top = Math.max(getRowBorderInset(row, 'borderTop'), previous ? getRowBorderInset(previous, 'borderBottom') : 0);
+ const bottom = Math.max(getRowBorderInset(row, 'borderBottom'), next ? getRowBorderInset(next, 'borderTop') : 0);
+ return minimum + top + bottom;
+}
+
+function applyTableOuterBorderSpacing(table: IDocumentSkeletonTable, config: ISectionBreakConfig): void {
+ if (!isTraditionalDocumentCompatibility(config.documentCompatibilityPolicy) || table.rows.length === 0) {
+ return;
+ }
+ const firstRow = table.rows[0].rowSource;
+ const lastRow = table.rows[table.rows.length - 1].rowSource;
+ const top = getRowBorderInset(firstRow, 'borderTop', true);
+ for (const row of table.rows) {
+ row.top += top;
+ }
+ table.height += top + getRowBorderInset(lastRow, 'borderBottom', true);
+}
+
+function getCellPagesLayoutHeight(
+ pages: IDocumentSkeletonPage[],
+ includeContinuations: boolean,
+ viewModel: DocumentViewModel,
+ rowSource?: ITableRow
+): number {
+ const measuredPages = includeContinuations ? pages : pages.slice(0, 1);
+ return measuredPages.reduce((total, page) => total + getCellPageLayoutHeight(page, viewModel, rowSource), 0);
+}
+
+function getCellPageLayoutHeight(page: IDocumentSkeletonPage, viewModel: DocumentViewModel, rowSource?: ITableRow): number {
+ if (
+ rowSource?.trHeight.hRule === TableRowHeightRule.AT_LEAST &&
+ rowSource.trHeight.val.v > 0 &&
+ isStructurallyEmptyCellPage(page, viewModel)
+ ) {
+ return 0;
+ }
+
+ const { marginTop = 0, marginBottom = 0 } = page;
+ if (page.cellTextDirection === 'tbRlV') {
+ return page.height + page.marginLeft + page.marginRight;
+ }
+ return page.height + marginTop + marginBottom;
+}
+
+function isStructurallyEmptyCellPage(page: IDocumentSkeletonPage, viewModel: DocumentViewModel): boolean {
+ if (
+ (page.skeTables?.size ?? 0) > 0 ||
+ (page.skeDrawings?.size ?? 0) > 0 ||
+ (page.skeColumnGroups?.size ?? 0) > 0
+ ) {
+ return false;
+ }
+
+ const lines = page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines));
+ // An authored blank paragraph with fixed/minimum leading is content, not a table terminator.
+ if (lines.some((line) => {
+ const style = viewModel.getParagraph(line.paragraphIndex)?.paragraphStyle;
+ return (style?.spacingRule === SpacingRule.EXACT || style?.spacingRule === SpacingRule.AT_LEAST) &&
+ (style.lineSpacing ?? 0) > 0;
+ })) {
+ return false;
+ }
+ const glyphs = lines.flatMap((line) =>
+ line.divides.flatMap((divide) => divide.glyphGroup)
+ );
+ // Only one empty paragraph can be the cell terminator. Additional blank
+ // paragraphs are authored vertical content, even with automatic line spacing.
+ if (glyphs.length === 0 || glyphs.filter((glyph) => glyph.streamType === DataStreamTreeTokenType.PARAGRAPH).length > 1) {
+ return false;
+ }
+
+ return glyphs.every(
+ (glyph) =>
+ glyph.streamType === DataStreamTreeTokenType.PARAGRAPH ||
+ glyph.streamType === DataStreamTreeTokenType.SECTION_BREAK ||
+ glyph.streamType === DataStreamTreeTokenType.DOCS_END
+ );
+}
+
export interface ISlicedTableSkeletonParams {
skeTables: IDocumentSkeletonTable[];
fromCurrentPage: boolean;
@@ -370,10 +522,15 @@ export function startTableSkeletonsBuild(
availableHeight: number
): Nullable<ISlicedTableSkeletonBuildState> {
const { startIndex, endIndex, children: rowNodes } = tableNode;
- const table = viewModel.getTableByStartIndex(startIndex)?.tableSource;
- if (table == null) {
+ const tableSource = viewModel.getTableByStartIndex(startIndex)?.tableSource;
+ if (tableSource == null) {
return null;
}
+ const table = resolveTableLayoutColumns(
+ tableSource,
+ getTableAvailableWidth(curPage),
+ isTraditionalDocumentCompatibility(sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy())
+ );
const skeTables = [getNullTableSkeleton(startIndex, endIndex, table)];
return {
@@ -387,7 +544,7 @@ export function startTableSkeletonsBuild(
skeTables,
createCache: {
rowTop: 0,
- tableWidth: precomputedTableSkeletons.get(ctx)?.get(startIndex)?.width ?? 0,
+ tableWidth: precomputedTableSkeletons.get(ctx)?.get(tableNode)?.width ?? 0,
remainHeight: availableHeight,
repeatRows: getLeadingRepeatHeaderRows(table, rowNodes),
repeatRowsHeight: 0,
@@ -416,19 +573,25 @@ export function stepTableSkeletonsBuild(state: ISlicedTableSkeletonBuildState):
const cellNode = rowNode.children[state.columnIndex];
const rowSource = state.table.tableRows[state.rowIndex];
const cellConfig = rowSource.tableCells[state.columnIndex];
- const precomputedRow = precomputedTableSkeletons.get(state.ctx)?.get(state.tableNode.startIndex)?.rows[state.rowIndex];
+ const traditional = isTraditionalDocumentCompatibility(state.sectionBreakConfig.documentCompatibilityPolicy);
+ const firstRowSource = getCurTableSkeleton(state.skeTables).rows[0]?.rowSource ?? rowSource;
+ const firstBorderHeight = getTableBorderHeight(firstRowSource, rowSource, traditional);
+ const nextBorderHeight = getTableBorderHeight(rowSource, rowSource, traditional);
+ const precomputedRow = precomputedTableSkeletons.get(state.ctx)?.get(state.tableNode)?.rows[state.rowIndex];
// Pagination uses the same current-generation measurements as the synchronous
// path. Only cells in rows that actually need splitting must be laid out again.
- const reusePrecomputedRow = state.cellPageHeights == null && canReusePrecomputedTableRow(state.curPage, state.createCache, rowSource, precomputedRow);
+ const minimumHeight = traditional && rowSource.trHeight.hRule === TableRowHeightRule.AT_LEAST ? getRowMinimumHeight(state.table, state.rowIndex, true) : 0;
+ const reusePrecomputedRow = state.cellPageHeights == null && canReusePrecomputedTableRow(state.curPage, state.createCache, rowSource, precomputedRow, firstBorderHeight, minimumHeight);
if (!reusePrecomputedRow && cellNode != null && !isCoveredTableCell(cellConfig)) {
- const pageContentHeight = getAvailableHeight(state.curPage, state.createCache, false);
- const availableHeight = getAvailableHeight(state.curPage, state.createCache, true);
+ const pageContentHeight = getAvailableHeight(state.curPage, state.createCache, traditional && state.rowIndex >= state.createCache.repeatRows.length) - nextBorderHeight;
+ const availableHeight = getAvailableHeight(state.curPage, state.createCache, true) - nextBorderHeight;
const canRowSplit =
rowSource.cantSplit !== BooleanNumber.TRUE &&
- rowSource.trHeight.hRule === TableRowHeightRule.AUTO;
- const needOpenNewTable = state.createCache.remainHeight <= 72;
+ rowSource.trHeight.hRule !== TableRowHeightRule.EXACT;
+ const needOpenNewTable = state.createCache.remainHeight <= firstBorderHeight ||
+ (minimumHeight <= availableHeight && minimumHeight + firstBorderHeight > state.createCache.remainHeight);
const firstCellPageHeight = canRowSplit && !needOpenNewTable
- ? state.createCache.remainHeight
+ ? state.createCache.remainHeight - firstBorderHeight
: availableHeight;
state.pendingCellBuild ??= startSkeletonCellPagesBuild(
state.ctx,
@@ -503,20 +666,21 @@ export function stepTableSkeletonsBuild(state: ISlicedTableSkeletonBuildState):
export function cachePrecomputedSlicedTableSkeletons(
ctx: ILayoutContext,
- tableStartIndex: number,
+ tableNode: DataStreamTreeNode,
availableHeight: number,
result: ISlicedTableSkeletonParams
): void {
let cache = precomputedSlicedTableSkeletons.get(ctx);
if (cache == null) {
- cache = new Map();
+ cache = new WeakMap();
precomputedSlicedTableSkeletons.set(ctx, cache);
}
- cache.set(tableStartIndex, { availableHeight, result });
+ cache.set(tableNode, { availableHeight, result });
}
function _finishTableSkeletonsBuild(state: ISlicedTableSkeletonBuildState): void {
updateTableSkeletonsPosition(state.createCache, state.curPage, state.skeTables, state.table);
+ state.skeTables.forEach((table) => applyTableOuterBorderSpacing(table, state.sectionBreakConfig));
const policy =
state.sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy();
state.result = {
@@ -540,13 +704,13 @@ export function createTableSkeletons(
): ISlicedTableSkeletonParams {
const skeTables: IDocumentSkeletonTable[] = [];
const { startIndex, endIndex, children: rowNodes } = tableNode;
- const precomputedSliced = precomputedSlicedTableSkeletons.get(ctx)?.get(startIndex);
+ const precomputedSliced = precomputedSlicedTableSkeletons.get(ctx)?.get(tableNode);
if (
precomputedSliced != null &&
Math.abs(precomputedSliced.availableHeight - availableHeight) < 0.01
) {
- precomputedSlicedTableSkeletons.get(ctx)?.delete(startIndex);
- precomputedTableSkeletons.get(ctx)?.delete(startIndex);
+ precomputedSlicedTableSkeletons.get(ctx)?.delete(tableNode);
+ precomputedTableSkeletons.get(ctx)?.delete(tableNode);
return precomputedSliced.result;
}
@@ -566,18 +730,23 @@ export function createTableSkeletons(
return { skeTables: [], fromCurrentPage: false };
}
- const table = viewModel.getTableByStartIndex(startIndex)?.tableSource;
- if (table == null) {
+ const tableSource = viewModel.getTableByStartIndex(startIndex)?.tableSource;
+ if (tableSource == null) {
console.warn(`Table not found when creating sliced table skeletons at index ${startIndex}`);
return {
skeTables,
fromCurrentPage: false,
};
}
+ const table = resolveTableLayoutColumns(
+ tableSource,
+ getTableAvailableWidth(curPage),
+ isTraditionalDocumentCompatibility(sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy())
+ );
const repeatRows = getLeadingRepeatHeaderRows(table, rowNodes);
- const precomputedTable = precomputedTableSkeletons.get(ctx)?.get(startIndex);
- precomputedTableSkeletons.get(ctx)?.delete(startIndex);
+ const precomputedTable = precomputedTableSkeletons.get(ctx)?.get(tableNode);
+ precomputedTableSkeletons.get(ctx)?.delete(tableNode);
const curTableSkeleton = getNullTableSkeleton(startIndex, endIndex, table);
const createCache: ICreateTableCache = {
@@ -615,6 +784,7 @@ export function createTableSkeletons(
}
updateTableSkeletonsPosition(createCache, curPage, skeTables, table);
+ skeTables.forEach((table) => applyTableOuterBorderSpacing(table, sectionBreakConfig));
const documentCompatibilityPolicy = sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy();
const fromCurrentPage =
@@ -636,10 +806,23 @@ function updateTableSkeletonsPosition(
const { pageWidth, marginLeft = 0, marginRight = 0 } = curPage;
const { tableWidth } = cache;
const tableLeft = getTableLeft(pageWidth - marginLeft - marginRight, tableWidth, table.align, table.indent);
+ const rowFragments = new Map<number, number>();
+ for (const part of skeTables) {
+ for (const row of part.rows) {
+ if (!row.isRepeatRow) {
+ rowFragments.set(row.index, (rowFragments.get(row.index) ?? 0) + 1);
+ }
+ }
+ }
let tableIndex = 0;
for (const tableSkeleton of skeTables) {
applyMergedCellSpanHeights(tableSkeleton);
+ // Pagination restores the visible merged height after aligning each row.
+ // Re-align only merged masters; actual split-row content stays top-aligned.
+ for (const row of tableSkeleton.rows) {
+ _verticalAlignInCell(row, table.tableRows[row.index], (rowFragments.get(row.index) ?? 0) > 1, true);
+ }
// Update table width and left.
tableSkeleton.width = tableWidth;
@@ -676,12 +859,33 @@ function canReusePrecomputedTableRow(
curPage: IDocumentSkeletonPage,
cache: ICreateTableCache,
rowSource: ITableRow,
- precomputedRow?: IDocumentSkeletonRow
+ precomputedRow?: IDocumentSkeletonRow,
+ borderHeight = 0,
+ minimumHeight = 0
): precomputedRow is IDocumentSkeletonRow {
const canRowSplit = rowSource.cantSplit !== BooleanNumber.TRUE && rowSource.trHeight.hRule !== TableRowHeightRule.EXACT;
return precomputedRow != null &&
- precomputedRow.height <= getAvailableHeight(curPage, cache, false) &&
- (cache.remainHeight <= 0 || !canRowSplit || precomputedRow.height <= cache.remainHeight);
+ precomputedRow.parent?.hasPageBreak !== true &&
+ precomputedRow.height + borderHeight <= getAvailableHeight(curPage, cache, false) &&
+ (cache.remainHeight <= 0 || !canRowSplit || precomputedRow.height + borderHeight <= cache.remainHeight ||
+ Math.max(minimumHeight, getRowFirstLineHeight(precomputedRow)) + borderHeight > cache.remainHeight);
+}
+
+function getRowFirstLineHeight(row: IDocumentSkeletonRow): number {
+ let minimum = Number.POSITIVE_INFINITY;
+ for (const [index, cell] of row.cells.entries()) {
+ if (isCoveredTableCell(row.rowSource.tableCells[index])) {
+ continue;
+ }
+ const line = cell.sections[0]?.columns[0]?.lines[0];
+ if (!line || cell.cellTextDirection || cell.skeTables.size > 0 || cell.skeDrawings.size > 0 || cell.skeColumnGroups.size > 0) {
+ return 0;
+ }
+ minimum = Math.min(minimum, cell.marginTop + line.top + line.lineHeight + cell.marginBottom);
+ }
+ // If no first line fits, keep the original row intact on the next page.
+ // Splitting it first can move both fragments there and add a spurious border.
+ return Number.isFinite(minimum) ? minimum : 0;
}
function dealWithTableRow(
@@ -699,16 +903,24 @@ function dealWithTableRow(
preparedCellPages?: Map<number, IDocumentSkeletonPage[]>,
cellPageHeights?: readonly number[]
): number[] | undefined {
- const pageContentHeight = getAvailableHeight(curPage, cache, false);
- const availableHeight = getAvailableHeight(curPage, cache, true);
const documentCompatibilityPolicy = sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy();
const { children: cellNodes, startIndex, endIndex } = rowNode;
const rowSource = table.tableRows[row];
+ const traditional = isTraditionalDocumentCompatibility(documentCompatibilityPolicy);
+ const firstRowSource = getCurTableSkeleton(skeTables).rows[0]?.rowSource ?? rowSource;
+ const firstBorderHeight = getTableBorderHeight(firstRowSource, rowSource, traditional);
+ const nextBorderHeight = getTableBorderHeight(rowSource, rowSource, traditional);
+ const pageContentHeight = getAvailableHeight(curPage, cache, traditional && !isRepeatRow && row >= cache.repeatRows.length) - nextBorderHeight;
+ const availableHeight = getAvailableHeight(curPage, cache, true) - nextBorderHeight;
const { trHeight, cantSplit } = rowSource;
const { hRule, val } = trHeight;
const canRowSplit = cantSplit !== BooleanNumber.TRUE && trHeight.hRule !== TableRowHeightRule.EXACT;
- const needOpenNewTable = cache.remainHeight <= 0;
- const precomputedRowFits = !isRepeatRow && cellPageHeights == null && canReusePrecomputedTableRow(curPage, cache, rowSource, precomputedRow);
+ const minimumHeight = traditional && hRule === TableRowHeightRule.AT_LEAST ? getRowMinimumHeight(table, row, true) : 0;
+ // A splittable row still needs room for its authored minimum on the first page.
+ // An oversized minimum cannot be satisfied on any page and must not prevent splitting.
+ const needOpenNewTable = cache.remainHeight <= firstBorderHeight ||
+ (minimumHeight <= availableHeight && minimumHeight + firstBorderHeight > cache.remainHeight);
+ const precomputedRowFits = !isRepeatRow && cellPageHeights == null && canReusePrecomputedTableRow(curPage, cache, rowSource, precomputedRow, firstBorderHeight, minimumHeight);
const rowSkeletons: IDocumentSkeletonRow[] = precomputedRowFits ? [precomputedRow] : [];
let curTableSkeleton = getCurTableSkeleton(skeTables);
@@ -743,7 +955,7 @@ function dealWithTableRow(
table,
row,
col,
- canRowSplit && !needOpenNewTable ? cache.remainHeight : availableHeight,
+ canRowSplit && !needOpenNewTable ? cache.remainHeight - firstBorderHeight : availableHeight,
pageContentHeight,
cellPageHeights
);
@@ -765,8 +977,7 @@ function dealWithTableRow(
}
for (const cellPageSkeleton of cellPageSkeletons) {
- const { marginTop: cellMarginTop = 0, marginBottom: cellMarginBottom = 0 } = cellPageSkeleton;
- const cellPageHeight = cellPageSkeleton.height + cellMarginTop + cellMarginBottom;
+ const cellPageHeight = getCellPageLayoutHeight(cellPageSkeleton, viewModel, rowSource);
const pageIndex = cellPageSkeletons.indexOf(cellPageSkeleton);
const rowSke = rowSkeletons[pageIndex];
@@ -784,19 +995,39 @@ function dealWithTableRow(
}
}
+ if (traditional && rowSkeletons.length > 1 && precomputedRow &&
+ precomputedRow.parent?.hasPageBreak !== true &&
+ precomputedRow.height <= availableHeight &&
+ rowSkeletons[0].cells.some((cell, column) =>
+ !isCoveredTableCell(rowSource.tableCells[column]) &&
+ cell.height === 0 && (precomputedRow.cells[column]?.height ?? 0) > 0
+ )) {
+ // A paragraph constraint can move all text in one cell off the first
+ // fragment. Keep its sibling cells with it when the whole row fits.
+ rowSkeletons.splice(0, rowSkeletons.length, precomputedRow);
+ rowHeights.splice(0, rowHeights.length, precomputedRow.height);
+ }
+
+ if (hRule === TableRowHeightRule.AT_LEAST && rowHeights.length > 0) {
+ // Word also reserves the row minimum on its final continuation. Earlier
+ // fragments can use the space left on their page without padding it again.
+ const contentHeight = traditional
+ ? rowHeights[rowHeights.length - 1]
+ : rowHeights.reduce((total, height) => total + height, 0);
+ rowHeights[rowHeights.length - 1] += Math.max(0, getRowMinimumHeight(table, row, traditional) - contentHeight);
+ }
+
for (const rowSke of rowSkeletons) {
// Update row height.
const rowIndex = rowSkeletons.indexOf(rowSke);
- if (hRule === TableRowHeightRule.AT_LEAST) {
- rowHeights[rowIndex] = Math.max(rowHeights[rowIndex], val.v);
- } else if (hRule === TableRowHeightRule.EXACT) {
+ if (hRule === TableRowHeightRule.EXACT) {
rowHeights[rowIndex] = val.v;
}
rowHeights[rowIndex] = Math.min(rowHeights[rowIndex], pageContentHeight);
- let left = 0;
+ let left = getOmittedGridWidth(table, rowSke.index, 'before');
// Set row height to cell page height.
for (let col = 0; col < rowSke.cells.length; col++) {
const cellPageSkeleton = rowSke.cells[col];
@@ -814,6 +1045,8 @@ function dealWithTableRow(
cache.tableWidth = Math.max(cache.tableWidth, left);
}
+ cache.tableWidth = Math.max(cache.tableWidth, left + getOmittedGridWidth(table, rowSke.index, 'after'));
+
// Set row Skeleton height.
rowSke.height = rowHeights[rowIndex];
}
@@ -847,7 +1080,8 @@ function dealWithTableRow(
while (rowSkeletons.length > 0) {
const rowSkeleton = rowSkeletons.shift()!;
const lastRow = curTableSkeleton.rows[curTableSkeleton.rows.length - 1];
- const rowOverflowHeight = rowSkeleton.height - cache.remainHeight;
+ const borderHeight = getTableBorderHeight(curTableSkeleton.rows[0]?.rowSource ?? rowSource, rowSource, traditional);
+ const rowOverflowHeight = rowSkeleton.height + borderHeight - cache.remainHeight;
const geometryOverflow =
cache.remainHeight <= 0 ||
forcedPageBreakRows.has(rowSkeleton) ||
@@ -860,16 +1094,15 @@ function dealWithTableRow(
if (cache.notes && skeTables.length === 1 && curTableSkeleton.rows.length === 0) {
cache.fromCurrentPage = false;
}
- cache.remainHeight = getAvailableHeight(curPage, cache, row !== 0 && rowSkeleton.index !== lastRow?.index);
+ cache.remainHeight = getAvailableHeight(curPage, cache, row !== 0 && (traditional || rowSkeleton.index !== lastRow?.index));
cache.rowTop = 0;
if (curTableSkeleton.rows.length > 0) {
curTableSkeleton = getNullTableSkeleton(startIndex, endIndex, table);
skeTables.push(curTableSkeleton);
- // Repeat all leading header rows. If the current row crosses pages,
- // there is no need to repeat the header rows on the second slice.
- if (cache.repeatRows.length > 0 && isRepeatRow === false && row >= cache.repeatRows.length && rowSkeleton.index !== lastRow.index) {
+ // Word repeats leading headers even when the body row continues across pages.
+ if (cache.repeatRows.length > 0 && isRepeatRow === false && row >= cache.repeatRows.length && (traditional || rowSkeleton.index !== lastRow.index)) {
cache.remainHeight = getAvailableHeight(curPage, cache, false);
cache.repeatRows.forEach((repeatRow, repeatRowIndex) => {
dealWithTableRow(
@@ -924,10 +1157,14 @@ function getLeadingRepeatHeaderRows(table: ITable, rowNodes: DataStreamTreeNode[
function _verticalAlignInCell(
rowSkeleton: IDocumentSkeletonRow,
rowSource: ITableRow,
- isSplitRow = false
+ isSplitRow = false,
+ mergedOnly = false
) {
for (let i = 0; i < rowSource.tableCells.length; i++) {
const cellConfig = rowSource.tableCells[i];
+ if (mergedOnly && (cellConfig.rowSpan ?? 1) <= 1) {
+ continue;
+ }
const cellPageSkeleton = rowSkeleton.cells[i];
@@ -936,36 +1173,48 @@ function _verticalAlignInCell(
}
const { vAlign = VerticalAlignmentType.CONTENT_ALIGNMENT_UNSPECIFIED } = cellConfig;
- const { pageHeight, height, originMarginTop, originMarginBottom } = cellPageSkeleton;
+ const { originMarginTop, originMarginBottom } = cellPageSkeleton;
+ const isVerticalCell = cellPageSkeleton.cellTextDirection === 'tbRlV';
+ const pageHeight = isVerticalCell ? cellPageSkeleton.pageWidth : cellPageSkeleton.pageHeight;
+ const height = isVerticalCell ? cellPageSkeleton.width : cellPageSkeleton.height;
let marginTop = originMarginTop;
// Word applies cell vertical alignment to an unsplit row as a whole. Centering or bottom-aligning
// every continuation fragment independently creates large blank areas and clipped text.
- if (isSplitRow) {
- cellPageSkeleton.marginTop = originMarginTop;
- continue;
- }
-
- switch (vAlign) {
- case VerticalAlignmentType.TOP: {
- marginTop = originMarginTop;
- break;
- }
- case VerticalAlignmentType.CENTER: {
- marginTop = (pageHeight - height) / 2;
- break;
- }
- case VerticalAlignmentType.BOTTOM: {
- marginTop = pageHeight - height - originMarginBottom;
- break;
+ if (!isSplitRow) {
+ switch (vAlign) {
+ case VerticalAlignmentType.TOP: {
+ marginTop = originMarginTop;
+ break;
+ }
+ case VerticalAlignmentType.CENTER: {
+ marginTop = (pageHeight - height) / 2;
+ break;
+ }
+ case VerticalAlignmentType.BOTTOM: {
+ marginTop = pageHeight - height - originMarginBottom;
+ break;
+ }
+ default:
+ break;
}
- default:
- break;
}
marginTop = Math.max(originMarginTop, marginTop);
+ // Cell margins also carry text alignment. Page/margin anchors must stay fixed when that offset changes.
+ const alignmentDelta = marginTop - cellPageSkeleton.marginTop;
+ cellPageSkeleton.skeDrawings?.forEach((drawing) => {
+ const { layoutType, docTransform } = drawing.drawingOrigin;
+ const relativeFrom = docTransform.positionV.relativeFrom;
+ if (
+ layoutType !== PositionedObjectLayoutType.INLINE &&
+ (relativeFrom === ObjectRelativeFromV.PAGE || relativeFrom === ObjectRelativeFromV.MARGIN)
+ ) {
+ drawing.aTop -= alignmentDelta;
+ }
+ });
cellPageSkeleton.marginTop = marginTop;
}
}
@@ -1056,7 +1305,7 @@ function resolveMergedRowHeights(tableSkeleton: IDocumentSkeletonTable): boolean
if (hRule === TableRowHeightRule.EXACT) {
row.height = val.v;
} else if (hRule === TableRowHeightRule.AT_LEAST) {
- row.height = Math.max(contentHeight, val.v);
+ row.height = Math.max(contentHeight, getRowMinimumHeight(tableSkeleton.tableSource, row.index, true));
}
}
@@ -1069,9 +1318,9 @@ function resolveMergedRowHeights(tableSkeleton: IDocumentSkeletonTable): boolean
const extraHeight = cellHeight(row.cells[column]) - span.reduce((height, item) => height + item.height, 0);
const expandable = span.filter((item) => sources[item.index].trHeight.hRule !== TableRowHeightRule.EXACT);
if (extraHeight > 0 && expandable.length > 0) {
- for (const item of expandable) {
- item.height += extraHeight / expandable.length;
- }
+ // Extending a vertical merge must not move boundaries between its
+ // preceding rows. Word puts the deficit into the final flexible row.
+ expandable[expandable.length - 1].height += extraHeight;
}
});
}
@@ -1096,13 +1345,18 @@ function createMergedAwareNullCellPage(
col: number,
rowSkeleton: IDocumentSkeletonRow
): IDocumentSkeletonPage {
- const cellSkeleton = createNullCellPage(
+ const { page: cellSkeleton, verticalCellWidth } = createNullCellPage(
ctx,
sectionBreakConfig,
table,
row,
col
- ).page;
+ );
+ if (verticalCellWidth != null) {
+ cellSkeleton.pageHeight = cellSkeleton.pageWidth;
+ cellSkeleton.pageWidth = verticalCellWidth;
+ cellSkeleton.cellTextDirection = 'tbRlV';
+ }
cellSkeleton.parent = rowSkeleton;
if (isCoveredTableCell(table.tableRows[row].tableCells[col])) {
@@ -1160,6 +1414,47 @@ function isCoveredTableCell(cellConfig: ITableCell | undefined): boolean {
return cellConfig?.rowSpan === 0 || cellConfig?.columnSpan === 0;
}
+function getTableAvailableWidth(page: IDocumentSkeletonPage): number {
+ return Math.max(0, page.pageWidth - (page.marginLeft ?? 0) - (page.marginRight ?? 0));
+}
+
+export function resolveTableLayoutColumns(table: ITable, availableWidth: number, traditional = false): ITable {
+ if (table.size?.type !== TableSizeType.SPECIFIED || !table.tableColumns?.length) {
+ return table;
+ }
+
+ let preferredWidth = table.size.width.u === NumberUnitType.PERCENT
+ ? availableWidth * table.size.width.v / 100
+ : table.size.width.v;
+ if (traditional && table.size.width.u === NumberUnitType.PERCENT && table.legacyIndentAdjustment != null) {
+ // Legacy Word percentage widths align cell text to the page margins;
+ // the outer cell margins extend beyond that text width.
+ const cells = table.tableRows[0]?.tableCells;
+ const lastCell = cells?.[cells.length - 1];
+ const endMargin = lastCell?.margin?.end?.v ?? table.cellMargin?.end?.v ?? 7.2;
+ preferredWidth += Math.max(0, table.legacyIndentAdjustment.v) + Math.max(0, endMargin);
+ }
+ const gridWidth = table.tableColumns.reduce((sum, column) => sum + column.size.width.v, 0);
+ if (!Number.isFinite(preferredWidth) || preferredWidth <= 0 || gridWidth <= 0 || Math.abs(preferredWidth - gridWidth) < 0.01) {
+ return table;
+ }
+
+ const scale = preferredWidth / gridWidth;
+ return {
+ ...table,
+ tableColumns: table.tableColumns.map((column) => ({
+ ...column,
+ size: {
+ ...column.size,
+ width: {
+ ...column.size.width,
+ v: column.size.width.v * scale,
+ },
+ },
+ })),
+ };
+}
+
export function getTableLeft(pageWidth: number, tableWidth: number, align: TableAlignmentType, indent: INumberUnit = { v: 0 }) {
switch (align) {
case TableAlignmentType.START: {
diff --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.ts
index c9b113b509..657b1fa1f3 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,18 @@
*/
import type { IDocumentData, ITextRun, ITextStyle } from '@univerjs/core';
-import { getFontStyleString } from '../../../basics/tools';
+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 { getPairKerningAdjustment, measureTextWithCharacterSpacing } from './model/glyph';
import { FontCache } from './shaping-engine/font-cache';
function splitDocumentNoWrapMeasureLines(text: string): string[] {
- return text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n');
+ return text.replace(/\r\n/g, '\n').split(/[\r\n\u2028]/u);
}
function isDocumentNoWrapMeasureTrailingWhitespace(char: string): boolean {
@@ -44,12 +49,19 @@ function isDocumentNoWrapMeasureLatinText(char: string): boolean {
return /[a-z\d]/i.test(char);
}
-function measureDocumentNoWrapTextByStyle(text: string, textStyle: ITextStyle | undefined): number {
+function measureDocumentNoWrapTextByStyle(text: string, textStyle: ITextStyle | undefined, font: IDocumentSkeletonFontStyle): number {
if (!text) {
return 0;
}
- return FontCache.getMeasureText(text, getFontStyleString(textStyle).fontCache).width;
+ const content = getTextWithCaps(text, textStyle?.caps || textStyle?.smallCaps);
+ const measure = (segment: string) => FontCache.getMeasureText(segment, font.fontCache, font.fontKerning).width;
+ return measureTextWithCharacterSpacing(
+ content,
+ textStyle?.sc == null ? undefined : textStyle.sc / 0.75,
+ measure,
+ (left, right) => getPairKerningAdjustment(left, right, font)
+ )?.width ?? measure(content);
}
function measureDocumentNoWrapCJKLatinSpacing(
@@ -61,7 +73,7 @@ function measureDocumentNoWrapCJKLatinSpacing(
for (const char of Array.from(segment)) {
const isCJK = isDocumentNoWrapMeasureCJKText(char);
- const cjkWidth = isCJK ? measureDocumentNoWrapTextByStyle(char, textStyle) : 0;
+ const cjkWidth = isCJK ? FontCache.getMeasureText(char, getFontStyleString(textStyle).fontCache).width : 0;
if (isCJK && isDocumentNoWrapMeasureLatinText(previous.char)) {
spacing += cjkWidth / 4;
@@ -78,25 +90,31 @@ function measureDocumentNoWrapCJKLatinSpacing(
return spacing;
}
-function measureDocumentNoWrapLineByStyle(text: string, textStyle: ITextStyle | undefined): number {
- const visibleText = text.slice(0, getDocumentNoWrapMeasureTrailingWhitespaceStart(text));
- const previous = { char: '', cjkWidth: 0 };
-
- return measureDocumentNoWrapTextByStyle(visibleText, textStyle) +
- measureDocumentNoWrapCJKLatinSpacing(visibleText, textStyle, previous);
-}
-
function measureDocumentNoWrapRunsWidth(
dataStream: string,
textRuns: ITextRun[],
- fallbackTextStyle: ITextStyle | undefined
+ fallbackTextStyle: ITextStyle | undefined,
+ policy: IDocumentCompatibilityPolicy,
+ spaceWidthEastAsian: boolean
): number {
let currentLineWidth = 0;
let maxLineWidth = 0;
let pendingTrailingWhitespaceWidth = 0;
const previous = { char: '', cjkWidth: 0 };
+ let previousText = '';
+ let previousFont: ReturnType<typeof getFontStyleString> | undefined;
+
+ const measureSegment = (segment: string, textStyle: ITextStyle | undefined, font: IDocumentSkeletonFontStyle) => {
+ const content = getTextWithCaps(segment, textStyle?.caps || textStyle?.smallCaps);
+ const adjustment = previousFont?.fontString === font.fontString && previousFont.fontKerning === font.fontKerning
+ ? getPairKerningAdjustment(previousText, content, font)
+ : 0;
+ previousText = content;
+ previousFont = font;
+ return measureDocumentNoWrapTextByStyle(segment, textStyle, font) + adjustment;
+ };
- const appendSegment = (segment: string, textStyle: ITextStyle | undefined) => {
+ const appendSegment = (segment: string, textStyle: ITextStyle | undefined, font: IDocumentSkeletonFontStyle) => {
if (!segment) {
return;
}
@@ -108,13 +126,17 @@ function measureDocumentNoWrapRunsWidth(
if (visibleSegment) {
currentLineWidth += pendingTrailingWhitespaceWidth;
pendingTrailingWhitespaceWidth = 0;
- currentLineWidth += measureDocumentNoWrapTextByStyle(visibleSegment, textStyle);
- currentLineWidth += measureDocumentNoWrapCJKLatinSpacing(visibleSegment, textStyle, previous);
+ currentLineWidth += measureSegment(visibleSegment, textStyle, font);
+ if (spaceWidthEastAsian) {
+ currentLineWidth += measureDocumentNoWrapCJKLatinSpacing(visibleSegment, textStyle, previous);
+ }
}
if (trailingWhitespace) {
- pendingTrailingWhitespaceWidth += measureDocumentNoWrapTextByStyle(trailingWhitespace, textStyle);
- measureDocumentNoWrapCJKLatinSpacing(trailingWhitespace, textStyle, previous);
+ pendingTrailingWhitespaceWidth += measureSegment(trailingWhitespace, textStyle, font);
+ if (spaceWidthEastAsian) {
+ measureDocumentNoWrapCJKLatinSpacing(trailingWhitespace, textStyle, previous);
+ }
}
};
@@ -124,17 +146,36 @@ function measureDocumentNoWrapRunsWidth(
pendingTrailingWhitespaceWidth = 0;
previous.char = '';
previous.cjkWidth = 0;
+ previousText = '';
+ previousFont = undefined;
};
const appendRange = (text: string, textStyle: ITextStyle | undefined) => {
const segments = splitDocumentNoWrapMeasureLines(text);
+ const font = getFontStyleString(textStyle);
segments.forEach((segment, index) => {
if (index > 0) {
finishLine();
}
- appendSegment(segment, textStyle);
+ if (!textStyle?.smallCaps || textStyle.caps) {
+ appendSegment(segment, textStyle, font);
+ return;
+ }
+ let start = 0;
+ let currentFont = font;
+ for (let offset = 0; offset < segment.length;) {
+ const raw = getFirstGrapheme(segment.slice(offset))!;
+ const nextFont = getSmallCapsFontStyle(raw, textStyle, font, policy);
+ if (nextFont.fontString !== currentFont.fontString) {
+ appendSegment(segment.slice(start, offset), textStyle, currentFont);
+ start = offset;
+ currentFont = nextFont;
+ }
+ offset += raw.length;
+ }
+ appendSegment(segment.slice(start), textStyle, currentFont);
});
};
@@ -149,7 +190,7 @@ function measureDocumentNoWrapRunsWidth(
}
const effectiveStart = Math.max(start, cursor);
if (end > effectiveStart) {
- appendRange(dataStream.slice(effectiveStart, end), run.ts);
+ appendRange(dataStream.slice(effectiveStart, end), { ...fallbackTextStyle, ...run.ts });
}
cursor = Math.max(cursor, end);
});
@@ -182,11 +223,13 @@ export function measureDocumentNoWrapTextRangeWidth(documentData: IDocumentData,
})
.filter((run): run is ITextRun => run !== null);
- if (textRuns.length) {
- return measureDocumentNoWrapRunsWidth(rangeText, textRuns, documentData.documentStyle?.textStyle);
- }
-
- return measureDocumentNoWrapLineByStyle(rangeText, documentData.documentStyle?.textStyle);
+ return measureDocumentNoWrapRunsWidth(
+ rangeText,
+ textRuns,
+ documentData.documentStyle?.textStyle,
+ getDocumentCompatibilityPolicy(documentData.documentStyle?.documentFlavor),
+ documentData.documentStyle?.spaceWidthEastAsian !== BooleanNumber.FALSE
+ );
}
/**
@@ -205,19 +248,12 @@ export function measureDocumentNoWrapTextWidth(documentData: IDocumentData | nul
const dataStream = body?.dataStream ?? '';
const textRuns = body?.textRuns;
- if (textRuns?.length) {
- return measureDocumentNoWrapRunsWidth(
- dataStream,
- textRuns,
- documentData?.documentStyle?.textStyle
- );
- }
-
- const fallbackTextStyle = documentData?.documentStyle?.textStyle;
-
- return Math.max(
- 0,
- ...splitDocumentNoWrapMeasureLines(dataStream).map((line) => measureDocumentNoWrapLineByStyle(line, fallbackTextStyle))
+ return measureDocumentNoWrapRunsWidth(
+ dataStream,
+ textRuns ?? [],
+ documentData?.documentStyle?.textStyle,
+ getDocumentCompatibilityPolicy(documentData?.documentStyle?.documentFlavor),
+ documentData?.documentStyle?.spaceWidthEastAsian !== BooleanNumber.FALSE
);
}
diff --git a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
index a2fa9bd53f..043fde2098 100644
--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
@@ -38,7 +38,7 @@ import type {
INodeSearch,
ISectionBreakConfig,
} from '../../../basics/interfaces';
-import type { IViewportInfo, Vector2 } from '../../../basics/vector2';
+import type { IBoundRectNoAngle, IViewportInfo, Vector2 } from '../../../basics/vector2';
import type { IDocsCustomBlockRenderViewport } from '../custom-block-render-viewport';
import type { DataStreamTreeNode } from '../view-model/data-stream-tree-node';
import type { DocumentViewModel } from '../view-model/document-view-model';
@@ -1155,6 +1155,9 @@ export class DocumentSkeleton extends Skeleton {
private _layoutProgress$ = new Subject<IDocumentLayoutProgress>();
readonly layoutProgress$ = this._layoutProgress$.asObservable();
+ private readonly _layoutPageMaterialized$ = new Subject<void>();
+ readonly layoutPageMaterialized$ = this._layoutPageMaterialized$.asObservable();
+
private _skeletonData: Nullable<IDocumentSkeletonCached>;
private _findLiquid: Liquid = new Liquid();
@@ -1225,6 +1228,7 @@ export class DocumentSkeleton extends Skeleton {
this.cancelIncrementalLayout();
super.dispose();
this._layoutProgress$.complete();
+ this._layoutPageMaterialized$.complete();
this._skeletonData = null;
this._lastCompleteSkeletonData = null;
this._pendingInvalidationAnchor = null;
@@ -2459,7 +2463,8 @@ export class DocumentSkeleton extends Skeleton {
publicationRevision: 0,
didPublish: false,
didPublishAnchor: false,
- publishedPageCount: pages.length,
+ // Retained geometry preserves the viewport, not progress for this new layout.
+ publishedPageCount: 0,
reason: options.reason,
mode,
complete: false,
@@ -2784,6 +2789,7 @@ export class DocumentSkeleton extends Skeleton {
);
this._compactMaterializedPages(skeletonData, materializedPageRange);
this._dirty$.next(true);
+ this._layoutPageMaterialized$.next();
return true;
}
@@ -3348,7 +3354,7 @@ export class DocumentSkeleton extends Skeleton {
const page = pages[pi];
const { headerId, footerId, pageWidth } = page;
- let exactMatch = null;
+ let exactMatch: Nullable<INodeInfo> = null;
if (editArea === DocumentEditArea.HEADER || editArea === DocumentEditArea.FOOTER) {
const headerSke = skeHeaders.get(headerId)?.get(pageWidth) as IDocumentSkeletonPage;
@@ -3405,7 +3411,7 @@ export class DocumentSkeleton extends Skeleton {
}
} else {
const { segmentId, segmentPage, strict } = restrictions;
- let exactMatch = null;
+ let exactMatch: Nullable<INodeInfo> = null;
if (strict && this._docViewModel.getNoteTreeMap().has(segmentId)) {
for (let pi = 0; pi < pageLength; pi++) {
@@ -3542,18 +3548,10 @@ export class DocumentSkeleton extends Skeleton {
y: number,
pageLength: number,
nestLevel: number = 0
- // eslint-disable-next-line ts/no-explicit-any
- ): any {
- const { sections, skeTables, skeColumnGroups = new Map() } = segmentPage;
+ ): Nullable<INodeInfo> {
this._findLiquid.translateSave();
-
- const note = pageType === DocumentSkeletonPageType.NOTE
- ? page.notes?.find((fragment) => fragment.page === segmentPage)
- : undefined;
- const pageLeft = this._findLiquid.x + (note?.left ?? 0);
- const pageRight = pageLeft + (note ? segmentPage.pageWidth : page.pageWidth);
- const pageTop = this._findLiquid.y + (note?.top ?? (pageType === DocumentSkeletonPageType.FOOTER ? page.pageHeight - segmentPage.pageHeight : 0));
- const pageBottom = pageTop + (note ? segmentPage.height : segmentPage.pageHeight);
+ const { bounds, paddingLeft, paddingTop } = this._getHitTestPageLayout(segmentPage, pageType, page);
+ const { left: pageLeft, right: pageRight, top: pageTop, bottom: pageBottom } = bounds;
let pointInPage = x >= pageLeft
&& x <= pageRight
@@ -3562,190 +3560,108 @@ export class DocumentSkeleton extends Skeleton {
// Handle the outmost page.
if (nestLevel === 0 && pageType === DocumentSkeletonPageType.BODY) {
- const isFirstPage = pi === 0;
- const isLastPage = pi === pageLength - 1;
// TODO: Use page margin top as page gap now, need to consider the page gap in the future.
const halfMarginTop = page.originMarginTop / 2;
-
- // It's the only page, point always in page.
- if (isFirstPage && isLastPage) {
- pointInPage = true;
- } else if (isFirstPage) {
- pointInPage = y <= pageBottom + halfMarginTop;
- } else if (isLastPage) {
- pointInPage = y >= pageTop - halfMarginTop;
- } else {
- pointInPage = y >= pageTop - halfMarginTop && y <= pageBottom + halfMarginTop;
- }
+ pointInPage = (pi === 0 || y >= pageTop - halfMarginTop)
+ && (pi === pageLength - 1 || y <= pageBottom + halfMarginTop);
}
- switch (pageType) {
- case DocumentSkeletonPageType.NOTE: {
- this._findLiquid.translate(note?.left ?? page.marginLeft, note?.top ?? page.marginTop);
- break;
- }
- case DocumentSkeletonPageType.HEADER: {
- this._findLiquid.translatePagePadding({
- ...segmentPage,
- marginLeft: page.marginLeft, // Because header or footer margin Left is 0.
- });
- break;
- }
+ if (segmentPage.cellTextDirection === 'tbRlV') {
+ const physicalX = x;
+ x = pageLeft + y - pageTop;
+ y = pageTop + segmentPage.pageWidth - (physicalX - pageLeft);
+ }
- case DocumentSkeletonPageType.FOOTER: {
- const footerTop = page.pageHeight - segmentPage.height - segmentPage.marginBottom;
- this._findLiquid.translate(page.marginLeft, footerTop);
- break;
- }
+ this._findLiquid.translate(paddingLeft, paddingTop);
- default: {
- this._findLiquid.translatePagePadding(page);
- break;
+ if (pointInPage) {
+ const textMatch = this._collectNearestTextNode(segmentPage, {
+ segmentPage: pageType === DocumentSkeletonPageType.BODY ? -1 : pi,
+ segmentId,
+ }, cache, x, y, nestLevel);
+ if (textMatch) {
+ this._findLiquid.translateRestore();
+ return textMatch;
}
}
- if (pointInPage) {
- let nearestNodeDistanceY = Number.POSITIVE_INFINITY;
-
- for (const section of sections) {
- const { columns } = section;
-
- this._findLiquid.translateSave();
- this._findLiquid.translateSection(section);
-
- for (const column of columns) {
- const { lines } = column;
-
- this._findLiquid.translateSave();
- this._findLiquid.translateColumn(column);
-
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- const { divides, type, lineHeight = 0 } = line;
-
- if (type === LineType.BLOCK) {
- continue;
- } else {
- this._findLiquid.translateSave();
- this._findLiquid.translateLine(line);
-
- const { y: startY } = this._findLiquid;
-
- const startY_fin = startY;
-
- const endY_fin = startY + lineHeight;
-
- const distanceY = Math.abs(y - endY_fin);
-
- const divideLength = divides.length;
- for (let i = 0; i < divideLength; i++) {
- const divide = divides[i];
- const { glyphGroup } = divide;
-
- this._findLiquid.translateSave();
- this._findLiquid.translateDivide(divide);
-
- const { x: startX } = this._findLiquid;
-
- for (const glyph of glyphGroup) {
- if (!isHitTestAddressableGlyph(glyph)) {
- continue;
- }
-
- const { width: glyphWidth, left: glyphLeft } = glyph;
- const startX_fin = startX + glyphLeft;
- const endX_fin = startX + glyphLeft + glyphWidth;
- const distanceX = Math.abs(x - endX_fin);
-
- // Handle pointer in the same line.
- if (y >= startY_fin && y <= endY_fin) {
- // Exact match glyph.
- if (x >= startX_fin && x <= endX_fin) {
- return {
- node: glyph,
- segmentPage: pageType === DocumentSkeletonPageType.BODY ? -1 : pi,
- segmentId,
- ratioX: x / (startX_fin + endX_fin),
- ratioY: y / (startY_fin + endY_fin),
- };
- }
-
- if (nearestNodeDistanceY !== Number.NEGATIVE_INFINITY) {
- cache.nearestNodeList = [];
- cache.nearestNodeDistanceList = [];
- }
- cache.nearestNodeList.push({
- node: glyph,
- segmentPage: pageType === DocumentSkeletonPageType.BODY ? -1 : pi,
- segmentId,
- ratioX: x / (startX_fin + endX_fin),
- ratioY: y / (startY_fin + endY_fin),
- });
-
- cache.nearestNodeDistanceList.push({
- coordInPage: pointInPage,
- distance: distanceX,
- nestLevel,
- });
-
- nearestNodeDistanceY = Number.NEGATIVE_INFINITY;
- continue;
- }
-
- if (distanceY < nearestNodeDistanceY) {
- nearestNodeDistanceY = distanceY;
- cache.nearestNodeList = [];
- cache.nearestNodeDistanceList = [];
- }
-
- if (distanceY === nearestNodeDistanceY) {
- cache.nearestNodeList.push({
- node: glyph,
- segmentPage: pageType === DocumentSkeletonPageType.BODY ? -1 : pi,
- segmentId,
- ratioX: x / (startX_fin + endX_fin),
- ratioY: y / (startY_fin + endY_fin),
- });
-
- cache.nearestNodeDistanceList.push({
- coordInPage: pointInPage,
- distance: distanceX,
- nestLevel,
- });
- }
- }
- this._findLiquid.translateRestore();
- }
- this._findLiquid.translateRestore();
- }
- }
- this._findLiquid.translateRestore();
- }
+ const tableMatch = pointInPage
+ ? this._collectNearestTableNode(segmentPage, segmentId, pi, cache, x, y, pageLength, nestLevel)
+ : undefined;
+ const exactMatch = tableMatch ?? this._collectNearestColumnGroupNode(segmentPage, segmentId, pi, x, y, pageLength, nestLevel);
+ this._findLiquid.translateRestore();
+ return exactMatch;
+ }
- this._findLiquid.translateRestore();
- }
+ private _getHitTestPageLayout(
+ segmentPage: IDocumentSkeletonPage,
+ pageType: DocumentSkeletonPageType,
+ page: IDocumentSkeletonPage
+ ): { bounds: IBoundRectNoAngle; paddingLeft: number; paddingTop: number } {
+ const note = pageType === DocumentSkeletonPageType.NOTE
+ ? page.notes?.find((fragment) => fragment.page === segmentPage)
+ : undefined;
+ const left = this._findLiquid.x + (note?.left ?? 0);
+ const footerOffset = pageType === DocumentSkeletonPageType.FOOTER ? page.pageHeight - segmentPage.pageHeight : 0;
+ const top = this._findLiquid.y + (note?.top ?? footerOffset);
+ const bounds = {
+ left,
+ top,
+ right: left + (note ? segmentPage.pageWidth : page.pageWidth),
+ bottom: top + (note ? segmentPage.height : segmentPage.pageHeight),
+ };
+ let paddingLeft = page.marginLeft;
+ let paddingTop = page.marginTop;
+ switch (pageType) {
+ case DocumentSkeletonPageType.NOTE:
+ paddingLeft = note?.left ?? paddingLeft;
+ paddingTop = note?.top ?? paddingTop;
+ break;
+ case DocumentSkeletonPageType.HEADER:
+ // Header/footer stories inherit their owning physical page's left margin.
+ paddingTop = segmentPage.marginTop;
+ break;
+ case DocumentSkeletonPageType.FOOTER:
+ paddingTop = page.pageHeight - segmentPage.height - segmentPage.marginBottom;
+ break;
}
+ return { bounds, paddingLeft, paddingTop };
+ }
- let exactMatch = null;
- if (pointInPage && skeTables.size > 0) {
+ private _collectNearestTableNode(
+ segmentPage: IDocumentSkeletonPage,
+ segmentId: string,
+ pi: number,
+ cache: INearestCache,
+ x: number,
+ y: number,
+ pageLength: number,
+ nestLevel: number
+ ): Nullable<INodeInfo> {
+ const { skeTables } = segmentPage;
+ let exactMatch: Nullable<INodeInfo>;
+ if (skeTables.size > 0) {
const unitId = this._docViewModel.getDataModel().getUnitId?.() ?? '';
- for (const table of skeTables.values()) {
+ for (const table of Array.from(skeTables.values()).reverse()) {
const { top: tableTop, left: tableLeft, rows } = table;
const sourceTableId = getTableIdAndSliceIndex(table.tableId).tableId;
const viewport = getDocsTableRenderViewport(unitId, sourceTableId);
- this._findLiquid?.translateSave();
- this._findLiquid?.translate(tableLeft, tableTop);
+ this._findLiquid.translateSave();
+ this._findLiquid.translate(tableLeft, tableTop);
+ const pointInTable = x >= this._findLiquid.x && x <= this._findLiquid.x + table.width
+ && y >= this._findLiquid.y && y <= this._findLiquid.y + table.height;
+ const tableCache: INearestCache = { nearestNodeList: [], nearestNodeDistanceList: [] };
if (hasDocsTableHorizontalViewport(viewport)) {
// Hit-test coordinates already include this page's padding.
const visibleLeft = this._findLiquid.x - (viewport.leadingInsetLeft ?? 0);
const visibleRight = visibleLeft + viewport.viewportWidth;
if (x < visibleLeft || x > visibleRight) {
- this._findLiquid?.translateRestore();
+ this._findLiquid.translateRestore();
continue;
}
- this._findLiquid?.translate(-viewport.scrollLeft, 0);
+ this._findLiquid.translate(-viewport.scrollLeft, 0);
}
for (const row of rows) {
@@ -3756,14 +3672,14 @@ export class DocumentSkeleton extends Skeleton {
continue;
}
- this._findLiquid?.translateSave();
- this._findLiquid?.translate(0, rowTop);
+ this._findLiquid.translateSave();
+ this._findLiquid.translate(0, rowTop);
for (const cell of cells) {
const { left: cellLeft } = cell;
- this._findLiquid?.translateSave();
- this._findLiquid?.translate(cellLeft, 0);
+ this._findLiquid.translateSave();
+ this._findLiquid.translate(cellLeft, 0);
exactMatch = exactMatch ?? this._collectNearestNode(
cell,
@@ -3771,24 +3687,47 @@ export class DocumentSkeleton extends Skeleton {
cell,
segmentId,
pi,
- cache,
+ tableCache,
x,
y,
pageLength,
nestLevel + 1
);
- this._findLiquid?.translateRestore();
+ this._findLiquid.translateRestore();
}
- this._findLiquid?.translateRestore();
+ this._findLiquid.translateRestore();
}
- this._findLiquid?.translateRestore();
+ this._findLiquid.translateRestore();
+ if (pointInTable) {
+ // Blank cell padding still belongs to the topmost painted table.
+ exactMatch ??= this._getNearestNode(tableCache.nearestNodeList, tableCache.nearestNodeDistanceList);
+ }
+ if (exactMatch) {
+ break;
+ }
+ cache.nearestNodeList.push(...tableCache.nearestNodeList);
+ cache.nearestNodeDistanceList.push(...tableCache.nearestNodeDistanceList);
}
}
- if (skeColumnGroups.size > 0) {
+ return exactMatch;
+ }
+
+ private _collectNearestColumnGroupNode(
+ segmentPage: IDocumentSkeletonPage,
+ segmentId: string,
+ pi: number,
+ x: number,
+ y: number,
+ pageLength: number,
+ nestLevel: number
+ ): Nullable<INodeInfo> {
+ const { skeColumnGroups } = segmentPage;
+ let exactMatch: Nullable<INodeInfo>;
+ if (skeColumnGroups && skeColumnGroups.size > 0) {
for (const columnGroup of skeColumnGroups.values()) {
const { top: columnGroupTop, left: columnGroupLeft, width: columnGroupWidth, height: columnGroupHeight, columns } = columnGroup;
const absoluteColumnGroupLeft = this._findLiquid.x + columnGroupLeft;
@@ -3803,8 +3742,8 @@ export class DocumentSkeleton extends Skeleton {
continue;
}
- this._findLiquid?.translateSave();
- this._findLiquid?.translate(columnGroupLeft, columnGroupTop);
+ this._findLiquid.translateSave();
+ this._findLiquid.translate(columnGroupLeft, columnGroupTop);
for (const column of columns) {
const absoluteColumnLeft = absoluteColumnGroupLeft + column.left;
@@ -3824,8 +3763,8 @@ export class DocumentSkeleton extends Skeleton {
nearestNodeDistanceList: [],
};
- this._findLiquid?.translateSave();
- this._findLiquid?.translate(column.left, column.top);
+ this._findLiquid.translateSave();
+ this._findLiquid.translate(column.left, column.top);
exactMatch = exactMatch ?? this._collectNearestNode(
column.page,
@@ -3840,19 +3779,65 @@ export class DocumentSkeleton extends Skeleton {
nestLevel + 1
) ?? this._getNearestNode(nestedCache.nearestNodeList, nestedCache.nearestNodeDistanceList);
- this._findLiquid?.translateRestore();
+ this._findLiquid.translateRestore();
}
- this._findLiquid?.translateRestore();
+ this._findLiquid.translateRestore();
}
}
- if (exactMatch) {
- this._findLiquid.translateRestore();
- return exactMatch;
- }
+ return exactMatch;
+ }
- this._findLiquid.translateRestore();
+ private _collectNearestTextNode(
+ page: IDocumentSkeletonPage,
+ segment: Pick<INodeInfo, 'segmentId' | 'segmentPage'>,
+ cache: INearestCache,
+ x: number,
+ y: number,
+ nestLevel: number
+ ): Nullable<INodeInfo> {
+ let nearestDistanceY = Number.POSITIVE_INFINITY;
+ const { x: originX, y: originY } = this._findLiquid;
+ for (const section of page.sections) {
+ for (const column of section.columns) {
+ for (const line of column.lines) {
+ if (line.type === LineType.BLOCK) {
+ continue;
+ }
+ const startY = originY + (section.top ?? 0) + line.top;
+ const endY = startY + (line.lineHeight ?? 0);
+ const sameLine = y >= startY && y <= endY;
+ const distanceY = sameLine ? Number.NEGATIVE_INFINITY : Math.abs(y - endY);
+ if (distanceY > nearestDistanceY) {
+ continue;
+ }
+ for (const divide of line.divides) {
+ const divideLeft = originX + column.left + divide.left + divide.paddingLeft;
+ for (const glyph of divide.glyphGroup) {
+ if (!isHitTestAddressableGlyph(glyph)) {
+ continue;
+ }
+ const startX = divideLeft + glyph.left;
+ const endX = startX + glyph.width;
+ const node = { node: glyph, ...segment, ratioX: x / (startX + endX), ratioY: y / (startY + endY) };
+ if (sameLine && x >= startX && x <= endX) {
+ return node;
+ }
+ if (distanceY < nearestDistanceY) {
+ nearestDistanceY = distanceY;
+ cache.nearestNodeList = [];
+ cache.nearestNodeDistanceList = [];
+ }
+ if (distanceY === nearestDistanceY) {
+ cache.nearestNodeList.push(node);
+ cache.nearestNodeDistanceList.push({ coordInPage: true, distance: Math.abs(x - endX), nestLevel });
+ }
+ }
+ }
+ }
+ }
+ }
}
private _getNearestNode(nearestNodeList: INodeInfo[], nearestNodeDistanceList: IDistance[]) {
@@ -4131,9 +4116,14 @@ export class DocumentSkeleton extends Skeleton {
);
}
- // First-open layout has no prior boundary. The first physical page becomes
- // stable as soon as layout has entered a second page.
- return state.laidOutThrough >= anchor && state.ctx.skeleton.pages.length > 1;
+ // A fresh Worker mount can resume at an anchor beyond the first page.
+ // Publishing its still-open page finalizes the available section height
+ // to the content height and pushes subsequent blocks onto an extra page.
+ if (state.stableLaidOutThrough < anchor || state.ctx.skeleton.pages.length < 2) {
+ return false;
+ }
+ const anchorPageIndex = this._findPublishablePriorityPageIndex(state);
+ return anchorPageIndex >= 0 && anchorPageIndex < state.ctx.skeleton.pages.length - 1;
}
private _tryReuseInteractionPageTail(
@@ -4390,13 +4380,19 @@ export class DocumentSkeleton extends Skeleton {
if (pending.result != null) {
cachePrecomputedSlicedTableSkeletons(
ctx,
- pending.tableNode.startIndex,
+ pending.tableNode,
pending.availableHeight,
pending.result
);
}
if (state.pendingParagraphCheckpoint != null) {
+ const tableAnchors = ctx.skeletonResourceReference.drawingAnchor?.get(pending.table.tableId);
this._restoreIncrementalParagraphCheckpoint(ctx, state.pendingParagraphCheckpoint);
+ // Restore the enclosing paragraph, not the completed table's
+ // newly paginated anchors with its old unbounded measurements.
+ if (tableAnchors != null) {
+ ctx.skeletonResourceReference.drawingAnchor?.set(pending.table.tableId, tableAnchors);
+ }
}
state.pendingSlicedTableBuild = null;
state.pendingParagraphCheckpoint = null;
@@ -4441,7 +4437,7 @@ export class DocumentSkeleton extends Skeleton {
const tableSkeleton = state.pendingTableBuild.tableSkeleton;
cachePrecomputedTableSkeleton(
ctx,
- tableNode.startIndex,
+ tableNode,
tableSkeleton
);
}
diff --git a/packages/engine-render/src/components/docs/layout/footnote-layout.ts b/packages/engine-render/src/components/docs/layout/footnote-layout.ts
index 1591284956..4ddeba3b29 100644
--- a/packages/engine-render/src/components/docs/layout/footnote-layout.ts
+++ b/packages/engine-render/src/components/docs/layout/footnote-layout.ts
@@ -136,7 +136,9 @@ export function layoutNoteSegment(
noteReferences: undefined,
footnoteLayout: undefined,
endnoteLayout: undefined,
- noteLabel: reference.label,
+ noteLabel: parentContext.dataModel.getSnapshot().notes?.[reference.noteId]?.showBodyReference === false
+ ? undefined
+ : reference.label,
noteReferenceTextStyle: parentContext.dataModel.getSnapshot().notes?.[reference.noteId]?.referenceTextStyle,
noteSegmentId: reference.noteId,
footnoteFirstColumn: constraints.firstColumn,
diff --git a/packages/engine-render/src/components/docs/layout/line-breaker/enhancers/__tests__/link-enhancer.spec.ts b/packages/engine-render/src/components/docs/layout/line-breaker/enhancers/__tests__/link-enhancer.spec.ts
index 31b6bee005..7702d7e690 100644
--- a/packages/engine-render/src/components/docs/layout/line-breaker/enhancers/__tests__/link-enhancer.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/line-breaker/enhancers/__tests__/link-enhancer.spec.ts
@@ -19,8 +19,8 @@ import { BreakPointType } from '../../break';
import { LineBreaker } from '../../line-breaker';
import { LineBreakerLinkEnhancer } from '../link-enhancer';
-function collectBreaks(content: string) {
- const enhancer = new LineBreakerLinkEnhancer(new LineBreaker(content));
+function collectBreaks(content: string, allowLinkBreaks = true) {
+ const enhancer = new LineBreakerLinkEnhancer(new LineBreaker(content), allowLinkBreaks);
const points: Array<{ position: number; type: BreakPointType }> = [];
while (true) {
const bk = enhancer.nextBreakPoint();
@@ -36,6 +36,37 @@ function collectBreaks(content: string) {
}
describe('link enhancer', () => {
+ it.each([
+ ['说明', 'http://www.swsresearch.com', '网站。'],
+ ['😀 ', 'https://example.com/a?b=1', ' next'],
+ ['', 'www.example.com', ''],
+ ['地址', 'https://example.com', ',继续 https://second.example/path 结束'],
+ ])('preserves a complete URL and surrounding text when internal breaks are disabled (%s)', (prefix, url, suffix) => {
+ const content = prefix + url + suffix;
+ const points = collectBreaks(content, false).map((point) => point.position);
+ const end = prefix.length + url.length;
+ expect(points.some((position) => position > prefix.length && position < end)).toBe(false);
+ // Keep normal trailing-space and closing-punctuation rules intact.
+ expect(points.find((position) => position >= end)).toBe(end + (suffix.startsWith(' ') || suffix.startsWith(',') ? 1 : 0));
+ expect(points[points.length - 1]).toBe(content.length);
+ expect(points.every((position, index) => index === 0 || position > points[index - 1])).toBe(true);
+ if (prefix) {
+ expect(points).toContain(prefix.length);
+ }
+ });
+
+ it.each([
+ ['需以本公司', 'http://www.swsresearch.com', '网站刊载为准'],
+ ['visit ', 'https://foo123bar.example/path-now', ' and continue'],
+ ['', `www.${'a'.repeat(40)}.com`, ''],
+ ])('keeps a link intact when character-level wrapping is disabled: %s%s%s', (prefix, link, suffix) => {
+ const content = prefix + link + suffix;
+ const breaks = collectBreaks(content, false);
+ expect(breaks.some((point) => point.position > prefix.length && point.position < prefix.length + link.length)).toBe(false);
+ expect(breaks[breaks.length - 1].position).toBe(content.length);
+ expect(breaks.every((point, index) => index === 0 || point.position > breaks[index - 1].position)).toBe(true);
+ });
+
it('keeps normal text breaking behavior without links', () => {
const breaks = collectBreaks('hello world');
expect(breaks.length).toBeGreaterThan(0);
diff --git a/packages/engine-render/src/components/docs/layout/line-breaker/enhancers/link-enhancer.ts b/packages/engine-render/src/components/docs/layout/line-breaker/enhancers/link-enhancer.ts
index 6851a85712..e927b6fa61 100644
--- a/packages/engine-render/src/components/docs/layout/line-breaker/enhancers/link-enhancer.ts
+++ b/packages/engine-render/src/components/docs/layout/line-breaker/enhancers/link-enhancer.ts
@@ -114,7 +114,8 @@ export class LineBreakerLinkEnhancer implements IBreakPoints {
public content = '';
constructor(
- private _lineBreaker: IBreakPoints
+ private _lineBreaker: IBreakPoints,
+ private readonly _allowLinkBreaks = true
) {
this.content = _lineBreaker.content;
}
@@ -135,7 +136,7 @@ export class LineBreakerLinkEnhancer implements IBreakPoints {
this._isInLink = true;
this._link = extractLink(this.content, this._curBreak.position);
// get link slice.
- this._linkSlice = linebreakLink(this._link);
+ this._linkSlice = this._allowLinkBreaks ? linebreakLink(this._link) : [];
this._index = 0;
while (this._nextBreak && this._nextBreak.position < this._curBreak.position + this._link.length) {
diff --git a/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts b/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts
index d2ac9e8d42..19af06ac5c 100644
--- a/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts
@@ -14,15 +14,363 @@
* limitations under the License.
*/
+import type { ITextStyle } from '@univerjs/core';
import type { IDocumentSkeletonGlyph } from '../../../../../basics/i-document-skeleton-cached';
-import { BooleanNumber, DataStreamTreeTokenType, DocumentFlavor } from '@univerjs/core';
+import type { IFontCreateConfig } from '../../../../../basics/interfaces';
+import { BooleanNumber, DataStreamTreeTokenType, DocumentFlavor, GridType } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
import { GlyphType } from '../../../../../basics/i-document-skeleton-cached';
+import { getFontStyleString } from '../../../../../basics/tools';
import { getDocumentCompatibilityPolicy } from '../../../document-compatibility';
import { FontCache } from '../../shaping-engine/font-cache';
-import { baseAdjustability, createSkeletonBulletGlyph, createSkeletonLetterGlyph, glyphShrinkLeft, glyphShrinkRight, isJustifiable, isSpace } from '../glyph';
+import {
+ applyGlyphKerning,
+ baseAdjustability,
+ createSkeletonBulletGlyph,
+ createSkeletonLetterGlyph,
+ getGlyphGroupFontBoundingBox,
+ getGlyphGroupShrinkability,
+ glyphShrinkLeft,
+ glyphShrinkRight,
+ isJustifiable,
+ isSpace,
+ measureTextWithCharacterSpacing,
+ preserveLineStartPunctuationSpace,
+ setGlyphGroupLeft,
+} from '../glyph';
describe('Glyph utils test cases', () => {
+ it.each(['A', '😀', 'مرحبا', '\t', '\r'])('preserves hidden %j offsets without painting or measuring it', (raw) => {
+ const textStyle: ITextStyle = { ff: 'Arial', fs: 80, hidden: true };
+ const glyph = createSkeletonLetterGlyph(raw, {
+ textStyle,
+ fontStyle: getFontStyleString(textStyle),
+ charSpace: 0,
+ gridType: GridType.SNAP_TO_CHARS,
+ snapToGrid: BooleanNumber.TRUE,
+ }, { width: 120, ascent: 90, descent: 20 });
+ expect(glyph).toMatchObject({ raw, count: raw.length, content: '', width: 0, bBox: { ba: 0, bd: 0, width: 0 } });
+ expect(glyph.streamType).toBe(raw === '\r' ? DataStreamTreeTokenType.PARAGRAPH : DataStreamTreeTokenType.LETTER);
+ expect(glyph.isJustifiable).toBe(false);
+ });
+
+ it.each([DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL])('uses the correct picture-only line metrics in %s mode', (flavor) => {
+ const policy = getDocumentCompatibilityPolicy(flavor);
+ const picture = {
+ streamType: DataStreamTreeTokenType.CUSTOM_BLOCK,
+ width: 100,
+ bBox: { ba: 54, bd: 0 },
+ } as IDocumentSkeletonGlyph;
+ const largeMark = {
+ streamType: DataStreamTreeTokenType.PARAGRAPH,
+ width: 0,
+ bBox: { ba: 96, bd: 24 },
+ } as IDocumentSkeletonGlyph;
+ const mark = { ...largeMark, bBox: { ba: 14, bd: 4 } } as IDocumentSkeletonGlyph;
+ const text = { ...mark, streamType: DataStreamTreeTokenType.LETTER, width: 8 };
+ expect(getGlyphGroupFontBoundingBox(policy, [text], [largeMark])).toEqual(
+ flavor === DocumentFlavor.TRADITIONAL
+ ? { boundingBoxAscent: 14, boundingBoxDescent: 4, normalLineHeight: 0 }
+ : { boundingBoxAscent: 96, boundingBoxDescent: 24, normalLineHeight: 0 }
+ );
+ expect(getGlyphGroupFontBoundingBox(policy, [picture], [largeMark])).toEqual(
+ flavor === DocumentFlavor.TRADITIONAL
+ ? { boundingBoxAscent: 54, boundingBoxDescent: 0, normalLineHeight: 0 }
+ : { boundingBoxAscent: 96, boundingBoxDescent: 24, normalLineHeight: 0 }
+ );
+ expect(getGlyphGroupFontBoundingBox(policy, [picture, text], [mark])).toEqual({
+ boundingBoxAscent: 54,
+ boundingBoxDescent: 4,
+ normalLineHeight: 0,
+ });
+ expect(getGlyphGroupFontBoundingBox(policy, [largeMark])).toEqual({
+ boundingBoxAscent: 96,
+ boundingBoxDescent: 24,
+ normalLineHeight: 0,
+ });
+ });
+
+ it.each([' ', '\t', '\u3000', '\u00A0', 'X'])('preserves the Word line-height distinction for %j', (content) => {
+ const mark = {
+ streamType: DataStreamTreeTokenType.PARAGRAPH,
+ content: '\r',
+ width: 0,
+ bBox: { ba: 8, bd: 2, normalLineHeight: 12 },
+ } as IDocumentSkeletonGlyph;
+ const large = {
+ streamType: DataStreamTreeTokenType.LETTER,
+ content,
+ width: 30,
+ bBox: { ba: 32, bd: 8, normalLineHeight: 48 },
+ } as IDocumentSkeletonGlyph;
+ for (const flavor of [DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN]) {
+ const ignored = flavor === DocumentFlavor.TRADITIONAL && [' ', '\t', '\u3000'].includes(content);
+ expect(getGlyphGroupFontBoundingBox(getDocumentCompatibilityPolicy(flavor), [large], [mark])).toEqual(
+ ignored
+ ? { boundingBoxAscent: 8, boundingBoxDescent: 2, normalLineHeight: 12 }
+ : { boundingBoxAscent: 32, boundingBoxDescent: 8, normalLineHeight: 48 }
+ );
+ }
+ });
+
+ it('restores pair-compressed opening punctuation at a line boundary without offering that space to justification', () => {
+ const glyph = {
+ content: '(',
+ width: 12,
+ xOffset: 0,
+ adjustability: baseAdjustability('(', 12),
+ } as IDocumentSkeletonGlyph;
+ glyphShrinkLeft(glyph, 6);
+ expect(glyph.width).toBe(6);
+ preserveLineStartPunctuationSpace(glyph);
+ preserveLineStartPunctuationSpace(glyph);
+ expect(glyph.width).toBe(12);
+ expect(glyph.xOffset).toBe(0);
+ expect(getGlyphGroupShrinkability([glyph])).toBe(0);
+ });
+
+ it('counts punctuation compression separately from authored and automatic spacing', () => {
+ const glyphs = [',', '“', '”', '・', ' ', ' ', '中'].map((content) => ({
+ content,
+ adjustability: baseAdjustability(content, 12),
+ } as IDocumentSkeletonGlyph));
+ glyphs[glyphs.length - 1].adjustability.shrinkability = [1.5, 1.5];
+ expect(getGlyphGroupShrinkability(glyphs, true)).toBe(24);
+ expect(getGlyphGroupShrinkability(glyphs)).toBe(35);
+ });
+
+ it.each([[')', [0, 0]], ['(', [0, 0]], ['・', [0, 0]]] as const)('does not compress already half-width DrawingML punctuation %s', (content, shrinkability) => {
+ const textStyle = { ff: 'Proportional punctuation regression', fs: 13.5 };
+ const fontStyle = getFontStyleString(textStyle);
+ FontCache.setFontMeasureCache(fontStyle.fontString, content, {
+ width: 9,
+ fontBoundingBoxAscent: 17,
+ fontBoundingBoxDescent: 5,
+ actualBoundingBoxAscent: 15,
+ actualBoundingBoxDescent: 2,
+ });
+ try {
+ for (const flavor of [DocumentFlavor.UNSPECIFIED, DocumentFlavor.DRAWINGML]) {
+ const glyph = createSkeletonLetterGlyph(content, {
+ textStyle,
+ fontStyle,
+ charSpace: 0,
+ snapToGrid: BooleanNumber.FALSE,
+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(flavor),
+ });
+ expect(glyph.width).toBe(9);
+ expect(glyph.adjustability.shrinkability).toEqual(flavor === DocumentFlavor.DRAWINGML
+ ? shrinkability
+ : baseAdjustability(content, 9).shrinkability);
+ }
+ expect(baseAdjustability(')', 18, 18).shrinkability).toEqual([0, 9]);
+ expect(baseAdjustability('。', 12, 18).shrinkability).toEqual([0, 3]);
+ } finally {
+ FontCache.clearFontMeasureCache(fontStyle.fontString);
+ }
+ });
+
+ it.each([
+ [11, 9, 8.8],
+ [12, 9.5, 9.6],
+ [13, 10.5, 10.4],
+ [24, 19, 19.2],
+ [36, 29, 28.8],
+ ])('uses native small-cap sizing at %s pt without shrinking line metrics or kerning thresholds', (fs, wordSize, drawingSize) => {
+ const textStyle = { ff: 'Small caps regression', fs, smallCaps: true, kerning: fs };
+ const fontStyle = getFontStyleString(textStyle);
+ for (const [flavor, expectedSize] of [[DocumentFlavor.MODERN, wordSize], [DocumentFlavor.DRAWINGML, drawingSize]] as const) {
+ const config = {
+ textStyle,
+ fontStyle,
+ charSpace: 0,
+ snapToGrid: BooleanNumber.FALSE,
+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(flavor),
+ };
+ const normal = createSkeletonLetterGlyph('H', config);
+ for (const [raw, content] of [['h', 'H'], ['é', 'É'], ['ß', 'ß'], ['a\u0301', 'A\u0301']]) {
+ const small = createSkeletonLetterGlyph(raw, config);
+ expect(small.fontStyle?.fontSize).toBeCloseTo(expectedSize);
+ expect(small.fontStyle?.originFontSize).toBe(fs);
+ expect(small.fontStyle?.fontKerning).toBe('normal');
+ expect(small.bBox.ba).toBe(normal.bBox.ba);
+ expect(small.bBox.bd).toBe(normal.bBox.bd);
+ expect(small.bBox.normalLineHeight).toBe(normal.bBox.normalLineHeight);
+ expect(small).toMatchObject({ raw, content, count: raw.length, ts: textStyle });
+ }
+ for (const raw of ['H', '1', ' ', '中', '😀']) {
+ expect(createSkeletonLetterGlyph(raw, config).fontStyle).toBe(fontStyle);
+ }
+ expect(createSkeletonLetterGlyph('h', { ...config, textStyle: { ...textStyle, caps: true } }).fontStyle).toBe(fontStyle);
+ expect(createSkeletonLetterGlyph('h', { ...config, textStyle: { ...textStyle, smallCaps: false } }).content).toBe('h');
+ }
+ });
+
+ it('measures display capitals while preserving Unicode text and source offsets', () => {
+ const raw = 'aéß中😀a\u0301';
+ const content = 'AÉß中😀A\u0301';
+ const textStyle = { ff: 'Caps regression', fs: 12, caps: true };
+ const fontStyle = getFontStyleString(textStyle);
+ FontCache.setFontMeasureCache(fontStyle.fontString, content, {
+ width: 70,
+ fontBoundingBoxAscent: 12,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 2,
+ });
+ try {
+ const glyph = createSkeletonLetterGlyph(raw, { textStyle, fontStyle, charSpace: 0, snapToGrid: BooleanNumber.FALSE });
+ expect(glyph).toMatchObject({ content, raw, count: raw.length, width: 70 });
+ expect(glyph.ts).toEqual(textStyle);
+ expect(glyph.fontStyle).toEqual(fontStyle);
+ } finally {
+ FontCache.clearFontMeasureCache(fontStyle.fontString);
+ }
+ });
+
+ it.each(['V', ' ', '\u00A0'].flatMap((right) => [50, 100, 200].map((sa) => ({ right, sa }))))('shares threshold decisions and recomputes pair advances at line splits ($right, scale=$sa)', ({ right, sa }) => {
+ const textStyle = { ff: 'Kerning regression', fs: 12, kerning: 12, sa };
+ const scale = sa / 100;
+ const fontStyle = getFontStyleString(textStyle);
+ expect(fontStyle.fontKerning).toBe('normal');
+ expect(getFontStyleString({ ...textStyle, fs: 11 }).fontKerning).toBe('none');
+ expect(getFontStyleString({ ...textStyle, kerning: 0 }).fontKerning).toBe('none');
+ expect(getFontStyleString({ fs: 12 }).fontKerning).toBeUndefined();
+ const metrics = { width: 10, fontBoundingBoxAscent: 12, fontBoundingBoxDescent: 3, actualBoundingBoxAscent: 10, actualBoundingBoxDescent: 2 };
+ for (const mode of ['normal', 'none']) {
+ for (const content of ['A', right, `A${right}`]) {
+ FontCache.setFontMeasureCache(`${fontStyle.fontString}\u0000${mode}`, content, {
+ ...metrics,
+ width: content === `A${right}` ? (mode === 'normal' ? 18 : 20) : 10,
+ });
+ }
+ }
+ try {
+ const config = { fontStyle, textStyle, charSpace: 0, snapToGrid: BooleanNumber.FALSE };
+ const glyphs = ['A', right].map((content) => createSkeletonLetterGlyph(content, config));
+ applyGlyphKerning(glyphs);
+ setGlyphGroupLeft(glyphs);
+ expect(glyphs.map((glyph) => [glyph.left, glyph.width, glyph.count])).toEqual([[0, 8 * scale, 1], [8 * scale, 10 * scale, 1]]);
+ applyGlyphKerning(glyphs);
+ expect(glyphs[0].width).toBe(8 * scale);
+ applyGlyphKerning(glyphs.slice(0, 1));
+ expect(glyphs[0].width).toBe(10 * scale);
+ expect(glyphs[0].bBox.width).toBe(10 * scale);
+ } finally {
+ for (const mode of ['normal', 'none']) {
+ FontCache.clearFontMeasureCache(`${fontStyle.fontString}\u0000${mode}`);
+ }
+ }
+ });
+
+ it('keeps DrawingML line separators zero-width without losing their source or font metrics', () => {
+ const fontStyle = getFontStyleString({ ff: 'Line separator regression', fs: 12 });
+ FontCache.setFontMeasureCache(fontStyle.fontString, '\u2028', {
+ width: 8,
+ fontBoundingBoxAscent: 12,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 0,
+ actualBoundingBoxDescent: 0,
+ });
+ const outlineFont = fontStyle.fontString.replace(/\b\d+(?:\.\d+)?(?:pt|px)\b/, '1024px');
+ FontCache.setFontMeasureCache(outlineFont, '\u2028', {
+ width: 8 * 64,
+ fontBoundingBoxAscent: 12 * 64,
+ fontBoundingBoxDescent: 3 * 64,
+ actualBoundingBoxAscent: 0,
+ actualBoundingBoxDescent: 0,
+ });
+ try {
+ for (const sc of [0, 2]) {
+ for (const snapToGrid of [BooleanNumber.FALSE, BooleanNumber.TRUE]) {
+ const config = {
+ fontStyle,
+ textStyle: { sc },
+ charSpace: 4,
+ gridType: GridType.SNAP_TO_CHARS,
+ snapToGrid,
+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(DocumentFlavor.DRAWINGML),
+ };
+ const glyph = createSkeletonLetterGlyph('\u2028', config);
+ expect(glyph.width).toBe(0);
+ expect(glyph.bBox).toMatchObject({ width: 0, ba: 12, bd: 3 });
+ expect(glyph).toMatchObject({ content: '\u2028', raw: '\u2028', count: 1, xOffset: 0 });
+ if (snapToGrid === BooleanNumber.FALSE) {
+ expect(createSkeletonLetterGlyph('\u2028', config, 25).width).toBe(25);
+ }
+ }
+ }
+ for (const flavor of [DocumentFlavor.UNSPECIFIED, DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL]) {
+ expect(createSkeletonLetterGlyph('\u2028', {
+ fontStyle,
+ textStyle: {},
+ charSpace: 0,
+ snapToGrid: BooleanNumber.FALSE,
+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(flavor),
+ }).width).toBe(8);
+ }
+ } finally {
+ FontCache.clearFontMeasureCache(fontStyle.fontString);
+ FontCache.clearFontMeasureCache(outlineFont);
+ }
+ });
+
+ it('applies character spacing to advances without changing ink, source positions, or explicit object widths', () => {
+ const fontStyle = getFontStyleString({ ff: 'Spacing regression', fs: 12 });
+ const metrics = {
+ width: 10,
+ fontBoundingBoxAscent: 12,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 2,
+ };
+ for (const text of ['A', '中', 'e\u0301', '👩‍💻', '\r', '\t']) {
+ FontCache.setFontMeasureCache(fontStyle.fontString, text, metrics);
+ }
+ try {
+ for (const sc of [-3, 0, 2]) {
+ const config = { fontStyle, textStyle: { sc }, charSpace: 0, snapToGrid: BooleanNumber.FALSE };
+ for (const text of ['A', '中', 'e\u0301', '👩‍💻']) {
+ const glyph = createSkeletonLetterGlyph(text, config);
+ expect(glyph.width).toBe(10 + sc / 0.75);
+ expect(glyph.bBox.width).toBe(10);
+ expect(glyph.count).toBe(text.length);
+ expect(glyph.raw).toBe(text);
+ expect(createSkeletonLetterGlyph(text, config, 25).width).toBe(25);
+ const next = createSkeletonLetterGlyph('A', config);
+ setGlyphGroupLeft([glyph, next]);
+ expect(next.left).toBe(10 + sc / 0.75);
+ }
+ expect(createSkeletonLetterGlyph('\r', config).width).toBe(10);
+ expect(createSkeletonLetterGlyph('\t', config).width).toBe(10);
+ expect(createSkeletonLetterGlyph(DataStreamTreeTokenType.DOCS_END, config).width).toBe(0);
+ }
+ } finally {
+ FontCache.clearFontMeasureCache(fontStyle.fontString);
+ }
+ });
+
+ it('tracks graphemes, keeps cursive words intact, and shares the measured offsets with painting', () => {
+ const measured: string[] = [];
+ const result = measureTextWithCharacterSpacing('e\u0301👩‍💻مرحباก้ข', -3, (text) => {
+ measured.push(text);
+ return 10;
+ })!;
+ expect(measured).toEqual(['e\u0301', '👩‍💻', 'مرحبا', 'ก้', 'ข']);
+ expect(result.segments.map((segment) => segment.left)).toEqual([0, 7, 14, 21, 28]);
+ expect(result.width).toBe(35);
+ expect(result.inkWidth).toBe(38);
+ const kerned = measureTextWithCharacterSpacing('AV', 2, () => 10, () => -2)!;
+ expect(kerned.segments.map((segment) => segment.left)).toEqual([0, 10]);
+ expect(kerned.width).toBe(22);
+ expect(kerned.inkWidth).toBe(20);
+ for (const spacing of [undefined, 0, Number.NaN, Infinity]) {
+ expect(measureTextWithCharacterSpacing('AV', spacing, () => {
+ throw new Error('Untracked text must retain its original shaping');
+ })).toBeUndefined();
+ }
+ });
+
describe('test baseAdjustability', () => {
it('should return correct adjustability for space', () => {
const result = baseAdjustability(' ', 12);
@@ -139,6 +487,41 @@ describe('Glyph utils test cases', () => {
});
describe('test bullet glyph style', () => {
+ it.each([DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL])('measures list markers with the same font policy as body text in %s mode', (flavor) => {
+ const textStyle = { ff: 'Symbol', fs: 12 };
+ const fontStyle = getFontStyleString(textStyle);
+ const outlineFont = fontStyle.fontString.replace('12pt', '1024px');
+ const content = '\uF0B7';
+ FontCache.setFontMeasureCache(fontStyle.fontString, content, {
+ width: 8,
+ fontBoundingBoxAscent: 16,
+ fontBoundingBoxDescent: 4,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 0,
+ });
+ FontCache.setFontMeasureCache(outlineFont, content, {
+ width: 500,
+ fontBoundingBoxAscent: 960,
+ fontBoundingBoxDescent: 224,
+ actualBoundingBoxAscent: 512,
+ actualBoundingBoxDescent: 0,
+ });
+ try {
+ const bullet = createSkeletonBulletGlyph(
+ { ts: textStyle, bBox: { ba: 15, bd: 3 } } as IDocumentSkeletonGlyph,
+ { listId: 'list', symbol: content, ts: textStyle, startIndexItem: 1 },
+ 10,
+ getDocumentCompatibilityPolicy(flavor)
+ );
+ expect(bullet.bBox.ba).toBe(flavor === DocumentFlavor.TRADITIONAL ? 15 : 16);
+ expect(bullet.bBox.bd).toBe(flavor === DocumentFlavor.TRADITIONAL ? 3.5 : 4);
+ expect(bullet.bBox.width).toBe(flavor === DocumentFlavor.TRADITIONAL ? 7.8125 : 8);
+ } finally {
+ FontCache.clearFontMeasureCache(fontStyle.fontString);
+ FontCache.clearFontMeasureCache(outlineFont);
+ }
+ });
+
it('uses explicit bullet style while inheriting omitted properties from the paragraph glyph', () => {
let measuredFont = '';
const measureSpy = vi.spyOn(FontCache, 'getTextSize').mockImplementation((_content, fontStyle) => {
@@ -197,6 +580,7 @@ describe('Glyph utils test cases', () => {
count: 1,
} as IDocumentSkeletonGlyph;
+ paragraphGlyph.bBox = { ...paragraphGlyph.bBox, ba: 28, width: 30 };
const bulletGlyph = createSkeletonBulletGlyph(
paragraphGlyph,
{
@@ -212,6 +596,8 @@ describe('Glyph utils test cases', () => {
);
expect(bulletGlyph.content).toBe('p');
+ expect(bulletGlyph.bBox).toMatchObject({ ba: 28, bd: 4, width: 12 });
+ expect(paragraphGlyph.bBox.width).toBe(30);
expect(bulletGlyph.ts).toMatchObject({
ff: 'Wingdings',
fs: 24,
@@ -273,22 +659,7 @@ describe('Glyph utils test cases', () => {
describe('test font compatibility policy', () => {
it('should apply traditional font metric width rules to letter glyphs only when enabled', () => {
- vi.stubGlobal('document', {
- createElement: () => ({
- getContext: () => ({
- font: '',
- textBaseline: 'alphabetic',
- measureText: () => ({
- width: 16,
- fontBoundingBoxAscent: 30,
- fontBoundingBoxDescent: 9,
- actualBoundingBoxAscent: 30,
- actualBoundingBoxDescent: 9,
- }),
- }),
- }),
- });
- const config = {
+ const config: IFontCreateConfig = {
fontStyle: {
fontString: 'normal bold 24pt "Calibri", Arial',
fontSize: 24,
@@ -299,8 +670,17 @@ describe('Glyph utils test cases', () => {
textStyle: {},
charSpace: 0,
snapToGrid: 0,
- } as any;
+ };
+ const metrics = {
+ width: 16,
+ fontBoundingBoxAscent: 30,
+ fontBoundingBoxDescent: 9,
+ actualBoundingBoxAscent: 30,
+ actualBoundingBoxDescent: 9,
+ };
+ FontCache.setFontMeasureCache(config.fontStyle.fontString, '5', metrics);
+ FontCache.setFontMeasureCache('normal bold 1024px "Calibri", Arial', '5', { ...metrics, width: 512 });
const traditionalGlyph = createSkeletonLetterGlyph('5', {
...config,
documentCompatibilityPolicy: getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL),
@@ -312,25 +692,11 @@ describe('Glyph utils test cases', () => {
expect(traditionalGlyph.width).toBeCloseTo(14.72);
expect(modernGlyph.width).toBe(16);
+ FontCache.clearFontMeasureCache(config.fontStyle.fontString);
});
it('should calibrate SimSun CJK width only for traditional documents', () => {
- vi.stubGlobal('document', {
- createElement: () => ({
- getContext: () => ({
- font: '',
- textBaseline: 'alphabetic',
- measureText: () => ({
- width: 16,
- fontBoundingBoxAscent: 15,
- fontBoundingBoxDescent: 4,
- actualBoundingBoxAscent: 15,
- actualBoundingBoxDescent: 4,
- }),
- }),
- }),
- });
- const config = {
+ const config: IFontCreateConfig = {
fontStyle: {
fontString: 'normal normal 12pt "Times New Roman", 宋体',
fontSize: 12,
@@ -341,8 +707,17 @@ describe('Glyph utils test cases', () => {
textStyle: {},
charSpace: 0,
snapToGrid: 0,
- } as any;
+ };
+ const metrics = {
+ width: 16,
+ fontBoundingBoxAscent: 15,
+ fontBoundingBoxDescent: 4,
+ actualBoundingBoxAscent: 15,
+ actualBoundingBoxDescent: 4,
+ };
+ FontCache.setFontMeasureCache(config.fontStyle.fontString, '文', metrics);
+ FontCache.setFontMeasureCache('normal normal 1024px "Times New Roman", 宋体', '文', { ...metrics, width: 1024 });
const traditionalGlyph = createSkeletonLetterGlyph('文', {
...config,
documentCompatibilityPolicy: getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL),
@@ -354,6 +729,150 @@ describe('Glyph utils test cases', () => {
expect(traditionalGlyph.width).toBeCloseTo(15.52);
expect(modernGlyph.width).toBe(16);
+ FontCache.clearFontMeasureCache(config.fontStyle.fontString);
+ });
+ });
+
+ it.each([
+ { enabled: BooleanNumber.TRUE, fontHint: 'eastAsia', flavor: DocumentFlavor.TRADITIONAL, content: ' ', sa: 100, expected: 12 },
+ { enabled: BooleanNumber.TRUE, fontHint: 'eastAsia', flavor: DocumentFlavor.TRADITIONAL, content: ' ', sa: 50, expected: 6 },
+ { enabled: BooleanNumber.FALSE, fontHint: 'eastAsia', flavor: DocumentFlavor.TRADITIONAL, content: ' ', sa: 100, expected: 6.66796875 },
+ { enabled: undefined, fontHint: 'eastAsia', flavor: DocumentFlavor.TRADITIONAL, content: ' ', sa: 100, expected: 6.66796875 },
+ { enabled: BooleanNumber.TRUE, fontHint: 'default', flavor: DocumentFlavor.TRADITIONAL, content: ' ', sa: 100, expected: 6.66796875 },
+ { enabled: BooleanNumber.TRUE, fontHint: 'eastAsia', flavor: DocumentFlavor.MODERN, content: ' ', sa: 100, expected: 6.66796875 },
+ { enabled: BooleanNumber.TRUE, fontHint: 'eastAsia', flavor: DocumentFlavor.TRADITIONAL, content: ' ', sa: 100, expected: 24 },
+ ] as const)('gates legacy East Asian half-em space advances: %j', ({ enabled, fontHint, flavor, content, sa, expected }) => {
+ const textStyle: ITextStyle = { ff: 'Arial', fs: 18, fontHint, sa };
+ const fontStyle = getFontStyleString(textStyle);
+ const measuredWidth = content === ' ' ? 24 : 6.66796875;
+ FontCache.setFontMeasureCache(fontStyle.fontString, content, {
+ width: measuredWidth,
+ fontBoundingBoxAscent: 18,
+ fontBoundingBoxDescent: 4,
+ actualBoundingBoxAscent: 0,
+ actualBoundingBoxDescent: 0,
+ });
+ const outlineFont = fontStyle.fontString.replace('18pt', '1024px');
+ FontCache.setFontMeasureCache(outlineFont, content, {
+ width: measuredWidth * 1024 / 24,
+ fontBoundingBoxAscent: 768,
+ fontBoundingBoxDescent: 170,
+ actualBoundingBoxAscent: 0,
+ actualBoundingBoxDescent: 0,
+ });
+ try {
+ const glyph = createSkeletonLetterGlyph(content, {
+ textStyle,
+ fontStyle,
+ charSpace: 0,
+ snapToGrid: BooleanNumber.FALSE,
+ balanceSingleByteDoubleByteWidth: enabled,
+ documentCompatibilityPolicy: getDocumentCompatibilityPolicy(flavor),
+ });
+ expect(glyph.width).toBeCloseTo(expected);
+ expect(glyph.bBox.width).toBeCloseTo(expected);
+ expect(glyph.bBox.ba).toBe(18);
+ expect(glyph.bBox.bd).toBe(flavor === DocumentFlavor.TRADITIONAL ? 170 * 24 / 1024 : 4);
+ expect(FontCache.getTextSize(content, fontStyle).width).toBe(measuredWidth);
+ } finally {
+ FontCache.clearFontMeasureCache(fontStyle.fontString);
+ FontCache.clearFontMeasureCache(outlineFont);
+ }
+ });
+
+ it.each([-0.5, 1, 0, -100, Number.NaN, Number.POSITIVE_INFINITY])('applies point tracking without changing ink or structural advances: %s', (sc) => {
+ const fontStyle = getFontStyleString({ ff: 'Arial', fs: 10 });
+ const content = '😀';
+ FontCache.setFontMeasureCache(fontStyle.fontString, content, {
+ width: 20,
+ fontBoundingBoxAscent: 10,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 9,
+ actualBoundingBoxDescent: 2,
});
+ try {
+ const config = { fontStyle, textStyle: { sc }, charSpace: 1, snapToGrid: BooleanNumber.FALSE };
+ const glyph = createSkeletonLetterGlyph(content, config);
+ expect(glyph.width).toBeCloseTo(Math.max(0, 20 + (Number.isFinite(sc) ? sc / 0.75 : 0)));
+ expect(glyph.bBox.width).toBe(20);
+ expect(createSkeletonLetterGlyph(content, config, 30).width).toBe(30);
+ expect(createSkeletonLetterGlyph(DataStreamTreeTokenType.CUSTOM_RANGE_START, config).width).toBe(0);
+ } finally {
+ FontCache.clearFontMeasureCache(fontStyle.fontString);
+ }
+ });
+
+ it.each([50, 90, 100, 200, 0, -1, Number.NaN])('scales glyph advances and ink widths without scaling height: %s', (sa) => {
+ const fontStyle = getFontStyleString({ ff: 'Arial', fs: 10 });
+ FontCache.setFontMeasureCache(fontStyle.fontString, 'AB', {
+ width: 20,
+ fontBoundingBoxAscent: 10,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 9,
+ actualBoundingBoxDescent: 2,
+ });
+ try {
+ const config = { fontStyle, textStyle: { sa }, charSpace: 1, snapToGrid: BooleanNumber.FALSE };
+ const scale = Number.isFinite(sa) && sa > 0 ? sa / 100 : 1;
+ const glyph = createSkeletonLetterGlyph('AB', config);
+ const overrideGlyph = createSkeletonLetterGlyph('AB', config, 30);
+ expect(glyph.width).toBeCloseTo(20 * scale);
+ expect(glyph.bBox.width).toBeCloseTo(20 * scale);
+ expect(overrideGlyph.width).toBeCloseTo(30 * scale);
+ expect(glyph.bBox.ba).toBe(10);
+ expect(glyph.bBox.bd).toBe(3);
+ expect(FontCache.getTextSize('AB', fontStyle).width).toBe(20);
+ } finally {
+ FontCache.clearFontMeasureCache(fontStyle.fontString);
+ }
+ });
+
+ it.each([undefined, 'default', 'eastAsia', 'cs'] as const)('uses the East Asian font only for applicable characters with hint %s', (fontHint) => {
+ const textStyle: ITextStyle = { ff: 'Arial', eastAsiaFontFamily: '微软雅黑', fontHint, fs: 7.5, bl: BooleanNumber.TRUE };
+ const fontStyle = getFontStyleString({ ...textStyle, ff: 'Arial, 微软雅黑' });
+ const eastAsiaFontStyle = getFontStyleString({ ...textStyle, ff: '微软雅黑, Arial, 微软雅黑' });
+ const config = { textStyle, fontStyle, charSpace: 0, snapToGrid: BooleanNumber.FALSE };
+ const metrics = {
+ width: 10,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 2,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 1,
+ };
+ const ambiguous = ['“', '”', '‘', '’', '·', '℃', '①', 'α', 'Ж'];
+ const latin = ['A', '7', ' ', 'é'];
+ for (const content of ['工', ':', 'か', '한', ...ambiguous, ...latin]) {
+ FontCache.setFontMeasureCache(fontStyle.fontString, content, metrics);
+ FontCache.setFontMeasureCache(eastAsiaFontStyle.fontString, content, {
+ ...metrics,
+ width: 14,
+ fontBoundingBoxAscent: 11,
+ fontBoundingBoxDescent: 3,
+ });
+ }
+
+ try {
+ for (const content of ['工', ':', 'か', '한']) {
+ const glyph = createSkeletonLetterGlyph(content, config);
+ expect(glyph.fontStyle).toEqual(eastAsiaFontStyle);
+ expect(glyph.bBox.normalLineHeight).toBe(14);
+ expect(glyph.ts).toBe(textStyle);
+ }
+ for (const content of [...ambiguous, ...latin]) {
+ const glyph = createSkeletonLetterGlyph(content, config);
+ const eastAsian = fontHint === 'eastAsia' && ambiguous.includes(content);
+ expect(glyph.fontStyle).toEqual(eastAsian ? eastAsiaFontStyle : fontStyle);
+ expect(glyph.width).toBe(eastAsian ? 14 : 10);
+ expect(glyph.bBox.normalLineHeight).toBe(eastAsian ? 14 : 11);
+ }
+ expect(config.fontStyle).toBe(fontStyle);
+
+ const withoutEastAsiaFont = createSkeletonLetterGlyph('工', { ...config, textStyle: { ...textStyle, eastAsiaFontFamily: undefined } });
+ expect(withoutEastAsiaFont.fontStyle).toBe(fontStyle);
+ expect(withoutEastAsiaFont.bBox.normalLineHeight).toBe(11);
+ } finally {
+ FontCache.clearFontMeasureCache(fontStyle.fontString);
+ FontCache.clearFontMeasureCache(eastAsiaFontStyle.fontString);
+ }
});
});
diff --git a/packages/engine-render/src/components/docs/layout/model/__tests__/line.spec.ts b/packages/engine-render/src/components/docs/layout/model/__tests__/line.spec.ts
index f267c06781..2c3533322b 100644
--- a/packages/engine-render/src/components/docs/layout/model/__tests__/line.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/model/__tests__/line.spec.ts
@@ -15,9 +15,10 @@
*/
import type { IDocumentSkeletonPage } from '../../../../../basics/i-document-skeleton-cached';
-import { BooleanNumber, PositionedObjectLayoutType, TableTextWrapType, WrapTextType } from '@univerjs/core';
+import { BooleanNumber, DocumentFlavor, PositionedObjectLayoutType, TableTextWrapType, WrapTextType } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
import { LineType } from '../../../../../basics/i-document-skeleton-cached';
+import { getDocumentCompatibilityPolicy } from '../../../document-compatibility';
import {
calculateLineTopByDrawings,
collisionDetection,
@@ -44,6 +45,44 @@ function createTopBottomDrawing(top: number, height: number, angle = 0) {
}
describe('line model', () => {
+ it.each([
+ { flavor: DocumentFlavor.TRADITIONAL, left: -10, right: 0, expectedLeft: -10, expectedRight: 100 },
+ { flavor: DocumentFlavor.TRADITIONAL, left: 0, right: -15, expectedLeft: 0, expectedRight: 115 },
+ { flavor: DocumentFlavor.TRADITIONAL, left: -10, right: -15, expectedLeft: -10, expectedRight: 115 },
+ { flavor: DocumentFlavor.TRADITIONAL, left: -10, right: 10, expectedLeft: -10, expectedRight: 90 },
+ { flavor: DocumentFlavor.MODERN, left: -10, right: -15, expectedLeft: 0, expectedRight: 100 },
+ ])('honors negative Word indents without moving floating obstacles: %j', ({ flavor, left, right, expectedLeft, expectedRight }) => {
+ const drawing = {
+ aTop: 0,
+ aLeft: 30,
+ width: 20,
+ height: 30,
+ angle: 0,
+ drawingOrigin: { layoutType: PositionedObjectLayoutType.WRAP_SQUARE, wrapText: WrapTextType.BOTH_SIDES },
+ };
+ const page = { skeDrawings: new Map([['obstacle', drawing]]), skeTables: new Map() } as unknown as IDocumentSkeletonPage;
+ const line = createSkeletonLine(0, LineType.PARAGRAPH, { lineHeight: 16, contentHeight: 16, lineTop: 0, paddingLeft: left, paddingRight: right }, 100, 0, true, { documentCompatibilityPolicy: getDocumentCompatibilityPolicy(flavor) } as never, page, null, null);
+ expect(line.divides.map((divide) => [divide.left, divide.left + divide.width]))
+ .toEqual([[expectedLeft, 30], [50, expectedRight]]);
+ expect(drawing).toMatchObject({ aLeft: 30, width: 20 });
+ });
+
+ it.each([PositionedObjectLayoutType.WRAP_SQUARE, PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM])('reserves asymmetric effect bounds while leaving drawing geometry unchanged (%s)', (layoutType) => {
+ const drawing = {
+ aTop: 20,
+ aLeft: 10,
+ width: 80,
+ height: 40,
+ angle: 0,
+ drawingOrigin: { layoutType, distB: 2, effectExtent: { left: 10, top: 4, right: 10, bottom: 9 } },
+ };
+ const page = { skeDrawings: new Map([['effects', drawing]]), skeTables: new Map() } as unknown as IDocumentSkeletonPage;
+ expect(calculateLineTopByDrawings(10, 58, page, null, null, 0, 100)).toBe(71);
+ expect(collisionDetection({ ...drawing, top: 20, left: 10, effectExtent: drawing.drawingOrigin.effectExtent } as never, 2, 64, 0, 100)).toBe(true);
+ expect(collisionDetection({ ...drawing, top: 20, left: 10 } as never, 2, 64, 0, 100)).toBe(false);
+ expect(drawing).toMatchObject({ aTop: 20, aLeft: 10, width: 80, height: 40 });
+ });
+
it.each([
{ gap: 24, minimumWidth: 24, expectedTop: 130 },
{ gap: 25, minimumWidth: 24, expectedTop: 20 },
@@ -534,7 +573,7 @@ describe('line model', () => {
expect(calculateLineTopByDrawings(15, 10, page, null, null, 110, 100)).toBe(10);
});
- it('only applies no-wrap tables to intersecting columns', () => {
+ it.each([TableTextWrapType.NONE, TableTextWrapType.WRAP])('moves text below a full-column table without affecting adjacent columns: %s', (textWrap) => {
const page = {
skeDrawings: new Map(),
skeTables: new Map([
@@ -543,7 +582,7 @@ describe('line model', () => {
left: 0,
width: 100,
height: 42,
- tableSource: { textWrap: TableTextWrapType.NONE },
+ tableSource: { textWrap },
}],
]),
} as any;
diff --git a/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts b/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts
index dcfd44cb25..dedffd4bfb 100644
--- a/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts
@@ -32,6 +32,7 @@ import {
createSkeletonPage,
expandCellPageHeightForFlowTables,
expandCellPageHeightForInlineDrawings,
+ getRowBorderInset,
} from '../page';
const dealWithSectionMock = vi.fn();
@@ -39,6 +40,22 @@ const updateBlockIndexMock = vi.fn();
const updateInlineDrawingCoordsAndBorderMock = vi.fn();
const resetContextMock = vi.fn();
+it.each(['borderTop', 'borderBottom'] as const)('uses the inherited outer %s only for a table fragment, not for internal row spacing', (edge) => {
+ const outer = { color: { rgb: '#000000' }, width: { v: 0 } };
+ const row = {
+ tableCells: [{ [edge]: {
+ color: { rgb: '#000000' },
+ width: { v: 6 },
+ [edge === 'borderTop' ? 'tableTopBorder' : 'tableBottomBorder']: outer,
+ } }],
+ trHeight: { hRule: 0, val: { v: 0 } },
+ };
+ expect(getRowBorderInset(row, edge)).toBe(3);
+ expect(getRowBorderInset(row, edge, true)).toBe(0);
+ outer.width.v = 4;
+ expect(getRowBorderInset(row, edge, true)).toBe(2);
+});
+
vi.mock('../../block/section', () => ({
dealWithSection: (...args: unknown[]) => dealWithSectionMock(...args),
}));
@@ -88,8 +105,8 @@ describe('page model', () => {
isDirty: false,
} as any;
- const headerVM = { getChildren: () => [{}] };
- const footerVM = { getChildren: () => [{}] };
+ const headerVM = { getChildren: () => [{}], getParagraph: () => undefined };
+ const footerVM = { getChildren: () => [{}], getParagraph: () => undefined };
const sectionBreakConfig = {
sectionId: 'section-page-model',
pageNumberStart: 1,
@@ -143,6 +160,17 @@ describe('page model', () => {
const evenPage = createSkeletonPage(ctx, sectionBreakConfig, skeletonResourceReference, 2);
expect(evenPage.headerId).toBe('h-even');
expect(evenPage.footerId).toBe('f-even');
+
+ const portraitHeader = skeletonResourceReference.skeHeaders.get('h-even').get(200);
+ const portraitFooter = skeletonResourceReference.skeFooters.get('f-even').get(200);
+ createSkeletonPage(ctx, { ...sectionBreakConfig, pageSize: { width: 300, height: 200 } }, skeletonResourceReference, 4);
+ expect(skeletonResourceReference.skeHeaders.get('h-even').get(200)).toBe(portraitHeader);
+ expect(skeletonResourceReference.skeFooters.get('f-even').get(200)).toBe(portraitFooter);
+ expect(skeletonResourceReference.skeHeaders.get('h-even').has(300)).toBe(true);
+ expect(skeletonResourceReference.skeFooters.get('f-even').has(300)).toBe(true);
+ createSkeletonPage(ctx, sectionBreakConfig, skeletonResourceReference, 6);
+ expect(skeletonResourceReference.skeHeaders.get('h-even').has(300)).toBe(true);
+ expect(skeletonResourceReference.skeFooters.get('f-even').has(300)).toBe(true);
});
it('keeps the configured margin when header and footer content fit inside it', () => {
@@ -178,8 +206,8 @@ describe('page model', () => {
pageSize: { width: 200, height: 300 },
headerIds: { defaultHeaderId: 'h-default' },
footerIds: { defaultFooterId: 'f-default' },
- headerTreeMap: new Map([['h-default', { getChildren: () => [{}] }]]),
- footerTreeMap: new Map([['f-default', { getChildren: () => [{}] }]]),
+ headerTreeMap: new Map([['h-default', { getChildren: () => [{}], getParagraph: () => undefined }]]),
+ footerTreeMap: new Map([['f-default', { getChildren: () => [{}], getParagraph: () => undefined }]]),
columnProperties: [],
marginTop: 40,
marginBottom: 40,
@@ -194,50 +222,6 @@ describe('page model', () => {
expect(page.marginBottom).toBe(40);
});
- it('keeps traditional document margins when header and footer content overlap the body', () => {
- dealWithSectionMock.mockImplementation((_ctx: any, _vm: any, _node: any, areaPage: any) => ({
- pages: [{
- ...areaPage,
- height: 80,
- sections: [{ columns: [{ lines: [{ paragraphIndex: 0 }] }] }],
- skeDrawings: new Map(),
- skeTables: new Map(),
- }],
- }));
-
- const skeletonResourceReference = createSkeletonResourceReference();
- const ctx = {
- layoutStartPointer: {},
- skeletonResourceReference,
- isDirty: false,
- } as any;
-
- const page = createSkeletonPage(
- ctx,
- {
- pageNumberStart: 1,
- pageSize: { width: 816, height: 1056 },
- headerIds: { defaultHeaderId: 'h-default' },
- footerIds: { defaultFooterId: 'f-default' },
- headerTreeMap: new Map([['h-default', { getChildren: () => [{}] }]]),
- footerTreeMap: new Map([['f-default', { getChildren: () => [{}] }]]),
- columnProperties: [],
- marginTop: 24,
- marginBottom: 42,
- marginHeader: 24,
- marginFooter: 24,
- documentCompatibilityPolicy: getDocumentCompatibilityPolicy(DocumentFlavor.TRADITIONAL),
- } as any,
- skeletonResourceReference,
- 1
- );
-
- expect(page.originMarginTop).toBe(24);
- expect(page.marginTop).toBe(24);
- expect(page.originMarginBottom).toBe(42);
- expect(page.marginBottom).toBe(42);
- });
-
it('does not create negative-width columns for oversized single-column section properties', () => {
const skeletonResourceReference = createSkeletonResourceReference();
const ctx = {
@@ -405,6 +389,7 @@ describe('page model', () => {
adjustLineHeightInTable: BooleanNumber.TRUE,
characterSpacingControl: 2,
useFELayout: BooleanNumber.TRUE,
+ balanceSingleByteDoubleByteWidth: BooleanNumber.TRUE,
spaceWidthEastAsian: BooleanNumber.TRUE,
autoHyphenation: BooleanNumber.TRUE,
consecutiveHyphenLimit: 3,
@@ -436,6 +421,7 @@ describe('page model', () => {
adjustLineHeightInTable: cellConfig.adjustLineHeightInTable,
characterSpacingControl: cellConfig.characterSpacingControl,
useFELayout: cellConfig.useFELayout,
+ balanceSingleByteDoubleByteWidth: cellConfig.balanceSingleByteDoubleByteWidth,
spaceWidthEastAsian: cellConfig.spaceWidthEastAsian,
autoHyphenation: cellConfig.autoHyphenation,
consecutiveHyphenLimit: cellConfig.consecutiveHyphenLimit,
@@ -452,6 +438,7 @@ describe('page model', () => {
adjustLineHeightInTable: BooleanNumber.TRUE,
characterSpacingControl: 2,
useFELayout: BooleanNumber.TRUE,
+ balanceSingleByteDoubleByteWidth: BooleanNumber.TRUE,
spaceWidthEastAsian: BooleanNumber.TRUE,
autoHyphenation: BooleanNumber.TRUE,
consecutiveHyphenLimit: 3,
@@ -756,7 +743,7 @@ describe('page model', () => {
expect(pages[0].height).toBe(48);
});
- it('DOCX golden e2e expands table cell height to include inline drawings', () => {
+ it.each([0, 9])('expands a cell for inline drawing geometry and effect bounds (%s)', (bottom) => {
const page = {
height: 20,
skeDrawings: new Map([
@@ -765,6 +752,7 @@ describe('page model', () => {
height: 48,
drawingOrigin: {
layoutType: PositionedObjectLayoutType.INLINE,
+ effectExtent: { bottom },
},
}],
['float-1', {
@@ -779,7 +767,28 @@ describe('page model', () => {
expandCellPageHeightForInlineDrawings([page as never]);
- expect(page.height).toBe(54);
+ expect(page.height).toBe(54 + bottom);
+ });
+
+ it('keeps trailing paragraph spacing below a final inline drawing in a table cell', () => {
+ const line = {
+ spaceBelowApply: 10.4,
+ divides: [{ glyphGroup: [{ drawingId: 'logo' }] }],
+ };
+ const page = {
+ height: 20,
+ sections: [{ columns: [{ lines: [line] }] }],
+ skeDrawings: new Map([['logo', {
+ drawingId: 'logo',
+ aTop: 0,
+ height: 54,
+ drawingOrigin: { layoutType: PositionedObjectLayoutType.INLINE },
+ }]]),
+ };
+
+ expandCellPageHeightForInlineDrawings([page as never]);
+
+ expect(page.height).toBe(64.4);
});
it('expands table cell height to include nested flow tables', () => {
diff --git a/packages/engine-render/src/components/docs/layout/model/glyph.ts b/packages/engine-render/src/components/docs/layout/model/glyph.ts
index d21bf28d35..509a98fc54 100644
--- a/packages/engine-render/src/components/docs/layout/model/glyph.ts
+++ b/packages/engine-render/src/components/docs/layout/model/glyph.ts
@@ -19,14 +19,19 @@ import type {
IDocumentSkeletonBoundingBox,
IDocumentSkeletonBullet,
IDocumentSkeletonDivide,
+ IDocumentSkeletonFontStyle,
IDocumentSkeletonGlyph,
} from '../../../../basics/i-document-skeleton-cached';
import type { IFontCreateConfig } from '../../../../basics/interfaces';
+import type { IDocumentCompatibilityPolicy } from '../../document-compatibility';
import { BooleanNumber, BulletAlignment, DataStreamTreeTokenType, GridType } from '@univerjs/core';
import { cjk } from '../../../../basics/cjk-regexp';
import { GlyphType } from '../../../../basics/i-document-skeleton-cached';
import {
+ getFirstGrapheme,
getFontStyleString,
+ getTextWithCaps,
+ hasArabic,
isCjkCenterAlignedPunctuation,
isCjkLeftAlignedPunctuation,
isCjkRightAlignedPunctuation,
@@ -35,6 +40,7 @@ import { getCheckboxShapeSize, isCheckboxGlyph } from '../../../../shape/checkbo
import {
applyFontMetricCompatibility,
getDocumentCompatibilityPolicy,
+ getSmallCapsFontStyle,
isTraditionalDocumentCompatibility,
} from '../../document-compatibility';
import { FontCache } from '../shaping-engine/font-cache';
@@ -45,6 +51,59 @@ export function isSpace(char: string) {
return SPACE_CHARS.includes(char);
}
+
+export function getGlyphGroupFontBoundingBox(
+ policy: IDocumentCompatibilityPolicy | undefined,
+ ...glyphGroups: IDocumentSkeletonGlyph[][]
+): { boundingBoxAscent: number; boundingBoxDescent: number; normalLineHeight: number } {
+ let boundingBoxAscent = 0;
+ let boundingBoxDescent = 0;
+ let markAscent = 0;
+ let markDescent = 0;
+ let normalLineHeight = 0;
+ let markNormalLineHeight = 0;
+ const traditional = isTraditionalDocumentCompatibility(policy);
+ let hasInlineObject = false;
+ let hasOtherContent = false;
+ for (const glyphs of glyphGroups) {
+ for (const glyph of glyphs) {
+ // Word excludes breakable whitespace from line height, but not NBSP.
+ if (traditional && (glyph.content === ' ' || glyph.content === '\t' || glyph.content === '\u3000')) {
+ continue;
+ }
+ const { ba, bd } = glyph.bBox;
+ if (glyph.streamType === DataStreamTreeTokenType.PARAGRAPH) {
+ markAscent = Math.max(markAscent, ba);
+ markDescent = Math.max(markDescent, bd);
+ markNormalLineHeight = Math.max(markNormalLineHeight, glyph.bBox.normalLineHeight ?? 0);
+ continue;
+ }
+ boundingBoxAscent = Math.max(boundingBoxAscent, ba);
+ boundingBoxDescent = Math.max(boundingBoxDescent, bd);
+ normalLineHeight = Math.max(normalLineHeight, glyph.bBox.normalLineHeight ?? 0);
+ if (glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width > 0) {
+ hasInlineObject = true;
+ } else if (glyph.width !== 0 || ba !== 0 || bd !== 0) {
+ hasOtherContent = true;
+ }
+ }
+ }
+ // Word uses the paragraph-end font for empty lines, not to enlarge a line
+ // that already contains text or an inline object.
+ const ignoreDrawingMLMark = policy?.mode === 'drawingml' && glyphGroups.some((glyphs) => glyphs.some((glyph) =>
+ glyph.content && glyph.streamType !== DataStreamTreeTokenType.PARAGRAPH && glyph.glyphType !== GlyphType.LIST
+ ));
+ if (!ignoreDrawingMLMark && (!traditional || (!hasInlineObject && !hasOtherContent))) {
+ boundingBoxAscent = Math.max(boundingBoxAscent, markAscent);
+ boundingBoxDescent = Math.max(boundingBoxDescent, markDescent);
+ normalLineHeight = Math.max(normalLineHeight, markNormalLineHeight);
+ }
+ return { boundingBoxAscent, boundingBoxDescent, normalLineHeight };
+}
+
+export function getTextHorizontalScale(percent?: number): number {
+ return percent != null && Number.isFinite(percent) && percent > 0 ? percent / 100 : 1;
+}
// Whether the glyph is justifiable.
export function isJustifiable(
content: string
@@ -57,7 +116,10 @@ export function isJustifiable(
|| isCjkCenterAlignedPunctuation(content);
}
-export function baseAdjustability(content: string, width: number): IAdjustability {
+export function baseAdjustability(content: string, width: number, emWidth = width): IAdjustability {
+ // CJK punctuation compression removes side spacing, not the half-em glyph itself.
+ // Proportional fonts may already provide half-width punctuation with no spacing to remove.
+ const punctuationSpacing = Math.min(width / 2, Math.max(0, width - emWidth / 2));
if (isSpace(content)) {
return {
// The number for spaces is from Knuth-Plass' paper
@@ -67,17 +129,17 @@ export function baseAdjustability(content: string, width: number): IAdjustabilit
} else if (isCjkLeftAlignedPunctuation(content)) {
return {
stretchability: [0, 0],
- shrinkability: [0, width / 2.0],
+ shrinkability: [0, punctuationSpacing],
};
} else if (isCjkRightAlignedPunctuation(content)) {
return {
stretchability: [0, 0],
- shrinkability: [width / 2.0, 0],
+ shrinkability: [punctuationSpacing, 0],
};
} else if (isCjkCenterAlignedPunctuation(content)) {
return {
stretchability: [0, 0],
- shrinkability: [width / 4.0, width / 4.0],
+ shrinkability: [punctuationSpacing / 2, punctuationSpacing / 2],
};
} else {
return {
@@ -87,6 +149,30 @@ export function baseAdjustability(content: string, width: number): IAdjustabilit
}
}
+export function getGlyphGroupStretchability(glyphGroup: IDocumentSkeletonGlyph[]): number {
+ let stretchability = 0;
+ for (const glyph of glyphGroup) {
+ const [left, right] = glyph.adjustability.stretchability;
+ stretchability += left + right;
+ }
+ return stretchability;
+}
+
+export function getGlyphGroupShrinkability(glyphGroup: IDocumentSkeletonGlyph[], punctuationOnly = false): number {
+ let shrinkability = 0;
+ for (const glyph of glyphGroup) {
+ if (punctuationOnly
+ && !isCjkLeftAlignedPunctuation(glyph.content)
+ && !isCjkRightAlignedPunctuation(glyph.content)
+ && !isCjkCenterAlignedPunctuation(glyph.content)) {
+ continue;
+ }
+ const [left, right] = glyph.adjustability.shrinkability;
+ shrinkability += left + right;
+ }
+ return shrinkability;
+}
+
export function createSkeletonWordGlyph(
content: string,
config: IFontCreateConfig,
@@ -103,7 +189,7 @@ export function createSkeletonLetterGlyph(
const glyphWidth = typeof glyphMetrics === 'number' ? glyphMetrics : glyphMetrics?.width;
const glyph = _createSkeletonWordOrLetter(GlyphType.LETTER, content, config, glyphWidth);
- if (typeof glyphMetrics === 'object') {
+ if (typeof glyphMetrics === 'object' && config.textStyle.hidden !== true) {
if (glyphMetrics.ascent != null) {
glyph.bBox.ba = glyph.bBox.aba = glyphMetrics.ascent;
}
@@ -132,6 +218,10 @@ export function createSkeletonWholeEntityGlyph(
): IDocumentSkeletonGlyph {
const glyph = createSkeletonLetterGlyph(raw, config, glyphMetrics);
+ if (config.textStyle.hidden === true) {
+ return glyph;
+ }
+
glyph.adjustability = baseAdjustability(WHOLE_ENTITY_RENDER_MARKER, glyph.width);
glyph.bBox.width = glyph.width;
glyph.content = WHOLE_ENTITY_RENDER_MARKER;
@@ -189,13 +279,114 @@ export function createSkeletonCustomBlockGlyph(config: IFontCreateConfig, glyphW
};
}
+export function getPairKerningAdjustment(left: string, right: string, font: IDocumentSkeletonFontStyle): number {
+ if (font.fontKerning !== 'normal' || !left || !right || /[\u0000-\u001F\u2028\u2029]/u.test(left + right)) {
+ return 0;
+ }
+ // Subtract unkerned shaping to isolate kerning from ligatures and script shaping.
+ const adjustment = (text: string) => FontCache.getMeasureText(text, font.fontString, 'normal').width -
+ FontCache.getMeasureText(text, font.fontString, 'none').width;
+ return adjustment(left + right) - adjustment(left) - adjustment(right);
+}
+
+export function applyGlyphKerning(glyphs: IDocumentSkeletonGlyph[]): void {
+ for (const glyph of glyphs) {
+ if (glyph.kerningAdjustment) {
+ glyph.width -= glyph.kerningAdjustment;
+ glyph.kerningAdjustment = 0;
+ }
+ }
+ for (let i = 1; i < glyphs.length; i++) {
+ const left = glyphs[i - 1];
+ const right = glyphs[i];
+ const adjustment = getGlyphPairKerningAdjustment(left, right);
+ if (adjustment) {
+ left.kerningAdjustment = adjustment;
+ left.width += adjustment;
+ }
+ }
+}
+
+export function getGlyphPairKerningAdjustment(left?: IDocumentSkeletonGlyph, right?: IDocumentSkeletonGlyph): number {
+ const font = left?.fontStyle;
+ if (!left || !right || !font || font.fontKerning !== 'normal' || right.fontStyle?.fontKerning !== 'normal' ||
+ font.fontString !== right.fontStyle.fontString ||
+ left.glyphType !== GlyphType.LETTER || right.glyphType !== GlyphType.LETTER ||
+ left.streamType !== DataStreamTreeTokenType.LETTER || right.streamType !== DataStreamTreeTokenType.LETTER ||
+ getTextWithCaps(left.raw, left.ts?.caps || left.ts?.smallCaps) !== left.content ||
+ getTextWithCaps(right.raw, right.ts?.caps || right.ts?.smallCaps) !== right.content ||
+ left.xOffset !== 0 || right.xOffset !== 0 ||
+ left.kerningAdjustment == null || right.kerningAdjustment == null ||
+ getTextHorizontalScale(left.ts?.sa) !== getTextHorizontalScale(right.ts?.sa)) {
+ return 0;
+ }
+ const adjustment = getPairKerningAdjustment(left.content, right.content, font) * getTextHorizontalScale(left.ts?.sa);
+ return Number.isFinite(adjustment) && left.width - left.kerningAdjustment + adjustment >= 0 ? adjustment : 0;
+}
+
+/** Shared by skeleton layout and lightweight host measurement; offsets also drive painting. */
+export function measureTextWithCharacterSpacing(
+ content: string,
+ spacing: number | undefined,
+ measure: (text: string) => number,
+ pairAdjustment?: (left: string, right: string) => number
+): { content: string; width: number; inkWidth: number; segments: Array<{ content: string; left: number }> } | undefined {
+ if (!spacing || !Number.isFinite(spacing) || !content) {
+ return;
+ }
+
+ const segments: Array<{ content: string; left: number }> = [];
+ let width = 0;
+ let inkWidth = 0;
+ let index = 0;
+ while (index < content.length) {
+ let text = getFirstGrapheme(content.slice(index))!;
+ index += text.length;
+ // Keep cursive joins intact. Canvas cannot insert tracking inside an Arabic word without reshaping it.
+ if (hasArabic(text)) {
+ while (index < content.length) {
+ const next = getFirstGrapheme(content.slice(index))!;
+ if (!hasArabic(next)) {
+ break;
+ }
+ text += next;
+ index += next.length;
+ }
+ }
+ const measuredWidth = measure(text);
+ const previous = segments[segments.length - 1];
+ if (previous && pairAdjustment) {
+ width += pairAdjustment(previous.content, text);
+ }
+ segments.push({ content: text, left: width });
+ inkWidth = Math.max(inkWidth, width + measuredWidth);
+ // Structural and zero-width formatting characters do not reserve a tracking interval.
+ const extra = /^[\u0000-\u001F\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]+$/u.test(text) ? 0 : spacing;
+ width += Math.max(0, measuredWidth + extra);
+ }
+ return { content, width, inkWidth, segments };
+}
+
export function _createSkeletonWordOrLetter(
glyphType: GlyphType,
- content: string,
+ raw: string,
config: IFontCreateConfig,
glyphWidth?: number
): IDocumentSkeletonGlyph {
- const { fontStyle, textStyle, charSpace = 1, gridType = GridType.LINES, snapToGrid = BooleanNumber.FALSE } = config;
+ const { textStyle, charSpace = 1, gridType = GridType.LINES, snapToGrid = BooleanNumber.FALSE } = config;
+ const documentCompatibilityPolicy = config.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy();
+ const content = getTextWithCaps(raw, textStyle.caps || textStyle.smallCaps);
+ const eastAsiaFontFamily = textStyle.eastAsiaFontFamily?.trim();
+ // A fallback font can paint CJK glyphs while Canvas still reports the Latin font's line metrics.
+ // Word uses the East Asian font for ambiguous punctuation/symbols only when the run requests it.
+ // Language/charset-dependent Latin extensions are not covered by the font-type hint alone.
+ const hintedEastAsian = textStyle.fontHint === 'eastAsia'
+ && /^[\u00A1\u00A4\u00A7\u00A8\u00AA\u00AD\u00AF-\u00B4\u00B6-\u00BA\u00BC-\u00BF\u00D7\u00F7\u02B0-\u03CF\u0400-\u04FF\u2000-\u27BF\u2E80-\u2EFF\uE000-\uF8FF\uFB00-\uFB1C]+$/.test(content);
+ const baseFontStyle = eastAsiaFontFamily && (cjk.hasCJK(content) || hintedEastAsian)
+ ? getFontStyleString({ ...textStyle, ff: `${eastAsiaFontFamily}, ${config.fontStyle.fontFamily}` })
+ : config.fontStyle;
+
+ const fontStyle = getSmallCapsFontStyle(raw, textStyle, baseFontStyle, documentCompatibilityPolicy);
const skipWidthList: string[] = [
DataStreamTreeTokenType.SECTION_BREAK,
DataStreamTreeTokenType.TABLE_START,
@@ -219,10 +410,13 @@ export function _createSkeletonWordOrLetter(
];
let streamType = DataStreamTreeTokenType.LETTER;
- if (skipWidthList.indexOf(content) > -1) {
+ if (skipWidthList.indexOf(content) > -1 || textStyle.hidden === true) {
+ const zeroWidthStreamType = skipWidthList.includes(content) || content === DataStreamTreeTokenType.PARAGRAPH
+ ? content as DataStreamTreeTokenType
+ : DataStreamTreeTokenType.LETTER;
return {
content: '',
- raw: content,
+ raw,
ts: textStyle,
fontStyle,
width: 0,
@@ -243,8 +437,8 @@ export function _createSkeletonWordOrLetter(
isJustifiable: false,
adjustability: baseAdjustability(content, 0),
glyphType: GlyphType.PLACEHOLDER,
- streamType: content as DataStreamTreeTokenType,
- count: 1,
+ streamType: zeroWidthStreamType,
+ count: raw.length,
};
}
@@ -255,30 +449,70 @@ export function _createSkeletonWordOrLetter(
let bBox = null;
let xOffset = 0;
- const documentCompatibilityPolicy = config.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy();
+ const isDrawingMLLineSeparator = glyphWidth == null && content === '\u2028' && documentCompatibilityPolicy.mode === 'drawingml';
bBox = FontCache.getTextSize(content, fontStyle, isTraditionalDocumentCompatibility(documentCompatibilityPolicy));
+ if (fontStyle !== baseFontStyle) {
+ bBox = {
+ ...FontCache.getTextSize(content, baseFontStyle, isTraditionalDocumentCompatibility(documentCompatibilityPolicy)),
+ width: bBox.width,
+ aba: bBox.aba,
+ abd: bBox.abd,
+ };
+ }
bBox = applyFontMetricCompatibility(
content,
fontStyle,
bBox,
documentCompatibilityPolicy
);
- if (content === DataStreamTreeTokenType.PARAGRAPH && isTraditionalDocumentCompatibility(documentCompatibilityPolicy)) {
+ // Canvas normalizes a line separator to a space; DrawingML breaks must not consume line width.
+ if (isDrawingMLLineSeparator ||
+ (content === DataStreamTreeTokenType.PARAGRAPH && isTraditionalDocumentCompatibility(documentCompatibilityPolicy))) {
bBox = { ...bBox, width: 0 };
}
+ if (content === ' ' && (textStyle.fontHint === 'eastAsia' || config.balanceSpaceWidth)
+ && config.balanceSingleByteDoubleByteWidth === BooleanNumber.TRUE
+ && isTraditionalDocumentCompatibility(documentCompatibilityPolicy)) {
+ // Word's compatibility option also expands leading/trailing and consecutive spaces in Latin text.
+ bBox = { ...bBox, width: fontStyle.fontSize / 0.75 / 2 };
+ }
+ const horizontalScale = glyphType === GlyphType.TAB ? 1 : getTextHorizontalScale(textStyle.sa);
+ if (horizontalScale !== 1) {
+ bBox = { ...bBox, width: bBox.width * horizontalScale };
+ }
+ const unspacedWidth = bBox.width;
+ const spacing = glyphWidth == null && !isDrawingMLLineSeparator && streamType === DataStreamTreeTokenType.LETTER && glyphType !== GlyphType.TAB
+ ? measureTextWithCharacterSpacing(
+ content,
+ textStyle.sc == null ? undefined : textStyle.sc / 0.75,
+ (text) => text === content
+ ? unspacedWidth
+ : applyFontMetricCompatibility(text, fontStyle, FontCache.getTextSize(text, fontStyle), documentCompatibilityPolicy).width * horizontalScale,
+ (left, right) => getPairKerningAdjustment(left, right, fontStyle) * horizontalScale
+ )
+ : undefined;
+ if (spacing) {
+ bBox = { ...bBox, width: spacing.inkWidth };
+ }
const { width: contentWidth = 0 } = bBox;
- let width = glyphWidth ?? contentWidth;
+ let width = glyphWidth == null ? spacing?.width ?? contentWidth : glyphWidth * horizontalScale;
- if (validationGrid(gridType, snapToGrid)) {
+ if (!isDrawingMLLineSeparator && validationGrid(gridType, snapToGrid)) {
// When text also needs to align to the grid, process it
// const multiple = Math.ceil(contentWidth / charSpace);
- width = contentWidth + (cjk.hasCJK(content) ? charSpace : charSpace / 2);
+ width = (spacing?.width ?? contentWidth) + (cjk.hasCJK(content) ? charSpace : charSpace / 2);
if (gridType === GridType.SNAP_TO_CHARS) {
xOffset = (width - contentWidth) / 2;
}
}
+ if (content === DataStreamTreeTokenType.PARAGRAPH && isTraditionalDocumentCompatibility(documentCompatibilityPolicy)) {
+ // The end mark retains its font height, but occupies no grid cell in Word.
+ width = 0;
+ xOffset = 0;
+ }
+
return {
content,
ts: textStyle,
@@ -290,16 +524,23 @@ export function _createSkeletonWordOrLetter(
glyphType,
streamType,
isJustifiable: isJustifiable(content),
- adjustability: baseAdjustability(content, width),
- count: content.length,
- raw: content,
+ adjustability: baseAdjustability(content, width, documentCompatibilityPolicy.mode === 'drawingml' && glyphWidth == null
+ ? fontStyle.fontSize * (96 / 72)
+ : width),
+ count: raw.length,
+ raw,
+ ...(glyphWidth == null && !validationGrid(gridType, snapToGrid) && fontStyle.fontKerning === 'normal'
+ ? { kerningAdjustment: 0 }
+ : {}),
+ ...(spacing && spacing.segments.length > 1 ? { textSpacing: spacing } : {}),
};
}
export function createSkeletonBulletGlyph(
glyph: IDocumentSkeletonGlyph,
bulletSkeleton: IDocumentSkeletonBullet,
- charSpaceApply: number
+ charSpaceApply: number,
+ documentCompatibilityPolicy?: IDocumentCompatibilityPolicy
): IDocumentSkeletonGlyph {
const {
symbol: content,
@@ -315,7 +556,8 @@ export function createSkeletonBulletGlyph(
},
};
const fontStyle = getFontStyleString(textStyle);
- const measuredBoundingBox = FontCache.getTextSize(content, fontStyle);
+ const metrics = FontCache.getTextSize(content, fontStyle, isTraditionalDocumentCompatibility(documentCompatibilityPolicy));
+ const measuredBoundingBox = { ...metrics, width: metrics.width * getTextHorizontalScale(textStyle.sa) };
const checkboxSize = isCheckboxGlyph(content) ? getCheckboxShapeSize(textStyle.fs) : null;
const boundingBox = checkboxSize == null
? measuredBoundingBox
@@ -324,7 +566,10 @@ export function createSkeletonBulletGlyph(
// When text also needs to align to the grid, process it. LINES default reference is the global font size of the doc
const multiple = Math.ceil(contentWidth / charSpaceApply);
- let width = (multiple < 2 ? 2 : multiple) * charSpaceApply; // Default bullet has 2 tabs
+ // DrawingML uses paragraph indents for bullet spacing, not Word's default tab reservation.
+ let width = documentCompatibilityPolicy?.mode === 'drawingml'
+ ? contentWidth
+ : Math.max(2, multiple) * charSpaceApply;
let left = 0;
@@ -339,16 +584,18 @@ export function createSkeletonBulletGlyph(
}
}
- const bBox = checkboxSize == null ? _getMaxBoundingBox(glyph, boundingBox) : boundingBox;
+ // The marker can inherit a taller line box, but its ink width must not become the text's width.
+ const bBox = checkboxSize == null ? { ..._getMaxBoundingBox(glyph, boundingBox), width: contentWidth } : boundingBox;
return {
content,
ts: textStyle,
fontStyle,
width,
- xOffset: 0,
+ // Line adjustment recomputes advances; keep Word marker alignment as an ink offset.
+ xOffset: isTraditionalDocumentCompatibility(documentCompatibilityPolicy) ? left : 0,
bBox,
- left,
+ left: isTraditionalDocumentCompatibility(documentCompatibilityPolicy) ? 0 : left,
isJustifiable: isJustifiable(content),
adjustability: baseAdjustability(content, width),
glyphType: GlyphType.LIST,
@@ -399,7 +646,20 @@ export function addGlyphToDivide(
glyphGroup: IDocumentSkeletonGlyph[],
offsetLeft: number = 0
) {
- setGlyphGroupLeft(glyphGroup, offsetLeft);
+ if (divide.glyphGroup.length === 0 && glyphGroup.length > 0) {
+ removeGlyphAutoSpacing(glyphGroup[0], 0);
+ }
+ applyGlyphKerning(glyphGroup);
+ let left = offsetLeft;
+ const previous = divide.glyphGroup[divide.glyphGroup.length - 1];
+ if (previous?.kerningAdjustment != null && glyphGroup.length) {
+ const adjustment = getGlyphPairKerningAdjustment(previous, glyphGroup[0]);
+ const delta = adjustment - previous.kerningAdjustment;
+ previous.width += delta;
+ previous.kerningAdjustment = adjustment;
+ left += delta;
+ }
+ setGlyphGroupLeft(glyphGroup, left);
// Set glyph parent pointer.
for (const glyph of glyphGroup) {
@@ -409,6 +669,21 @@ export function addGlyphToDivide(
divide.glyphGroup.push(...glyphGroup);
}
+export function removeGlyphAutoSpacing(glyph: IDocumentSkeletonGlyph, side: 0 | 1): void {
+ const autoSpacing = glyph.autoSpacing;
+ if (!autoSpacing || autoSpacing[side] === 0) {
+ return;
+ }
+ const spacing = autoSpacing[side];
+ glyph.width -= spacing;
+ glyph.adjustability.shrinkability[side] -= spacing / 2;
+ glyph.adjustability.stretchability[side] = Math.max(0, glyph.adjustability.stretchability[side] - spacing / 2);
+ if (side === 0) {
+ glyph.xOffset -= spacing;
+ }
+ autoSpacing[side] = 0;
+}
+
function _getMaxBoundingBox(glyph: IDocumentSkeletonGlyph, bulletBBox: IDocumentSkeletonBoundingBox) {
const { ba: spanAscent, bd: spanDescent } = glyph.bBox;
const { ba: bulletAscent, bd: bulletDescent } = bulletBBox;
@@ -429,4 +704,18 @@ export function glyphShrinkLeft(glyph: IDocumentSkeletonGlyph, amount: number) {
glyph.width -= amount;
glyph.xOffset -= amount;
glyph.adjustability.shrinkability[0] -= amount;
+ if (isCjkRightAlignedPunctuation(glyph.content)) {
+ glyph.leadingPunctuationCompression = (glyph.leadingPunctuationCompression ?? 0) + amount;
+ }
+}
+
+export function preserveLineStartPunctuationSpace(glyph: IDocumentSkeletonGlyph): void {
+ if (!isCjkRightAlignedPunctuation(glyph.content)) {
+ return;
+ }
+ const compressed = glyph.leadingPunctuationCompression ?? 0;
+ glyph.width += compressed;
+ glyph.xOffset += compressed;
+ glyph.leadingPunctuationCompression = 0;
+ glyph.adjustability.shrinkability[0] = 0;
}
diff --git a/packages/engine-render/src/components/docs/layout/model/line.ts b/packages/engine-render/src/components/docs/layout/model/line.ts
index 26d21798e8..1dde4b2db7 100644
--- a/packages/engine-render/src/components/docs/layout/model/line.ts
+++ b/packages/engine-render/src/components/docs/layout/model/line.ts
@@ -137,9 +137,7 @@ export function createSkeletonLine(
headersDrawings,
footersDrawings,
wrapTypeTables,
- paragraphConfig.documentCompatibilityPolicy && isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)
- ? TRADITIONAL_TABLE_WRAP_MIN_WIDTH
- : 0
+ isTraditionalDocumentCompatibility(paragraphConfig.documentCompatibilityPolicy)
);
for (const divide of lineSke.divides) {
@@ -163,7 +161,12 @@ export function calculateLineTopByDrawings(
const absoluteLineTop = sectionTop + lineTop;
let maxTop = absoluteLineTop;
const pageSkeDrawings = page.skeDrawings;
- const skeNonWrapTables = new Map(Array.from(page.skeTables).filter(([_, table]) => table.tableSource.textWrap === TableTextWrapType.NONE));
+ const flowBlockingTables = new Map(Array.from(page.skeTables).filter(([_, table]) =>
+ table.tableSource.textWrap === TableTextWrapType.NONE ||
+ (table.tableSource.textWrap === TableTextWrapType.WRAP && columnWidth > 0 &&
+ table.left - (table.tableSource.dist?.distL ?? 0) <= columnLeft &&
+ table.left + table.width + (table.tableSource.dist?.distR ?? 0) >= columnLeft + columnWidth)
+ ));
const headersDrawings = headerPage?.skeDrawings;
const footersDrawings = footerPage?.skeDrawings;
@@ -210,7 +213,7 @@ export function calculateLineTopByDrawings(
}
});
- skeNonWrapTables?.forEach((table) => {
+ flowBlockingTables.forEach((table) => {
const top = _getLineTopWidthWrapNone(table, lineHeight, absoluteLineTop, columnLeft, columnWidth);
if (top) {
maxTop = Math.max(maxTop, top);
@@ -261,6 +264,18 @@ function _getTableWrapSplit(
return split;
}
+function _getDrawingWrapBounds(drawing: IDocumentSkeletonDrawing) {
+ const { angle = 0, aLeft, width, aTop, height, drawingOrigin } = drawing;
+ const bounds = getBoundingBox(angle, aLeft, width, aTop, height);
+ const extent = drawingOrigin.effectExtent;
+ return {
+ left: (bounds.left ?? aLeft) - (extent?.left ?? 0),
+ top: (bounds.top ?? aTop) - (extent?.top ?? 0),
+ width: (bounds.width ?? width) + (extent?.left ?? 0) + (extent?.right ?? 0),
+ height: (bounds.height ?? height) + (extent?.top ?? 0) + (extent?.bottom ?? 0),
+ };
+}
+
function _getLineTopWithFullColumnWrap(
drawing: IDocumentSkeletonDrawing,
lineHeight: number,
@@ -296,6 +311,14 @@ function _getLineTopWithFullColumnWrap(
drawingWidth = boundingBox.width ?? drawingWidth;
}
+ if (layoutType === PositionedObjectLayoutType.WRAP_SQUARE) {
+ const bounds = _getDrawingWrapBounds(drawing);
+ top = bounds.top;
+ left = bounds.left - columnLeft;
+ drawingWidth = bounds.width;
+ drawingHeight = bounds.height;
+ }
+
const newTop = top - (layoutType === PositionedObjectLayoutType.WRAP_SQUARE ? distT : 0);
const newHeight = drawingHeight + (layoutType === PositionedObjectLayoutType.WRAP_SQUARE ? distB + distT : 0);
const bottom = newTop + newHeight;
@@ -356,48 +379,28 @@ function _getLineTopWidthWrapTopBottom(
columnLeft: number,
columnWidth: number
) {
- const { aTop, height, aLeft, width, angle = 0, drawingOrigin } = drawing;
+ const { drawingOrigin } = drawing;
const { layoutType, distT = 0, distB = 0 } = drawingOrigin;
if (layoutType !== PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM) {
return;
}
+ const bounds = _getDrawingWrapBounds(drawing);
if (columnWidth > 0) {
- const bounds = angle === 0 ? { left: aLeft, width } : getBoundingBox(angle, aLeft, width, aTop, height);
- const drawingLeft = bounds.left ?? aLeft;
- const drawingRight = drawingLeft + (bounds.width ?? width);
+ const drawingLeft = bounds.left;
+ const drawingRight = drawingLeft + bounds.width;
if (drawingRight <= columnLeft || drawingLeft >= columnLeft + columnWidth) {
return;
}
}
- // if (elementIndex && showElementIndex < elementIndex) {
- // // Drawing appears after a specific element, usually in the same paragraph cross-page scenario
- // // When operating on drawing, set showElementIndex if cross-page
- // return;
- // }
-
- if (angle === 0) {
- const newAtop = aTop - distT;
- const newHeight = distT + height + distB;
-
- if (newAtop + newHeight < lineTop || newAtop > lineHeight + lineTop) {
- return;
- }
-
- return newAtop + newHeight;
- }
- // In rotation case, consider the maximum area obtained by the first/last position of the line and the rotated drawing
- let { top: sTop = 0, height: sHeight = 0 } = getBoundingBox(angle, aLeft, width, aTop, height);
-
- sTop -= distT;
- sHeight += distB;
-
- if (sTop + sHeight < lineTop || sTop > lineHeight + lineTop) {
+ const top = bounds.top - distT;
+ const bottom = bounds.top + bounds.height + distB;
+ if (bottom < lineTop || top > lineHeight + lineTop) {
return;
}
- return sTop + sHeight;
+ return bottom;
}
function _calculateDividesByDrawings(
@@ -414,7 +417,7 @@ function _calculateDividesByDrawings(
headersDrawings?: Map<string, IDocumentSkeletonDrawing>,
footersDrawings?: Map<string, IDocumentSkeletonDrawing>,
wrapTypeTables?: Map<string, IDocumentSkeletonTable>,
- minimumTableWrapWidth: number = 0
+ traditionalLayout = false
): IDocumentSkeletonDivide[] {
const drawingsMix: IDrawingsSplit[] = []; // Mixed text and graphics case
// Insert indent placeholder
@@ -461,7 +464,7 @@ function _calculateDividesByDrawings(
if (wrapTypeTables && wrapTypeTables.size > 0) {
wrapTypeTables.forEach((table) => {
- const split = _getTableWrapSplit(table, lineTop, lineHeight, columnLeft, columnWidth, minimumTableWrapWidth);
+ const split = _getTableWrapSplit(table, lineTop, lineHeight, columnLeft, columnWidth, traditionalLayout ? TRADITIONAL_TABLE_WRAP_MIN_WIDTH : 0);
if (split) {
drawingsMix.push(split);
@@ -469,6 +472,18 @@ function _calculateDividesByDrawings(
});
}
+ // Negative Word indents expand the usable text interval beyond the column.
+ // Translate that interval before subtracting obstacles; a negative-width
+ // indent placeholder is not an obstacle and would otherwise be discarded.
+ const left = traditionalLayout ? Math.min(0, paddingLeft) : 0;
+ const right = traditionalLayout ? Math.min(0, paddingRight) : 0;
+ if (left < 0 || right < 0) {
+ const divides = _calculateDivideByDrawings(columnWidth - left - right, drawingsMix.map((split) => ({ ...split, left: split.left - left })));
+ for (const divide of divides) {
+ divide.left += left;
+ }
+ return divides;
+ }
return _calculateDivideByDrawings(columnWidth, drawingsMix);
}
@@ -490,12 +505,13 @@ export function collisionDetection(
const { top: oTop, height: oHeight, left: oLeft, width: oWidth, angle = 0 } = floatObject;
const { top = 0, left = 0, width = 0, height = 0 } = getBoundingBox(angle, oLeft, oWidth, oTop, oHeight);
+ const extent = floatObject.effectExtent;
- if (top + height < lineTop || top > lineHeight + lineTop) {
+ if (top + height + (extent?.bottom ?? 0) < lineTop || top - (extent?.top ?? 0) > lineHeight + lineTop) {
return false;
}
- if (left + width < columnLeft || left > columnLeft + columnWidth) {
+ if (left + width + (extent?.right ?? 0) < columnLeft || left - (extent?.left ?? 0) > columnLeft + columnWidth) {
return false;
}
@@ -550,6 +566,11 @@ function _calculateSplit(
const { distL = 0, distT = 0, distB = 0, distR = 0, wrapText } = drawingOrigin;
const dist = { distL, distT, distB, distR };
+ if (layoutType === PositionedObjectLayoutType.WRAP_SQUARE) {
+ const bounds = _getDrawingWrapBounds(drawing);
+ return __getSplitWidthNoAngle(bounds.top, bounds.height, bounds.left - columnLeft, bounds.width, lineTop, lineHeight, columnWidth, dist, layoutType, wrapText);
+ }
+
if (angle === 0) {
// No rotation case, wrapSquare | wrapThrough | wrapTight
return __getSplitWidthNoAngle(aTop, height, aLeft - columnLeft, width, lineTop, lineHeight, columnWidth, dist, layoutType, wrapText);
@@ -558,23 +579,6 @@ function _calculateSplit(
// In rotation case, consider the maximum area obtained by the first/last position of the line and the rotated drawing
const boundingBox = getBoundingBox(angle, aLeft - columnLeft, width, aTop, height);
- if (layoutType === PositionedObjectLayoutType.WRAP_SQUARE) {
- // In WRAP_SQUARE case, the rotated shape will have a new rect, use this new rect to determine split
- const { left: sLeft, width: sWidth, top: sTop, height: sHeight } = boundingBox;
- return __getSplitWidthNoAngle(
- sTop!,
- sHeight!,
- sLeft!,
- sWidth!,
- lineTop,
- lineHeight,
- columnWidth,
- dist,
- layoutType,
- wrapText
- );
- }
-
// wrapThrough | wrapTight
return __getCrossPoint(boundingBox.points, lineTop, lineHeight, columnWidth);
}
diff --git a/packages/engine-render/src/components/docs/layout/model/page.ts b/packages/engine-render/src/components/docs/layout/model/page.ts
index a16c9a8e2c..9f3a8d38cf 100644
--- a/packages/engine-render/src/components/docs/layout/model/page.ts
+++ b/packages/engine-render/src/components/docs/layout/model/page.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IDocumentBody, IParagraph, ITable, Nullable } from '@univerjs/core';
+import type { IDocumentBody, ITable, ITableCellBorder, ITableRow, Nullable } from '@univerjs/core';
import type {
IDocumentSkeletonHeaderFooter,
IDocumentSkeletonPage,
@@ -29,14 +29,14 @@ import {
GridType,
PageOrientType,
PositionedObjectLayoutType,
- SpacingRule,
TableTextWrapType,
} from '@univerjs/core';
import { BreakType, DocumentSkeletonPageType } from '../../../../basics/i-document-skeleton-cached';
import { getDocumentCompatibilityPolicy, isTraditionalDocumentCompatibility } from '../../document-compatibility';
import { dealWithSection } from '../block/section';
import {
- reachesNextDocumentGridLine,
+ getGlyphGroupWidth,
+ getLastLine,
resetContext,
updateBlockIndex,
updateInlineDrawingCoordsAndBorder,
@@ -54,7 +54,8 @@ export function createSkeletonPage(
sectionBreakConfig: ISectionBreakConfig,
skeletonResourceReference: ISkeletonResourceReference,
pageNumber = 1,
- breakType = BreakType.SECTION
+ breakType = BreakType.SECTION,
+ pageContext?: Pick<IDocumentSkeletonPage, 'type' | 'segmentId'>
): IDocumentSkeletonPage {
let page: IDocumentSkeletonPage;
if (sectionBreakConfig.cellTableId) {
@@ -62,7 +63,7 @@ export function createSkeletonPage(
} else if (ctx.noteSegmentId) {
page = _getNullPage(DocumentSkeletonPageType.NOTE, ctx.noteSegmentId);
} else {
- page = _getNullPage();
+ page = _getNullPage(pageContext?.type, pageContext?.segmentId);
}
const {
@@ -133,7 +134,9 @@ export function createSkeletonPage(
true
);
- skeHeaders.set(headerId, new Map([[pageWidth, header]]));
+ const widths = skeHeaders.get(headerId) ?? new Map();
+ widths.set(pageWidth, header);
+ skeHeaders.set(headerId, widths);
}
page.headerId = headerId;
}
@@ -151,25 +154,17 @@ export function createSkeletonPage(
false
);
- skeFooters.set(footerId, new Map([[pageWidth, footer]]));
+ const widths = skeFooters.get(footerId) ?? new Map();
+ widths.set(pageWidth, footer);
+ skeFooters.set(footerId, widths);
}
page.footerId = footerId;
}
page.originMarginTop = marginTop;
page.originMarginBottom = marginBottom;
- const documentCompatibilityPolicy =
- sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy();
- if (isTraditionalDocumentCompatibility(documentCompatibilityPolicy)) {
- // Word places body content at the configured page margins even when a tall
- // header or footer overlaps that area. Expanding the margins here changes
- // pagination and pushes page-anchored cover content into the body flow.
- page.marginTop = marginTop;
- page.marginBottom = marginBottom;
- } else {
- page.marginTop = _getVerticalMargin(marginTop, header);
- page.marginBottom = _getVerticalMargin(marginBottom, footer);
- }
+ page.marginTop = _getVerticalMargin(marginTop, header);
+ page.marginBottom = _getVerticalMargin(marginBottom, footer);
const sections = page.sections;
const lastSection = sections[sections.length - 1];
@@ -254,6 +249,25 @@ function _createSkeletonHeaderFooter(
marginRight = 0,
marginHeader = 0,
marginFooter = 0,
+ documentCompatibilityPolicy,
+ documentTextStyle,
+ fontFamilyFallbacks,
+ paragraphLineGapDefault,
+ defaultTabStop,
+ adjustLineHeightInTable,
+ characterSpacingControl,
+ useFELayout,
+ balanceSingleByteDoubleByteWidth,
+ spaceWidthEastAsian,
+ autoHyphenation,
+ consecutiveHyphenLimit,
+ doNotHyphenateCaps,
+ hyphenationZone,
+ charSpace,
+ linePitch,
+ gridType,
+ contentDirection,
+ textDirection,
} = sectionBreakConfig;
const pageWidth = pageSize?.width || Number.POSITIVE_INFINITY;
const pageHeight = pageSize?.height || Number.POSITIVE_INFINITY;
@@ -268,6 +282,25 @@ function _createSkeletonHeaderFooter(
},
localeService,
drawings,
+ documentCompatibilityPolicy,
+ documentTextStyle,
+ fontFamilyFallbacks,
+ paragraphLineGapDefault,
+ defaultTabStop,
+ adjustLineHeightInTable,
+ characterSpacingControl,
+ useFELayout,
+ balanceSingleByteDoubleByteWidth,
+ spaceWidthEastAsian,
+ autoHyphenation,
+ consecutiveHyphenLimit,
+ doNotHyphenateCaps,
+ hyphenationZone,
+ charSpace,
+ linePitch,
+ gridType,
+ contentDirection,
+ textDirection,
};
if (areaPage == null) {
@@ -304,23 +337,93 @@ function _createSkeletonHeaderFooter(
);
}
+ const traditional = isTraditionalDocumentCompatibility(
+ sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy()
+ );
+ if (traditional) {
+ positionUnwrappedStoryFrames(page, headerOrFooterViewModel);
+ }
updateBlockIndex([page], -1, sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy());
+ // Word reserves the complete text flow, including the final paragraph's spacing,
+ // but does not add the modern document's synthetic gap between stories.
+ const trailingSpace = traditional ? Math.max(0, getLastLine(page)?.spaceBelowApply ?? 0) : 0;
if (isHeader) {
Object.assign(page, {
marginTop: marginHeader,
- marginBottom: 5, // Space between header and content
+ marginBottom: traditional ? trailingSpace : 5,
});
} else {
Object.assign(page, {
- marginTop: 5, // Space between content and footer
- marginBottom: marginFooter,
+ marginTop: traditional ? 0 : 5,
+ marginBottom: marginFooter + trailingSpace,
});
}
return page;
}
+function positionUnwrappedStoryFrames(page: IDocumentSkeletonHeaderFooter, viewModel: DocumentViewModel) {
+ // Positioned text-only frames share editable glyphs with their story. Wrapped
+ // frames and stories with anchored objects require the object-wrap layout path.
+ if (page.skeTables.size > 0 || page.skeDrawings.size > 0) {
+ return;
+ }
+ for (const section of page.sections) {
+ for (const column of section.columns) {
+ const { lines } = column;
+ let removedHeight = 0;
+ for (let index = 0; index < lines.length; index++) {
+ const line = lines[index];
+ const frame = viewModel.getParagraph(line.paragraphIndex)?.paragraphStyle?.paragraphFrame;
+ const y = typeof frame === 'object' ? Number(frame.y ?? 0) / 15 : 0;
+ if (frame == null || typeof frame !== 'object' || frame.wrap !== 'none'
+ || frame.horizontalAnchor !== 'margin' || frame.verticalAnchor !== 'text'
+ || !['left', 'center', 'right'].includes(frame.xAlign ?? '')
+ || frame.yAlign != null || !Number.isFinite(y)) {
+ line.top -= removedHeight;
+ continue;
+ }
+ let end = index + 1;
+ while (end < lines.length && lines[end].paragraphIndex === line.paragraphIndex) {
+ end++;
+ }
+ // A following flow paragraph supplies the frame's text anchor.
+ if (end === lines.length) {
+ for (; index < end; index++) {
+ lines[index].top -= removedHeight;
+ }
+ break;
+ }
+ const frameLines = lines.slice(index, end);
+ let width = 0;
+ for (const item of frameLines) {
+ for (const divide of item.divides) {
+ width = Math.max(width, divide.left + divide.paddingLeft + getGlyphGroupWidth(divide, true));
+ }
+ }
+ const available = Math.max(0, column.width - width);
+ let left = 0;
+ if (frame.xAlign === 'right') {
+ left = available;
+ } else if (frame.xAlign === 'center') {
+ left = available / 2;
+ }
+ const occupiedHeight = lines[end].top - line.top;
+ for (const frameLine of frameLines) {
+ frameLine.top += y - removedHeight;
+ for (const divide of frameLine.divides) {
+ divide.left += left;
+ divide.width = Math.max(0, width - divide.left + left);
+ }
+ }
+ removedHeight += occupiedHeight;
+ index = end - 1;
+ }
+ }
+ }
+}
+
export function createNullCellPage(
ctx: ILayoutContext,
sectionBreakConfig: ISectionBreakConfig,
@@ -342,11 +445,13 @@ export function createNullCellPage(
drawings,
documentCompatibilityPolicy,
documentTextStyle,
+ fontFamilyFallbacks,
paragraphLineGapDefault,
defaultTabStop,
adjustLineHeightInTable,
characterSpacingControl,
useFELayout,
+ balanceSingleByteDoubleByteWidth,
spaceWidthEastAsian,
autoHyphenation,
consecutiveHyphenLimit,
@@ -369,6 +474,13 @@ export function createNullCellPage(
top = { v: 5 },
bottom = { v: 5 },
} = cellConfig.margin ?? cellMargin ?? {};
+ if (isTraditionalDocumentCompatibility(documentCompatibilityPolicy)) {
+ // Word aligns all cells to the row's largest vertical padding and border,
+ // even when the tallest text is in a different, thinner-bordered cell.
+ top = { ...top, v: getRowVerticalInset(tableConfig, row, 'top') };
+ const lastRow = Math.min(tableRows.length - 1, row + Math.max(1, cellConfig.rowSpan ?? 1) - 1);
+ bottom = { ...bottom, v: getRowVerticalInset(tableConfig, lastRow, 'bottom') };
+ }
const columnSpan = Math.max(1, cellConfig.columnSpan ?? 1);
const gridColumn = getTableCellGridColumn(tableConfig, row, col);
const pageWidth = tableColumns
@@ -383,6 +495,15 @@ export function createNullCellPage(
end = { ...end, v: availableMarginWidth - start.v };
}
const pageHeight = maxCellPageHeight;
+ const isVerticalCell = cellConfig.textDirection === 'tbRlV';
+ const rowHeight = tableRows.slice(row, row + Math.max(1, cellConfig.rowSpan ?? 1))
+ .reduce((sum, tableRow) => sum + Math.max(0, tableRow.trHeight?.val.v ?? 0), 0);
+ // Shape vertical text along the row's height, then restore physical bounds for table layout.
+ // ponytail: auto-height rows start from the cell width; content-driven height feedback needs a second layout pass.
+ const layoutWidth = isVerticalCell
+ ? Math.max(1, rowHeight || (Number.isFinite(availableHeight) ? availableHeight : pageWidth))
+ : pageWidth;
+ const layoutHeight = isVerticalCell ? Number.POSITIVE_INFINITY : pageHeight;
const cellSectionBreakConfig: ISectionBreakConfig = {
sectionId,
@@ -392,22 +513,24 @@ export function createNullCellPage(
footerTreeMap,
headerTreeMap,
pageSize: {
- width: pageWidth,
- height: pageHeight,
+ width: layoutWidth,
+ height: layoutHeight,
},
- marginTop: top.v,
- marginBottom: bottom.v,
- marginLeft: start.v,
- marginRight: end.v,
+ marginTop: isVerticalCell ? end.v : top.v,
+ marginBottom: isVerticalCell ? start.v : bottom.v,
+ marginLeft: isVerticalCell ? top.v : start.v,
+ marginRight: isVerticalCell ? bottom.v : end.v,
localeService,
drawings,
documentCompatibilityPolicy,
documentTextStyle,
+ fontFamilyFallbacks,
paragraphLineGapDefault,
defaultTabStop,
adjustLineHeightInTable: enableDocumentTableLineGrid ? adjustLineHeightInTable : undefined,
characterSpacingControl,
useFELayout,
+ balanceSingleByteDoubleByteWidth,
spaceWidthEastAsian,
autoHyphenation,
consecutiveHyphenLimit,
@@ -426,8 +549,8 @@ export function createNullCellPage(
// Set first page height to availableHeight.
Object.assign({}, cellSectionBreakConfig, {
pageSize: {
- width: pageWidth,
- height: Number.isFinite(availableHeight) ? availableHeight : pageHeight,
+ width: layoutWidth,
+ height: isVerticalCell ? layoutHeight : (Number.isFinite(availableHeight) ? availableHeight : pageHeight),
},
}),
skeletonResourceReference
@@ -438,9 +561,50 @@ export function createNullCellPage(
return {
page: areaPage,
sectionBreakConfig: cellSectionBreakConfig,
+ verticalCellWidth: isVerticalCell ? pageWidth : undefined,
};
}
+function finishVerticalCellLayout(pages: IDocumentSkeletonPage[], physicalWidth: number | undefined): void {
+ if (physicalWidth == null) {
+ return;
+ }
+ for (const page of pages) {
+ const logicalWidth = page.width;
+ page.width = page.height;
+ page.height = logicalWidth;
+ page.pageHeight = page.pageWidth;
+ page.pageWidth = physicalWidth;
+ page.cellTextDirection = 'tbRlV';
+ }
+}
+
+export function getCellBorderWidth(border: ITableCellBorder | undefined): number {
+ return border == null || border.color?.rgb === 'transparent' ? 0 : Math.max(0, border.width?.v ?? 1);
+}
+
+export function getRowBorderInset(row: ITableRow, edge: 'borderTop' | 'borderBottom', tableBoundary = false): number {
+ return row.tableCells.reduce((inset, cell) => {
+ const border = cell[edge];
+ const outer = edge === 'borderTop' ? border?.tableTopBorder : border?.tableBottomBorder;
+ const effective = tableBoundary ? outer ?? border : border;
+ return Math.max(inset, getCellBorderWidth(effective) / 2);
+ }, 0);
+}
+
+function getRowVerticalInset(table: ITable, index: number, edge: 'top' | 'bottom'): number {
+ const row = table.tableRows[index];
+ const padding = row.tableCells.reduce((max, cell) => {
+ const margin = cell.margin?.[edge] ?? table.cellMargin?.[edge] ?? { v: 5 };
+ return Math.max(max, margin.v ?? 0);
+ }, 0);
+ const borderEdge = edge === 'top' ? 'borderTop' : 'borderBottom';
+ const neighbour = table.tableRows[index + (edge === 'top' ? -1 : 1)];
+ const oppositeEdge = edge === 'top' ? 'borderBottom' : 'borderTop';
+ const border = Math.max(getRowBorderInset(row, borderEdge), neighbour ? getRowBorderInset(neighbour, oppositeEdge) : 0);
+ return padding + border;
+}
+
function getTableCellGridColumn(table: ITable, row: number, col: number): number {
const tableRow = table.tableRows[row];
let gridColumn = tableRow?.gridBefore ?? 0;
@@ -480,67 +644,32 @@ function isVerticallyCoveredGridColumn(table: ITable, row: number, gridColumn: n
return false;
}
-interface ICellLineGridCache {
- body: IDocumentBody;
- paragraphIndexes: number[];
- enableDocumentTableLineGrid: boolean;
-}
-
-// A context owns one layout generation. Reuse only metadata from its current
-// body and line pitch; edits and sections with another pitch get fresh decisions.
-const cellLineGridCaches = new WeakMap<ILayoutContext, Map<number, ICellLineGridCache>>();
-
function getCellLineGridOptions(
- ctx: ILayoutContext,
- cellNode: DataStreamTreeNode,
sectionBreakConfig: ISectionBreakConfig
): { inheritDocumentLinePitch: boolean; enableDocumentTableLineGrid: boolean } {
- const body = ctx.dataModel?.getBody?.();
- const linePitch = sectionBreakConfig.linePitch ?? 0;
const usesLineGrid = sectionBreakConfig.gridType === GridType.LINES ||
sectionBreakConfig.gridType === GridType.LINES_AND_CHARS;
const documentCompatibilityPolicy = sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy();
const isTraditionalLineGrid = isTraditionalDocumentCompatibility(documentCompatibilityPolicy) && usesLineGrid;
- if (!isTraditionalLineGrid || body == null) {
- return { enableDocumentTableLineGrid: false, inheritDocumentLinePitch: false };
- }
-
- let cacheByPitch = cellLineGridCaches.get(ctx);
- if (cacheByPitch == null) {
- cacheByPitch = new Map();
- cellLineGridCaches.set(ctx, cacheByPitch);
- }
- let cache = cacheByPitch.get(linePitch);
- if (cache?.body !== body) {
- const usesNextDocumentGridLine = (paragraph: IParagraph) => {
- const paragraphStyle = paragraph.paragraphStyle;
- const lineSpacing = paragraphStyle?.lineSpacing;
- return lineSpacing != null &&
- paragraphStyle?.spacingRule === SpacingRule.AUTO &&
- paragraphStyle.snapToGrid !== BooleanNumber.FALSE &&
- reachesNextDocumentGridLine(lineSpacing, paragraphStyle.spaceBelow?.v ?? 0, linePitch);
- };
- const paragraphIndexes = (body.paragraphs ?? [])
- .filter(usesNextDocumentGridLine)
- .map((paragraph) => paragraph.startIndex);
- cache = {
- body,
- paragraphIndexes,
- enableDocumentTableLineGrid: body.tables?.some((table) => paragraphIndexes.some(
- (index) => index > table.startIndex && index < table.endIndex
- )) === true,
- };
- cacheByPitch.set(linePitch, cache);
- }
-
+ // A cell inherits its section's grid, independently of spacing in other paragraphs.
return {
- enableDocumentTableLineGrid: cache.enableDocumentTableLineGrid,
- inheritDocumentLinePitch: cache.paragraphIndexes.some(
- (index) => index > cellNode.startIndex && index < cellNode.endIndex
- ),
+ enableDocumentTableLineGrid: isTraditionalLineGrid,
+ inheritDocumentLinePitch: isTraditionalLineGrid,
};
}
+function resetCellDrawingAnchors(ctx: ILayoutContext, cellNode: DataStreamTreeNode, tableId: string): void {
+ const anchors = ctx.skeletonResourceReference.drawingAnchor?.get(tableId);
+ if (!anchors) {
+ return;
+ }
+ // A paginated cell replaces its earlier unbounded measurement. Do not retain
+ // provisional line references or their off-page drawing anchor positions.
+ for (const paragraph of cellNode.children[0].children) {
+ anchors.delete(paragraph.endIndex);
+ }
+}
+
export function createSkeletonCellPages(
ctx: ILayoutContext,
viewModel: DocumentViewModel,
@@ -557,12 +686,10 @@ export function createSkeletonCellPages(
const sectionNode = cellNode.children[0];
const body = ctx.dataModel?.getBody?.();
const { enableDocumentTableLineGrid, inheritDocumentLinePitch } = getCellLineGridOptions(
- ctx,
- cellNode,
sectionBreakConfig
);
- const { page: areaPage, sectionBreakConfig: cellSectionBreakConfig } = createNullCellPage(
+ const { page: areaPage, sectionBreakConfig: cellSectionBreakConfig, verticalCellWidth } = createNullCellPage(
ctx,
sectionBreakConfig,
tableConfig,
@@ -575,7 +702,11 @@ export function createSkeletonCellPages(
cellPageHeights
);
+ if (tableConfig.tableRows[row].tableCells[col].tcHideMark === BooleanNumber.TRUE) {
+ cellSectionBreakConfig.cellHiddenEndMarkIndex = sectionNode.children[sectionNode.children.length - 1]?.endIndex;
+ }
const segmentId = tableConfig.tableId;
+ resetCellDrawingAnchors(ctx, cellNode, segmentId);
const retainedPages: IDocumentSkeletonPage[] = [];
let currentPage = areaPage;
let pages: IDocumentSkeletonPage[] = [];
@@ -625,6 +756,7 @@ export function createSkeletonCellPages(
updateInlineDrawingCoordsAndBorder(ctx, pages);
expandCellPageHeightForInlineDrawings(pages);
expandCellPageHeightForFlowTables(pages);
+ finishVerticalCellLayout(pages, verticalCellWidth);
return pages;
}
@@ -637,6 +769,7 @@ export interface ICellSkeletonBuildState {
sectionBreakConfig: ISectionBreakConfig;
cellSectionBreakConfig: ISectionBreakConfig;
tableConfig: ITable;
+ verticalCellWidth?: number;
paragraphIndex: number;
layoutAnchor: Nullable<number>;
pages: IDocumentSkeletonPage[];
@@ -658,11 +791,9 @@ export function startSkeletonCellPagesBuild(
): ICellSkeletonBuildState {
const sectionNode = cellNode.children[0];
const { enableDocumentTableLineGrid, inheritDocumentLinePitch } = getCellLineGridOptions(
- ctx,
- cellNode,
sectionBreakConfig
);
- const { page, sectionBreakConfig: cellSectionBreakConfig } = createNullCellPage(
+ const { page, sectionBreakConfig: cellSectionBreakConfig, verticalCellWidth } = createNullCellPage(
ctx,
sectionBreakConfig,
tableConfig,
@@ -674,9 +805,14 @@ export function startSkeletonCellPagesBuild(
enableDocumentTableLineGrid,
cellPageHeights
);
+ if (tableConfig.tableRows[row].tableCells[col].tcHideMark === BooleanNumber.TRUE) {
+ cellSectionBreakConfig.cellHiddenEndMarkIndex = sectionNode.children[sectionNode.children.length - 1]?.endIndex;
+ }
page.type = DocumentSkeletonPageType.CELL;
page.segmentId = tableConfig.tableId;
+ resetCellDrawingAnchors(ctx, cellNode, tableConfig.tableId);
+
const layoutAnchor = ctx.layoutStartPointer[tableConfig.tableId];
ctx.layoutStartPointer[tableConfig.tableId] = null;
@@ -689,6 +825,7 @@ export function startSkeletonCellPagesBuild(
cellSectionBreakConfig,
tableConfig,
paragraphIndex: 0,
+ verticalCellWidth,
layoutAnchor,
pages: [page],
complete: false,
@@ -752,6 +889,7 @@ export function stepSkeletonCellPagesBuild(state: ICellSkeletonBuildState): bool
updateInlineDrawingCoordsAndBorder(state.ctx, state.pages);
expandCellPageHeightForInlineDrawings(state.pages);
expandCellPageHeightForFlowTables(state.pages);
+ finishVerticalCellLayout(state.pages, state.verticalCellWidth);
state.complete = true;
}
@@ -773,12 +911,8 @@ function applyTrailingCellParagraphSpaceBelow(
}
const spaceBelow = Math.max(0, lastLine.spaceBelowApply ?? 0);
- const linePitch = sectionBreakConfig.linePitch ?? 0;
- const usesLineGrid = sectionBreakConfig.gridType === GridType.LINES || sectionBreakConfig.gridType === GridType.LINES_AND_CHARS;
if (
spaceBelow === 0 ||
- !usesLineGrid ||
- linePitch <= 0 ||
!isTraditionalDocumentCompatibility(sectionBreakConfig.documentCompatibilityPolicy!)
) {
return;
@@ -795,28 +929,31 @@ function applyTrailingCellParagraphSpaceBelow(
return;
}
- const paragraphStyle = body?.paragraphs?.find((paragraph) => paragraph.startIndex === paragraphIndex)?.paragraphStyle;
- const lineSpacing = paragraphStyle?.lineSpacing;
- if (
- lineSpacing == null ||
- paragraphStyle?.spacingRule !== SpacingRule.AUTO ||
- paragraphStyle.snapToGrid === BooleanNumber.FALSE ||
- !reachesNextDocumentGridLine(lineSpacing, spaceBelow, linePitch)
- ) {
+ if (body?.paragraphs?.find((paragraph) => paragraph.startIndex === paragraphIndex)?.paragraphStyle?.afterAutoSpacing === BooleanNumber.TRUE) {
+ lastLine.spaceBelowApply = 0;
return;
}
+ // Word includes the last paragraph's after-spacing in the cell's content height,
+ // except automatic spacing at the cell boundary.
page.height += spaceBelow;
}
export function expandCellPageHeightForInlineDrawings(pages: IDocumentSkeletonPage[]) {
for (const page of pages) {
+ const lastSection = page.sections?.[page.sections.length - 1];
+ const lastColumn = lastSection?.columns[lastSection.columns.length - 1];
+ const lastLine = lastColumn?.lines[lastColumn.lines.length - 1];
+ const trailingDrawingIds = new Set(lastLine?.divides?.flatMap((divide) =>
+ divide.glyphGroup.map((glyph) => glyph.drawingId).filter((id): id is string => id != null)) ?? []);
page.skeDrawings?.forEach((drawing) => {
if (drawing.drawingOrigin?.layoutType !== PositionedObjectLayoutType.INLINE) {
return;
}
- const drawingBottom = (drawing.aTop ?? 0) + (drawing.height ?? 0);
+ const trailingSpace = trailingDrawingIds.has(drawing.drawingId) ? (lastLine?.spaceBelowApply ?? 0) : 0;
+ const drawingBottom = (drawing.aTop ?? 0) + (drawing.height ?? 0) +
+ (drawing.drawingOrigin.effectExtent?.bottom ?? 0) + trailingSpace;
if (drawingBottom > page.height) {
page.height = drawingBottom;
}
diff --git a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts
index d26a40a66f..9df3fe1f0d 100644
--- a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts
@@ -18,6 +18,31 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { FontCache, invalidateDocumentFontMetrics } from '../font-cache';
describe('font cache', () => {
+ it('isolates kerning metrics and resets the context for legacy measurements', () => {
+ const context = {
+ font: '',
+ fontKerning: 'auto',
+ measureText: () => ({
+ width: context.fontKerning === 'normal' ? 18 : 20,
+ fontBoundingBoxAscent: 10,
+ fontBoundingBoxDescent: 2,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 2,
+ }),
+ };
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return context;
+ }
+ });
+ expect(FontCache.getMeasureText('AV', '12pt Arial', 'normal').width).toBe(18);
+ expect(FontCache.getMeasureText('AV', '12pt Arial', 'none').width).toBe(20);
+ expect(FontCache.getMeasureText('AV', '12pt Arial').width).toBe(20);
+ expect(context.fontKerning).toBe('auto');
+ expect(FontCache.getMeasureText('AV', '12pt Arial', 'normal').width).toBe(18);
+ });
+
beforeEach(() => {
invalidateDocumentFontMetrics(() => true);
(FontCache as any)._globalFontMeasureCache = new Map();
@@ -126,7 +151,42 @@ describe('font cache', () => {
expect(measureRect).toHaveBeenCalledTimes(2);
});
- it('measures text with OffscreenCanvas when the DOM is unavailable', () => {
+ it('uses scalable print advances and line metrics without changing native ink or screen measurements', () => {
+ const measureText = vi.fn(function (this: CanvasRenderingContext2D) {
+ return {
+ width: this.font.startsWith('1024px') ? 1024 : 16,
+ fontBoundingBoxAscent: this.font.startsWith('1024px') ? 880 : 13,
+ fontBoundingBoxDescent: this.font.startsWith('1024px') ? 144 : 2,
+ actualBoundingBoxAscent: 11,
+ actualBoundingBoxDescent: 0,
+ };
+ });
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
+ font: '',
+ measureText,
+ } as unknown as CanvasRenderingContext2D);
+ const fontStyle = {
+ fontString: '11pt "MS Gothic"',
+ fontCache: '11pt "MS Gothic"',
+ fontSize: 11,
+ originFontSize: 11,
+ fontFamily: 'MS Gothic',
+ };
+ const screen = FontCache.getTextSize('☐', fontStyle);
+ const print = FontCache.getTextSize('☐', fontStyle, true);
+ expect(screen.width).toBe(16);
+ expect(print.width).toBeCloseTo(44 / 3);
+ expect(print).toMatchObject({ aba: screen.aba, abd: screen.abd });
+ expect(print.ba).toBeCloseTo(880 * (44 / 3) / 1024);
+ expect(print.bd).toBeCloseTo(144 * (44 / 3) / 1024);
+ expect(print.normalLineHeight).toBeCloseTo(44 / 3);
+ expect(screen).toMatchObject({ ba: 13, bd: 2, normalLineHeight: 15 });
+ expect(FontCache.getTextSize('☐', fontStyle).width).toBe(16);
+ expect(FontCache.getTextSize('☐', fontStyle, true)).toEqual(print);
+ expect(measureText).toHaveBeenCalledTimes(2);
+ });
+
+ it.each(['auto', 'normal', 'none'] as const)('measures text without a DOM or native kerning support in %s mode', (kerning) => {
const measureText = vi.fn(() => ({
width: 16,
fontBoundingBoxAscent: 9,
@@ -146,7 +206,7 @@ describe('font cache', () => {
}
});
- const result = FontCache.getMeasureText('W', '12px Arial');
+ const result = FontCache.getMeasureText('W', '12px Arial', kerning);
expect(result).toEqual({
width: 16,
diff --git a/packages/engine-render/src/components/docs/layout/shaping-engine/font-cache.ts b/packages/engine-render/src/components/docs/layout/shaping-engine/font-cache.ts
index d147b4b92e..56409fa805 100644
--- a/packages/engine-render/src/components/docs/layout/shaping-engine/font-cache.ts
+++ b/packages/engine-render/src/components/docs/layout/shaping-engine/font-cache.ts
@@ -268,18 +268,26 @@ export class FontCache {
static getTextSize(
content: string,
fontStyle: IDocumentSkeletonFontStyle,
- includeNormalFontLeading = false
+ includeNormalFontLeading = false,
+ useUnhintedMetrics = includeNormalFontLeading
): IDocumentSkeletonBoundingBox {
const { fontString, fontSize, fontFamily } = fontStyle;
let bBox = this._getBoundingBoxByFont(fontFamily, fontSize);
if (!bBox) {
- // if (content === DataStreamTreeTokenType.PARAGRAPH) {
- // content = '0';
- // }
- const measureText = this.getMeasureText(content, fontString);
+ const measureText = this.getMeasureText(content, fontString, fontStyle.fontKerning);
bBox = this._calculateBoundingBoxByMeasureText(measureText, fontStyle);
+ if (useUnhintedMetrics) {
+ // Native-size font boxes and bitmap strikes round to device pixels. Print layout
+ // needs scalable advances and line metrics; retain native-size ink bounds.
+ const outlineFont = fontString.replace(/\b\d+(?:\.\d+)?(?:pt|px)\b/, '1024px');
+ const outlineMetrics = this.getMeasureText(content, outlineFont, fontStyle.fontKerning);
+ bBox.width = outlineMetrics.width * (fontSize / 0.75) / 1024;
+ const metricScale = (fontStyle.originFontSize / 0.75) / 1024;
+ bBox.ba = outlineMetrics.fontBoundingBoxAscent * metricScale;
+ bBox.bd = outlineMetrics.fontBoundingBoxDescent * metricScale;
+ }
}
return {
@@ -294,7 +302,7 @@ export class FontCache {
* @param fontString
* @returns IMeasureTextCache
*/
- static getMeasureText(content: string, fontString: string): IMeasureTextCache {
+ static getMeasureText(content: string, fontString: string, kerning: CanvasFontKerning = 'auto'): IMeasureTextCache {
if (!this._context) {
this._context = this._createMeasureContext();
}
@@ -311,11 +319,15 @@ export class FontCache {
const ctx = this._context;
- const mtc = this.getFontMeasureCache(fontString, content);
+ const cacheKey = kerning === 'auto' ? fontString : `${fontString}\u0000${kerning}`;
+ const mtc = this.getFontMeasureCache(cacheKey, content);
if (mtc != null) {
return mtc;
}
ctx.font = fontString;
+ if ('fontKerning' in ctx) {
+ ctx.fontKerning = kerning;
+ }
const textMetrics = ctx.measureText(content);
@@ -359,7 +371,7 @@ export class FontCache {
}
}
- this.setFontMeasureCache(fontString, content, cache);
+ this.setFontMeasureCache(cacheKey, content, cache);
return cache;
}
diff --git a/packages/engine-render/src/components/docs/layout/style/__tests__/color.spec.ts b/packages/engine-render/src/components/docs/layout/style/__tests__/color.spec.ts
index 415dbf21e0..c604612910 100644
--- a/packages/engine-render/src/components/docs/layout/style/__tests__/color.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/style/__tests__/color.spec.ts
@@ -18,6 +18,12 @@ import { describe, expect, it } from 'vitest';
import { getColorStyleForCanvas } from '../color';
describe('getColorStyleForCanvas', () => {
+ it.each(['auto', '#auto', 'AUTO'])('uses the renderer default for Word automatic color %s', (rgb) => {
+ const color = Object.freeze({ rgb });
+ expect(getColorStyleForCanvas(color)).toBeUndefined();
+ expect(color.rgb).toBe(rgb);
+ });
+
it.each(['0000FF', 'aAbBcC', '000000'])('renders legacy imported RGB %s without making text transparent', (rgb) => {
const color = Object.freeze({ rgb, th: 0 });
expect(getColorStyleForCanvas(color)).toBe(`#${rgb.toLowerCase()}`);
diff --git a/packages/engine-render/src/components/docs/layout/style/__tests__/custom-range.spec.ts b/packages/engine-render/src/components/docs/layout/style/__tests__/custom-range.spec.ts
index 6a8516012e..de0954511c 100644
--- a/packages/engine-render/src/components/docs/layout/style/__tests__/custom-range.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/style/__tests__/custom-range.spec.ts
@@ -52,4 +52,12 @@ describe('custom range style', () => {
it('does not style unsupported custom range types', () => {
expect(getCustomRangeStyle({ rangeType: CustomRangeType.COMMENT } as never)).toBeNull();
});
+
+ it.each([true, false])('leaves authored hyperlink formatting unchanged when active is %s', (active) => {
+ expect(getCustomRangeStyle({
+ rangeType: CustomRangeType.HYPERLINK,
+ active,
+ properties: { textStyleMode: 'text' },
+ } as never)).toBeNull();
+ });
});
diff --git a/packages/engine-render/src/components/docs/layout/style/color.ts b/packages/engine-render/src/components/docs/layout/style/color.ts
index 6e83586461..bfc0922d58 100644
--- a/packages/engine-render/src/components/docs/layout/style/color.ts
+++ b/packages/engine-render/src/components/docs/layout/style/color.ts
@@ -21,6 +21,9 @@ const THEME_COLOR_TOKEN_PATTERN = /^[a-z][a-z0-9-]*\.\d+$/i;
export function getColorStyleForCanvas(color: Nullable<IColorStyle>): Nullable<string> {
const rgb = color?.rgb;
+ if (rgb && /^#?auto$/i.test(rgb.trim())) {
+ return undefined;
+ }
if (rgb && THEME_COLOR_TOKEN_PATTERN.test(rgb)) {
return rgb;
}
diff --git a/packages/engine-render/src/components/docs/layout/style/custom-range.ts b/packages/engine-render/src/components/docs/layout/style/custom-range.ts
index 8d11c93f92..60ca8a7e6a 100644
--- a/packages/engine-render/src/components/docs/layout/style/custom-range.ts
+++ b/packages/engine-render/src/components/docs/layout/style/custom-range.ts
@@ -20,6 +20,9 @@ import { BaselineOffset, BooleanNumber, CustomRangeType } from '@univerjs/core';
const CUSTOM_RANGE_COLOR_TOKEN = 'blue.600';
export function getCustomRangeStyle(customRange: ICustomRangeForInterceptor): Nullable<ITextStyle> {
+ if (customRange.rangeType === CustomRangeType.HYPERLINK && customRange.properties?.textStyleMode === 'text') {
+ return null;
+ }
if ((customRange.rangeType === CustomRangeType.FOOTNOTE || customRange.rangeType === CustomRangeType.ENDNOTE)) {
return { va: BaselineOffset.SUPERSCRIPT };
}
diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.ts
index fa1c19178d..f90ba93cb4 100644
--- a/packages/engine-render/src/components/docs/layout/tools.ts
+++ b/packages/engine-render/src/components/docs/layout/tools.ts
@@ -18,6 +18,7 @@ import type {
DocumentDataModel,
IBullet,
ICustomRangeForInterceptor,
+ IDocDrawingBase,
IDocumentStyle,
INumberUnit,
IObjectPositionH,
@@ -90,6 +91,7 @@ import {
hasDocsTableHorizontalViewport,
} from '../table-render-viewport';
import { updateInlineDrawingPosition } from './block/paragraph/layout-ruler';
+import { getGlyphGroupFontBoundingBox } from './model/glyph';
import { getCustomDecorationStyle } from './style/custom-decoration';
import { getCustomRangeStyle } from './style/custom-range';
@@ -395,6 +397,7 @@ function getParagraphLogicalStartAnchors(pages: IDocumentSkeletonPage[]): Map<ID
const paragraphs = new Map<number, {
firstLine: IDocumentSkeletonLine;
glyphCount: number;
+ paragraphEndGlyphCount?: number;
terminal?: string;
}>();
@@ -402,15 +405,26 @@ function getParagraphLogicalStartAnchors(pages: IDocumentSkeletonPage[]): Map<ID
for (const section of page.sections) {
for (const column of section.columns) {
for (const line of column.lines) {
- const glyphCount = line.divides.reduce((divideCount, divide) =>
- divideCount + divide.glyphGroup.reduce((count, glyph) =>
- count + (glyph.glyphType === GlyphType.LIST ? 0 : glyph.count), 0), 0);
+ const paragraph = paragraphs.get(line.paragraphIndex);
+ let glyphCount = paragraph?.glyphCount ?? 0;
+ let paragraphEndGlyphCount = paragraph?.paragraphEndGlyphCount;
+ for (const divide of line.divides) {
+ for (const glyph of divide.glyphGroup) {
+ if (glyph.glyphType === GlyphType.LIST) {
+ continue;
+ }
+ glyphCount += glyph.count;
+ if ((glyph.raw ?? glyph.streamType) === DataStreamTreeTokenType.PARAGRAPH) {
+ paragraphEndGlyphCount = glyphCount;
+ }
+ }
+ }
const lastDivide = line.divides[line.divides.length - 1];
const lastGlyph = lastDivide?.glyphGroup[lastDivide.glyphGroup.length - 1];
- const paragraph = paragraphs.get(line.paragraphIndex);
paragraphs.set(line.paragraphIndex, {
firstLine: paragraph?.firstLine ?? line,
- glyphCount: (paragraph?.glyphCount ?? 0) + glyphCount,
+ glyphCount,
+ paragraphEndGlyphCount,
terminal: lastGlyph?.raw ?? lastGlyph?.streamType,
});
}
@@ -420,7 +434,7 @@ function getParagraphLogicalStartAnchors(pages: IDocumentSkeletonPage[]): Map<ID
const anchors = new Map<IDocumentSkeletonLine, number>();
for (const [paragraphIndex, paragraph] of paragraphs) {
- const { firstLine, glyphCount, terminal } = paragraph;
+ const { firstLine, glyphCount, paragraphEndGlyphCount, terminal } = paragraph;
if (!firstLine.paragraphStart || paragraphIndex < 0) {
continue;
}
@@ -433,12 +447,36 @@ function getParagraphLogicalStartAnchors(pages: IDocumentSkeletonPage[]): Map<ID
continue;
}
- anchors.set(firstLine, paragraphIndex - glyphCount + 1);
+ // paragraphIndex points at the paragraph mark, not at a following section
+ // terminator that shaping may append to the same line (including in cells).
+ anchors.set(firstLine, paragraphIndex - (paragraphEndGlyphCount ?? glyphCount) + 1);
}
return anchors;
}
+export function getLineMetricGlyphs(
+ glyphGroup: IDocumentSkeletonGlyph[],
+ documentCompatibilityPolicy?: IDocumentCompatibilityPolicy,
+ previousGlyphs: IDocumentSkeletonGlyph[] = []
+): IDocumentSkeletonGlyph[] {
+ if (documentCompatibilityPolicy?.mode !== 'drawingml') {
+ return glyphGroup;
+ }
+ const hasText = (glyph: IDocumentSkeletonGlyph) =>
+ glyph.content && glyph.streamType !== DataStreamTreeTokenType.PARAGRAPH && glyph.glyphType !== GlyphType.LIST;
+ // An empty line needs the paragraph-end font; a populated DrawingML line does not.
+ return glyphGroup.some(hasText) || previousGlyphs.some(hasText)
+ ? glyphGroup.filter((glyph) => glyph.streamType !== DataStreamTreeTokenType.PARAGRAPH)
+ : glyphGroup;
+}
+
+export function getDrawingMLLineBaseline(lineHeight: number, ascent: number, descent: number): number {
+ const bottomAlignedBaseline = lineHeight - descent;
+ // Preserve the quarter-line descent without crossing either natural font edge near its line height.
+ return Math.min(Math.max(lineHeight * 0.75, Math.min(ascent, bottomAlignedBaseline)), Math.max(ascent, bottomAlignedBaseline));
+}
+
export function updateBlockIndex(
pages: IDocumentSkeletonPage[],
start: number = -1,
@@ -447,9 +485,9 @@ export function updateBlockIndex(
let prePageStartIndex = start;
const paragraphLogicalStartAnchors = getParagraphLogicalStartAnchors(pages);
// Real docs declare a classic/modern compatibility mode, so their measured layout column
- // width can be reused. Embedded editors keep the mode unspecified and must fall back to
+ // width can be reused. Embedded editors (including DrawingML text) must fall back to
// content width; otherwise a sheet cell editor may stretch to the far edge of the canvas.
- const shouldUseLayoutColumnWidth = documentCompatibilityPolicy?.mode !== 'unspecified';
+ const shouldUseLayoutColumnWidth = documentCompatibilityPolicy?.mode !== 'unspecified' && documentCompatibilityPolicy?.mode !== 'drawingml';
for (const page of pages) {
const { sections, skeTables, skeColumnGroups = new Map() } = page;
@@ -505,8 +543,6 @@ export function updateBlockIndex(
const lineEndIndex = lineStartIndex;
let preDivideStartIndex = lineStartIndex;
let actualWidth = 0;
- let maxLineAsc = 0;
- let macLineDsc = 0;
columnHeight = top + lineHeight;
const divideLength = divides.length;
let lineHasGlyph = false;
@@ -523,12 +559,6 @@ export function updateBlockIndex(
divEndIndex += increaseValue;
- const bBox = glyph.bBox;
- const { ba, bd } = bBox;
-
- maxLineAsc = Math.max(maxLineAsc, ba);
- macLineDsc = Math.max(macLineDsc, bd);
-
if (i === divideLength - 1) {
actualWidth += glyph.width;
}
@@ -566,8 +596,17 @@ export function updateBlockIndex(
line.st = lineHasGlyph ? lineStartIndex + 1 : lineStartIndex;
line.ed = preDivideStartIndex >= line.st ? preDivideStartIndex : line.st;
line.width = actualWidth;
- line.asc = maxLineAsc;
- line.dsc = macLineDsc;
+ const { boundingBoxAscent, boundingBoxDescent } = getGlyphGroupFontBoundingBox(
+ documentCompatibilityPolicy,
+ ...divides.map((divide) => divide.glyphGroup)
+ );
+ line.asc = boundingBoxAscent;
+ line.dsc = boundingBoxDescent;
+ if (line.drawingMLBaselineHeight != null) {
+ const lineBoxHeight = line.paddingTop + line.contentHeight + line.paddingBottom;
+ line.paddingTop = getDrawingMLLineBaseline(line.drawingMLBaselineHeight, boundingBoxAscent, boundingBoxDescent) - boundingBoxAscent;
+ line.paddingBottom = lineBoxHeight - line.contentHeight - line.paddingTop;
+ }
maxColumnWidth = Math.max(maxColumnWidth, actualWidth);
// Please do not use pre line's top and height to calculate the current's top,
// because of float objects will between lines.
@@ -575,6 +614,13 @@ export function updateBlockIndex(
}
column.st = columStartIndex + 1;
column.ed = preLineStartIndex >= column.st ? preLineStartIndex : column.st;
+ const lastLine = lines[lines.length - 1];
+ if (lastLine?.drawingMLNormalLineHeight != null) {
+ // Automatic spacing is a baseline interval. Its trailing leading does not enlarge the text body.
+ const terminalHeight = Math.max(lastLine.drawingMLNormalLineHeight, lastLine.paddingTop + lastLine.asc + lastLine.dsc);
+ const lineBoxHeight = lastLine.paddingTop + lastLine.contentHeight + lastLine.paddingBottom;
+ columnHeight -= Math.max(0, lineBoxHeight - terminalHeight);
+ }
column.height = columnHeight;
const measuredColumnWidth = shouldUseLayoutColumnWidth && Number.isFinite(column.width) && column.width > 0
@@ -651,7 +697,7 @@ function collapseRedundantColumnBreakOverflow(section: IDocumentSkeletonSection)
section.columns.splice(expectedColumnCount);
}
-function isParagraphEnd(line: IDocumentSkeletonLine) {
+export function isParagraphEnd(line: IDocumentSkeletonLine) {
const lastDivide = line.divides[line.divides.length - 1];
const lastGlyph = lastDivide?.glyphGroup[lastDivide.glyphGroup.length - 1];
@@ -696,7 +742,8 @@ export function updateInlineDrawingCoordsAndBorder(ctx: ILayoutContext, pages: I
affectInlineDrawings,
ctx.dataModel.getUnitId?.() ?? '',
drawingAnchor?.top,
- affectNonInlineDrawings
+ affectNonInlineDrawings,
+ paragraphConfig?.documentCompatibilityPolicy
);
}
@@ -748,6 +795,14 @@ export function updateParagraphBorders(
line.paragraphBorders = paragraphBorders;
}
+ // A floating object's zero-height anchor is not an extra bordered text line.
+ if (line.lineHeight === 0) {
+ if (target) {
+ line.borderTop = line.borderBottom = line.borderBetween = line.borderLeft = line.borderRight = undefined;
+ }
+ return;
+ }
+
renderLines.push({
line,
paragraphBorders: paragraphConfig ? paragraphBorders : line.paragraphBorders,
@@ -782,7 +837,7 @@ export function updateParagraphBorders(
hasSameParagraphBorderSet(paragraphBorders, next.paragraphBorders);
if (updateTop) {
- line.borderTop = line.paragraphStart && !hasMatchingPrevious
+ line.borderTop = (line.paragraphStart || (line.borderTopSpace ?? 0) > 0) && !hasMatchingPrevious
? paragraphBorders?.borderTop
: undefined;
}
@@ -794,7 +849,7 @@ export function updateParagraphBorders(
line.borderBetween = undefined;
line.borderBottom = undefined;
if (isParagraphEnd(line)) {
- if (hasMatchingNext && paragraphBorders?.borderBetween) {
+ if (hasMatchingNext) {
line.borderBetween = paragraphBorders.borderBetween;
} else if (paragraphBorders?.borderBottom) {
line.borderBottom = paragraphBorders.borderBottom;
@@ -896,7 +951,7 @@ export interface IDocumentSkeletonLineContext {
visualWidth?: number;
}
-export type DocumentSkeletonTableSource = 'page' | 'column' | 'header' | 'footer';
+export type DocumentSkeletonTableSource = 'page' | 'table-cell' | 'column' | 'header' | 'footer';
type HeaderFooterSkeletonMap = Map<string, Map<number, IDocumentSkeletonPage>>;
export interface IDocumentSkeletonTableCellGeometry {
@@ -1309,33 +1364,34 @@ function collectPageTables(options: ICollectPageTablesOptions): void {
const tableViewportRight = tableViewportLeft + (hasHorizontalViewport ? viewport.viewportWidth : table.width);
const tableScrollLeft = hasHorizontalViewport ? viewport.scrollLeft : 0;
const cells: IDocumentSkeletonTableCellGeometry[] = [];
+ const nestedCells: Array<{ cell: IDocumentSkeletonPage; pageLeft: number; pageTop: number }> = [];
- if (includeCells) {
- table.rows.forEach((row, rowIndex) => {
- row.cells.forEach((cell, columnIndex) => {
- if ((cell as IDocumentSkeletonPage & { isMergedCellCovered?: boolean }).isMergedCellCovered) {
- return;
- }
-
- const cellMarginLeft = cell.marginLeft ?? 0;
- const cellMarginRight = cell.marginRight ?? 0;
- const cellMarginTop = cell.marginTop ?? 0;
- const cellMarginBottom = cell.marginBottom ?? 0;
- const cellPageWidth = cell.pageWidth ?? 0;
- const cellPageHeight = cell.pageHeight ?? 0;
- const cellTop = tableTop + (row.top ?? 0) + cellMarginTop;
- const cellLeft = tableLeft + (cell.left ?? 0) - tableScrollLeft + cellMarginLeft;
- const cellContentRight = cellLeft + cellPageWidth - cellMarginLeft - cellMarginRight;
- const visualLeft = cellLeft + tableCellInsetX;
- const visualRight = cellContentRight - tableCellInsetX;
- const visualWidth = Math.max(0, visualRight - visualLeft);
- const clipLeft = tableViewportLeft;
- const clipRight = Math.min(cellContentRight, tableViewportRight);
+ table.rows.forEach((row, rowIndex) => {
+ row.cells.forEach((cell, columnIndex) => {
+ if ((cell as IDocumentSkeletonPage & { isMergedCellCovered?: boolean }).isMergedCellCovered) {
+ return;
+ }
- if (visualWidth <= 0 || Math.min(visualRight, clipRight) <= Math.max(visualLeft, clipLeft)) {
- return;
- }
+ const cellMarginLeft = cell.marginLeft ?? 0;
+ const cellMarginRight = cell.marginRight ?? 0;
+ const cellMarginTop = cell.marginTop ?? 0;
+ const cellMarginBottom = cell.marginBottom ?? 0;
+ const cellPageWidth = cell.pageWidth ?? 0;
+ const cellPageHeight = cell.pageHeight ?? 0;
+ const cellTop = tableTop + (row.top ?? 0) + cellMarginTop;
+ const cellLeft = tableLeft + (cell.left ?? 0) - tableScrollLeft + cellMarginLeft;
+ const cellContentRight = cellLeft + cellPageWidth - cellMarginLeft - cellMarginRight;
+ const visualLeft = cellLeft + tableCellInsetX;
+ const visualRight = cellContentRight - tableCellInsetX;
+ const visualWidth = Math.max(0, visualRight - visualLeft);
+ const clipLeft = tableViewportLeft;
+ const clipRight = Math.min(cellContentRight, tableViewportRight);
+
+ if (cell.skeTables?.size) {
+ nestedCells.push({ cell, pageLeft: cellLeft, pageTop: cellTop });
+ }
+ if (includeCells && visualWidth > 0 && Math.min(visualRight, clipRight) > Math.max(visualLeft, clipLeft)) {
cells.push({
cell,
cellRect: {
@@ -1354,9 +1410,9 @@ function collectPageTables(options: ICollectPageTablesOptions): void {
visualLeft,
visualWidth,
});
- });
+ }
});
- }
+ });
contexts.push({
cells,
@@ -1375,6 +1431,16 @@ function collectPageTables(options: ICollectPageTablesOptions): void {
top: tableTop,
},
});
+
+ nestedCells.forEach(({ cell, pageLeft: nestedPageLeft, pageTop: nestedPageTop }) => {
+ collectPageTables({
+ ...options,
+ page: cell,
+ pageLeft: nestedPageLeft,
+ pageTop: nestedPageTop,
+ source: 'table-cell',
+ });
+ });
});
}
@@ -1583,11 +1649,26 @@ export function getPositionVertical(
}
}
-export function getGlyphGroupWidth(divide: IDocumentSkeletonDivide) {
+export function getGlyphGroupWidth(divide: IDocumentSkeletonDivide, excludeTrailingSpaces = false) {
let width = 0;
+ const glyphs = divide.glyphGroup;
+ let end = glyphs.length;
+ if (excludeTrailingSpaces) {
+ while (end > 0) {
+ const glyph = glyphs[end - 1];
+ // Word excludes trailing ordinary/full-width spaces from alignment,
+ // including those followed by paragraph or custom-range markers.
+ // NBSP and tabs still occupy their authored advance.
+ if (glyph.width !== 0 && glyph.content !== ' ' && glyph.content !== '\u3000' &&
+ glyph.streamType !== DataStreamTreeTokenType.PARAGRAPH) {
+ break;
+ }
+ end--;
+ }
+ }
- for (const glyph of divide.glyphGroup) {
- width += glyph.width;
+ for (let i = 0; i < end; i++) {
+ width += glyphs[i].width;
}
return width;
@@ -1601,6 +1682,7 @@ interface IFontCreateConfig {
gridType: GridType;
snapToGrid: BooleanNumber;
pageWidth: number;
+ balanceSingleByteDoubleByteWidth?: BooleanNumber;
}
const fontCreateConfigCache = new ObjectMatrix<IFontCreateConfig>();
@@ -1632,6 +1714,7 @@ export function getFontConfigFromLastGlyph(
documentCompatibilityPolicy: sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy(),
fontStyle: fontStyle!,
textStyle: ts!,
+ balanceSingleByteDoubleByteWidth: sectionBreakConfig.balanceSingleByteDoubleByteWidth,
charSpace,
gridType,
snapToGrid,
@@ -1672,7 +1755,7 @@ export function getFontCreateConfig(
} = sectionBreakConfig;
const { paragraphStyle = {}, bullet } = paragraph;
const { isRenderStyle } = renderConfig;
- const { startIndex } = paragraphNode;
+ const startIndex = paragraphNode.contentStartIndex;
const originTextRun = viewModel.getTextRun(index + startIndex);
const textRun = isRenderStyle === BooleanNumber.FALSE
@@ -1684,7 +1767,7 @@ export function getFontCreateConfig(
const customRange = viewModel.getCustomRange(index + startIndex);
const showCustomRange = customRange && (customRange.show !== false);
const customRangeStyle = showCustomRange ? getCustomRangeStyle(customRange) : null;
- const hasAddonStyle = showCustomRange || showCustomDecoration || !!bullet || paragraphStyle?.namedStyleType || paragraphStyle?.textStyle != null;
+ const hasAddonStyle = showCustomRange || showCustomDecoration || !!bullet || paragraphStyle?.namedStyleType || paragraphStyle?.textStyle != null || paragraphStyle?.paragraphMarkTextStyle != null;
const { st, ed } = textRun;
let textStyle: ITextStyle = textRun.ts ?? {};
const cache = fontCreateConfigCache.getValue(st, ed);
@@ -1695,13 +1778,15 @@ export function getFontCreateConfig(
const { snapToGrid = BooleanNumber.TRUE, namedStyleType, textStyle: paragraphTextStyle } = paragraphStyle;
const bulletTextStyle = bullet ? getBulletParagraphTextStyle(bullet, viewModel) : null;
// Apply named style if it exists
- const namedStyle = namedStyleType ? NAMED_STYLE_MAP[namedStyleType] : null;
+ // Imported Word styles are already resolved; the outline role does not imply an SDK preset.
+ const namedStyle = namedStyleType && paragraph.styleId == null ? NAMED_STYLE_MAP[namedStyleType] : null;
textStyle = {
...documentTextStyle,
...namedStyle,
...paragraphTextStyle,
...textStyle,
+ ...(index + startIndex === paragraph.startIndex ? paragraphStyle.paragraphMarkTextStyle : undefined),
...customDecorationStyle,
...customRangeStyle,
...bulletTextStyle,
@@ -1713,7 +1798,7 @@ export function getFontCreateConfig(
...textStyle,
ff: `${textStyle.ff || DEFAULT_STYLES.ff}, ${eastAsiaFontFamily}`,
}
- : textStyle);
+ : textStyle, sectionBreakConfig.fontFamilyFallbacks);
const mixTextStyle: ITextStyle = {
...documentTextStyle,
@@ -1725,6 +1810,7 @@ export function getFontCreateConfig(
const result = {
fontStyle,
textStyle: mixTextStyle,
+ balanceSingleByteDoubleByteWidth: sectionBreakConfig.balanceSingleByteDoubleByteWidth,
charSpace,
gridType,
snapToGrid,
@@ -1777,7 +1863,7 @@ export function getCustomRangeGlyphMetrics(
paragraphNode: DataStreamTreeNode,
config: IFontCreateConfig
): { ascent?: number; descent?: number; width?: number } | undefined {
- const customRange = viewModel.getCustomRange(index + paragraphNode.startIndex);
+ const customRange = viewModel.getCustomRange(index + paragraphNode.contentStartIndex);
if (!customRange) {
return undefined;
}
@@ -1839,6 +1925,7 @@ export interface IFloatObject {
angle: number;
behindDoc?: BooleanNumber;
layoutType?: PositionedObjectLayoutType;
+ effectExtent?: IDocDrawingBase['effectExtent'];
type: FloatObjectType;
positionV: IObjectPositionV;
}
@@ -2034,6 +2121,7 @@ export function prepareSectionBreakConfig(ctx: ILayoutContext, nodeIndex: number
marginFooter: global_marginFooter = 0,
autoHyphenation = BooleanNumber.FALSE,
+ spaceWidthEastAsian,
doNotHyphenateCaps = BooleanNumber.FALSE,
consecutiveHyphenLimit = Number.POSITIVE_INFINITY,
hyphenationZone,
@@ -2100,6 +2188,8 @@ export function prepareSectionBreakConfig(ctx: ILayoutContext, nodeIndex: number
const sectionBreakConfig: ISectionBreakConfig = {
sectionId,
+ fontFamilyFallbacks: documentStyle.fontFamilyFallbacks,
+ balanceSingleByteDoubleByteWidth: documentStyle.balanceSingleByteDoubleByteWidth,
charSpace,
linePitch,
gridType,
@@ -2129,6 +2219,7 @@ export function prepareSectionBreakConfig(ctx: ILayoutContext, nodeIndex: number
renderConfig,
autoHyphenation,
+ spaceWidthEastAsian,
doNotHyphenateCaps,
consecutiveHyphenLimit,
hyphenationZone,
diff --git a/packages/engine-render/src/components/docs/page-borders.ts b/packages/engine-render/src/components/docs/page-borders.ts
new file mode 100644
index 0000000000..4c2bcf89cd
--- /dev/null
+++ b/packages/engine-render/src/components/docs/page-borders.ts
@@ -0,0 +1,147 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IPageBorder, IPageBorders } from '@univerjs/core';
+import type { IDocumentSkeletonPage } from '../../basics/i-document-skeleton-cached';
+import type { UniverRenderingContext } from '../../context';
+import { COLOR_BLACK_RGB } from '../../basics/const';
+import { getColorStyleForCanvas } from './layout/style/color';
+
+function getBorderBands(border: IPageBorder | undefined): number[] {
+ if (!border) {
+ return [];
+ }
+ const width = border.width ?? 1;
+ if (!Number.isFinite(width) || width <= 0) {
+ return [];
+ }
+ // Alternating ink and transparent space, in increasing document coordinates.
+ switch (border.style ?? 'single') {
+ case 'single':
+ case 'thick':
+ case 'dotted':
+ case 'dashed':
+ case 'dashSmallGap':
+ case 'dotDash':
+ case 'dotDotDash':
+ return [width];
+ case 'double':
+ return [width, width, width];
+ case 'triple':
+ return [width, width, width, width, width];
+ case 'thickThinSmallGap':
+ return [width / 4, width / 4, width];
+ case 'thinThickSmallGap':
+ return [width, width / 4, width / 4];
+ case 'thinThickThinSmallGap':
+ return [width / 4, width / 4, width, width / 4, width / 4];
+ default:
+ // Unsupported art/line styles retain their public model for export.
+ return [];
+ }
+}
+
+/** Draws section page borders without contributing to text/table layout. */
+export function drawPageBorders(
+ ctx: UniverRenderingContext,
+ page: IDocumentSkeletonPage,
+ borders: IPageBorders | undefined,
+ pageLeft: number,
+ pageTop: number,
+ firstPageInSection: boolean
+): void {
+ if (!borders || (borders.display === 'firstPage' && !firstPageInSection) ||
+ (borders.display === 'notFirstPage' && firstPageInSection)) {
+ return;
+ }
+ const sides = [borders.top, borders.right, borders.bottom, borders.left];
+ const bands = sides.map(getBorderBands);
+ const widths = bands.map((values) => values.reduce((sum, value) => sum + value, 0));
+ const padding = sides.map((side) => Number.isFinite(side?.padding) ? Math.max(0, side!.padding!) : 0);
+ const fromPage = borders.offsetFrom === 'page';
+ const left = pageLeft + (fromPage ? padding[3] : page.marginLeft - padding[3] - widths[3]);
+ const top = pageTop + (fromPage ? padding[0] : page.originMarginTop - padding[0] - widths[0]);
+ const right = pageLeft + page.pageWidth - (fromPage ? padding[1] : page.marginRight - padding[1] - widths[1]);
+ const bottom = pageTop + page.pageHeight - (fromPage ? padding[2] : page.originMarginBottom - padding[2] - widths[2]);
+ if (![left, top, right, bottom].every(Number.isFinite) || right <= left || bottom <= top) {
+ return;
+ }
+
+ for (let sideIndex = 0; sideIndex < sides.length; sideIndex++) {
+ const border = sides[sideIndex];
+ const thickness = widths[sideIndex];
+ if (!border || thickness === 0) {
+ continue;
+ }
+ const horizontal = sideIndex % 2 === 0;
+ const reverse = sideIndex === 1 || sideIndex === 2;
+ const values = reverse ? [...bands[sideIndex]].reverse() : bands[sideIndex];
+ const color = getColorStyleForCanvas(border.color) ?? COLOR_BLACK_RGB;
+ const corners = [[left, top], [right, top], [right, bottom], [left, bottom]];
+ const inner = [
+ [left + widths[3], top + widths[0]],
+ [right - widths[1], top + widths[0]],
+ [right - widths[1], bottom - widths[2]],
+ [left + widths[3], bottom - widths[2]],
+ ];
+ const next = (sideIndex + 1) % 4;
+ ctx.save();
+ ctx.beginPath();
+ ctx.moveTo(corners[sideIndex][0], corners[sideIndex][1]);
+ ctx.lineTo(corners[next][0], corners[next][1]);
+ ctx.lineTo(inner[next][0], inner[next][1]);
+ ctx.lineTo(inner[sideIndex][0], inner[sideIndex][1]);
+ ctx.closePath();
+ ctx.clip();
+ ctx.fillStyle = color;
+ ctx.strokeStyle = color;
+ let offset = 0;
+ for (let bandIndex = 0; bandIndex < values.length; bandIndex++) {
+ const width = values[bandIndex];
+ if (bandIndex % 2 === 0) {
+ let x = left;
+ let y = top;
+ if (horizontal) {
+ y = reverse ? bottom - offset - width : top + offset;
+ } else {
+ x = reverse ? right - offset - width : left + offset;
+ }
+ const dash = border.style;
+ if (dash === 'dotted' || dash === 'dashed' || dash === 'dashSmallGap' || dash === 'dotDash' || dash === 'dotDotDash') {
+ let pattern = [3 * width, width];
+ if (dash === 'dotted') {
+ pattern = [width, width];
+ } else if (dash === 'dotDash') {
+ pattern = [3 * width, width, width, width];
+ } else if (dash === 'dotDotDash') {
+ pattern = [3 * width, width, width, width, width, width];
+ }
+ ctx.setLineDash(pattern);
+ ctx.lineWidth = width;
+ ctx.lineCap = 'butt';
+ ctx.beginPath();
+ ctx.moveTo(x + (horizontal ? 0 : width / 2), y + (horizontal ? width / 2 : 0));
+ ctx.lineTo(horizontal ? right : x + width / 2, horizontal ? y + width / 2 : bottom);
+ ctx.stroke();
+ } else {
+ ctx.fillRect(x, y, horizontal ? right - left : width, horizontal ? width : bottom - top);
+ }
+ }
+ offset += width;
+ }
+ ctx.restore();
+ }
+}
diff --git a/packages/engine-render/src/components/docs/table-hit-test.ts b/packages/engine-render/src/components/docs/table-hit-test.ts
new file mode 100644
index 0000000000..7ffb33be1b
--- /dev/null
+++ b/packages/engine-render/src/components/docs/table-hit-test.ts
@@ -0,0 +1,40 @@
+/**
+ * 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 function getTopmostDocsTableHit<T>(
+ tables: readonly T[],
+ hitBody: (table: T) => boolean,
+ hitControls: (table: T) => boolean,
+ isNestedTable: (outer: T, inner: T) => boolean = () => false
+): T | undefined {
+ const bodyHit = tables.findLast(hitBody);
+ if (bodyHit) {
+ const bodyDepth = tables.filter((outer) => outer !== bodyHit && isNestedTable(outer, bodyHit)).length;
+ for (let index = tables.length - 1; index >= 0; index--) {
+ const table = tables[index];
+ if (
+ table !== bodyHit &&
+ hitControls(table) &&
+ tables.filter((outer) => outer !== table && isNestedTable(outer, table)).length > bodyDepth
+ ) {
+ return table;
+ }
+ }
+ return bodyHit;
+ }
+
+ return tables.findLast(hitControls);
+}
diff --git a/packages/engine-render/src/components/docs/table-render-viewport.ts b/packages/engine-render/src/components/docs/table-render-viewport.ts
index 3e0a64ed9f..6887f5e376 100644
--- a/packages/engine-render/src/components/docs/table-render-viewport.ts
+++ b/packages/engine-render/src/components/docs/table-render-viewport.ts
@@ -14,6 +14,34 @@
* limitations under the License.
*/
+import type { DocumentFlavor, ITable } from '@univerjs/core';
+import type { IDocumentSkeletonPage } from '../../basics/i-document-skeleton-cached';
+import { TableTextWrapType } from '@univerjs/core';
+import { DocumentSkeletonPageType } from '../../basics/i-document-skeleton-cached';
+import { getDocumentCompatibilityPolicy, shouldAllowImportedTableMarginOverflow } from './document-compatibility';
+
+/** Shared by the canvas renderer and interactive table viewport provider. */
+export function getDocsTableLayoutViewportWidth(
+ page: Pick<IDocumentSkeletonPage, 'pageWidth' | 'marginLeft' | 'marginRight'> & Partial<Pick<IDocumentSkeletonPage, 'type'>>,
+ tableLeft: number,
+ tableSource: unknown,
+ documentFlavor?: DocumentFlavor
+): number {
+ const { pageWidth, marginLeft = 0, marginRight = 0 } = page;
+ const policy = getDocumentCompatibilityPolicy(documentFlavor);
+ const allowMarginOverflow = shouldAllowImportedTableMarginOverflow(policy, tableSource);
+ const width = allowMarginOverflow
+ ? Math.max(0, pageWidth - Math.max(0, marginLeft + tableLeft))
+ : Math.max(0, pageWidth - marginLeft - marginRight - tableLeft);
+ const table = tableSource as Partial<ITable> | undefined;
+ if (allowMarginOverflow && page.type === DocumentSkeletonPageType.CELL && table?.textWrap === TableTextWrapType.WRAP) {
+ // A floating nested table owns its grid width, not its anchor cell's width.
+ const gridWidth = table.tableColumns?.reduce((sum, column) => sum + column.size.width.v, 0) ?? 0;
+ return Math.max(width, gridWidth);
+ }
+ return width;
+}
+
export interface IDocsTableRenderViewport {
contentWidth: number;
leadingInsetLeft?: number;
diff --git a/packages/engine-render/src/components/docs/view-model/data-stream-tree-node.ts b/packages/engine-render/src/components/docs/view-model/data-stream-tree-node.ts
index 08943b00fa..bb8a93d45e 100644
--- a/packages/engine-render/src/components/docs/view-model/data-stream-tree-node.ts
+++ b/packages/engine-render/src/components/docs/view-model/data-stream-tree-node.ts
@@ -43,6 +43,12 @@ export class DataStreamTreeNode {
return new DataStreamTreeNode(nodeType, content);
}
+ get contentStartIndex(): number {
+ // A table wrapper includes its child in the structural range, but not in its text content.
+ const firstChild = this.children[0];
+ return firstChild?.nodeType === DataStreamTreeNodeType.TABLE ? firstChild.endIndex + 1 : this.startIndex;
+ }
+
dispose() {
this.children.forEach((child) => {
child.dispose();
diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.ts
index 3402aff49d..d2ca783540 100644
--- a/packages/engine-render/src/index.ts
+++ b/packages/engine-render/src/index.ts
@@ -89,11 +89,13 @@ export {
export type { IDocumentSkeletonColumnPagePathInfo, IDocumentSkeletonLineContext, IDocumentSkeletonLineIteratorOptions, IDocumentSkeletonTableCellGeometry, IDocumentSkeletonTableContext, IDocumentSkeletonTableIteratorOptions } from './components/docs/layout/tools';
export { getLastColumn } from './components/docs/layout/tools';
export { Liquid } from './components/docs/liquid';
+export { getTopmostDocsTableHit } from './components/docs/table-hit-test';
export type {
DocsTableRenderViewportProvider,
IDocsTableRenderViewport,
} from './components/docs/table-render-viewport';
export {
+ getDocsTableLayoutViewportWidth,
getDocsTableRenderViewport,
getDocsTableViewportLeft,
setDocsTableRenderViewportProvider,
diff --git a/packages/engine-render/src/scene.input-manager.ts b/packages/engine-render/src/scene.input-manager.ts
index 9a52f66721..4bc57261b1 100644
--- a/packages/engine-render/src/scene.input-manager.ts
+++ b/packages/engine-render/src/scene.input-manager.ts
@@ -59,6 +59,7 @@ export class InputManager extends Disposable {
private _delayedTripeTimeout: NodeJS.Timeout | number = -1;
private _doubleClickOccurred = 0;
private _tripleClickState = false;
+ private _lastClickTime = Number.NEGATIVE_INFINITY;
private _currentObject: Nullable<BaseObject | Scene>;
constructor(scene: Scene) {
@@ -509,14 +510,24 @@ export class InputManager extends Disposable {
private _prePointerDoubleOrTripleClick(evt: IPointerEvent) {
const { clientX, clientY } = evt;
+ const clickTime = Number.isFinite(evt.timeStamp) ? evt.timeStamp : performance.now();
+ const elapsed = clickTime - this._lastClickTime;
+ this._lastClickTime = clickTime;
const movementThreshold = evt.deviceType === DeviceType.Touch
? InputManager.TouchDoubleClickMovementThreshold
: InputManager.DragMovementThreshold;
const isMoveThreshold = this._isPointerSwiping(clientX, clientY, this._startingPosition, movementThreshold);
+ // Timers may run late after layout or a browser focus round trip.
if (isMoveThreshold) {
this._resetClickSequence();
+ } else if (elapsed < 0 || elapsed > InputManager.DoubleClickDelay) {
+ this._resetDoubleClickParam();
+ }
+ if (isMoveThreshold || elapsed < 0 || elapsed > InputManager.TripleClickDelay) {
+ this._tripleClickState = false;
+ clearTimeout(this._delayedTripeTimeout);
}
clearTimeout(this._delayedTimeout);
diff --git a/packages/engine-render/src/scene.transformer.ts b/packages/engine-render/src/scene.transformer.ts
index 11b469a242..814e92d7c9 100644
--- a/packages/engine-render/src/scene.transformer.ts
+++ b/packages/engine-render/src/scene.transformer.ts
@@ -605,6 +605,9 @@ export class Transformer extends Disposable implements ITransformerConfig {
this._addCancelObserver(scene);
+ // Selection can mount DOM chrome under the pointer before pointerup.
+ // Keep the complete gesture on the canvas, including a click with no move.
+ scene.getEngine()?.setCapture();
scene.disableObjectsEvent();
const scrollTimer = ScrollTimer.create(scene);
@@ -1185,6 +1188,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
if (topScene == null) {
return;
}
+ topScene.getEngine()?.setCapture();
topScene.disableObjectsEvent();
const scrollTimer = ScrollTimer.create(topScene);
scrollTimer.startScroll(evtOffsetX, evtOffsetY);
@@ -1305,6 +1309,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
return;
}
+ topScene.getEngine()?.setCapture();
topScene.disableObjectsEvent();
const viewportActualXY = topScene.getScrollXYInfoByViewport(Vector2.create(evtOffsetX, evtOffsetY));
diff --git a/packages/engine-render/src/worker-layout.ts b/packages/engine-render/src/worker-layout.ts
index 77bebfe08d..557aba8bd4 100644
--- a/packages/engine-render/src/worker-layout.ts
+++ b/packages/engine-render/src/worker-layout.ts
@@ -28,6 +28,8 @@ import { DocumentSkeleton } from './components/docs/layout/doc-skeleton';
import { hydrateDocumentSkeletonPage, serializeDocumentSkeletonContinuousBlock, serializeDocumentSkeletonPage } from './components/docs/layout/document-layout-page-patch';
import { DocumentViewModel } from './components/docs/view-model/document-view-model';
+const MAX_PAGES_PER_PUBLICATION = 4;
+
export interface IDocumentLayoutSessionStartOptions {
reason?: DocumentLayoutReason;
anchor?: number;
@@ -43,6 +45,13 @@ export interface IDocumentLayoutStepResult {
publication: IDocumentLayoutGeometryPublication | null;
}
+export interface IDocumentLayoutPageResolution {
+ pageIndex: number;
+ pageNumber: number;
+ startOffset: number;
+ endOffset: number;
+}
+
/**
* Worker-safe owner of the document view model and incremental layout state.
* Scheduling, transport, presentation and model revision ordering belong to callers.
@@ -124,6 +133,34 @@ export class DocumentLayoutSession extends Disposable {
};
}
+ resolvePageByOffset(offset: number): IDocumentLayoutPageResolution | null {
+ const pages = this._skeleton.getSkeletonData()?.pages;
+ if (pages == null || offset < 0) {
+ return null;
+ }
+ let low = 0;
+ let high = pages.length - 1;
+ while (low <= high) {
+ const pageIndex = Math.floor((low + high) / 2);
+ const page = pages[pageIndex];
+ if (offset < page.st) {
+ high = pageIndex - 1;
+ } else if (offset > page.ed) {
+ low = pageIndex + 1;
+ } else if (!page.isLayoutPlaceholder) {
+ return {
+ pageIndex,
+ pageNumber: page.pageNumber,
+ startOffset: page.st,
+ endOffset: page.ed,
+ };
+ } else {
+ return null;
+ }
+ }
+ return null;
+ }
+
cancel(generation?: number): void {
if (generation == null || this._pendingPaginatedCompletion?.generation === generation) {
this._pendingPaginatedCompletion = null;
@@ -156,11 +193,28 @@ export class DocumentLayoutSession extends Disposable {
super.dispose();
}
- private _collectPublications(progress: IDocumentLayoutProgress): IDocumentLayoutStepResult {
+ private _collectPublications(initialProgress: IDocumentLayoutProgress): IDocumentLayoutStepResult {
+ let progress = initialProgress;
if (!progress.didPublish) {
return { progress, publication: null };
}
+ // The transport already accepts multiple pages. Drain only computed,
+ // stable pages so a long document does not require one visual frame per
+ // page. Keep the priority-anchor publication separate and bound hydration.
+ while (progress.mode === 'paginated' && !progress.complete && !progress.didPublishAnchor &&
+ progress.publishedPageCount < Math.min(this._lastPublishedPageCount + MAX_PAGES_PER_PUBLICATION, progress.pageCount - 1)) {
+ const next = this._skeleton.publishIncrementalLayoutBacklog(progress.generation);
+ if (!next.didPublish || next.cancelled) {
+ break;
+ }
+ const previousPageCount = progress.publishedPageCount;
+ progress = next;
+ if (progress.publishedPageCount <= previousPageCount) {
+ break;
+ }
+ }
+
if (
progress.complete &&
progress.mode === 'paginated' &&
@@ -180,7 +234,7 @@ export class DocumentLayoutSession extends Disposable {
}
const publishedPageCount = Math.min(
completion.publishedPageCount,
- this._lastPublishedPageCount + 1
+ this._lastPublishedPageCount + (completion.didPublishAnchor && !this._didPublishEditAnchor ? 1 : MAX_PAGES_PER_PUBLICATION)
);
const complete = publishedPageCount === completion.publishedPageCount;
const progress: IDocumentLayoutProgress = {
diff --git a/packages/ui/src/views/components/ribbon/ToolbarItem.tsx b/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
index a9d077c060..5098461117 100644
--- a/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
+++ b/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
@@ -305,6 +305,7 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IToolbarItemProps>((pr
<div
data-u-command={id}
data-disabled={disabled}
+ aria-disabled={disabled}
className={clsx(toolbarButtonSelectorRootVariants({ disabled }), {
'univer-box-border univer-h-full univer-min-w-14 univer-flex-col !univer-pr-0': grid && large,
'univer-box-border univer-h-full': grid && !large,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a9727f94df..6a97b5d01f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1056,6 +1056,83 @@ importers:
specifier: ^5.0.0
+ packages/docs-toc:
+ dependencies:
+ '@univerjs/core':
+ specifier: workspace:*
+ version: link:../core
+ '@univerjs/docs':
+ specifier: workspace:*
+ version: link:../docs
+ '@univerjs/engine-render':
+ specifier: workspace:*
+ version: link:../engine-render
+ devDependencies:
+ '@univerjs-infra/shared':
+ specifier: workspace:*
+ version: link:../../common/shared
+ rxjs:
+ specifier: ^7.8.2
+ version: 7.8.2
+ typescript:
+ specifier: ^6.0.3
+ version: 6.0.3
+ vitest:
+ specifier: ^5.0.0
+
+ packages/docs-toc-ui:
+ dependencies:
+ '@univerjs/core':
+ specifier: workspace:*
+ version: link:../core
+ '@univerjs/design':
+ specifier: workspace:*
+ version: link:../design
+ '@univerjs/docs':
+ specifier: workspace:*
+ version: link:../docs
+ '@univerjs/docs-toc':
+ specifier: workspace:*
+ version: link:../docs-toc
+ '@univerjs/docs-ui':
+ specifier: workspace:*
+ version: link:../docs-ui
+ '@univerjs/engine-render':
+ specifier: workspace:*
+ version: link:../engine-render
+ '@univerjs/protocol':
+ specifier: workspace:*
+ version: link:../protocol
+ '@univerjs/ui':
+ specifier: workspace:*
+ version: link:../ui
+ devDependencies:
+ '@univerjs-infra/shared':
+ specifier: workspace:*
+ version: link:../../common/shared
+ postcss:
+ specifier: ^8.5.26
+ version: 8.5.26
+ react:
+ specifier: 19.3.0
+ version: 19.3.0
+ react-dom:
+ specifier: 19.3.0
+ version: 19.3.0([email protected])
+ rxjs:
+ specifier: ^7.8.2
+ version: 7.8.2
+ tailwindcss:
+ specifier: 3.4.18
+ version: 3.4.18
+ typescript:
+ specifier: ^6.0.3
+ version: 6.0.3
+ vitest:
+ specifier: ^5.0.0
+
packages/docs-ui:
dependencies:
'@univerjs/core':
@@ -1067,6 +1144,9 @@ importers:
'@univerjs/docs':
specifier: workspace:*
version: link:../docs
+ '@univerjs/drawing':
+ specifier: workspace:*
+ version: link:../drawing
'@univerjs/engine-render':
specifier: workspace:*
version: link:../engine-render
@@ -14374,6 +14454,15 @@ snapshots:
optionalDependencies:
+ dependencies:
+ '@jridgewell/trace-mapping': 0.3.31
+ '@vitest/spy': 5.0.0
+ estree-walker: 3.0.3
+ magic-string: 1.2.3
+ optionalDependencies:
+
dependencies:
'@jridgewell/trace-mapping': 0.3.31
@@ -19269,6 +19358,23 @@ snapshots:
tsx: 4.23.13
yaml: 2.9.0
+ dependencies:
+ lightningcss: 1.33.0
+ picomatch: 4.0.7
+ postcss: 8.5.28
+ rolldown: 1.2.8
+ tinyglobby: 0.2.17
+ optionalDependencies:
+ '@types/node': 26.2.0
+ esbuild: 0.28.1
+ fsevents: 2.3.3
+ jiti: 2.7.0
+ sass: 1.87.0
+ terser: 5.47.1
+ tsx: 4.23.13
+ yaml: 2.9.0
+
dependencies:
lightningcss: 1.33.0