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): add incremental layout worker (#7433)

Univer8f5e911f22c7
diff --git a/examples/src/docs/mount.ts b/examples/src/docs/mount.ts
index 0a53ff180a..c048bfb473 100644
--- a/examples/src/docs/mount.ts
+++ b/examples/src/docs/mount.ts
@@ -1,5 +1,6 @@
import type { MountExample } from '../mount-example';
import type { IWorkbenchMountOptions } from '../workbench-settings';
+import { UniverDocsLayoutWorkerPlugin } from '@univerjs/docs';
import { SetDocZoomRatioOperation } from '@univerjs/docs-ui';
import { UniverDocsCorePreset } from '@univerjs/preset-docs-core';
import { UniverDocsDrawingPreset } from '@univerjs/preset-docs-drawing';
@@ -55,6 +56,9 @@ export const mount: MountExample = async (host, options) => {
UniverDocsThreadCommentPreset(),
],
});
+ univer.registerPlugin(UniverDocsLayoutWorkerPlugin, {
+ workerFactory: () => new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' }),
+ });
try {
applyWorkbenchUIChrome(univerAPI, options.uiChrome);
diff --git a/examples/src/docs/worker.ts b/examples/src/docs/worker.ts
new file mode 100644
index 0000000000..cc61f282fb
--- /dev/null
+++ b/examples/src/docs/worker.ts
@@ -0,0 +1,3 @@
+import { startDocsLayoutWorker } from '@univerjs/docs';
+
+startDocsLayoutWorker();
diff --git a/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.ts b/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.ts
index 4d9ca76547..d458559beb 100644
--- a/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.ts
+++ b/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.ts
@@ -105,6 +105,26 @@ describe('DocumentDataModel + RichTextBuilder integration', () => {
model.dispose();
});
+ it('should normalize missing and duplicate legacy section ids at the model boundary', () => {
+ const model = new DocumentDataModel({
+ id: 'legacy-section-ids',
+ body: {
+ dataStream: 'A\nB\n',
+ sectionBreaks: [
+ { startIndex: 1, sectionId: '' },
+ { startIndex: 3, sectionId: '' },
+ ],
+ },
+ });
+ const sectionIds = model.getBody()?.sectionBreaks?.map((sectionBreak) => sectionBreak.sectionId) ?? [];
+
+ expect(sectionIds).toHaveLength(2);
+ expect(sectionIds.every(Boolean)).toBe(true);
+ expect(new Set(sectionIds).size).toBe(2);
+
+ model.dispose();
+ });
+
it('should keep internal editor document snapshots shallow', () => {
const model = new DocumentDataModel({
id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
@@ -314,4 +334,26 @@ describe('DocumentDataModel + RichTextBuilder integration', () => {
expect(model.sliceBody(0, 5)?.dataStream).toContain('Reset');
model.dispose();
});
+
+ it('normalizes legacy section metadata that follows page breaks when loading a document', () => {
+ const model = new DocumentDataModel({
+ id: 'legacy-page-breaks',
+ body: {
+ dataStream: 'Before\r\n\fAfter\r\n\fTail\r\n\n',
+ paragraphs: [
+ { startIndex: 6, paragraphId: 'before' },
+ { startIndex: 14, paragraphId: 'after' },
+ { startIndex: 21, paragraphId: 'tail' },
+ ],
+ sectionBreaks: [
+ { startIndex: 9, sectionId: 'legacy-1' },
+ { startIndex: 17, sectionId: 'legacy-2' },
+ { startIndex: 23, sectionId: 'final' },
+ ],
+ },
+ });
+
+ expect(model.getBody()?.sectionBreaks).toEqual([{ startIndex: 23, sectionId: 'final' }]);
+ model.dispose();
+ });
});
diff --git a/packages/core/src/docs/data-model/document-data-model.ts b/packages/core/src/docs/data-model/document-data-model.ts
index 1d103b2599..6efa88dc7e 100644
--- a/packages/core/src/docs/data-model/document-data-model.ts
+++ b/packages/core/src/docs/data-model/document-data-model.ts
@@ -33,6 +33,7 @@ import { mergeWith } from '../../common/lodash';
import { UnitModel, UniverInstanceType } from '../../common/unit';
import { generateRandomId } from '../../shared/random-id';
import { Tools } from '../../shared/tools';
+import { createSectionId } from '../section-break-id';
import { calculateDocumentStatistics } from './document-statistics';
import { getEmptySnapshot } from './empty-snapshot';
import { JSONX } from './json-x/json-x';
@@ -60,6 +61,29 @@ export interface IDocumentStatisticsOptions {
signal?: AbortSignal;
}
+function normalizeLegacyPageBreakSectionMetadata(body: IDocumentBody | undefined): IDocumentBody | undefined {
+ if (body?.dataStream == null || body.sectionBreaks == null) {
+ return body;
+ }
+
+ const compatibleSectionBreaks = body.sectionBreaks.filter(({ startIndex }) =>
+ body.dataStream[startIndex] === '\n' || startIndex <= 0 || body.dataStream[startIndex - 1] !== '\f'
+ );
+ const existingSectionIds = new Set<string>();
+ let didChange = compatibleSectionBreaks.length !== body.sectionBreaks.length;
+ const sectionBreaks = compatibleSectionBreaks.map((sectionBreak) => {
+ if (sectionBreak.sectionId && !existingSectionIds.has(sectionBreak.sectionId)) {
+ existingSectionIds.add(sectionBreak.sectionId);
+ return sectionBreak;
+ }
+
+ didChange = true;
+ return { ...sectionBreak, sectionId: createSectionId(existingSectionIds) };
+ });
+
+ return didChange ? { ...body, sectionBreaks } : body;
+}
+
function createDocumentSnapshot(snapshot: Partial<IDocumentData>): IDocumentData {
if (snapshot.id != null && isInternalEditorID(snapshot.id)) {
return { ...DEFAULT_DOC, ...snapshot } as IDocumentData;
@@ -87,6 +111,8 @@ function createDocumentSnapshot(snapshot: Partial<IDocumentData>): IDocumentData
delete mergedSnapshot.documentStyle.defaultParagraphStyle;
}
+ mergedSnapshot.body = normalizeLegacyPageBreakSectionMetadata(mergedSnapshot.body);
+
return mergedSnapshot;
}
@@ -108,6 +134,7 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
override name$ = this._name$.asObservable();
protected snapshot: IDocumentData;
+ private _mutationRevision = 0;
constructor(snapshot: Partial<IDocumentData>) {
super();
@@ -130,6 +157,7 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
setName(name: string) {
this.snapshot.title = name;
+ this._markMutation();
this._name$.next(name);
}
@@ -152,6 +180,7 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
resetDrawing(drawings: IDrawings, drawingsOrder: string[]) {
this.snapshot.drawings = drawings;
this.snapshot.drawingsOrder = drawingsOrder;
+ this._markMutation();
}
getBody() {
@@ -187,6 +216,7 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
...config,
};
}
+ this._markMutation();
}
getDocumentStyle() {
@@ -202,6 +232,7 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
...config,
};
}
+ this._markMutation();
}
updateDocumentDataMargin(data: IPaddingData) {
@@ -223,6 +254,7 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
if (r != null) {
documentStyle.marginRight = r;
}
+ this._markMutation();
}
updateDocumentDataPageSize(width?: number, height?: number) {
@@ -233,7 +265,7 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
width: width ?? Number.POSITIVE_INFINITY,
height: height ?? Number.POSITIVE_INFINITY,
};
-
+ this._markMutation();
return;
}
@@ -244,6 +276,7 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
if (height !== undefined) {
documentStyle.pageSize.height = height;
}
+ this._markMutation();
}
updateDrawing(id: string, config: IDrawingUpdateConfig) {
@@ -262,6 +295,7 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
objectTransform.positionH.posOffset = left;
objectTransform.positionV.posOffset = top;
+ this._markMutation();
}
setZoomRatio(zoomRatio: number = 1) {
@@ -272,10 +306,12 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
} else {
this.snapshot.settings.zoomRatio = zoomRatio;
}
+ this._markMutation();
}
setDisabled(disabled: boolean) {
this.snapshot.disabled = disabled;
+ this._markMutation();
}
getDisabled() {
@@ -285,6 +321,14 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
getTitle() {
return this.snapshot.title;
}
+
+ getMutationRevision(): number {
+ return this._mutationRevision;
+ }
+
+ protected _markMutation(): void {
+ this._mutationRevision++;
+ }
}
export class DocumentDataModel extends DocumentDataModelSimple {
@@ -347,6 +391,7 @@ export class DocumentDataModel extends DocumentDataModelSimple {
this.snapshot = createDocumentSnapshot(snapshot);
this._initializeHeaderFooterModel();
+ this._markMutation();
this.change$.next(this.change$.value + 1);
}
@@ -376,6 +421,7 @@ export class DocumentDataModel extends DocumentDataModelSimple {
}
this.snapshot = JSONX.apply(this.snapshot, actions) as unknown as IDocumentData;
+ this._markMutation();
// FIXME: @JOCS, ANY better solution to find action that create or delete header/footer?
if (actions?.some((a) => Array.isArray(a) && (a?.[0] === 'headers' || a?.[0] === 'footers'))) {
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.ts
index 80a6019935..2ac2f5e54e 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.ts
@@ -26,6 +26,21 @@ import { TextX } from '../text-x';
import { getBodySlice, getBodySliceForTextXAction, getParagraphsSlice, SliceBodyType } from '../utils';
describe('document block ranges', () => {
+ it('keeps a collapsed deletion as a no-op during structural normalization', () => {
+ const body: IDocumentBody = {
+ dataStream: 'A\r\n',
+ paragraphs: [{ paragraphId: 'paragraph-1', startIndex: 1 }],
+ sectionBreaks: [{ sectionId: 'section-1', startIndex: 2 }],
+ };
+
+ const actions = BuildTextUtils.selection.delete([
+ { startOffset: 1, endOffset: 1, collapsed: true },
+ ], body);
+ TextX.apply(body, actions);
+
+ expect(body.dataStream).toBe('A\r\n');
+ });
+
it('moves following block ranges when text is inserted before them', () => {
const body: IDocumentBody = {
dataStream: 'A\rB\r\n',
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 98af229cdd..5e2c9fe38a 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
@@ -275,6 +275,22 @@ describe('validateDocBodyStructure', () => {
}).map((issue) => issue.code)).toContain('custom-block-token-mismatch');
});
+ it('accepts DOCX raw custom-block metadata as the owner of its sentinel', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `${T.CUSTOM_BLOCK}${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 1, paragraphId: 'after-raw-block' }],
+ sectionBreaks: [{ sectionId: 'section_raw_block', startIndex: 2 }],
+ docxRawCustomBlocks: [{
+ startIndex: 0,
+ blockId: 'raw-0',
+ docxRawXml: '<w:r><w:footnoteReference w:id="1"/></w:r>',
+ }],
+ };
+
+ expect(validateDocBodyStructure(body)).toEqual([]);
+ });
+
it('reports unbalanced structural tokens', () => {
const T = DataStreamTreeTokenType;
const body: IDocumentBody = {
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/docx-raw-metadata.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/docx-raw-metadata.spec.ts
new file mode 100644
index 0000000000..6567da6d34
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/__tests__/docx-raw-metadata.spec.ts
@@ -0,0 +1,87 @@
+/**
+ * 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';
+import type { TextXAction } from '../action-types';
+import { describe, expect, it } from 'vitest';
+import { DataStreamTreeTokenType } from '../../types';
+import { TextXActionType } from '../action-types';
+import { validateDocBodyStructure } from '../structure-validator';
+import { TextX } from '../text-x';
+
+describe('DOCX raw metadata', () => {
+ it('moves raw custom-block offsets through insertion and undo', () => {
+ const T = DataStreamTreeTokenType;
+ const body: IDocumentBody = {
+ dataStream: `A${T.PARAGRAPH}${T.CUSTOM_BLOCK}${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 1, paragraphId: 'before-raw-block' },
+ { startIndex: 3, paragraphId: 'after-raw-block' },
+ ],
+ sectionBreaks: [{ sectionId: 'section_docx_raw', startIndex: 4 }],
+ docxRawCustomBlocks: [{
+ startIndex: 2,
+ blockId: 'raw-2',
+ docxRawXml: '<w:r><w:footnoteReference w:id="1"/></w:r>',
+ }],
+ docxRawBlocks: [{ startIndex: 2, xml: '<w:sdt/>' }],
+ docxExportExcludedRanges: [{ start: 2, end: 4 }],
+ };
+ const original = structuredClone(body);
+ const actions: TextXAction[] = [
+ { t: TextXActionType.RETAIN, len: 1 },
+ { t: TextXActionType.INSERT, len: 1, body: { dataStream: 'B' } },
+ ];
+
+ TextX.makeInvertible(actions, body);
+ TextX.apply(body, actions);
+
+ expect(body.docxRawCustomBlocks?.[0].startIndex).toBe(3);
+ expect(body.docxRawBlocks?.[0].startIndex).toBe(3);
+ expect(body.docxExportExcludedRanges).toEqual([{ start: 3, end: 5 }]);
+ expect(validateDocBodyStructure(body)).toEqual([]);
+
+ TextX.apply(body, TextX.invert(actions));
+ expect(body.dataStream).toBe(original.dataStream);
+ expect(body.paragraphs).toEqual(original.paragraphs);
+ expect(body.sectionBreaks).toEqual(original.sectionBreaks);
+ expect(body.docxRawCustomBlocks).toEqual(original.docxRawCustomBlocks);
+ expect(body.docxRawBlocks).toEqual(original.docxRawBlocks);
+ expect(body.docxExportExcludedRanges).toEqual(original.docxExportExcludedRanges);
+ expect(validateDocBodyStructure(body)).toEqual([]);
+ });
+
+ it('restores raw metadata after deleting and undoing its range', () => {
+ const body: IDocumentBody = {
+ dataStream: 'ABCDE',
+ docxRawBlocks: [{ startIndex: 2, xml: '<w:sdt/>' }],
+ docxExportExcludedRanges: [{ start: 1, end: 4 }],
+ };
+ const actions: TextXAction[] = [
+ { t: TextXActionType.RETAIN, len: 1 },
+ { t: TextXActionType.DELETE, len: 3 },
+ ];
+
+ TextX.makeInvertible(actions, body);
+ TextX.apply(body, actions);
+ expect(body.docxRawBlocks).toEqual([]);
+ expect(body.docxExportExcludedRanges).toEqual([]);
+
+ TextX.apply(body, TextX.invert(actions));
+ expect(body.docxRawBlocks).toEqual([{ startIndex: 2, xml: '<w:sdt/>' }]);
+ expect(body.docxExportExcludedRanges).toEqual([{ start: 1, end: 4 }]);
+ });
+});
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 9fc80f1a3d..5b65f4fed9 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
@@ -16,13 +16,40 @@
import type { IDocumentBody } from '../../../../types/interfaces/i-document-data';
import type { IRetainAction } from '../action-types';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
+import { Tools } from '../../../../shared/tools';
import { BooleanNumber } from '../../../../types/enum/text-style';
import { PresetListType } from '../../preset-list-type';
import { TextXActionType } from '../action-types';
-import { composeBody, getBodySlice, isUselessRetainAction } from '../utils';
+import { composeBody, getBodySlice, getTextRunSlice, isUselessRetainAction } from '../utils';
describe('test text-x utils', () => {
+ it('only clones text runs intersecting the requested slice', () => {
+ const body: IDocumentBody = {
+ dataStream: 'a'.repeat(10_000),
+ textRuns: Array.from({ length: 1_000 }, (_, index) => ({
+ st: index * 10,
+ ed: index * 10 + 10,
+ ts: {
+ bl: index % 2 === 0 ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ },
+ })),
+ };
+ const deepClone = vi.spyOn(Tools, 'deepClone');
+
+ const slice = getTextRunSlice(body, 5_000, 5_010);
+
+ expect(slice).toEqual([{
+ st: 0,
+ ed: 10,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ },
+ }]);
+ expect(deepClone.mock.calls.length).toBeLessThan(50);
+ deepClone.mockRestore();
+ });
+
it('test getBodySlice fn', () => {
const body: IDocumentBody = {
dataStream: 'hello\nworld',
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 7bda20cd55..8d7afc544d 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
@@ -23,6 +23,8 @@ import type {
ICustomTable,
IDocumentBlockRange,
IDocumentBody,
+ IDocxExportExcludedRange,
+ IDocxRawBlock,
IParagraph,
ISectionBreak,
ITextRun,
@@ -447,13 +449,19 @@ export function normalizeInsertedSectionIdsForDocument(
}
}
-export function insertCustomBlocks(
+type CustomBlockField = 'customBlocks' | 'docxRawCustomBlocks';
+
+function insertCustomBlockMetadata(
body: IDocumentBody,
insertBody: IDocumentBody,
textLength: number,
- currentIndex: number
+ currentIndex: number,
+ field: CustomBlockField
) {
- const { customBlocks = [] } = body;
+ if (body[field] == null && insertBody[field] == null) {
+ return;
+ }
+ const customBlocks = body[field] ?? [];
for (let i = 0, len = customBlocks.length; i < len; i++) {
const customBlock = customBlocks[i];
@@ -463,7 +471,7 @@ export function insertCustomBlocks(
}
}
- const insertCustomBlocks = insertBody.customBlocks;
+ const insertCustomBlocks = insertBody[field];
if (insertCustomBlocks) {
for (let i = 0, len = insertCustomBlocks.length; i < len; i++) {
const customBlock = insertCustomBlocks[i];
@@ -474,11 +482,92 @@ export function insertCustomBlocks(
customBlocks.sort(sortRulesFactory('startIndex'));
}
- if (customBlocks.length && !body.customBlocks) {
- body.customBlocks = customBlocks;
+ if (customBlocks.length && !body[field]) {
+ body[field] = customBlocks;
}
}
+export function insertCustomBlocks(
+ body: IDocumentBody,
+ insertBody: IDocumentBody,
+ textLength: number,
+ currentIndex: number
+) {
+ insertCustomBlockMetadata(body, insertBody, textLength, currentIndex, 'customBlocks');
+}
+
+export function insertDocxRawCustomBlocks(
+ body: IDocumentBody,
+ insertBody: IDocumentBody,
+ textLength: number,
+ currentIndex: number
+) {
+ insertCustomBlockMetadata(body, insertBody, textLength, currentIndex, 'docxRawCustomBlocks');
+}
+
+export function insertDocxRawBlocks(
+ body: IDocumentBody,
+ insertBody: IDocumentBody,
+ textLength: number,
+ currentIndex: number
+): void {
+ if (body.docxRawBlocks == null && insertBody.docxRawBlocks == null) {
+ return;
+ }
+
+ const rawBlocks = body.docxRawBlocks ?? [];
+ rawBlocks.forEach((rawBlock) => {
+ if (rawBlock.startIndex >= currentIndex) {
+ rawBlock.startIndex += textLength;
+ }
+ });
+ rawBlocks.push(...(insertBody.docxRawBlocks ?? []).map((rawBlock) => ({
+ ...rawBlock,
+ startIndex: rawBlock.startIndex + currentIndex,
+ })));
+ rawBlocks.sort(sortRulesFactory('startIndex'));
+ body.docxRawBlocks = rawBlocks;
+}
+
+function mergeDocxExportExcludedRanges(ranges: IDocxExportExcludedRange[]): IDocxExportExcludedRange[] {
+ const sorted = [...ranges].sort((left, right) => left.start - right.start || left.end - right.end);
+ const merged: IDocxExportExcludedRange[] = [];
+ for (const range of sorted) {
+ const previous = merged[merged.length - 1];
+ if (previous && range.start <= previous.end) {
+ previous.end = Math.max(previous.end, range.end);
+ } else if (range.end > range.start) {
+ merged.push({ ...range });
+ }
+ }
+ return merged;
+}
+
+export function insertDocxExportExcludedRanges(
+ body: IDocumentBody,
+ insertBody: IDocumentBody,
+ textLength: number,
+ currentIndex: number
+): void {
+ if (body.docxExportExcludedRanges == null && insertBody.docxExportExcludedRanges == null) {
+ return;
+ }
+
+ const shifted = (body.docxExportExcludedRanges ?? []).map((range) => {
+ const result = shiftExclusiveRangeOnInsert(
+ { startIndex: range.start, endIndex: range.end },
+ currentIndex,
+ textLength
+ );
+ return { start: result.startIndex, end: result.endIndex };
+ });
+ const inserted = (insertBody.docxExportExcludedRanges ?? []).map((range) => ({
+ start: range.start + currentIndex,
+ end: range.end + currentIndex,
+ }));
+ body.docxExportExcludedRanges = mergeDocxExportExcludedRanges([...shifted, ...inserted]);
+}
+
export function insertTables(body: IDocumentBody, insertBody: IDocumentBody, textLength: number, currentIndex: number) {
if (!body.tables && !insertBody.tables?.length) {
return;
@@ -1001,38 +1090,102 @@ export function deleteSectionBreaks(body: IDocumentBody, textLength: number, cur
return removeSectionBreaks;
}
-export function deleteCustomBlocks(body: IDocumentBody, textLength: number, currentIndex: number) {
- const { customBlocks = [] } = body;
+function deleteCustomBlockMetadata(
+ body: IDocumentBody,
+ textLength: number,
+ currentIndex: number,
+ field: CustomBlockField
+) {
+ const customBlocks = body[field];
+ if (customBlocks == null) {
+ return;
+ }
const startIndex = currentIndex;
const endIndex = currentIndex + textLength - 1;
const removeCustomBlocks: ICustomBlock[] = [];
- if (customBlocks) {
- const newCustomBlocks = [];
- for (let i = 0, len = customBlocks.length; i < len; i++) {
- const customBlock = customBlocks[i];
- const { startIndex: index } = customBlock;
- if (index >= startIndex && index <= endIndex) {
- removeCustomBlocks.push({
- ...customBlock,
- startIndex: index - currentIndex,
- });
- continue;
- } else if (index > endIndex) {
- customBlock.startIndex -= textLength;
- }
-
- newCustomBlocks.push(customBlock);
+ const newCustomBlocks = [];
+ for (let i = 0, len = customBlocks.length; i < len; i++) {
+ const customBlock = customBlocks[i];
+ const { startIndex: index } = customBlock;
+ if (index >= startIndex && index <= endIndex) {
+ removeCustomBlocks.push({
+ ...customBlock,
+ startIndex: index - currentIndex,
+ });
+ continue;
+ } else if (index > endIndex) {
+ customBlock.startIndex -= textLength;
}
- body.customBlocks = newCustomBlocks;
+
+ newCustomBlocks.push(customBlock);
}
+ body[field] = newCustomBlocks;
- if (customBlocks.length && !body.customBlocks) {
- body.customBlocks = customBlocks;
+ if (customBlocks.length && !body[field]) {
+ body[field] = customBlocks;
}
return removeCustomBlocks;
}
+export function deleteCustomBlocks(body: IDocumentBody, textLength: number, currentIndex: number) {
+ body.customBlocks ??= [];
+ return deleteCustomBlockMetadata(body, textLength, currentIndex, 'customBlocks');
+}
+
+export function deleteDocxRawCustomBlocks(body: IDocumentBody, textLength: number, currentIndex: number) {
+ return deleteCustomBlockMetadata(body, textLength, currentIndex, 'docxRawCustomBlocks');
+}
+
+export function deleteDocxRawBlocks(body: IDocumentBody, textLength: number, currentIndex: number) {
+ if (body.docxRawBlocks == null) {
+ return;
+ }
+
+ const deleteEnd = currentIndex + textLength;
+ const removed: IDocxRawBlock[] = [];
+ const remaining: IDocxRawBlock[] = [];
+ for (const rawBlock of body.docxRawBlocks) {
+ if (rawBlock.startIndex >= currentIndex && rawBlock.startIndex < deleteEnd) {
+ removed.push({ ...rawBlock, startIndex: rawBlock.startIndex - currentIndex });
+ } else {
+ remaining.push(rawBlock.startIndex >= deleteEnd
+ ? { ...rawBlock, startIndex: rawBlock.startIndex - textLength }
+ : rawBlock);
+ }
+ }
+ body.docxRawBlocks = remaining;
+ return removed;
+}
+
+export function deleteDocxExportExcludedRanges(body: IDocumentBody, textLength: number, currentIndex: number) {
+ if (body.docxExportExcludedRanges == null) {
+ return;
+ }
+
+ const deleteEnd = currentIndex + textLength;
+ const removed: IDocxExportExcludedRange[] = [];
+ const remaining: IDocxExportExcludedRange[] = [];
+ for (const range of body.docxExportExcludedRanges) {
+ const overlapStart = Math.max(range.start, currentIndex);
+ const overlapEnd = Math.min(range.end, deleteEnd);
+ if (overlapEnd > overlapStart) {
+ removed.push({ start: overlapStart - currentIndex, end: overlapEnd - currentIndex });
+ }
+
+ const shifted = shiftExclusiveRangeOnDelete(
+ { startIndex: range.start, endIndex: range.end },
+ currentIndex,
+ textLength
+ );
+ if (shifted) {
+ remaining.push({ start: shifted.startIndex, end: shifted.endIndex });
+ }
+ }
+ body.docxExportExcludedRanges = mergeDocxExportExcludedRanges(remaining);
+ return removed;
+}
+
export function deleteTables(body: IDocumentBody, textLength: number, currentIndex: number) {
const { tables } = body;
const removeTables: ICustomTable[] = [];
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 e601e55b63..954148d09f 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
@@ -22,6 +22,9 @@ import {
deleteCustomBlocks,
deleteCustomDecorations,
deleteCustomRanges,
+ deleteDocxExportExcludedRanges,
+ deleteDocxRawBlocks,
+ deleteDocxRawCustomBlocks,
deleteParagraphs,
deleteSectionBreaks,
deleteTables,
@@ -42,6 +45,12 @@ export function updateAttributeByDelete(body: IDocumentBody, textLength: number,
const removeCustomBlocks = deleteCustomBlocks(body, textLength, currentIndex);
+ const removeDocxRawCustomBlocks = deleteDocxRawCustomBlocks(body, textLength, currentIndex);
+
+ const removeDocxRawBlocks = deleteDocxRawBlocks(body, textLength, currentIndex);
+
+ const removeDocxExportExcludedRanges = deleteDocxExportExcludedRanges(body, textLength, currentIndex);
+
const removeTables = deleteTables(body, textLength, currentIndex);
const removeColumnGroups = deleteColumnGroups(body, textLength, currentIndex);
@@ -64,6 +73,9 @@ export function updateAttributeByDelete(body: IDocumentBody, textLength: number,
paragraphs: removeParagraphs,
sectionBreaks: removeSectionBreaks,
customBlocks: removeCustomBlocks,
+ docxRawCustomBlocks: removeDocxRawCustomBlocks,
+ docxRawBlocks: removeDocxRawBlocks,
+ docxExportExcludedRanges: removeDocxExportExcludedRanges,
tables: removeTables,
columnGroups: removeColumnGroups,
blockRanges: removeBlockRanges,
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 15580dc158..e456065aba 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
@@ -22,6 +22,9 @@ import {
insertCustomBlocks,
insertCustomDecorations,
insertCustomRanges,
+ insertDocxExportExcludedRanges,
+ insertDocxRawBlocks,
+ insertDocxRawCustomBlocks,
insertParagraphs,
insertSectionBreaks,
insertTables,
@@ -45,6 +48,12 @@ export function updateAttributeByInsert(
insertCustomBlocks(body, insertBody, textLength, currentIndex);
+ insertDocxRawCustomBlocks(body, insertBody, textLength, currentIndex);
+
+ insertDocxRawBlocks(body, insertBody, textLength, currentIndex);
+
+ insertDocxExportExcludedRanges(body, insertBody, textLength, currentIndex);
+
insertTables(body, insertBody, textLength, currentIndex);
insertColumnGroups(body, insertBody, textLength, currentIndex);
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 afb151ae19..3899483ddd 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
@@ -33,6 +33,7 @@ import {
deleteBlockRanges,
deleteColumnGroups,
deleteCustomBlocks,
+ deleteDocxRawCustomBlocks,
deleteParagraphs,
deleteSectionBreaks,
deleteTables,
@@ -40,6 +41,7 @@ import {
insertBlockRanges,
insertColumnGroups,
insertCustomBlocks,
+ insertDocxRawCustomBlocks,
insertParagraphs,
insertSectionBreaks,
insertTables,
@@ -62,6 +64,7 @@ export function updateAttribute(
const removeParagraphs = updateParagraphs(body, updateBody, textLength, currentIndex, coverType);
const removeSectionBreaks = updateSectionBreaks(body, updateBody, textLength, currentIndex, coverType);
const removeCustomBlocks = updateCustomBlocks(body, updateBody, textLength, currentIndex, coverType);
+ const removeDocxRawCustomBlocks = updateDocxRawCustomBlocks(body, updateBody, textLength, currentIndex, coverType);
const removeTables = updateTables(body, updateBody, textLength, currentIndex, coverType);
const removeColumnGroups = updateColumnGroups(body, updateBody, textLength, currentIndex, coverType);
const removeBlockRanges = updateBlockRanges(body, updateBody, textLength, currentIndex, coverType);
@@ -74,6 +77,7 @@ export function updateAttribute(
paragraphs: removeParagraphs,
sectionBreaks: removeSectionBreaks,
customBlocks: removeCustomBlocks,
+ docxRawCustomBlocks: removeDocxRawCustomBlocks,
tables: removeTables,
columnGroups: removeColumnGroups,
blockRanges: removeBlockRanges,
@@ -390,7 +394,7 @@ function updateCustomBlocks(
return;
}
- const removeCustomBlocks = deleteCustomBlocks(body, textLength, currentIndex);
+ const removeCustomBlocks = deleteCustomBlocks(body, textLength, currentIndex) ?? [];
if (coverType !== UpdateDocsAttributeType.REPLACE) {
const newUpdateCustomBlocks: ICustomBlock[] = [];
for (const updateCustomBlock of updateDataCustomBlocks) {
@@ -426,6 +430,43 @@ function updateCustomBlocks(
return removeCustomBlocks;
}
+function updateDocxRawCustomBlocks(
+ body: IDocumentBody,
+ updateBody: IDocumentBody,
+ textLength: number,
+ currentIndex: number,
+ coverType: UpdateDocsAttributeType
+) {
+ const customBlocks = body.docxRawCustomBlocks;
+ const updateDataCustomBlocks = updateBody.docxRawCustomBlocks;
+
+ if (customBlocks == null || updateDataCustomBlocks == null) {
+ return;
+ }
+
+ const removeCustomBlocks = deleteDocxRawCustomBlocks(body, textLength, currentIndex) ?? [];
+ if (coverType !== UpdateDocsAttributeType.REPLACE) {
+ const newUpdateCustomBlocks: ICustomBlock[] = [];
+ for (const updateCustomBlock of updateDataCustomBlocks) {
+ const removed = removeCustomBlocks.find((customBlock) =>
+ customBlock.startIndex === updateCustomBlock.startIndex
+ );
+ if (removed) {
+ newUpdateCustomBlocks.push(coverType === UpdateDocsAttributeType.COVER
+ ? { ...removed, ...updateCustomBlock }
+ : { ...updateCustomBlock, ...removed });
+ }
+ }
+ updateBody.docxRawCustomBlocks = newUpdateCustomBlocks;
+ }
+ insertDocxRawCustomBlocks(body, updateBody, textLength, currentIndex);
+
+ if (customBlocks.length && !body.docxRawCustomBlocks) {
+ body.docxRawCustomBlocks = customBlocks;
+ }
+ return removeCustomBlocks;
+}
+
function updateTables(
body: IDocumentBody,
updateBody: IDocumentBody,
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 f3baf929cd..334ebc645f 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
@@ -516,6 +516,9 @@ function normalizeSelectionsForStructuralSentinels(
const structuralSelections = insertBody == null
? expandFullyCoveredStructuralSelections(selections, body)
: selections;
+ if (!structuralSelections.length) {
+ return selections;
+ }
const insertOffset = structuralSelections[0].startOffset;
const protectedOffsets = new Set<number>();
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 f36184bae8..2aedd46d2b 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
@@ -65,6 +65,39 @@ interface IValidationContext {
segmentId?: string;
}
+interface IPairedTokenRanges {
+ pairs: Map<number, number>;
+ unmatchedEnds: number[];
+ unmatchedStarts: number[];
+}
+
+interface IDocumentStructuralTokenScan {
+ hasRootParagraph: boolean;
+ hasRootSectionBreak: boolean;
+ tableRanges: IPairedTokenRanges;
+ blockRanges: IPairedTokenRanges;
+ columnGroupRanges: IPairedTokenRanges;
+ customBlockIndexes: Set<number>;
+}
+
+const DOCUMENT_STRUCTURAL_TOKEN_PATTERN_SOURCE = `[${[
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.SECTION_BREAK,
+ DataStreamTreeTokenType.TABLE_START,
+ DataStreamTreeTokenType.TABLE_ROW_START,
+ DataStreamTreeTokenType.TABLE_CELL_START,
+ DataStreamTreeTokenType.TABLE_CELL_END,
+ DataStreamTreeTokenType.TABLE_ROW_END,
+ DataStreamTreeTokenType.TABLE_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_START,
+ DataStreamTreeTokenType.COLUMN_START,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_END,
+ DataStreamTreeTokenType.BLOCK_START,
+ DataStreamTreeTokenType.BLOCK_END,
+ DataStreamTreeTokenType.CUSTOM_BLOCK,
+].join('')}]`;
+
function createIssue(
context: IValidationContext,
code: DocStructureIssueCode,
@@ -79,12 +112,12 @@ function createIssue(
};
}
-function validateMinimumRootSentinels(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {
- if (!body.dataStream.includes(DataStreamTreeTokenType.PARAGRAPH)) {
+function validateMinimumRootSentinels(scan: IDocumentStructuralTokenScan, issues: IDocStructureIssue[], context: IValidationContext) {
+ if (!scan.hasRootParagraph) {
issues.push(createIssue(context, 'missing-root-paragraph', 'Document body must contain at least one paragraph sentinel.'));
}
- if (!body.dataStream.includes(DataStreamTreeTokenType.SECTION_BREAK)) {
+ if (!scan.hasRootSectionBreak) {
issues.push(createIssue(context, 'missing-root-section-break', 'Document body must contain at least one section break sentinel.'));
}
}
@@ -162,43 +195,85 @@ function validatePointMetadataDuplicates(
}
}
-function collectPairedTokenRanges(
- dataStream: string,
- startToken: string,
- endToken: string,
- exclusiveEnd: boolean
-) {
- const pairs = new Map<number, number>();
- const stack: number[] = [];
- const unmatchedEnds: number[] = [];
-
- for (let index = 0; index < dataStream.length; index++) {
- if (dataStream[index] === startToken) {
- stack.push(index);
- } else if (dataStream[index] === endToken) {
- const startIndex = stack.pop();
- if (startIndex === undefined) {
- unmatchedEnds.push(index);
- } else {
- pairs.set(startIndex, exclusiveEnd ? index + 1 : index);
- }
+function sortStructuralRanges<T extends { startIndex: number; endIndex: number }>(ranges: readonly T[]): readonly T[] {
+ for (let index = 1; index < ranges.length; index++) {
+ const previous = ranges[index - 1];
+ const current = ranges[index];
+ if (
+ current.startIndex < previous.startIndex ||
+ (current.startIndex === previous.startIndex && current.endIndex < previous.endIndex)
+ ) {
+ return [...ranges].sort((left, right) =>
+ left.startIndex - right.startIndex || left.endIndex - right.endIndex
+ );
+ }
+ }
+
+ return ranges;
+}
+
+function createPairedTokenRanges(): IPairedTokenRanges {
+ return {
+ pairs: new Map(),
+ unmatchedEnds: [],
+ unmatchedStarts: [],
+ };
+}
+
+function closeTokenRange(ranges: IPairedTokenRanges, index: number, exclusiveEnd: boolean): void {
+ const startIndex = ranges.unmatchedStarts.pop();
+ if (startIndex === undefined) {
+ ranges.unmatchedEnds.push(index);
+ return;
+ }
+
+ ranges.pairs.set(startIndex, exclusiveEnd ? index + 1 : index);
+}
+
+function scanDocumentStructuralTokens(dataStream: string): IDocumentStructuralTokenScan {
+ const scan: IDocumentStructuralTokenScan = {
+ hasRootParagraph: false,
+ hasRootSectionBreak: false,
+ tableRanges: createPairedTokenRanges(),
+ blockRanges: createPairedTokenRanges(),
+ columnGroupRanges: createPairedTokenRanges(),
+ customBlockIndexes: new Set(),
+ };
+
+ const tokenPattern = new RegExp(DOCUMENT_STRUCTURAL_TOKEN_PATTERN_SOURCE, 'g');
+ for (const match of dataStream.matchAll(tokenPattern)) {
+ const index = match.index;
+ const token = match[0];
+ if (token === DataStreamTreeTokenType.PARAGRAPH) {
+ scan.hasRootParagraph = true;
+ } else if (token === DataStreamTreeTokenType.SECTION_BREAK) {
+ scan.hasRootSectionBreak = true;
+ } else if (token === DataStreamTreeTokenType.TABLE_START) {
+ scan.tableRanges.unmatchedStarts.push(index);
+ } else if (token === DataStreamTreeTokenType.TABLE_END) {
+ closeTokenRange(scan.tableRanges, index, true);
+ } else if (token === DataStreamTreeTokenType.BLOCK_START) {
+ scan.blockRanges.unmatchedStarts.push(index);
+ } else if (token === DataStreamTreeTokenType.BLOCK_END) {
+ closeTokenRange(scan.blockRanges, index, false);
+ } else if (token === DataStreamTreeTokenType.COLUMN_GROUP_START) {
+ scan.columnGroupRanges.unmatchedStarts.push(index);
+ } else if (token === DataStreamTreeTokenType.COLUMN_GROUP_END) {
+ closeTokenRange(scan.columnGroupRanges, index, false);
+ } else if (token === DataStreamTreeTokenType.CUSTOM_BLOCK) {
+ scan.customBlockIndexes.add(index);
}
}
- return { pairs, unmatchedEnds, unmatchedStarts: stack };
+ return scan;
}
-function validateTableMetadata(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {
- const pairedTables = collectPairedTokenRanges(
- body.dataStream,
- DataStreamTreeTokenType.TABLE_START,
- DataStreamTreeTokenType.TABLE_END,
- true
- ).pairs;
+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 tables = [...(body.tables ?? [])].sort((a, b) => a.startIndex - b.startIndex || a.endIndex - b.endIndex);
+ const tables = sortStructuralRanges(body.tables ?? []);
for (const table of tables) {
metadataStarts.add(table.startIndex);
if (!Number.isInteger(table.startIndex) || body.dataStream[table.startIndex] !== DataStreamTreeTokenType.TABLE_START) {
@@ -238,18 +313,13 @@ function validateTableMetadata(body: IDocumentBody, issues: IDocStructureIssue[]
}
}
-function validateBlockRangeMetadata(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {
- const pairedBlocks = collectPairedTokenRanges(
- body.dataStream,
- DataStreamTreeTokenType.BLOCK_START,
- DataStreamTreeTokenType.BLOCK_END,
- false
- );
+function validateBlockRangeMetadata(body: IDocumentBody, scan: IDocumentStructuralTokenScan, issues: IDocStructureIssue[], context: IValidationContext) {
+ const pairedBlocks = scan.blockRanges;
for (const index of [...pairedBlocks.unmatchedStarts, ...pairedBlocks.unmatchedEnds]) {
issues.push(createIssue(context, 'unbalanced-block', 'Block sentinel has no matching boundary.', index));
}
- const blockRanges = [...(body.blockRanges ?? [])].sort((a, b) => a.startIndex - b.startIndex || a.endIndex - b.endIndex);
+ const blockRanges = sortStructuralRanges(body.blockRanges ?? []);
const metadataStarts = new Set<number>();
let previousBlockRange: (typeof blockRanges)[number] | undefined;
for (let i = 0; i < blockRanges.length; i++) {
@@ -285,15 +355,10 @@ function validateBlockRangeMetadata(body: IDocumentBody, issues: IDocStructureIs
}
}
-function validateColumnGroupMetadata(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {
- const pairedColumnGroups = collectPairedTokenRanges(
- body.dataStream,
- DataStreamTreeTokenType.COLUMN_GROUP_START,
- DataStreamTreeTokenType.COLUMN_GROUP_END,
- false
- ).pairs;
+function validateColumnGroupMetadata(body: IDocumentBody, scan: IDocumentStructuralTokenScan, issues: IDocStructureIssue[], context: IValidationContext) {
+ const pairedColumnGroups = scan.columnGroupRanges.pairs;
const metadataStarts = new Set<number>();
- const columnGroups = [...(body.columnGroups ?? [])].sort((a, b) => a.startIndex - b.startIndex || a.endIndex - b.endIndex);
+ const columnGroups = sortStructuralRanges(body.columnGroups ?? []);
let previousColumnGroup: (typeof columnGroups)[number] | undefined;
for (const columnGroup of columnGroups) {
@@ -341,9 +406,10 @@ function validateColumnGroupMetadata(body: IDocumentBody, issues: IDocStructureI
}
}
-function validateCustomBlockMetadata(body: IDocumentBody, issues: IDocStructureIssue[], context: IValidationContext) {
+function validateCustomBlockMetadata(body: IDocumentBody, scan: IDocumentStructuralTokenScan, issues: IDocStructureIssue[], context: IValidationContext) {
const metadataCounts = new Map<number, number>();
- for (const customBlock of body.customBlocks ?? []) {
+ const customBlocks = [...(body.customBlocks ?? []), ...(body.docxRawCustomBlocks ?? [])];
+ for (const customBlock of customBlocks) {
const { startIndex } = customBlock;
if (!Number.isInteger(startIndex) || body.dataStream[startIndex] !== DataStreamTreeTokenType.CUSTOM_BLOCK) {
issues.push(createIssue(
@@ -364,8 +430,8 @@ function validateCustomBlockMetadata(body: IDocumentBody, issues: IDocStructureI
duplicateMessage: 'Custom block sentinel must have exactly one custom block metadata entry.',
}, issues);
- for (let index = 0; index < body.dataStream.length; index++) {
- if (body.dataStream[index] === DataStreamTreeTokenType.CUSTOM_BLOCK && !metadataCounts.has(index)) {
+ for (const index of scan.customBlockIndexes) {
+ if (!metadataCounts.has(index)) {
issues.push(createIssue(
context,
'missing-custom-block-metadata',
@@ -383,8 +449,10 @@ function validateStructuralContainers(body: IDocumentBody, issues: IDocStructure
const tableRowStack: number[] = [];
const tableCellStack: Array<{ startIndex: number; hasParagraph: boolean; hasSectionBreak: boolean }> = [];
- for (let i = 0; i < body.dataStream.length; i++) {
- const char = body.dataStream[i];
+ 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];
@@ -467,14 +535,15 @@ export function validateDocBodyStructure(
context: IValidationContext = { segmentType: 'body' }
): IDocStructureIssue[] {
const issues: IDocStructureIssue[] = [];
+ const scan = scanDocumentStructuralTokens(body.dataStream);
- validateMinimumRootSentinels(body, issues, context);
+ validateMinimumRootSentinels(scan, issues, context);
validateParagraphMetadata(body, issues, context);
validateSectionBreakMetadata(body, issues, context);
- validateTableMetadata(body, issues, context);
- validateBlockRangeMetadata(body, issues, context);
- validateColumnGroupMetadata(body, issues, context);
- validateCustomBlockMetadata(body, issues, context);
+ validateTableMetadata(body, scan, issues, context);
+ validateBlockRangeMetadata(body, scan, issues, context);
+ validateColumnGroupMetadata(body, scan, issues, context);
+ validateCustomBlockMetadata(body, scan, issues, context);
validateStructuralContainers(body, issues, context);
return issues;
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 e9e05f47a4..996b557349 100644
--- a/packages/core/src/docs/data-model/text-x/utils.ts
+++ b/packages/core/src/docs/data-model/text-x/utils.ts
@@ -21,6 +21,8 @@ import type {
ICustomRange,
IDocumentBlockRange,
IDocumentBody,
+ IDocxExportExcludedRange,
+ IDocxRawBlock,
IParagraph,
ISectionBreak,
ITextRun,
@@ -88,10 +90,10 @@ export function getTextRunSlice(
const newTextRuns: ITextRun[] = [];
for (const textRun of textRuns) {
- const clonedTextRun = Tools.deepClone(textRun);
- const { st, ed } = clonedTextRun;
+ const { st, ed } = textRun;
if (Tools.hasIntersectionBetweenTwoRanges(st, ed, startOffset, endOffset)) {
+ const clonedTextRun = Tools.deepClone(textRun);
if (startOffset >= st && startOffset <= ed) {
newTextRuns.push({
...clonedTextRun,
@@ -283,7 +285,22 @@ export function getCustomBlockSlice(
startOffset: number,
endOffset: number
) {
- const { customBlocks = [] } = body;
+ return getCustomBlockMetadataSlice(body.customBlocks ?? [], startOffset, endOffset);
+}
+
+function getDocxRawCustomBlockSlice(
+ body: IDocumentBody,
+ startOffset: number,
+ endOffset: number
+) {
+ return getCustomBlockMetadataSlice(body.docxRawCustomBlocks ?? [], startOffset, endOffset);
+}
+
+function getCustomBlockMetadataSlice(
+ customBlocks: ICustomBlock[],
+ startOffset: number,
+ endOffset: number
+) {
const newCustomBlocks: ICustomBlock[] = [];
for (const block of customBlocks) {
@@ -301,6 +318,24 @@ export function getCustomBlockSlice(
}
}
+function getDocxRawBlockSlice(body: IDocumentBody, startOffset: number, endOffset: number): IDocxRawBlock[] {
+ return (body.docxRawBlocks ?? [])
+ .filter((rawBlock) => rawBlock.startIndex >= startOffset && rawBlock.startIndex < endOffset)
+ .map((rawBlock) => ({ ...Tools.deepClone(rawBlock), startIndex: rawBlock.startIndex - startOffset }));
+}
+
+function getDocxExportExcludedRangeSlice(
+ body: IDocumentBody,
+ startOffset: number,
+ endOffset: number
+): IDocxExportExcludedRange[] {
+ return (body.docxExportExcludedRanges ?? []).flatMap((range) => {
+ const start = Math.max(range.start, startOffset);
+ const end = Math.min(range.end, endOffset);
+ return end > start ? [{ start: start - startOffset, end: end - startOffset }] : [];
+ });
+}
+
export function getBodySlice(
body: IDocumentBody,
startOffset: number,
@@ -360,6 +395,15 @@ export function getBodySlice(
}
docBody.customBlocks = getCustomBlockSlice(body, startOffset, endOffset);
+ if (body.docxRawCustomBlocks != null) {
+ docBody.docxRawCustomBlocks = getDocxRawCustomBlockSlice(body, startOffset, endOffset) ?? [];
+ }
+ if (body.docxRawBlocks != null) {
+ docBody.docxRawBlocks = getDocxRawBlockSlice(body, startOffset, endOffset);
+ }
+ if (body.docxExportExcludedRanges != null) {
+ docBody.docxExportExcludedRanges = getDocxExportExcludedRangeSlice(body, startOffset, endOffset);
+ }
return docBody;
}
@@ -384,8 +428,47 @@ export function getBodySliceForSplitTextXAction(
return getBodySlice(body, startOffset, endOffset, returnEmptyArray, type, SliceStructuralRangeMode.ending);
}
+function shiftBodyMetadata(body: IDocumentBody, leftOffset: number, rightOffset: number): void {
+ body.textRuns?.forEach((textRun) => {
+ textRun.st += leftOffset;
+ textRun.ed += leftOffset;
+ });
+ body.paragraphs?.forEach((paragraph) => {
+ paragraph.startIndex += leftOffset;
+ });
+ body.customBlocks?.forEach((customBlock) => {
+ customBlock.startIndex += leftOffset;
+ });
+ body.docxRawCustomBlocks?.forEach((customBlock) => {
+ customBlock.startIndex += leftOffset;
+ });
+ body.docxRawBlocks?.forEach((rawBlock) => {
+ rawBlock.startIndex += leftOffset;
+ });
+ body.docxExportExcludedRanges?.forEach((range) => {
+ range.start += leftOffset;
+ range.end += leftOffset;
+ });
+ body.customRanges?.forEach((range) => {
+ range.startIndex += leftOffset;
+ range.endIndex += leftOffset;
+ });
+ body.customDecorations?.forEach((decoration) => {
+ decoration.startIndex += leftOffset;
+ decoration.endIndex += rightOffset;
+ });
+ body.tables?.forEach((table) => {
+ table.startIndex += leftOffset;
+ table.endIndex += rightOffset;
+ });
+ body.columnGroups?.forEach((columnGroup) => {
+ columnGroup.startIndex += leftOffset;
+ columnGroup.endIndex += rightOffset;
+ });
+}
+
export function normalizeBody(body: IDocumentBody): IDocumentBody {
- const { dataStream, textRuns, paragraphs, customRanges, customDecorations, tables, columnGroups, blockRanges } = body;
+ const { dataStream, textRuns, customRanges } = body;
let leftOffset = 0;
let rightOffset = 0;
@@ -411,45 +494,11 @@ export function normalizeBody(body: IDocumentBody): IDocumentBody {
}
}
- textRuns?.forEach((textRun) => {
- textRun.st += leftOffset;
- textRun.ed += leftOffset;
- });
-
- paragraphs?.forEach((p) => {
- p.startIndex += leftOffset;
- });
-
- customRanges?.forEach((range) => {
- range.startIndex += leftOffset;
- range.endIndex += leftOffset;
- });
-
- customDecorations?.forEach((d) => {
- d.startIndex += leftOffset;
- d.endIndex += rightOffset;
- });
-
- tables?.forEach((table) => {
- table.startIndex += leftOffset;
- table.endIndex += rightOffset;
- });
-
- columnGroups?.forEach((columnGroup) => {
- columnGroup.startIndex += leftOffset;
- columnGroup.endIndex += rightOffset;
- });
+ shiftBodyMetadata(body, leftOffset, rightOffset);
return {
...body,
dataStream: newData,
- textRuns,
- paragraphs,
- customRanges,
- customDecorations,
- tables,
- columnGroups,
- blockRanges,
};
}
@@ -706,9 +755,9 @@ export function isUselessRetainAction(action: IRetainAction): boolean {
return true;
}
- const { textRuns, paragraphs, customRanges, customBlocks, customDecorations, tables, columnGroups, blockRanges } = body;
+ const { textRuns, paragraphs, customRanges, customBlocks, docxRawCustomBlocks, docxRawBlocks, docxExportExcludedRanges, customDecorations, tables, columnGroups, blockRanges } = body;
- if (textRuns == null && paragraphs == null && customRanges == null && customBlocks == null && customDecorations == null && tables == null && columnGroups == null && blockRanges == null) {
+ if (textRuns == null && paragraphs == null && customRanges == null && customBlocks == null && docxRawCustomBlocks == null && docxRawBlocks == null && docxExportExcludedRanges == null && customDecorations == null && tables == null && columnGroups == null && blockRanges == null) {
return true;
}
diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.ts
index be1324464a..d0eb8af42b 100644
--- a/packages/core/src/types/interfaces/i-document-data.ts
+++ b/packages/core/src/types/interfaces/i-document-data.ts
@@ -140,6 +140,18 @@ export interface IDocumentBody {
customBlocks?: ICustomBlock[]; // customBlock user-defined block through plug-in
+ /**
+ * Opaque DOCX runs represented by custom-block sentinels for lossless round-trip.
+ * They participate in text offsets like regular custom blocks but are not rendered as drawings.
+ */
+ docxRawCustomBlocks?: ICustomBlock[];
+
+ /** Opaque DOCX XML anchored at a document offset for lossless round-trip. */
+ docxRawBlocks?: IDocxRawBlock[];
+
+ /** Document ranges excluded from generated DOCX content because their raw XML is preserved separately. */
+ docxExportExcludedRanges?: IDocxExportExcludedRange[];
+
tables?: ICustomTable[]; // Table
columnGroups?: ICustomColumnGroup[]; // ColumnGroup
@@ -441,6 +453,22 @@ export interface ICustomBlock {
blockType?: BlockType;
// A unique ID associated with a custom block.
blockId: string;
+
+ /** Original DOCX run XML retained by the exchange layer for lossless round-trip. */
+ docxRawXml?: string;
+
+ /** Original DOCX text style retained by the exchange layer for lossless round-trip. */
+ docxExportTs?: ITextStyle;
+}
+
+export interface IDocxRawBlock {
+ startIndex: number;
+ xml: string;
+}
+
+export interface IDocxExportExcludedRange {
+ start: number;
+ end: number;
}
export enum CustomDecorationType {
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 40684b3da5..a4aaca4b7b 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
@@ -37,6 +37,7 @@ import {
getDocsTableCellAnchorContext,
shouldUseDocsDrawingOuterPageOrigin,
} from '../doc-drawing-transformer-update.controller';
+import { getDocsOverlayRuntimeDrawing } from '../render-controllers/doc-drawing-transform-update.controller';
function createController() {
const controller = Object.create(DocDrawingTransformerController.prototype) as any;
@@ -85,6 +86,28 @@ function drawing(drawingId = 'drawing-1') {
}
describe('DocDrawingTransformerController business methods', () => {
+ it('uses the latest model transform only while both drawing states are overlay-only', () => {
+ const skeletonOverlay = {
+ ...drawing(),
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ };
+ const currentOverlay = {
+ ...skeletonOverlay,
+ docTransform: {
+ ...skeletonOverlay.docTransform,
+ size: { width: 160, height: 120 },
+ positionH: {
+ relativeFrom: ObjectRelativeFromH.PAGE,
+ posOffset: 50,
+ },
+ },
+ };
+
+ expect(getDocsOverlayRuntimeDrawing(skeletonOverlay, currentOverlay)).toBe(currentOverlay);
+ expect(getDocsOverlayRuntimeDrawing(drawing(), currentOverlay)).not.toBe(currentOverlay);
+ expect(getDocsOverlayRuntimeDrawing(skeletonOverlay, drawing())).not.toBe(currentOverlay);
+ });
+
it('builds drawing transform updates for multi-select resize, rotation, and move changes', () => {
const controller = createController();
const drawingData = drawing();
diff --git a/packages/docs-drawing-ui/src/controllers/__tests__/doc-float-dom.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/__tests__/doc-float-dom.controller.spec.ts
index 96e4ec4c5c..af4b154242 100644
--- a/packages/docs-drawing-ui/src/controllers/__tests__/doc-float-dom.controller.spec.ts
+++ b/packages/docs-drawing-ui/src/controllers/__tests__/doc-float-dom.controller.spec.ts
@@ -20,6 +20,7 @@ import { SetDocZoomRatioOperation } from '@univerjs/docs-ui';
import { Rect } from '@univerjs/engine-render';
import { BehaviorSubject, Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
+import { DocRefreshDrawingsService } from '../../services/doc-refresh-drawings.service';
import {
calcDocFloatDomPositionByRect,
DocFloatDomController,
@@ -37,25 +38,55 @@ function createScene() {
};
}
-function createController(options: { drawing?: Record<string, unknown>; rects?: Rect[]; page?: any } = {}) {
+function createController(options: {
+ drawing?: Record<string, unknown>;
+ rects?: Rect[];
+ page?: any;
+ renderType?: UniverInstanceType;
+ refreshDrawingOnAdd?: { left: number; top: number; width: number; height: number; angle: number };
+ resolveRefreshDrawing?: () => { left: number; top: number; width: number; height: number; angle: number } | undefined;
+} = {}) {
const add$ = new Subject<any[]>();
const remove$ = new Subject<any[]>();
const refreshTransform$ = new Subject<any[]>();
const currentSkeleton$ = new Subject<any>();
+ const skeletonDirty$ = new Subject<boolean>();
+ const renderCreated$ = new Subject<any>();
+ const renderDisposed$ = new Subject<string>();
const commandHandlers: Array<(command: { id: string; params?: unknown }) => void> = [];
const scene = createScene();
const canvas = { dispatchEvent: vi.fn() };
+ const docRefreshDrawingsService = new DocRefreshDrawingsService();
+ const refreshDrawings = vi.spyOn(docRefreshDrawingsService, 'refreshDrawings');
+ docRefreshDrawingsService.refreshDrawings$.subscribe((skeleton) => {
+ const transform = options.resolveRefreshDrawing?.() ?? options.refreshDrawingOnAdd;
+ if (skeleton != null && transform) {
+ refreshTransform$.next([{
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ drawingId: 'dom-1',
+ transform,
+ }]);
+ }
+ });
+ const skeleton = {
+ dirty$: skeletonDirty$,
+ getSkeletonData: () => ({ pages: [options.page ?? { pageWidth: 240, marginLeft: 20, marginRight: 30 }] }),
+ };
const renderUnit = {
+ unitId: 'doc-1',
+ type: options.renderType ?? UniverInstanceType.UNIVER_DOC,
scene,
engine: { getCanvasElement: () => canvas },
+ isDisposed: vi.fn(() => false),
with: vi.fn(() => ({
currentSkeleton$,
- getSkeleton: () => ({
- getSkeletonData: () => ({ pages: [options.page ?? { pageWidth: 240, marginLeft: 20, marginRight: 30 }] }),
- }),
+ getSkeleton: () => skeleton,
})),
};
const renderManagerService = {
+ created$: renderCreated$,
+ disposed$: renderDisposed$,
getRenderUnitById: vi.fn(() => renderUnit),
};
const drawing = {
@@ -74,7 +105,7 @@ function createController(options: { drawing?: Record<string, unknown>; rects?:
getDrawingByParam: vi.fn(() => drawing),
};
const drawingRenderService = {
- renderFloatDom: vi.fn(async () => options.rects ?? []),
+ renderFloatDom: vi.fn(() => options.rects ?? []),
};
const domLayers: Array<[string, any]> = [];
const canvasFloatDomService = {
@@ -110,7 +141,8 @@ function createController(options: { drawing?: Record<string, unknown>; rects?:
drawingRenderService as never,
canvasFloatDomService as never,
univerInstanceService as never,
- commandService as never
+ commandService as never,
+ docRefreshDrawingsService
);
return {
@@ -126,9 +158,25 @@ function createController(options: { drawing?: Record<string, unknown>; rects?:
drawingRenderService,
canvasFloatDomService,
commandService,
+ refreshDrawings,
+ renderCreated$,
+ renderDisposed$,
+ skeletonDirty$,
};
}
+function publishEmbedRuntimeGeometry(
+ refreshTransform$: ReturnType<typeof createController>['refreshTransform$'],
+ transform = { left: 30, top: 50, width: 50, height: 40, angle: 0 }
+) {
+ refreshTransform$.next([{
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ drawingId: 'dom-1',
+ transform,
+ }]);
+}
+
describe('DocFloatDomController', () => {
it('preserves existing props while adding custom block runtime viewport', () => {
expect(mergeDocFloatDomRuntimeProps({ keep: true }, {
@@ -251,13 +299,14 @@ describe('DocFloatDomController', () => {
width: 50,
height: 40,
} as never);
- const { controller, add$, canvasFloatDomService } = createController({
+ const { controller, add$, refreshTransform$, canvasFloatDomService } = createController({
rects: [rect],
drawing: {
data: { version: 1, embedId: 'embed-1', hostAnchorId: 'anchor-1' },
},
});
+ publishEmbedRuntimeGeometry(refreshTransform$);
add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
await Promise.resolve();
@@ -269,6 +318,231 @@ describe('DocFloatDomController', () => {
controller.dispose();
});
+ it('waits for layout runtime geometry before mounting an embed custom block', () => {
+ const rect = new Rect('dom-rect', {
+ left: 10,
+ top: 20,
+ width: 50,
+ height: 40,
+ });
+ const { controller, add$, refreshTransform$, drawingRenderService, canvasFloatDomService } = createController({
+ rects: [rect],
+ drawing: {
+ data: { version: 1, embedId: 'embed-1', hostAnchorId: 'anchor-1' },
+ },
+ });
+
+ add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
+
+ expect(drawingRenderService.renderFloatDom).not.toHaveBeenCalled();
+ expect(canvasFloatDomService.addFloatDom).not.toHaveBeenCalled();
+
+ publishEmbedRuntimeGeometry(refreshTransform$, { left: 300, top: 500, width: 50, height: 40, angle: 0 });
+
+ expect(drawingRenderService.renderFloatDom).toHaveBeenCalledOnce();
+ expect(canvasFloatDomService.addFloatDom).toHaveBeenCalledOnce();
+ expect(canvasFloatDomService.addFloatDom.mock.calls[0][0].position$.getValue()).toMatchObject({
+ startX: 580,
+ startY: 1440,
+ width: 100,
+ height: 120,
+ });
+
+ controller.dispose();
+ });
+
+ it('refreshes current layout geometry when an embed drawing is added after publication', () => {
+ const rect = new Rect('dom-rect', {
+ left: 10,
+ top: 20,
+ width: 50,
+ height: 40,
+ });
+ const { controller, add$, refreshDrawings, canvasFloatDomService } = createController({
+ rects: [rect],
+ drawing: {
+ data: { version: 1, embedId: 'embed-1', hostAnchorId: 'anchor-1' },
+ },
+ refreshDrawingOnAdd: { left: 300, top: 500, width: 50, height: 40, angle: 0 },
+ });
+
+ add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
+
+ expect(refreshDrawings).toHaveBeenCalledOnce();
+ expect(canvasFloatDomService.addFloatDom).toHaveBeenCalledOnce();
+ expect(canvasFloatDomService.addFloatDom.mock.calls[0][0].position$.getValue()).toMatchObject({
+ startX: 580,
+ startY: 1440,
+ width: 100,
+ height: 120,
+ });
+
+ controller.dispose();
+ });
+
+ it('does not resolve layout services from a disposed render unit', () => {
+ const { controller, add$, renderUnit, refreshDrawings } = createController({
+ drawing: {
+ data: { version: 1, embedId: 'embed-1', hostAnchorId: 'anchor-1' },
+ },
+ });
+ renderUnit.isDisposed.mockReturnValue(true);
+
+ add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
+
+ expect(renderUnit.with).not.toHaveBeenCalled();
+ expect(refreshDrawings).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('does not resolve Doc layout services from a non-Doc render unit', () => {
+ const { controller, add$, renderUnit, refreshDrawings } = createController({
+ drawing: {
+ data: { version: 1, embedId: 'embed-1', hostAnchorId: 'anchor-1' },
+ },
+ renderType: UniverInstanceType.UNIVER_SHEET,
+ });
+
+ add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
+
+ expect(renderUnit.with).not.toHaveBeenCalled();
+ expect(refreshDrawings).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('resumes pending embed geometry when the host render is recreated', () => {
+ const rect = new Rect('dom-rect', {
+ left: 10,
+ top: 20,
+ width: 50,
+ height: 40,
+ });
+ const {
+ controller,
+ add$,
+ canvasFloatDomService,
+ renderCreated$,
+ renderDisposed$,
+ renderUnit,
+ } = createController({
+ rects: [rect],
+ drawing: {
+ data: { version: 1, embedId: 'embed-1', hostAnchorId: 'anchor-1' },
+ },
+ refreshDrawingOnAdd: { left: 300, top: 500, width: 50, height: 40, angle: 0 },
+ });
+ renderUnit.isDisposed.mockReturnValue(true);
+ add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
+ expect(canvasFloatDomService.addFloatDom).not.toHaveBeenCalled();
+
+ renderDisposed$.next('doc-1');
+ renderUnit.isDisposed.mockReturnValue(false);
+ renderCreated$.next(renderUnit);
+
+ expect(canvasFloatDomService.addFloatDom).toHaveBeenCalledOnce();
+
+ controller.dispose();
+ });
+
+ it('refreshes a pending embed drawing when the current skeleton becomes dirty', () => {
+ let geometry: { left: number; top: number; width: number; height: number; angle: number } | undefined;
+ const rect = new Rect('dom-rect', {
+ left: 10,
+ top: 20,
+ width: 50,
+ height: 40,
+ });
+ const { controller, add$, skeletonDirty$, refreshDrawings, canvasFloatDomService } = createController({
+ rects: [rect],
+ drawing: {
+ data: { version: 1, embedId: 'embed-1', hostAnchorId: 'anchor-1' },
+ },
+ resolveRefreshDrawing: () => geometry,
+ });
+
+ add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
+ expect(canvasFloatDomService.addFloatDom).not.toHaveBeenCalled();
+
+ geometry = { left: 300, top: 500, width: 50, height: 40, angle: 0 };
+ skeletonDirty$.next(true);
+
+ expect(canvasFloatDomService.addFloatDom).toHaveBeenCalledOnce();
+ const refreshCountAfterMount = refreshDrawings.mock.calls.length;
+ skeletonDirty$.next(true);
+ expect(refreshDrawings).toHaveBeenCalledTimes(refreshCountAfterMount);
+
+ controller.dispose();
+ });
+
+ it('ignores hidden fallback geometry while an embed layout is incomplete', () => {
+ const rect = new Rect('dom-rect', {
+ left: 10,
+ top: 20,
+ width: 50,
+ height: 40,
+ });
+ const { controller, add$, refreshTransform$, drawingRenderService, canvasFloatDomService } = createController({
+ rects: [rect],
+ drawing: {
+ data: { version: 1, embedId: 'embed-1', hostAnchorId: 'anchor-1' },
+ },
+ });
+
+ add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
+ refreshTransform$.next([{
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ drawingId: 'dom-1',
+ hidden: true,
+ transform: { left: 10, top: 20, width: 50, height: 40, angle: 0 },
+ }]);
+
+ expect(drawingRenderService.renderFloatDom).not.toHaveBeenCalled();
+ expect(canvasFloatDomService.addFloatDom).not.toHaveBeenCalled();
+
+ publishEmbedRuntimeGeometry(refreshTransform$, { left: 300, top: 500, width: 50, height: 40, angle: 0 });
+ const position$ = canvasFloatDomService.addFloatDom.mock.calls[0][0].position$;
+ const publishedPosition = position$.getValue();
+
+ refreshTransform$.next([{
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ drawingId: 'dom-1',
+ hidden: true,
+ transform: { left: 10, top: 20, width: 50, height: 40, angle: 0 },
+ }]);
+
+ expect(position$.getValue()).toEqual(publishedPosition);
+
+ controller.dispose();
+ });
+
+ it('does not mount a removed embed custom block when runtime geometry arrives later', () => {
+ const rect = new Rect('dom-rect', {
+ left: 10,
+ top: 20,
+ width: 50,
+ height: 40,
+ });
+ const { controller, add$, remove$, refreshTransform$, drawingRenderService, canvasFloatDomService } = createController({
+ rects: [rect],
+ drawing: {
+ data: { version: 1, embedId: 'embed-1', hostAnchorId: 'anchor-1' },
+ },
+ });
+
+ add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
+ remove$.next([{ drawingId: 'dom-1' }]);
+ publishEmbedRuntimeGeometry(refreshTransform$);
+
+ expect(drawingRenderService.renderFloatDom).not.toHaveBeenCalled();
+ expect(canvasFloatDomService.addFloatDom).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
it('updates float dom position from its own host viewport scroll even when current doc focus changes', async () => {
const rect = new Rect('dom-rect', {
left: 30,
@@ -313,6 +587,7 @@ describe('DocFloatDomController', () => {
},
});
+ publishEmbedRuntimeGeometry(refreshTransform$);
add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
await Promise.resolve();
@@ -390,7 +665,7 @@ describe('DocFloatDomController', () => {
width: 50,
height: 40,
} as never);
- const { controller, add$, canvasFloatDomService } = createController({
+ const { controller, add$, refreshTransform$, canvasFloatDomService } = createController({
rects: [rect],
drawing: {
data: {
@@ -402,6 +677,7 @@ describe('DocFloatDomController', () => {
},
});
+ publishEmbedRuntimeGeometry(refreshTransform$);
add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
await Promise.resolve();
@@ -420,7 +696,7 @@ describe('DocFloatDomController', () => {
width: 50,
height: 40,
} as never);
- const { controller, add$, canvasFloatDomService } = createController({
+ const { controller, add$, refreshTransform$, canvasFloatDomService } = createController({
rects: [rect],
drawing: {
data: {
@@ -432,6 +708,7 @@ describe('DocFloatDomController', () => {
},
});
+ publishEmbedRuntimeGeometry(refreshTransform$);
add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
await Promise.resolve();
@@ -457,6 +734,7 @@ describe('DocFloatDomController', () => {
},
});
+ publishEmbedRuntimeGeometry(refreshTransform$);
add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
await Promise.resolve();
@@ -495,6 +773,7 @@ describe('DocFloatDomController', () => {
},
});
+ publishEmbedRuntimeGeometry(refreshTransform$);
add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
await Promise.resolve();
@@ -540,6 +819,7 @@ describe('DocFloatDomController', () => {
},
});
+ publishEmbedRuntimeGeometry(refreshTransform$, { left: 30, top: 240, width: 720, height: 405, angle: 0 });
add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
await Promise.resolve();
diff --git a/packages/docs-drawing-ui/src/controllers/doc-float-dom.controller.ts b/packages/docs-drawing-ui/src/controllers/doc-float-dom.controller.ts
index 0595bd28e2..72b8aab0c9 100644
--- a/packages/docs-drawing-ui/src/controllers/doc-float-dom.controller.ts
+++ b/packages/docs-drawing-ui/src/controllers/doc-float-dom.controller.ts
@@ -43,6 +43,7 @@ import { DrawingRenderService } from '@univerjs/drawing-ui';
import { CURSOR_TYPE, IRenderManagerService } from '@univerjs/engine-render';
import { CanvasFloatDomService } from '@univerjs/ui';
import { BehaviorSubject, map, of, switchMap } from 'rxjs';
+import { DocRefreshDrawingsService } from '../services/doc-refresh-drawings.service';
export function calcDocFloatDomPositionByRect(
rect: IBoundRectNoAngle,
@@ -97,13 +98,14 @@ interface IDocFloatDomParams extends IDocFloatDomDataBase {
type IDocFloatDomRuntimeViewport = Partial<Pick<IDocsCustomBlockRenderViewport, 'bleedLeft' | 'bleedWidth' | 'contentHeight' | 'contentWidth' | 'height' | 'pageContentWidth' | 'viewScale' | 'viewportHeight'>>;
-interface IDocFloatDomRuntimeParam extends IDocFloatDom {
+interface IDocFloatDomRuntimeGeometry {
customBlockRenderViewport?: IDocFloatDomRuntimeViewport;
- transform?: Partial<ITransformState>;
- transforms?: Array<Partial<ITransformState>>;
+ hidden?: boolean;
+ transform?: Nullable<ITransformState>;
+ transforms?: Nullable<ITransformState[]>;
}
-export function mergeDocFloatDomRuntimeProps(existingProps: Record<string, unknown> | undefined, param: IDocFloatDomRuntimeParam): Record<string, unknown> | undefined {
+export function mergeDocFloatDomRuntimeProps(existingProps: Record<string, unknown> | undefined, param: IDocFloatDomRuntimeGeometry): Record<string, unknown> | undefined {
const customBlockRenderViewport = pickValidCustomBlockRenderViewport(param.customBlockRenderViewport);
if (!customBlockRenderViewport) {
return existingProps;
@@ -157,6 +159,9 @@ function isNonNegativeNumber(value: unknown): value is number {
export class DocFloatDomController extends Disposable {
private _domLayerInfoMap = new Map<string, ICanvasFloatDomInfo>();
+ private _pendingRuntimeGeometry = new Map<string, IDocFloatDomRuntimeGeometry>();
+ private _pendingRuntimeGeometryInsert = new Map<string, IDrawingSearch>();
+ private _pendingRuntimeGeometryRefresh = new Map<string, IDisposable>();
constructor(
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@@ -164,7 +169,8 @@ export class DocFloatDomController extends Disposable {
@Inject(DrawingRenderService) private readonly _drawingRenderService: DrawingRenderService,
@Inject(CanvasFloatDomService) private readonly _canvasFloatDomService: CanvasFloatDomService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @ICommandService private readonly _commandService: ICommandService
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(DocRefreshDrawingsService) private readonly _docRefreshDrawingsService: DocRefreshDrawingsService
) {
super();
@@ -172,15 +178,33 @@ export class DocFloatDomController extends Disposable {
}
override dispose(): void {
+ this._pendingRuntimeGeometry.clear();
+ this._pendingRuntimeGeometryInsert.clear();
+ for (const disposable of this._pendingRuntimeGeometryRefresh.values()) {
+ disposable.dispose();
+ }
+ this._pendingRuntimeGeometryRefresh.clear();
super.dispose();
}
private _initialize() {
+ this._renderLifecycleListener();
this._drawingAddRemoveListener();
this._drawingRuntimePropsListener();
this._initScrollAndZoomEvent();
}
+ private _renderLifecycleListener(): void {
+ this.disposeWithMe(this._renderManagerService.disposed$.subscribe((unitId) => {
+ this._disposePendingRuntimeGeometryRefresh(unitId);
+ }));
+ this.disposeWithMe(this._renderManagerService.created$.subscribe((render) => {
+ if (this._hasPendingRuntimeGeometryForUnit(render.unitId)) {
+ this._refreshDrawingsFromCurrentLayout(render.unitId);
+ }
+ }));
+ }
+
private _getSceneAndTransformerByDrawingSearch(unitId: Nullable<string>) {
if (unitId == null) {
return;
@@ -202,7 +226,27 @@ export class DocFloatDomController extends Disposable {
private _drawingAddRemoveListener() {
this.disposeWithMe(
this._drawingManagerService.add$.subscribe((params) => {
- this._insertRects(params);
+ const ready: IDrawingSearch[] = [];
+ const refreshUnitIds = new Set<string>();
+ for (const param of params) {
+ const drawing = this._drawingManagerService.getDrawingByParam(param);
+ if (
+ isEmbedFloatDomRuntimeParam(drawing) &&
+ this._univerInstanceService.getUnit(param.unitId, UniverInstanceType.UNIVER_DOC) != null
+ ) {
+ this._pendingRuntimeGeometryInsert.set(param.drawingId, param);
+ refreshUnitIds.add(param.unitId);
+ if (this._pendingRuntimeGeometry.has(param.drawingId)) {
+ ready.push(param);
+ }
+ } else {
+ ready.push(param);
+ }
+ }
+ this._insertRects(ready);
+ for (const unitId of refreshUnitIds) {
+ this._refreshDrawingsFromCurrentLayout(unitId);
+ }
})
);
@@ -215,34 +259,85 @@ export class DocFloatDomController extends Disposable {
);
}
+ private _refreshDrawingsFromCurrentLayout(unitId: string): void {
+ const render = this._renderManagerService.getRenderUnitById(unitId);
+ if (
+ render == null ||
+ render.type !== UniverInstanceType.UNIVER_DOC ||
+ render.isDisposed()
+ ) {
+ return;
+ }
+
+ const skeleton = render.with(DocSkeletonManagerService).getSkeleton();
+ if (skeleton != null) {
+ if (!this._pendingRuntimeGeometryRefresh.has(unitId)) {
+ const subscription = skeleton.dirty$.subscribe(() => {
+ if (!this._hasPendingRuntimeGeometryForUnit(unitId)) {
+ this._disposePendingRuntimeGeometryRefresh(unitId);
+ return;
+ }
+ this._docRefreshDrawingsService.refreshDrawings(skeleton);
+ });
+ this._pendingRuntimeGeometryRefresh.set(
+ unitId,
+ toDisposable(() => subscription.unsubscribe())
+ );
+ }
+ this._docRefreshDrawingsService.refreshDrawings(skeleton);
+ }
+ }
+
+ private _hasPendingRuntimeGeometryForUnit(unitId: string): boolean {
+ for (const pending of this._pendingRuntimeGeometryInsert.values()) {
+ if (pending.unitId === unitId) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private _disposePendingRuntimeGeometryRefresh(unitId: string): void {
+ this._pendingRuntimeGeometryRefresh.get(unitId)?.dispose();
+ this._pendingRuntimeGeometryRefresh.delete(unitId);
+ }
+
private _insertRects(params: IDrawingSearch[]) {
- (params).forEach(async (param) => {
+ for (const param of params) {
const { unitId } = param;
const documentDataModel = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
if (!documentDataModel) {
- return;
+ continue;
}
const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
if (renderObject == null) {
- return;
+ continue;
}
const rectParam = this._drawingManagerService.getDrawingByParam(param) as IDocFloatDom;
if (rectParam == null) {
- return;
+ continue;
}
- const rects = await this._drawingRenderService.renderFloatDom(rectParam, renderObject.scene);
+ const preserveRuntimeGeometry = isEmbedFloatDomRuntimeParam(rectParam);
+ const publishedRuntimeParam = this._pendingRuntimeGeometry.get(param.drawingId);
+ if (
+ preserveRuntimeGeometry &&
+ (publishedRuntimeParam == null || this._pendingRuntimeGeometryInsert.get(param.drawingId) !== param)
+ ) {
+ continue;
+ }
+
+ const rects = this._drawingRenderService.renderFloatDom(rectParam, renderObject.scene);
if (rects == null || rects.length === 0) {
- return;
+ continue;
}
for (const rect of rects) {
- const runtimeParam = rectParam as IDocFloatDomRuntimeParam;
+ const runtimeParam: IDocFloatDomRuntimeGeometry = publishedRuntimeParam ?? rectParam;
const runtimeViewport = pickValidCustomBlockRenderViewport(runtimeParam.customBlockRenderViewport);
- const preserveRuntimeGeometry = isEmbedFloatDomRuntimeParam(runtimeParam);
syncRectWithRuntimeParam(rect, runtimeParam, runtimeViewport, undefined, preserveRuntimeGeometry);
const runtimeTransform = runtimeViewport || preserveRuntimeGeometry ? createTransformFromRect(rect) : undefined;
this._addHoverForRect(rect);
@@ -266,7 +361,7 @@ export class DocFloatDomController extends Disposable {
position$,
id: rectParam.drawingId,
componentKey: rectParam.componentKey,
- contentBox: isSheetLikeEmbedFloatDomRuntimeParam(runtimeParam)
+ contentBox: isSheetLikeEmbedFloatDomRuntimeParam(rectParam)
? { contentInset: 0, wrapperInset: 0 }
: undefined,
eventPassThrough: preserveRuntimeGeometry ? false : undefined,
@@ -284,7 +379,7 @@ export class DocFloatDomController extends Disposable {
canvas.dispatchEvent(new WheelEvent(evt.type, evt));
},
data,
- props: mergeDocFloatDomRuntimeProps(undefined, rectParam as IDocFloatDomRuntimeParam),
+ props: mergeDocFloatDomRuntimeProps(undefined, rectParam),
unitId,
});
@@ -306,7 +401,12 @@ export class DocFloatDomController extends Disposable {
scrollListener && disposableCollection.add(scrollListener);
this._domLayerInfoMap.set(rectParam.drawingId, info);
}
- });
+ this._pendingRuntimeGeometry.delete(param.drawingId);
+ this._pendingRuntimeGeometryInsert.delete(param.drawingId);
+ if (!this._hasPendingRuntimeGeometryForUnit(unitId)) {
+ this._disposePendingRuntimeGeometryRefresh(unitId);
+ }
+ }
}
private _drawingRuntimePropsListener() {
@@ -314,11 +414,28 @@ export class DocFloatDomController extends Disposable {
this._drawingManagerService.refreshTransform$.subscribe((params) => {
params.forEach((param) => {
const floatDomInfo = this._domLayerInfoMap.get(param.drawingId);
- if (!floatDomInfo || floatDomInfo.unitId !== param.unitId) {
+ if (!floatDomInfo) {
+ const pendingInsert = this._pendingRuntimeGeometryInsert.get(param.drawingId);
+ const drawing = this._drawingManagerService.getDrawingByParam(param);
+ if (pendingInsert != null || isEmbedFloatDomRuntimeParam(drawing)) {
+ if (param.hidden === true) {
+ return;
+ }
+ this._pendingRuntimeGeometry.set(param.drawingId, param);
+ if (pendingInsert != null) {
+ this._insertRects([pendingInsert]);
+ }
+ }
+ return;
+ }
+ if (floatDomInfo.unitId !== param.unitId) {
+ return;
+ }
+ if (floatDomInfo.preserveRuntimeGeometry && param.hidden === true) {
return;
}
- const runtimeParam = param as IDocFloatDomRuntimeParam;
+ const runtimeParam: IDocFloatDomRuntimeGeometry = param;
const runtimeViewport = pickValidCustomBlockRenderViewport(runtimeParam.customBlockRenderViewport);
if (runtimeViewport) {
floatDomInfo.runtimeViewport = runtimeViewport;
@@ -343,7 +460,7 @@ export class DocFloatDomController extends Disposable {
const currentProps = this._canvasFloatDomService.domLayers.find(([id]) => id === param.drawingId)?.[1].props;
this._canvasFloatDomService.updateFloatDom(param.drawingId, {
- props: mergeDocFloatDomRuntimeProps(currentProps, param as IDocFloatDomRuntimeParam),
+ props: mergeDocFloatDomRuntimeProps(currentProps, param),
});
});
})
@@ -369,6 +486,12 @@ export class DocFloatDomController extends Disposable {
}
private _removeDom(id: string) {
+ const pendingUnitId = this._pendingRuntimeGeometryInsert.get(id)?.unitId;
+ this._pendingRuntimeGeometry.delete(id);
+ this._pendingRuntimeGeometryInsert.delete(id);
+ if (pendingUnitId != null && !this._hasPendingRuntimeGeometryForUnit(pendingUnitId)) {
+ this._disposePendingRuntimeGeometryRefresh(pendingUnitId);
+ }
const info = this._domLayerInfoMap.get(id);
if (!info) {
return;
@@ -480,7 +603,7 @@ export class DocFloatDomController extends Disposable {
function syncRectWithRuntimeParam(
rect: Rect,
- param: IDocFloatDomRuntimeParam,
+ param: IDocFloatDomRuntimeGeometry,
fallbackViewport?: IDocFloatDomRuntimeViewport,
fallbackTransform?: Partial<ITransformState>,
preserveRuntimeGeometry?: boolean
@@ -495,7 +618,7 @@ function syncRectWithRuntimeParam(
}
function getRuntimeTransform(
- param: IDocFloatDomRuntimeParam,
+ param: IDocFloatDomRuntimeGeometry,
rect: Rect,
fallbackViewport?: IDocFloatDomRuntimeViewport,
fallbackTransform?: Partial<ITransformState>,
@@ -537,7 +660,11 @@ function getRuntimeTransform(
};
}
-function isEmbedFloatDomRuntimeParam(param: IDocFloatDomRuntimeParam): boolean {
+function isEmbedFloatDomRuntimeParam(param: unknown): param is IDocFloatDom {
+ if (param == null || typeof param !== 'object' || !('data' in param)) {
+ return false;
+ }
+
const data = param.data;
if (!data || typeof data !== 'object') {
return false;
@@ -547,7 +674,7 @@ function isEmbedFloatDomRuntimeParam(param: IDocFloatDomRuntimeParam): boolean {
return candidate.version === 1 && typeof candidate.embedId === 'string' && typeof candidate.hostAnchorId === 'string';
}
-function isSheetLikeEmbedFloatDomRuntimeParam(param: IDocFloatDomRuntimeParam): boolean {
+function isSheetLikeEmbedFloatDomRuntimeParam(param: unknown): param is IDocFloatDom {
if (!isEmbedFloatDomRuntimeParam(param)) {
return false;
}
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 ccc62fe1f3..5f50a9fb15 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
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { DocumentDrawingPublicationProgress } from '../doc-drawing-transform-update.controller';
import {
AlignTypeH,
AlignTypeV,
@@ -26,7 +27,9 @@ import { Liquid, setDocsTableRenderViewportProvider } from '@univerjs/engine-ren
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getDocsTableCellAnchorContext } from '../../doc-drawing-transformer-update.controller';
import {
+ DocDrawingPublicationTracker,
DocDrawingTransformUpdateController,
+
getDocsDrawingBehindText,
getDocsDrawingClipPage,
getDocsDrawingPageClipBounds,
@@ -41,6 +44,113 @@ describe('DocDrawingTransformUpdateController', () => {
setDocsTableRenderViewportProvider(null);
});
+ it('refreshes only incremental publications that can change drawing transforms', () => {
+ const drawing = {};
+ const pages = [
+ { headerId: '', footerId: '', pageWidth: 100, skeDrawings: new Map([['cover', drawing]]), skeTables: new Map(), skeColumnGroups: new Map() },
+ { headerId: '', footerId: '', pageWidth: 100, skeDrawings: new Map(), skeTables: new Map(), skeColumnGroups: new Map() },
+ { headerId: '', footerId: '', pageWidth: 100, skeDrawings: new Map([['later', drawing]]), skeTables: new Map(), skeColumnGroups: new Map() },
+ ];
+ const skeleton = {
+ getSkeletonData: () => ({
+ pages,
+ skeHeaders: new Map(),
+ skeFooters: new Map(),
+ }),
+ };
+ const tracker = new DocDrawingPublicationTracker();
+ const progress = (overrides: Partial<DocumentDrawingPublicationProgress>): DocumentDrawingPublicationProgress => ({
+ generation: 1,
+ didPublish: true,
+ didPublishAnchor: false,
+ publishedPageCount: 1,
+ reason: 'initial',
+ complete: false,
+ ...overrides,
+ });
+
+ expect(tracker.shouldRefresh(skeleton, progress({}))).toBe(true);
+ expect(tracker.shouldRefresh(skeleton, progress({ publishedPageCount: 2 }))).toBe(false);
+ expect(tracker.shouldRefresh(skeleton, progress({ publishedPageCount: 3 }))).toBe(true);
+ expect(tracker.shouldRefresh(skeleton, progress({
+ generation: 2,
+ reason: 'edit',
+ publishedPageCount: 3,
+ }))).toBe(false);
+ expect(tracker.shouldRefresh(skeleton, progress({
+ generation: 2,
+ reason: 'edit',
+ didPublishAnchor: true,
+ publishedPageCount: 3,
+ }))).toBe(true);
+ });
+
+ it('refreshes when a later anchor resolves a drawing onto an already published page', () => {
+ const firstPageDrawings = new Map();
+ const pages = [
+ { headerId: '', footerId: '', pageWidth: 100, skeDrawings: firstPageDrawings, skeTables: new Map(), skeColumnGroups: new Map() },
+ { headerId: '', footerId: '', pageWidth: 100, skeDrawings: new Map(), skeTables: new Map(), skeColumnGroups: new Map() },
+ ];
+ const skeleton = {
+ getSkeletonData: () => ({
+ pages,
+ skeHeaders: new Map(),
+ skeFooters: new Map(),
+ }),
+ };
+ const tracker = new DocDrawingPublicationTracker();
+ const progress = (publishedPageCount: number): DocumentDrawingPublicationProgress => ({
+ generation: 1,
+ didPublish: true,
+ didPublishAnchor: false,
+ publishedPageCount,
+ reason: 'edit',
+ complete: false,
+ });
+
+ expect(tracker.shouldRefresh(skeleton, progress(1))).toBe(false);
+ expect(tracker.shouldRefresh(skeleton, progress(2))).toBe(false);
+
+ firstPageDrawings.set('late-drawing', {});
+
+ expect(tracker.shouldRefresh(skeleton, progress(2))).toBe(true);
+ });
+
+ it('refreshes when a published column group contains drawings', () => {
+ const nestedPage = {
+ skeDrawings: new Map([['column-drawing', {}]]),
+ skeTables: new Map(),
+ skeColumnGroups: new Map(),
+ };
+ const pages = [{
+ headerId: '',
+ footerId: '',
+ pageWidth: 100,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ skeColumnGroups: new Map([['column-group', {
+ columns: [{ page: nestedPage }],
+ }]]),
+ }];
+ const skeleton = {
+ getSkeletonData: () => ({
+ pages,
+ skeHeaders: new Map(),
+ skeFooters: new Map(),
+ }),
+ };
+ const tracker = new DocDrawingPublicationTracker();
+
+ expect(tracker.shouldRefresh(skeleton, {
+ generation: 1,
+ didPublish: true,
+ didPublishAnchor: false,
+ publishedPageCount: 1,
+ reason: 'initial',
+ complete: false,
+ })).toBe(true);
+ });
+
it('projects drawings in table cells through table, row, cell and scroll offsets', () => {
setDocsTableRenderViewportProvider((unitId, tableId) => {
if (unitId !== 'unit-1' || tableId !== 'table-1') {
@@ -118,12 +228,16 @@ describe('DocDrawingTransformUpdateController', () => {
it('refreshes normal, table-cell, header, and multi-transform drawings into drawing notifications', () => {
const selectedShape = {};
+ const currentDrawings: Record<string, unknown> = {};
const transformer = {
getSelectedObjectMap: vi.fn(() => new Map([['multi-drawing', selectedShape]])),
setSelectedControl: vi.fn(),
};
const context = {
unitId: 'unit-1',
+ unit: {
+ getSnapshot: vi.fn(() => ({ drawings: currentDrawings })),
+ },
mainComponent: {
left: 5,
top: 7,
@@ -150,7 +264,7 @@ describe('DocDrawingTransformUpdateController', () => {
removeNotification: vi.fn(),
addNotification: vi.fn(),
};
- const controller = Object.create(DocDrawingTransformUpdateController.prototype) as any;
+ const controller = Object.create(DocDrawingTransformUpdateController.prototype);
controller._context = context;
controller._drawingManagerService = drawingManagerService;
controller._liquid = new Liquid();
@@ -183,6 +297,16 @@ describe('DocDrawingTransformUpdateController', () => {
},
},
};
+ currentDrawings['page-relative-drawing'] = {
+ ...pageRelativeDrawing.drawingOrigin,
+ behindDoc: BooleanNumber.FALSE,
+ docTransform: {
+ angle: 6,
+ size: { width: 31, height: 41 },
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 109 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 98 },
+ },
+ };
const squareDrawing = {
...normalDrawing,
drawingId: 'square-drawing',
@@ -226,6 +350,16 @@ describe('DocDrawingTransformUpdateController', () => {
docTransform: defaultDocTransform,
},
};
+ const columnDrawing = {
+ ...tableCellDrawing,
+ aLeft: 2,
+ aTop: 3,
+ drawingId: 'column-drawing',
+ };
+ const columnTableCellDrawing = {
+ ...tableCellDrawing,
+ drawingId: 'column-table-cell-drawing',
+ };
const inlineDrawing = {
aLeft: 15,
aTop: 25,
@@ -277,6 +411,39 @@ describe('DocDrawingTransformUpdateController', () => {
cells: [cell],
}],
};
+ const columnTableCell = {
+ left: 3,
+ marginLeft: 1,
+ marginTop: 1,
+ skeDrawings: new Map([['column-table-cell-drawing', columnTableCellDrawing]]),
+ skeTables: new Map(),
+ skeColumnGroups: new Map(),
+ };
+ const columnTable = {
+ left: 4,
+ top: 5,
+ tableId: 'column-table#-#0',
+ rows: [{
+ top: 2,
+ cells: [columnTableCell],
+ }],
+ };
+ const columnPage = {
+ marginLeft: 0,
+ marginTop: 0,
+ skeDrawings: new Map([['column-drawing', columnDrawing]]),
+ skeTables: new Map([['column-table', columnTable]]),
+ skeColumnGroups: new Map(),
+ };
+ const columnGroup = {
+ left: 50,
+ top: 60,
+ columns: [{
+ left: 8,
+ top: 9,
+ page: columnPage,
+ }],
+ };
const page = {
headerId: 'header-1',
pageWidth: 200,
@@ -293,6 +460,7 @@ describe('DocDrawingTransformUpdateController', () => {
['multi-drawing', multiDrawingOnPage],
]),
skeTables: [table],
+ skeColumnGroups: new Map([['column-group', columnGroup]]),
};
const headerPage = {
marginTop: 19,
@@ -324,8 +492,8 @@ describe('DocDrawingTransformUpdateController', () => {
}),
expect.objectContaining({
drawingId: 'page-relative-drawing',
- behindText: true,
- transform: expect.objectContaining({ left: 104, top: 95, width: 30, height: 40, angle: 5 }),
+ behindText: false,
+ transform: expect.objectContaining({ left: 114, top: 105, width: 31, height: 41, angle: 6 }),
}),
expect.objectContaining({
drawingId: 'square-drawing',
@@ -343,6 +511,14 @@ describe('DocDrawingTransformUpdateController', () => {
drawingId: 'cell-drawing',
transform: expect.objectContaining({ left: 56, top: 69, width: 11, height: 12, angle: 0 }),
}),
+ expect.objectContaining({
+ drawingId: 'column-drawing',
+ transform: expect.objectContaining({ left: 76, top: 92, width: 11, height: 12, angle: 0 }),
+ }),
+ expect.objectContaining({
+ drawingId: 'column-table-cell-drawing',
+ transform: expect.objectContaining({ left: 83, top: 99, width: 11, height: 12, angle: 0 }),
+ }),
expect.objectContaining({
drawingId: 'stale-normal',
hidden: true,
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 5ccf677e74..541ccae9a0 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
@@ -47,6 +47,11 @@ function createController(options: {
const commandHandlers: Array<(command: { id: string; params?: Record<string, unknown> }) => void> = [];
let editArea = options.editArea ?? DocumentEditArea.BODY;
let isFocusing = options.isFocusing ?? true;
+ let focusDrawings: Array<{ unitId: string; subUnitId: string; drawingId: string }> = [];
+
+ focus$.subscribe((drawings) => {
+ focusDrawings = drawings ?? [];
+ });
const transformer = {
changeEnd$,
@@ -155,7 +160,7 @@ function createController(options: {
update$,
getDrawingByParam: vi.fn(({ drawingId }: { drawingId: string }) => options.drawings?.[drawingId]),
focusDrawing: vi.fn(),
- getFocusDrawings: vi.fn(() => []),
+ getFocusDrawings: vi.fn(() => focusDrawings),
};
const contextService = {
setContextValue: vi.fn(),
@@ -569,6 +574,32 @@ describe('DocDrawingUpdateRenderController', () => {
expect(getShape('header-drawing').setOpacity).toHaveBeenLastCalledWith(1);
});
+ it('keeps peer drawings interactive while a drawing owns focus', () => {
+ const {
+ focus$,
+ getShape,
+ scene,
+ } = createController({
+ drawings: {
+ 'body-drawing': {
+ drawingId: 'body-drawing',
+ isMultiTransform: BooleanNumber.FALSE,
+ },
+ 'peer-drawing': {
+ drawingId: 'peer-drawing',
+ isMultiTransform: BooleanNumber.FALSE,
+ },
+ },
+ isFocusing: false,
+ });
+
+ scene.attachTransformerTo.mockClear();
+ focus$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'body-drawing' }]);
+
+ expect(scene.attachTransformerTo).toHaveBeenCalledWith(getShape('body-drawing'));
+ expect(scene.attachTransformerTo).toHaveBeenCalledWith(getShape('peer-drawing'));
+ });
+
it('ignores rich text mutations from other document units', async () => {
const { commandHandlers, getShape, scene } = createController({
drawings: {
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 62f81b5d8a..9e47375185 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
@@ -14,9 +14,23 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ICommandInfo, IDrawingParam, IExecutionOptions, ITransformState } from '@univerjs/core';
+import type { DocumentDataModel, ICommandInfo, IDocDrawingBase, IDrawingParam, IExecutionOptions, ITransformState } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
-import type { Documents, DocumentSkeleton, IDocsCustomBlockRenderViewport, IDocsTableRenderViewport, IDocumentSkeletonHeaderFooter, IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonTable, Image, IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import type {
+ DocumentSkeleton,
+ IDocsCustomBlockRenderViewport,
+ IDocsTableRenderViewport,
+ IDocumentLayoutProgress,
+ IDocumentSkeletonCached,
+ IDocumentSkeletonDrawing,
+ IDocumentSkeletonHeaderFooter,
+ IDocumentSkeletonPage,
+ IDocumentSkeletonRow,
+ IDocumentSkeletonTable,
+ Image,
+ IRenderContext,
+ IRenderModule,
+} from '@univerjs/engine-render';
import {
AlignTypeH,
AlignTypeV,
@@ -35,8 +49,14 @@ import {
import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { IEditorService, SetDocZoomRatioOperation } from '@univerjs/docs-ui';
import { IDrawingManagerService } from '@univerjs/drawing';
-import { getDocsTableRenderViewport, getTableIdAndSliceIndex, Liquid, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';
-import { debounceTime, filter, merge } from 'rxjs';
+import {
+ Documents,
+ getDocsTableRenderViewport,
+ getTableIdAndSliceIndex,
+ Liquid,
+ TRANSFORM_CHANGE_OBSERVABLE_TYPE,
+} from '@univerjs/engine-render';
+import { animationFrames, debounceTime, EMPTY, filter, map, merge, startWith, switchMap, take } from 'rxjs';
import { DocRefreshDrawingsService } from '../../services/doc-refresh-drawings.service';
interface IDrawingParamsWithBehindText {
@@ -64,6 +84,112 @@ interface IDrawingTransformStateWithClipBounds extends ITransformState {
clipBounds?: IDrawingClipBounds;
}
+interface IDrawingPositionContext {
+ unitId: string;
+ page: IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter;
+ docsLeft: number;
+ docsTop: number;
+ pageOffsetLeft: number;
+ pageOffsetTop: number;
+ updateDrawingMap: Record<string, IDrawingParamsWithBehindText>;
+ hostPage?: IDocumentSkeletonPage;
+ clipOffset?: { left: number; top: number };
+}
+
+/**
+ * Overlay drawings do not participate in text layout. While their skeleton
+ * anchor remains valid, use the latest model transform so drag/resize/front-
+ * behind changes can paint immediately without rebuilding document pages.
+ */
+export function getDocsOverlayRuntimeDrawing(
+ skeletonDrawing: Pick<IDocDrawingBase, 'docTransform' | 'layoutType'> & Partial<IDocDrawingBase>,
+ currentDrawing: (Pick<IDocDrawingBase, 'docTransform' | 'layoutType'> & Partial<IDocDrawingBase>) | undefined
+): Pick<IDocDrawingBase, 'docTransform' | 'layoutType'> & Partial<IDocDrawingBase> {
+ return skeletonDrawing.layoutType === PositionedObjectLayoutType.WRAP_NONE &&
+ currentDrawing?.layoutType === PositionedObjectLayoutType.WRAP_NONE
+ ? currentDrawing
+ : skeletonDrawing;
+}
+
+export type DocumentDrawingPublicationProgress = Pick<
+ IDocumentLayoutProgress,
+ 'generation' | 'didPublish' | 'complete' | 'publishedPageCount' | 'reason' | 'didPublishAnchor'
+>;
+
+interface IDocumentDrawingPublicationNestedPage {
+ skeDrawings: ReadonlyMap<string, unknown>;
+ skeTables?: ReadonlyMap<string, {
+ rows: Array<{ cells: IDocumentDrawingPublicationNestedPage[] }>;
+ }>;
+ skeColumnGroups?: ReadonlyMap<string, {
+ columns: Array<{ page: IDocumentDrawingPublicationNestedPage }>;
+ }>;
+}
+
+interface IDocumentDrawingPublicationPage extends IDocumentDrawingPublicationNestedPage {
+ headerId: string;
+ footerId: string;
+ pageWidth: number;
+}
+
+type DocumentDrawingPublicationSkeletonData = Pick<
+ IDocumentSkeletonCached,
+ 'skeHeaders' | 'skeFooters'
+> & { pages: IDocumentDrawingPublicationPage[] };
+
+export class DocDrawingPublicationTracker {
+ private _generation = -1;
+ private _publishedPageCount = 0;
+ private _drawingOccurrenceCount = 0;
+
+ reset(): void {
+ this._generation = -1;
+ this._publishedPageCount = 0;
+ this._drawingOccurrenceCount = 0;
+ }
+
+ shouldRefresh(
+ skeleton: {
+ getSkeletonData: () => DocumentDrawingPublicationSkeletonData | null | undefined | void;
+ },
+ progress: DocumentDrawingPublicationProgress
+ ): boolean {
+ if (!progress.didPublish && !progress.complete) {
+ return false;
+ }
+
+ const isNewGeneration = progress.generation !== this._generation;
+ if (isNewGeneration) {
+ this._generation = progress.generation;
+ this._publishedPageCount = 0;
+ this._drawingOccurrenceCount = 0;
+ }
+
+ const skeletonData = skeleton.getSkeletonData();
+ if (skeletonData == null) {
+ return false;
+ }
+
+ const previousPublishedPageCount = this._publishedPageCount;
+ const publishedPageCount = Math.min(progress.publishedPageCount, skeletonData.pages.length);
+ this._publishedPageCount = Math.max(previousPublishedPageCount, publishedPageCount);
+
+ const drawingOccurrenceCount = countPublishedDrawingOccurrences(skeletonData, publishedPageCount);
+ const didDrawingOccurrencesChange = !(isNewGeneration && progress.reason === 'edit') &&
+ drawingOccurrenceCount !== this._drawingOccurrenceCount;
+ this._drawingOccurrenceCount = drawingOccurrenceCount;
+
+ if (progress.complete || progress.didPublishAnchor || didDrawingOccurrencesChange) {
+ return true;
+ }
+ if (isNewGeneration && progress.reason === 'edit') {
+ return false;
+ }
+
+ return hasNewPublishedPageDrawings(skeletonData, previousPublishedPageCount, publishedPageCount);
+ }
+}
+
export function getDocsDrawingPageClipBounds(config: {
docsLeft: number;
docsTop: number;
@@ -222,9 +348,107 @@ function hasHorizontalTableViewport(viewport: IDocsTableRenderViewport | null |
(viewport.leadingInsetLeft ?? 0) + viewport.contentWidth + (viewport.trailingInsetRight ?? 0) > viewport.viewportWidth;
}
+function hasSkeletonPageDrawings(page: IDocumentDrawingPublicationNestedPage): boolean {
+ if (page.skeDrawings.size > 0) {
+ return true;
+ }
+
+ let hasDrawings = false;
+ page.skeTables?.forEach((table) => {
+ table.rows.forEach((row) => {
+ row.cells.forEach((cell) => {
+ if (hasSkeletonPageDrawings(cell)) {
+ hasDrawings = true;
+ }
+ });
+ });
+ });
+ page.skeColumnGroups?.forEach((columnGroup) => {
+ columnGroup.columns.forEach((column) => {
+ if (hasSkeletonPageDrawings(column.page)) {
+ hasDrawings = true;
+ }
+ });
+ });
+
+ return hasDrawings;
+}
+
+function countSkeletonPageDrawings(page: IDocumentDrawingPublicationNestedPage): number {
+ let count = page.skeDrawings.size;
+ page.skeTables?.forEach((table) => {
+ table.rows.forEach((row) => {
+ row.cells.forEach((cell) => {
+ count += countSkeletonPageDrawings(cell);
+ });
+ });
+ });
+ page.skeColumnGroups?.forEach((columnGroup) => {
+ columnGroup.columns.forEach((column) => {
+ count += countSkeletonPageDrawings(column.page);
+ });
+ });
+ return count;
+}
+
+function countPublishedDrawingOccurrences(
+ skeletonData: DocumentDrawingPublicationSkeletonData,
+ publishedPageCount: number
+): number {
+ let count = 0;
+ for (let index = 0; index < publishedPageCount; index++) {
+ const page = skeletonData.pages[index];
+ count += countSkeletonPageDrawings(page);
+
+ const header = page.headerId == null
+ ? undefined
+ : skeletonData.skeHeaders.get(page.headerId)?.get(page.pageWidth);
+ if (header != null) {
+ count += countSkeletonPageDrawings(header);
+ }
+
+ const footer = page.footerId == null
+ ? undefined
+ : skeletonData.skeFooters.get(page.footerId)?.get(page.pageWidth);
+ if (footer != null) {
+ count += countSkeletonPageDrawings(footer);
+ }
+ }
+ return count;
+}
+
+function hasNewPublishedPageDrawings(
+ skeletonData: DocumentDrawingPublicationSkeletonData,
+ startPageIndex: number,
+ publishedPageCount: number
+): boolean {
+ for (let index = startPageIndex; index < publishedPageCount; index++) {
+ const page = skeletonData.pages[index];
+ if (hasSkeletonPageDrawings(page)) {
+ return true;
+ }
+
+ const header = page.headerId == null
+ ? undefined
+ : skeletonData.skeHeaders.get(page.headerId)?.get(page.pageWidth);
+ if (header != null && hasSkeletonPageDrawings(header)) {
+ return true;
+ }
+
+ const footer = page.footerId == null
+ ? undefined
+ : skeletonData.skeFooters.get(page.footerId)?.get(page.pageWidth);
+ if (footer != null && hasSkeletonPageDrawings(footer)) {
+ return true;
+ }
+ }
+ return false;
+}
+
export class DocDrawingTransformUpdateController extends Disposable implements IRenderModule {
private _liquid = new Liquid();
private _changesetDrawingRefreshScheduled = false;
+ private readonly _publicationTracker = new DocDrawingPublicationTracker();
constructor(
private readonly _context: IRenderContext<DocumentDataModel>,
@@ -251,12 +475,45 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
private _initialRenderRefresh() {
this.disposeWithMe(
- this._docSkeletonManagerService.currentSkeleton$.subscribe((documentSkeleton) => {
- if (documentSkeleton == null) {
- return;
- }
+ this._docSkeletonManagerService.currentSkeleton$.pipe(
+ switchMap((documentSkeleton) => {
+ this._publicationTracker.reset();
+
+ if (documentSkeleton == null) {
+ return EMPTY;
+ }
+
+ this._refreshDrawing(documentSkeleton);
+ // The document component is attached offscreen before it is positioned. Bind once
+ // it becomes renderable so drawings never expose their temporary origin transform.
+ const positionRefresh$ = animationFrames().pipe(
+ startWith(null),
+ map(() => this._context.mainComponent),
+ filter((documentComponent): documentComponent is Documents => documentComponent instanceof Documents &&
+ documentComponent.left > -10000 &&
+ documentComponent.top > -10000),
+ take(1),
+ switchMap((documentComponent) => fromEventSubject(documentComponent.onTransformChange$).pipe(
+ filter((evt) => evt.type === TRANSFORM_CHANGE_OBSERVABLE_TYPE.translate &&
+ 'left' in evt.value &&
+ 'left' in evt.preValue &&
+ (evt.value.left !== evt.preValue.left || evt.value.top !== evt.preValue.top)),
+ map(() => ({ documentSkeleton, progress: null })),
+ startWith({ documentSkeleton, progress: null })
+ ))
+ );
- this._refreshDrawing(documentSkeleton);
+ return merge(
+ documentSkeleton.layoutProgress$.pipe(
+ map((progress) => ({ documentSkeleton, progress }))
+ ),
+ positionRefresh$
+ );
+ })
+ ).subscribe(({ documentSkeleton, progress }) => {
+ if (progress == null || this._publicationTracker.shouldRefresh(documentSkeleton, progress)) {
+ this._refreshDrawing(documentSkeleton);
+ }
})
);
@@ -375,63 +632,15 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
*/
for (let i = 0, len = pages.length; i < len; i++) {
const page = pages[i];
- const { headerId, footerId, pageWidth } = page;
-
- if (headerId) {
- const headerPage = skeHeaders.get(headerId)?.get(pageWidth);
-
- if (headerPage) {
- this._calculateDrawingPosition(
- unitId,
- headerPage,
- docsLeft,
- docsTop,
- updateDrawingMap,
- headerPage.marginTop,
- page.marginLeft,
- page
- );
- this._calculateTableCellDrawingPositions(
- unitId,
- headerPage,
- docsLeft,
- docsTop,
- updateDrawingMap,
- headerPage.marginTop,
- page.marginLeft
- );
- }
- }
-
- if (footerId) {
- const footerPage = skeFooters.get(footerId)?.get(pageWidth);
-
- if (footerPage) {
- const footerTop = page.pageHeight - page.marginBottom + footerPage.marginTop;
- this._calculateDrawingPosition(
- unitId,
- footerPage,
- docsLeft,
- docsTop,
- updateDrawingMap,
- footerTop,
- page.marginLeft,
- page
- );
- this._calculateTableCellDrawingPositions(
- unitId,
- footerPage,
- docsLeft,
- docsTop,
- updateDrawingMap,
- footerTop,
- page.marginLeft
- );
- }
- }
-
- this._calculateDrawingPosition(unitId, page, docsLeft, docsTop, updateDrawingMap, page.marginTop, page.marginLeft);
- this._calculateTableCellDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, page.marginTop, page.marginLeft);
+ this._collectPublishedPageDrawingPositions(
+ unitId,
+ page,
+ skeHeaders,
+ skeFooters,
+ docsLeft,
+ docsTop,
+ updateDrawingMap
+ );
this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
}
@@ -454,6 +663,96 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
this._handleMultiDrawingsTransform(multiDrawings as unknown as IDrawingParam[]);
}
+ private _collectPublishedPageDrawingPositions(
+ unitId: string,
+ page: IDocumentSkeletonPage,
+ skeHeaders: IDocumentSkeletonCached['skeHeaders'],
+ skeFooters: IDocumentSkeletonCached['skeFooters'],
+ docsLeft: number,
+ docsTop: number,
+ updateDrawingMap: Record<string, IDrawingParamsWithBehindText>
+ ): void {
+ const { headerId, footerId, pageWidth } = page;
+ const headerPage = headerId ? skeHeaders.get(headerId)?.get(pageWidth) : undefined;
+ if (headerPage != null) {
+ this._collectSegmentDrawingPositions(
+ unitId,
+ headerPage,
+ docsLeft,
+ docsTop,
+ updateDrawingMap,
+ headerPage.marginTop,
+ page.marginLeft,
+ page
+ );
+ }
+
+ const footerPage = footerId ? skeFooters.get(footerId)?.get(pageWidth) : undefined;
+ if (footerPage != null) {
+ const footerTop = page.pageHeight - page.marginBottom + footerPage.marginTop;
+ this._collectSegmentDrawingPositions(
+ unitId,
+ footerPage,
+ docsLeft,
+ docsTop,
+ updateDrawingMap,
+ footerTop,
+ page.marginLeft,
+ page
+ );
+ }
+
+ this._collectSegmentDrawingPositions(
+ unitId,
+ page,
+ docsLeft,
+ docsTop,
+ updateDrawingMap,
+ page.marginTop,
+ page.marginLeft
+ );
+ }
+
+ private _collectSegmentDrawingPositions(
+ unitId: string,
+ page: IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter,
+ docsLeft: number,
+ docsTop: number,
+ updateDrawingMap: Record<string, IDrawingParamsWithBehindText>,
+ marginTop: number,
+ marginLeft: number,
+ hostPage?: IDocumentSkeletonPage
+ ): void {
+ this._calculateDrawingPosition(
+ unitId,
+ page,
+ docsLeft,
+ docsTop,
+ updateDrawingMap,
+ marginTop,
+ marginLeft,
+ hostPage
+ );
+ this._calculateTableCellDrawingPositions(
+ unitId,
+ page,
+ docsLeft,
+ docsTop,
+ updateDrawingMap,
+ marginTop,
+ marginLeft
+ );
+ this._calculateColumnGroupDrawingPositions(
+ unitId,
+ page,
+ docsLeft,
+ docsTop,
+ updateDrawingMap,
+ marginTop,
+ marginLeft
+ );
+ }
+
private _getStaleNonMultiDrawings(
unitId: string,
updateDrawingMap: Record<string, IDrawingParamsWithBehindText>
@@ -532,78 +831,18 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
marginLeft,
} as IDocumentSkeletonPage);
- skeDrawings.forEach((drawing) => {
- const { aLeft, aTop, height, width, angle, drawingId, drawingOrigin } = drawing;
- const behindText = getDocsDrawingBehindText({ drawingOrigin, hostPage });
- const { isMultiTransform = BooleanNumber.FALSE } = drawingOrigin;
- const clipDrawing = {
- behindText,
- transform: {
- width,
- height,
- },
- };
- const clipPage = getDocsDrawingClipPage({
- drawing: clipDrawing,
- hostPage,
- page,
- });
- const pageClipBounds = getDocsDrawingPageClipBounds({
- docsLeft,
- docsTop,
- pageOffsetLeft,
- pageOffsetTop,
- clipOffsetLeft: clipOffset?.left,
- clipOffsetTop: clipOffset?.top,
- page: clipPage,
- });
- const pageRelativeAnchorPage = drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_NONE
- ? getDocsPageRelativeDrawingAnchorPage({
- page,
- clipPage,
- hostPage,
- })
- : undefined;
- const pageRelativeLeft = pageRelativeAnchorPage != null
- ? getDocsPageRelativeDrawingLeft({
- hostPage: pageRelativeAnchorPage,
- positionH: drawingOrigin.docTransform.positionH,
- width,
- })
- : undefined;
- const pageRelativeTop = pageRelativeAnchorPage != null
- ? getDocsPageRelativeDrawingTop({
- hostPage: pageRelativeAnchorPage,
- positionV: drawingOrigin.docTransform.positionV,
- height,
- })
- : undefined;
- const transform = {
- left: (pageRelativeLeft ?? aLeft) + docsLeft + (pageRelativeLeft == null ? this._liquid.x : pageOffsetLeft),
- top: (pageRelativeTop ?? aTop) + docsTop + (pageRelativeTop == null ? this._liquid.y : pageOffsetTop),
- width,
- height,
- angle,
- // The layout engine resolves position and size, while flips remain drawing metadata.
- flipX: drawingOrigin.docTransform.flipX,
- flipY: drawingOrigin.docTransform.flipY,
- clipBounds: pageClipBounds,
- } as IDrawingTransformStateWithClipBounds;
- if (updateDrawingMap[drawingId] == null) {
- updateDrawingMap[drawingId] = {
- unitId,
- subUnitId: unitId,
- drawingId,
- behindText,
- transform,
- transforms: [transform],
- customBlockRenderViewport: drawing.customBlockRenderViewport,
- isMultiTransform,
- };
- } else if (isMultiTransform === BooleanNumber.TRUE) {
- updateDrawingMap[drawingId].transforms.push(transform);
- }
- });
+ const drawingPositionContext: IDrawingPositionContext = {
+ unitId,
+ page,
+ docsLeft,
+ docsTop,
+ pageOffsetLeft,
+ pageOffsetTop,
+ updateDrawingMap,
+ hostPage,
+ clipOffset,
+ };
+ skeDrawings.forEach((drawing) => this._collectDrawingPosition(drawing, drawingPositionContext));
this._liquid.restorePagePadding({
marginTop,
@@ -611,6 +850,83 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
} as IDocumentSkeletonPage);
}
+ private _collectDrawingPosition(
+ drawing: IDocumentSkeletonDrawing,
+ context: IDrawingPositionContext
+ ): 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 { angle = skeletonAngle, size } = runtimeDrawing.docTransform;
+ const height = size?.height ?? skeletonHeight;
+ const width = size?.width ?? skeletonWidth;
+ const { left: clipOffsetLeft, top: clipOffsetTop } = context.clipOffset ?? {};
+ const behindText = getDocsDrawingBehindText({ drawingOrigin: runtimeDrawing, hostPage: context.hostPage });
+ const { isMultiTransform = BooleanNumber.FALSE } = runtimeDrawing;
+ const clipPage = getDocsDrawingClipPage({
+ drawing: { behindText, transform: { width, height } },
+ hostPage: context.hostPage,
+ page: context.page,
+ });
+ const clipBounds = getDocsDrawingPageClipBounds({
+ docsLeft: context.docsLeft,
+ docsTop: context.docsTop,
+ pageOffsetLeft: context.pageOffsetLeft,
+ pageOffsetTop: context.pageOffsetTop,
+ clipOffsetLeft,
+ clipOffsetTop,
+ page: clipPage,
+ });
+ const anchorPage = runtimeDrawing.layoutType === PositionedObjectLayoutType.WRAP_NONE
+ ? getDocsPageRelativeDrawingAnchorPage({
+ page: context.page,
+ clipPage,
+ hostPage: context.hostPage,
+ })
+ : undefined;
+ const pageRelativeLeft = anchorPage == null
+ ? undefined
+ : getDocsPageRelativeDrawingLeft({
+ hostPage: anchorPage,
+ positionH: runtimeDrawing.docTransform.positionH,
+ width,
+ });
+ const pageRelativeTop = anchorPage == null
+ ? undefined
+ : getDocsPageRelativeDrawingTop({
+ hostPage: anchorPage,
+ positionV: runtimeDrawing.docTransform.positionV,
+ height,
+ });
+ const transform: IDrawingTransformStateWithClipBounds = {
+ left: (pageRelativeLeft ?? aLeft) + context.docsLeft +
+ (pageRelativeLeft == null ? this._liquid.x : context.pageOffsetLeft),
+ top: (pageRelativeTop ?? aTop) + context.docsTop +
+ (pageRelativeTop == null ? this._liquid.y : context.pageOffsetTop),
+ width,
+ height,
+ angle,
+ flipX: runtimeDrawing.docTransform.flipX,
+ flipY: runtimeDrawing.docTransform.flipY,
+ clipBounds,
+ };
+ const existingDrawing = context.updateDrawingMap[drawingId];
+ if (existingDrawing == null) {
+ context.updateDrawingMap[drawingId] = {
+ unitId: context.unitId,
+ subUnitId: context.unitId,
+ drawingId,
+ behindText,
+ transform,
+ transforms: [transform],
+ customBlockRenderViewport: drawing.customBlockRenderViewport,
+ isMultiTransform,
+ };
+ } else if (isMultiTransform === BooleanNumber.TRUE) {
+ existingDrawing.transforms.push(transform);
+ }
+ }
+
private _calculateTableCellDrawingPositions(
unitId: string,
page: IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter,
@@ -623,6 +939,14 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
page.skeTables?.forEach((table) => {
table.rows.forEach((row) => {
row.cells.forEach((cell) => {
+ if (
+ (cell.skeDrawings?.size ?? 0) === 0 &&
+ (cell.skeTables?.size ?? 0) === 0 &&
+ (cell.skeColumnGroups?.size ?? 0) === 0
+ ) {
+ return;
+ }
+
const cellOffset = getDocsTableCellDrawingOffset(unitId, table, row, cell);
const marginTop = baseMarginTop + cellOffset.top;
const marginLeft = baseMarginLeft + cellOffset.left;
@@ -647,11 +971,69 @@ export class DocDrawingTransformUpdateController extends Disposable implements I
marginTop,
marginLeft
);
+ this._calculateColumnGroupDrawingPositions(
+ unitId,
+ cell,
+ docsLeft,
+ docsTop,
+ updateDrawingMap,
+ marginTop,
+ marginLeft
+ );
});
});
});
}
+ private _calculateColumnGroupDrawingPositions(
+ unitId: string,
+ page: IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter,
+ docsLeft: number,
+ docsTop: number,
+ updateDrawingMap: Record<string, IDrawingParamsWithBehindText>,
+ baseMarginTop: number,
+ baseMarginLeft: number
+ ): void {
+ page.skeColumnGroups?.forEach((columnGroup) => {
+ columnGroup.columns.forEach((column) => {
+ const nestedPage = column.page;
+ const marginTop = baseMarginTop + columnGroup.top + column.top + nestedPage.marginTop;
+ const marginLeft = baseMarginLeft + columnGroup.left + column.left + nestedPage.marginLeft;
+ const clipOffset = { left: marginLeft, top: marginTop };
+
+ this._calculateDrawingPosition(
+ unitId,
+ nestedPage,
+ docsLeft,
+ docsTop,
+ updateDrawingMap,
+ marginTop,
+ marginLeft,
+ undefined,
+ clipOffset
+ );
+ this._calculateTableCellDrawingPositions(
+ unitId,
+ nestedPage,
+ docsLeft,
+ docsTop,
+ updateDrawingMap,
+ marginTop,
+ marginLeft
+ );
+ this._calculateColumnGroupDrawingPositions(
+ unitId,
+ nestedPage,
+ docsLeft,
+ docsTop,
+ updateDrawingMap,
+ marginTop,
+ marginLeft
+ );
+ });
+ });
+ }
+
private _drawingInitializeListener() {
const init = () => {
const skeleton = this._docSkeletonManagerService.getSkeleton();
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 089564f2e6..f92dcc99e5 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
@@ -484,7 +484,8 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
const snapshot = docDataModel.getSnapshot();
const { drawings = {} } = snapshot;
const isEditBody = viewModel.getEditArea() === DocumentEditArea.BODY;
- const isDocInputFocusing = this._docSelectionRenderService.isFocusing;
+ const isDocInteractionFocusing = this._docSelectionRenderService.isFocusing
+ || this._drawingManagerService.getFocusDrawings().some((drawing) => drawing.unitId === unitId);
const readOnlyDrawingIds = new Set<string>();
for (const key of Object.keys(drawings)) {
@@ -503,10 +504,10 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
scene.detachTransformerFrom(shape);
this._setTransformerEditable(shape, editable);
try {
- (shape as Image).setOpacity(isDocInputFocusing ? 0.5 : 1);
+ (shape as Image).setOpacity(isDocInteractionFocusing ? 0.5 : 1);
} catch {
}
- if (!isDocInputFocusing) {
+ if (!isDocInteractionFocusing) {
continue;
}
if (
diff --git a/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts b/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts
index 6a72817439..87b0858ba4 100644
--- a/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts
+++ b/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { DocumentDataModel, IDisposable, Nullable } from '@univerjs/core';
+import type { DocumentDataModel, IDisposable, INeedCheckDisposable, Nullable } from '@univerjs/core';
import type { IDocDrawing } from '@univerjs/docs-drawing';
import type { BaseObject, Scene } from '@univerjs/engine-render';
import {
@@ -56,7 +56,8 @@ export class DocDrawingPopupMenuController extends RxDisposable {
private _initImagePopupMenu = new Set<string>();
private _embeddedRenderUnits = new Set<string>();
private _popupMenuListeners = new Map<string, IDisposable>();
- private _disposePopups: IDisposable[] = [];
+ private _disposePopupsByUnit = new Map<string, INeedCheckDisposable[]>();
+ private _popupTargetKeys = new Map<string, string>();
private _isDrawingPanelOpen = false;
constructor(
@@ -81,13 +82,13 @@ export class DocDrawingPopupMenuController extends RxDisposable {
this._commandService.onCommandExecuted((command) => {
if (command.id === EditDocDrawingOperation.id) {
this._isDrawingPanelOpen = true;
- this._clearPopups();
+ this._clearPopups(undefined, true);
}
if (command.id === SidebarDocDrawingOperation.id) {
const params = command.params as { value?: string } | undefined;
this._isDrawingPanelOpen = params?.value === 'open';
if (this._isDrawingPanelOpen) {
- this._clearPopups();
+ this._clearPopups(undefined, true);
}
}
})
@@ -104,7 +105,7 @@ export class DocDrawingPopupMenuController extends RxDisposable {
this._univerInstanceService.getUnitType(drawing.unitId) === UniverInstanceType.UNIVER_DOC &&
!this._canEditDrawing(drawing.unitId, drawing.drawingId)
)) {
- this._clearPopups();
+ this._clearPopups(undefined, true);
}
}));
@@ -142,14 +143,45 @@ export class DocDrawingPopupMenuController extends RxDisposable {
private _dispose(documentDataModel: DocumentDataModel) {
const unitId = documentDataModel.getUnitId();
- this._clearPopups();
+ this._clearPopups(unitId, true);
this._disposePopupMenuListener(unitId);
this._renderManagerService.removeRender(unitId);
}
- private _clearPopups() {
- this._disposePopups.forEach((dispose) => dispose.dispose());
- this._disposePopups.length = 0;
+ private _clearPopups(unitId?: string, force = false) {
+ if (unitId == null) {
+ [...this._disposePopupsByUnit.keys()].forEach((popupUnitId) => this._clearPopups(popupUnitId, force));
+ return;
+ }
+
+ const popups = this._disposePopupsByUnit.get(unitId);
+ if (!popups) {
+ return;
+ }
+
+ for (let index = popups.length - 1; index >= 0; index -= 1) {
+ const popup = popups[index];
+ if (force || popup.canDispose()) {
+ popup.dispose();
+ popups.splice(index, 1);
+ }
+ }
+
+ if (popups.length === 0) {
+ this._disposePopupsByUnit.delete(unitId);
+ this._popupTargetKeys.delete(unitId);
+ }
+ }
+
+ private _getDisposePopups(unitId: string): INeedCheckDisposable[] {
+ const popups = this._disposePopupsByUnit.get(unitId);
+ if (popups) {
+ return popups;
+ }
+
+ const nextPopups: INeedCheckDisposable[] = [];
+ this._disposePopupsByUnit.set(unitId, nextPopups);
+ return nextPopups;
}
private _create(documentDataModel: Nullable<DocumentDataModel>) {
@@ -174,7 +206,7 @@ export class DocDrawingPopupMenuController extends RxDisposable {
this._popupMenuListeners.get(unitId)?.dispose();
this._popupMenuListeners.delete(unitId);
this._initImagePopupMenu.delete(unitId);
- this._clearPopups();
+ this._clearPopups(unitId, true);
}
private _hasCropObject(scene: Scene) {
@@ -200,22 +232,22 @@ export class DocDrawingPopupMenuController extends RxDisposable {
return;
}
- const disposePopups: IDisposable[] = this._disposePopups;
const subscriptions = [
transformer.createControl$.subscribe(() => {
if (this._hasCropObject(scene)) {
+ this._clearPopups(unitId, true);
return;
}
const selectedObjects = transformer.getSelectedObjectMap();
- disposePopups.forEach((dispose) => dispose.dispose());
- disposePopups.length = 0;
if (this._isDrawingPanelOpen || selectedObjects.size > 1) {
+ this._clearPopups(unitId, this._isDrawingPanelOpen);
return;
}
const object = selectedObjects.values().next().value as Nullable<BaseObject>;
if (!object) {
+ this._clearPopups(unitId);
return;
}
@@ -225,13 +257,23 @@ export class DocDrawingPopupMenuController extends RxDisposable {
drawingParam.drawingType === DrawingTypeEnum.DRAWING_DOM ||
drawingParam.drawingType === DrawingTypeEnum.DRAWING_SHAPE
) {
+ this._clearPopups(unitId);
return;
}
- const { unitId, subUnitId, drawingId, drawingType } = drawingParam;
- if (!this._canEditDrawing(unitId, drawingId)) {
+ const { unitId: drawingUnitId, subUnitId, drawingId, drawingType } = drawingParam;
+ if (!this._canEditDrawing(drawingUnitId, drawingId)) {
+ this._clearPopups(unitId, true);
return;
}
+ const disposePopups = this._disposePopupsByUnit.get(unitId);
+ const popupTargetKey = `${drawingUnitId}:${subUnitId}:${drawingId}`;
+ const previousPopupTargetKey = this._popupTargetKeys.get(unitId);
+ if (previousPopupTargetKey === popupTargetKey && disposePopups && disposePopups.length > 0) {
+ return;
+ }
+
+ this._clearPopups(unitId, previousPopupTargetKey != null);
const isImage = drawingType === DrawingTypeEnum.DRAWING_IMAGE;
// Charts use the document toolbar placement, while retaining chart-specific actions and controls.
const isChart = drawingType === DrawingTypeEnum.DRAWING_CHART;
@@ -242,37 +284,38 @@ export class DocDrawingPopupMenuController extends RxDisposable {
direction: isImage || isChart ? 'top-center' : 'horizontal',
offset: isImage || isChart ? [0, 8] : [2, 0],
extraProps: {
- menuItems: this._getDrawingPopupMenuItems(unitId, subUnitId, drawingId, drawingType),
+ menuItems: this._getDrawingPopupMenuItems(drawingUnitId, subUnitId, drawingId, drawingType),
variant: isImage ? 'doc-floating-toolbar' : isChart ? 'doc-chart-floating-toolbar' : undefined,
- unitId,
+ unitId: drawingUnitId,
subUnitId,
drawingId,
},
},
- unitId
+ drawingUnitId
);
- disposePopups.push(this.disposeWithMe(popup));
+ this.disposeWithMe(popup);
+ this._getDisposePopups(unitId).push(popup);
+ this._popupTargetKeys.set(unitId, popupTargetKey);
const focusDrawings = this._drawingManagerService.getFocusDrawings();
- const alreadyFocused = focusDrawings.find((drawing) => drawing.unitId === unitId && drawing.subUnitId === subUnitId && drawing.drawingId === drawingId);
+ const alreadyFocused = focusDrawings.find((drawing) => drawing.unitId === drawingUnitId && drawing.subUnitId === subUnitId && drawing.drawingId === drawingId);
if (!alreadyFocused) {
- this._drawingManagerService.focusDrawing([{ unitId, subUnitId, drawingId }]);
+ this._drawingManagerService.focusDrawing([{ unitId: drawingUnitId, subUnitId, drawingId }]);
}
}),
transformer.clearControl$.subscribe(() => {
- disposePopups.forEach((dispose) => dispose.dispose());
- disposePopups.length = 0;
- this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, false);
- this._drawingManagerService.focusDrawing(null);
+ this._clearPopups(unitId);
+ queueMicrotask(() => {
+ if (transformer.getSelectedObjectMap().size > 0) {
+ return;
+ }
+ this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, false);
+ this._drawingManagerService.focusDrawing(null);
+ });
}),
transformer.changing$.subscribe(() => {
- disposePopups.forEach((dispose) => dispose.dispose());
- disposePopups.length = 0;
- }),
- transformer.changeStart$.subscribe(() => {
- disposePopups.forEach((dispose) => dispose.dispose());
- disposePopups.length = 0;
+ this._clearPopups(unitId, true);
}),
];
const disposable = toDisposable(() => subscriptions.forEach((subscription) => subscription.unsubscribe()));
diff --git a/packages/docs-drawing/src/controllers/__tests__/doc-drawing.controller.spec.ts b/packages/docs-drawing/src/controllers/__tests__/doc-drawing.controller.spec.ts
index c19d16fea0..4852e88e29 100644
--- a/packages/docs-drawing/src/controllers/__tests__/doc-drawing.controller.spec.ts
+++ b/packages/docs-drawing/src/controllers/__tests__/doc-drawing.controller.spec.ts
@@ -107,7 +107,10 @@ describe('DocDrawingController', () => {
unitId: 'doc-1',
subUnitId: 'doc-1',
data: {
+ mask: expect.objectContaining({ hidden: true }),
+ photo: expect.objectContaining({ hidden: true }),
d2: expect.objectContaining({
+ hidden: true,
docTransform: {
size: { width: 320, height: 180 },
positionH: { posOffset: 12 },
@@ -121,6 +124,7 @@ describe('DocDrawingController', () => {
});
const loadedDocDrawingData = registerDrawingData.mock.calls.at(-1)?.[1];
expect(loadedDocDrawingData?.['doc-1']?.order).toEqual(['mask', 'photo', 'd2']);
+ expect(loadedDocDrawingData?.['doc-1']?.data?.d2).not.toHaveProperty('hidden');
expect(loadedDrawingData?.['doc-1']?.data?.d2).not.toHaveProperty('transform');
capturedResource.onUnLoad('doc-1');
diff --git a/packages/docs-drawing/src/controllers/doc-drawing.controller.ts b/packages/docs-drawing/src/controllers/doc-drawing.controller.ts
index 3d5cb4f135..f4963b38f3 100644
--- a/packages/docs-drawing/src/controllers/doc-drawing.controller.ts
+++ b/packages/docs-drawing/src/controllers/doc-drawing.controller.ts
@@ -157,9 +157,14 @@ export class DocDrawingController extends Disposable {
order: drawingOrderModel,
},
};
+ const renderDrawingData: IDrawingMapItemData<IDocDrawing> = {};
+ for (const [drawingId, drawing] of Object.entries(drawingDataModels)) {
+ renderDrawingData[drawingId] = { ...drawing, hidden: true };
+ }
const renderSubDrawings = {
[subUnitId]: {
...subDrawings[subUnitId],
+ data: renderDrawingData,
order: getDocDrawingRenderOrder(drawingOrderModel, drawingDataModels),
},
};
diff --git a/packages/docs-quick-insert-ui/src/services/__tests__/doc-quick-insert-popup.service.spec.ts b/packages/docs-quick-insert-ui/src/services/__tests__/doc-quick-insert-popup.service.spec.ts
index f0569cb103..0956b03249 100644
--- a/packages/docs-quick-insert-ui/src/services/__tests__/doc-quick-insert-popup.service.spec.ts
+++ b/packages/docs-quick-insert-ui/src/services/__tests__/doc-quick-insert-popup.service.spec.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+import { DocSkeletonManagerService } from '@univerjs/docs';
+import { DocEventManagerService } from '@univerjs/docs-ui';
import { of } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { DeleteSearchKeyCommand } from '../../commands/commands/doc-quick-insert.command';
@@ -65,17 +67,17 @@ function createServiceTestBed() {
const docEventManagerService = {
findParagraphBoundByIndex: vi.fn(() => paragraphBound),
};
+ let layoutInteractionActive = false;
const skeleton = {
findNodeByCharIndex: vi.fn(() => glyph),
findNodePositionByCharIndex: vi.fn(() => undefined),
};
const currentRender = {
with: vi.fn((token: unknown) => {
- const name = (token as { name?: string })?.name;
- if (name === 'DocEventManagerService') {
+ if (token === DocEventManagerService) {
return docEventManagerService;
}
- if (name === 'DocSkeletonManagerService') {
+ if (token === DocSkeletonManagerService) {
return { getSkeleton: () => skeleton };
}
return undefined;
@@ -91,6 +93,16 @@ function createServiceTestBed() {
return disposable;
}),
};
+ const docLayoutInteractionService = {
+ beginInteraction: vi.fn(() => {
+ layoutInteractionActive = true;
+ return {
+ dispose: () => {
+ layoutInteractionActive = false;
+ },
+ };
+ }),
+ };
const commandService = {
syncExecuteCommand: vi.fn(() => true),
};
@@ -107,13 +119,15 @@ function createServiceTestBed() {
} as never,
{
getActiveTextRange: vi.fn(() => activeRange),
- } as never
+ } as never,
+ docLayoutInteractionService as never
);
return {
service,
popupEntries,
commandService,
+ isLayoutInteractionActive: () => layoutInteractionActive,
paragraphBound,
setDataStream: (value: string) => {
dataStream = value;
@@ -159,7 +173,7 @@ describe('DocQuickInsertPopupService', () => {
});
it('shows the popup on an empty line and remounts the keyword placeholder as input state changes', () => {
- const { service, popupEntries, setDataStream } = createServiceTestBed();
+ const { service, popupEntries, isLayoutInteractionActive, setDataStream } = createServiceTestBed();
const popup = {
keyword: '/',
menus$: of([]),
@@ -170,6 +184,7 @@ describe('DocQuickInsertPopupService', () => {
expect(popupEntries).toHaveLength(2);
expect(popupEntries[0].popup.componentKey).toBe(KeywordInputPlaceholder.componentKey);
expect(popupEntries[1].popup.componentKey).toBe(QuickInsertPopup.componentKey);
+ expect(isLayoutInteractionActive()).toBe(true);
expect(service.editPopup).toEqual(expect.objectContaining({ popup, anchor: 0, unitId: 'doc-1' }));
setDataStream('/a');
@@ -192,6 +207,7 @@ describe('DocQuickInsertPopupService', () => {
expect(popupEntries[1].disposable.dispose).toHaveBeenCalledTimes(1);
expect(popupEntries[3].disposable.dispose).toHaveBeenCalledTimes(1);
expect(service.editPopup).toBeNull();
+ expect(isLayoutInteractionActive()).toBe(false);
service.dispose();
});
diff --git a/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts b/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts
index 7212e6448b..752243d99b 100644
--- a/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts
+++ b/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts
@@ -16,19 +16,14 @@
import type { DocumentDataModel, IDisposable, Nullable } from '@univerjs/core';
import type { IInsertTextCommandParams } from '@univerjs/docs';
-import type {
- Documents,
- DocumentSkeleton,
- IBoundRectNoAngle,
- IDocumentSkeletonGlyph,
- ITextRangeWithStyle,
-} from '@univerjs/engine-render';
+import type { Documents, DocumentSkeleton, IBoundRectNoAngle, IDocumentSkeletonGlyph, ITextRangeWithStyle } from '@univerjs/engine-render';
import type { Observable } from 'rxjs';
-import { Disposable, ICommandService, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { Disposable, DisposableCollection, ICommandService, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
import {
DocCanvasPopManagerService,
DocEventManagerService,
+ DocLayoutInteractionService,
getAnchorBounding,
NodePositionConvertToCursor,
} from '@univerjs/docs-ui';
@@ -122,7 +117,7 @@ export class DocQuickInsertPopupService extends Disposable {
mount: () => void;
} | null = null;
- private getDocEventManagerService(unitId: string) {
+ private _getDocEventManagerService(unitId: string) {
return this._renderManagerService.getRenderUnitById(unitId)?.with(DocEventManagerService);
}
@@ -131,7 +126,8 @@ export class DocQuickInsertPopupService extends Disposable {
@Inject(IUniverInstanceService) private readonly _univerInstanceService: IUniverInstanceService,
@Inject(ICommandService) private readonly _commandService: ICommandService,
@Inject(IRenderManagerService) private readonly _renderManagerService: IRenderManagerService,
- @Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService
+ @Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService,
+ @Inject(DocLayoutInteractionService) private readonly _docLayoutInteractionService: DocLayoutInteractionService
) {
super();
@@ -225,7 +221,7 @@ export class DocQuickInsertPopupService extends Disposable {
return null;
}
- const docEventManagerService = this.getDocEventManagerService(unitId);
+ const docEventManagerService = this._getDocEventManagerService(unitId);
return docEventManagerService?.findParagraphBoundByIndex(paragraph.startIndex) ?? null;
}
@@ -318,7 +314,8 @@ export class DocQuickInsertPopupService extends Disposable {
this._inputPlaceholderRenderRoot = this._createInputPlaceholderRenderRoot(() => this._mountInputPlaceholder(unitId, paragraphBound.firstLine));
this._inputPlaceholderRenderRoot.mount();
- const disposable = this._docCanvasPopupManagerService.attachPopupToRect(
+ const layoutInteraction = this._docLayoutInteractionService.beginInteraction();
+ const popupDisposable = this._docCanvasPopupManagerService.attachPopupToRect(
paragraphBound.firstLine,
{
componentKey: QuickInsertPopup.componentKey,
@@ -329,6 +326,9 @@ export class DocQuickInsertPopupService extends Disposable {
},
unitId
);
+ const disposable = new DisposableCollection();
+ disposable.add(popupDisposable);
+ disposable.add(layoutInteraction);
this._editPopup$.next({ disposable, popup, anchor: index, unitId });
}
diff --git a/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertPopup.spec.tsx b/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertPopup.spec.tsx
index 702bfd1e9a..c6465c24f7 100644
--- a/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertPopup.spec.tsx
+++ b/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertPopup.spec.tsx
@@ -32,7 +32,7 @@ import {
LocaleType,
} from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
-import { CutContentCommand, DocCanvasPopManagerService, DocEventManagerService } from '@univerjs/docs-ui';
+import { CutContentCommand, DocCanvasPopManagerService, DocEventManagerService, DocLayoutInteractionService } from '@univerjs/docs-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
import {
ComponentManager,
@@ -102,6 +102,14 @@ class TestDocCanvasPopManagerService {
}
}
+class TestDocLayoutInteractionService {
+ beginInteraction() {
+ return {
+ dispose: () => {},
+ };
+ }
+}
+
class TestRenderManagerService {
getRenderUnitById() {
return {
@@ -154,6 +162,7 @@ function createQuickInsertPopupTestBed(options?: {
injector.add([IconManager, { useClass: IconManager }]);
injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
injector.add([DocCanvasPopManagerService, { useClass: TestDocCanvasPopManagerService as never }]);
+ injector.add([DocLayoutInteractionService, { useClass: TestDocLayoutInteractionService as never }]);
injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
injector.add([DocSelectionManagerService, { useClass: TestDocSelectionManagerService as never }]);
injector.add([DocQuickInsertPopupService, { useClass: DocQuickInsertPopupService }]);
diff --git a/packages/docs-thread-comment-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts b/packages/docs-thread-comment-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts
index bd29979ae2..49fd5dc505 100644
--- a/packages/docs-thread-comment-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts
+++ b/packages/docs-thread-comment-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts
@@ -39,8 +39,8 @@ describe('DocThreadCommentRenderController', () => {
const reRender = vi.fn();
const docRenderController = { reRender };
- const activeCommentId$ = new Subject<any>();
- const hoveredCommentId$ = new Subject<any>();
+ const activeCommentId$ = new BehaviorSubject<any>(undefined);
+ const hoveredCommentId$ = new BehaviorSubject<any>(undefined);
const threadCommentPanelService = {
activeCommentId: { unitId: 'doc-1', subUnitId: DEFAULT_DOC_SUBUNIT_ID, commentId: 'c2' },
activeCommentId$,
@@ -109,6 +109,7 @@ describe('DocThreadCommentRenderController', () => {
themeService as any
);
+ expect(reRender).not.toHaveBeenCalled();
expect(threadCommentModel.addComment).not.toHaveBeenCalled();
const next = (v: any) => v;
diff --git a/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts b/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts
index c773ab53d0..bc21dacb57 100644
--- a/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts
+++ b/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts
@@ -34,7 +34,7 @@ import { DocRenderController } from '@univerjs/docs-ui';
import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService } from '@univerjs/drawing';
import { deserializeThreadCommentAnchor, ThreadCommentAnchorKind, ThreadCommentModel } from '@univerjs/thread-comment';
import { ThreadCommentCanvasOverlay, ThreadCommentPanelService } from '@univerjs/thread-comment-ui';
-import { pairwise, startWith } from 'rxjs';
+import { pairwise, skip, startWith } from 'rxjs';
import { ShowCommentPanelOperation } from '../../commands/operations/show-comment-panel.operation';
const DOC_COMMENT_DRAWING_OVERLAY_KEY = 'doc-thread-comment-drawing-overlay';
@@ -76,6 +76,7 @@ export class DocThreadCommentRenderController extends Disposable implements IRen
this._threadCommentPanelService.activeCommentId$,
this._threadCommentPanelService.hoveredCommentId$,
].forEach((observable) => this.disposeWithMe(observable.pipe(
+ skip(1),
startWith(undefined),
pairwise()
).subscribe(([previous, current]) => {
diff --git a/packages/docs-ui/src/commands/commands/__tests__/break-line.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/break-line.command.spec.ts
index 8aaae56abb..b24466d52e 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/break-line.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/break-line.command.spec.ts
@@ -17,8 +17,7 @@
import type { DocumentDataModel, ICommand, IDocumentData, Injector, Univer } from '@univerjs/core';
import { awaitTime, DataStreamTreeTokenType, DocumentBlockRangeType, DocumentFlavor, ICommandService, IUniverInstanceService, NamedStyleType, PresetListType, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
-import { NORMAL_TEXT_SELECTION_PLUGIN_STYLE } from '@univerjs/engine-render';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { BreakLineCommand, BreakLineInsertionMode } from '../break-line.command';
import { createCommandTestBed } from './create-command-test-bed';
@@ -246,28 +245,11 @@ describe('break line command', () => {
}
async function executeBreakLineAndApplyRenderedSelection(selectionManager: DocSelectionManagerService) {
- const replaceDocRanges = vi.spyOn(selectionManager, 'replaceDocRanges');
-
await commandService.executeCommand(BreakLineCommand.id);
await awaitTime(0);
- const refreshedRanges = replaceDocRanges.mock.calls.at(-1)?.[0];
- replaceDocRanges.mockRestore();
- if (!refreshedRanges?.length) {
- throw new Error('BreakLineCommand did not request a rendered selection refresh');
+ if (selectionManager.getActiveTextRange() == null) {
+ throw new Error('BreakLineCommand did not preserve an active text range');
}
-
- selectionManager.__replaceTextRangesWithNoRefresh({
- textRanges: refreshedRanges.map((range, index) => ({
- ...range,
- collapsed: range.startOffset === range.endOffset,
- isActive: index === refreshedRanges.length - 1,
- })),
- rectRanges: [],
- segmentId: '',
- segmentPage: -1,
- style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
- isEditing: true,
- }, { unitId: 'test-doc', subUnitId: 'test-doc' });
}
beforeEach(() => {
@@ -336,14 +318,11 @@ describe('break line command', () => {
it('keeps the cursor fixed for explicit gap insertion mode', async () => {
const selectionManager = get(DocSelectionManagerService);
- const replaceDocRanges = vi.spyOn(selectionManager, 'replaceDocRanges');
await commandService.executeCommand(BreakLineCommand.id, { insertionMode: BreakLineInsertionMode.InsertGap });
await awaitTime(0);
- expect(replaceDocRanges).toHaveBeenCalledWith([
- expect.objectContaining({ startOffset: 5, endOffset: 5 }),
- ], { unitId: 'test-doc', subUnitId: 'test-doc' }, true, undefined);
+ expect(selectionManager.getActiveTextRange()).toMatchObject({ startOffset: 5, endOffset: 5 });
});
it('keeps column groups when breaking a blank paragraph below a column group', async () => {
diff --git a/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.ts
index cd14058b3d..956464a6dd 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ICommand, IDocumentData, Injector, ITextStyle, Univer } from '@univerjs/core';
+import type { DocumentDataModel, ICommand, IDocumentBody, IDocumentData, Injector, ITextStyle, Univer } from '@univerjs/core';
+import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import {
BaselineOffset,
BooleanNumber,
@@ -23,12 +24,14 @@ import {
ICommandService,
IUniverInstanceService,
RedoCommand,
+ Tools,
UndoCommand,
UniverInstanceType,
} from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
+ getStyleInTextRange,
ResetInlineFormatTextBackgroundColorCommand,
ResetInlineFormatTextColorCommand,
SetInlineFormatBoldCommand,
@@ -46,6 +49,30 @@ import {
} from '../inline-format.command';
import { createCommandTestBed } from './create-command-test-bed';
+describe('getStyleInTextRange', () => {
+ it('reads an expanded selection without cloning unrelated text runs', () => {
+ const body = {
+ dataStream: 'x'.repeat(10_000),
+ textRuns: Array.from({ length: 1_000 }, (_value, index) => ({
+ st: index * 10,
+ ed: index * 10 + 5,
+ ts: { fs: 10 + index % 3 },
+ })),
+ } satisfies IDocumentBody;
+ const range = {
+ startOffset: 5_001,
+ endOffset: 5_004,
+ collapsed: false,
+ } satisfies ITextRangeWithStyle;
+ const cloneSpy = vi.spyOn(Tools, 'deepClone');
+
+ expect(getStyleInTextRange(body, range, {})).toMatchObject({ fs: 12 });
+ expect(cloneSpy.mock.calls.length).toBeLessThan(10);
+
+ cloneSpy.mockRestore();
+ });
+});
+
describe('Test inline format commands', () => {
let univer: Univer;
let get: Injector['get'];
diff --git a/packages/docs-ui/src/commands/commands/inline-format.command.ts b/packages/docs-ui/src/commands/commands/inline-format.command.ts
index ece259eda9..77ef429c2a 100644
--- a/packages/docs-ui/src/commands/commands/inline-format.command.ts
+++ b/packages/docs-ui/src/commands/commands/inline-format.command.ts
@@ -14,17 +14,7 @@
* limitations under the License.
*/
-import type {
- DocumentDataModel,
- ICommand,
- IDocumentBody,
- IMutationInfo,
- IStyleBase,
- ITextDecoration,
- ITextRun,
- ITextStyle,
- Nullable,
-} from '@univerjs/core';
+import type { DocumentDataModel, ICommand, IDocumentBody, IMutationInfo, IStyleBase, ITextDecoration, ITextRun, ITextStyle, Nullable } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import {
@@ -32,8 +22,8 @@ import {
BooleanNumber,
CommandType,
DOC_RANGE_TYPE,
- getBodySlice,
getRichTextEditPath,
+ getTextRunSlice,
ICommandService,
isInternalEditorID,
IUniverInstanceService,
@@ -562,7 +552,11 @@ export function getStyleInTextRange(
return textRun?.ts ? { ...defaultStyle, ...textRun.ts } : defaultStyle;
}
- const { textRuns = [] } = getBodySlice(body, startOffset, endOffset);
+ // Menu state only reads text style. Building a full body slice also scans and
+ // clones tables, paragraphs, decorations and custom ranges for every toolbar
+ // observable. The text-run slice preserves normalization without touching those
+ // unrelated structures.
+ const textRuns = getTextRunSlice(body, startOffset, endOffset) ?? [];
const style = Tools.deepClone(defaultStyle);
diff --git a/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
index 15be785201..cdfe1dc4d2 100644
--- a/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
@@ -14,12 +14,17 @@
* limitations under the License.
*/
+// @vitest-environment jsdom
+
import type { ICommandInfo, IExecutionOptions } from '@univerjs/core';
-import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DocumentFlavor } from '@univerjs/core';
-import { RichTextEditingMutation } from '@univerjs/docs';
+import type { IDocLayoutMountIdentity } from '@univerjs/docs';
+import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DocumentFlavor, JSONX, PositionedObjectLayoutType } from '@univerjs/core';
+import { DocLayoutSessionStatus, RichTextEditingMutation } from '@univerjs/docs';
import { BehaviorSubject, Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { DOCS_VIEW_KEY } from '../../basics/docs-view-key';
+import { DocLayoutInteractionService } from '../../services/doc-layout-interaction.service';
+import { DocBackScrollRenderController } from '../render-controllers/back-scroll.render-controller';
import { DocRenderController } from '../render-controllers/doc.render-controller';
const mockScrollBarProps = vi.hoisted(() => [] as unknown[]);
@@ -70,6 +75,13 @@ vi.mock('@univerjs/engine-render', async (importOriginal) => {
this.fillColors = colors;
return this;
}
+
+ getOffsetConfig() {
+ return {
+ docsLeft: 0,
+ docsTop: 0,
+ };
+ }
}
return {
@@ -88,12 +100,34 @@ vi.mock('@univerjs/engine-render', async (importOriginal) => {
}
},
Viewport: class MockViewport {
+ onScrollAfter$ = {
+ subscribeEvent: vi.fn(() => ({ dispose: vi.fn() })),
+ };
+
constructor(..._args: unknown[]) { }
onMouseWheel() { }
},
};
});
+vi.mock('../../services/selection/convert-text-range', () => ({
+ NodePositionConvertToCursor: class MockNodePositionConvertToCursor {
+ getRangePointData(position: { page?: number }) {
+ const top = (position.page ?? 0) * 900 + 120;
+ return {
+ borderBoxPointGroup: [],
+ contentBoxPointGroup: [[
+ { x: 80, y: top },
+ { x: 80, y: top },
+ { x: 80, y: top + 20 },
+ { x: 80, y: top + 20 },
+ ]],
+ cursorList: [],
+ };
+ }
+ },
+}));
+
function createControllerFixture(options?: {
documentFlavor?: DocumentFlavor;
fitToWidth?: {
@@ -103,37 +137,165 @@ function createControllerFixture(options?: {
};
pendingEditorBackgroundColor?: string | null;
pages?: Array<Record<string, unknown>>;
+ viewBound?: { bottom: number; left: number; right: number; top: number };
+ layoutProgress?: Array<{
+ complete: boolean;
+ anchorReady: boolean;
+ didPublishAnchor?: boolean;
+ interactionWindowComplete?: boolean;
+ elapsedTime: number;
+ estimatedHeight?: number;
+ estimatedPageCount?: number;
+ laidOutThrough?: number;
+ stableLaidOutThrough?: number;
+ mode?: 'paginated' | 'continuous';
+ pageCount?: number;
+ publishedPageCount?: number;
+ processedBlockCount?: number;
+ totalBlockCount?: number;
+ }>;
+ anchorPageType?: number;
+ anchorPage?: number;
+ anchorPageAfterPublication?: number;
+ activeRange?: {
+ startOffset: number;
+ endOffset: number;
+ isActive: boolean;
+ };
+ selectionIsEditing?: boolean;
+ drawings?: Record<string, {
+ layoutType: PositionedObjectLayoutType;
+ }>;
+ hasCompleteLayout?: boolean;
+ initialSkeletonDataMissing?: boolean;
+ useWorker?: boolean;
+ workerCompletes?: boolean;
+ workerCompletionPromise?: Promise<void>;
+ workerReplacesProtectedPages?: boolean;
+ focusedUnitId?: string;
unitId?: string;
+ supportsIncrementalLayout?: boolean;
+ engineBeginFrame$?: Subject<number>;
+ sceneParent?: { width: number; height: number };
+ onWorkerStart?: (layoutInteractionService: DocLayoutInteractionService) => void;
}) {
mockScrollBarProps.length = 0;
const commandCallbacks: Array<(command: ICommandInfo, options?: IExecutionOptions) => void> = [];
const darkMode$ = new BehaviorSubject<boolean>(false);
const currentTheme$ = new BehaviorSubject<unknown>({});
+ const compositionStart$ = new Subject<Record<string, unknown> | null>();
+ const compositionEnd$ = new Subject<Record<string, unknown> | null>();
const canvasElement = { style: {} as Record<string, string> };
const canvasColorService = {
getRenderColor: vi.fn((color: string) => color),
};
+ const layoutProgress = [...(options?.layoutProgress ?? [{
+ complete: true,
+ anchorReady: true,
+ elapsedTime: 1,
+ }])];
+ let didPublishAnchor = false;
+ let skeletonDataReadCount = 0;
+ let publicationApplied = false;
const skeleton = {
calculate: vi.fn(),
- getSkeletonData: vi.fn(() => ({
- pages: options?.pages ?? [{
- pageWidth: 640,
- pageHeight: 900,
- skeDrawings: new Map(),
- skeTables: new Map(),
- }],
+ startIncrementalLayout: vi.fn(() => 1),
+ stepIncrementalLayout: vi.fn(() => {
+ const progress = layoutProgress.shift() ?? {
+ complete: true,
+ anchorReady: true,
+ elapsedTime: 1,
+ };
+ const publishesAnchor = progress.didPublishAnchor ??
+ (!didPublishAnchor && !progress.complete && progress.anchorReady);
+ didPublishAnchor ||= publishesAnchor;
+ return {
+ generation: 1,
+ publicationRevision: progress.complete ? 2 : 1,
+ didPublish: progress.anchorReady,
+ didPublishAnchor: publishesAnchor,
+ publishedPageCount: progress.publishedPageCount ?? 1,
+ reason: 'edit',
+ mode: (options?.documentFlavor ?? DocumentFlavor.TRADITIONAL) === DocumentFlavor.MODERN
+ ? 'continuous'
+ : 'paginated',
+ cancelled: false,
+ laidOutThrough: 1,
+ stableLaidOutThrough: 1,
+ pageCount: progress.pageCount ?? 1,
+ processedBlockCount: 1,
+ totalBlockCount: 1,
+ estimatedPageCount: 1,
+ estimatedHeight: 900,
+ maxBlockDuration: 1,
+ interactionWindowComplete: false,
+ ...progress,
+ };
+ }),
+ cancelIncrementalLayout: vi.fn(),
+ beginExternalLayout: vi.fn(),
+ cancelExternalLayout: vi.fn(),
+ applyLayoutPublication: vi.fn(() => {
+ publicationApplied = true;
+ return { didReplaceProtectedPages: options?.workerReplacesProtectedPages ?? false };
+ }),
+ hasCompleteLayout: vi.fn(() => options?.hasCompleteLayout ?? true),
+ findNodePositionByCharIndex: vi.fn(() => ({
+ page: publicationApplied
+ ? options?.anchorPageAfterPublication ?? options?.anchorPage ?? 0
+ : options?.anchorPage ?? 0,
+ pageType: options?.anchorPageType ?? 0,
})),
+ getSkeletonData: vi.fn(() => {
+ if (options?.initialSkeletonDataMissing && skeletonDataReadCount++ === 0) {
+ return null;
+ }
+ return {
+ pages: options?.pages ?? [{
+ marginTop: 0,
+ pageWidth: 640,
+ pageHeight: 900,
+ sections: [],
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ }],
+ };
+ }),
getViewModel: vi.fn(() => ({
getDataModel: vi.fn(() => ({
getSnapshot: vi.fn(() => ({ disabled: false })),
})),
})),
};
+ const unitId = options?.unitId ?? 'doc-unit';
const skeletonManager = {
currentSkeletonBefore$: new Subject(),
getSkeleton: vi.fn(() => skeleton),
+ supportsIncrementalLayout: vi.fn(() =>
+ options?.supportsIncrementalLayout ?? (
+ unitId !== DOCS_NORMAL_EDITOR_UNIT_ID_KEY &&
+ (options?.documentFlavor ?? DocumentFlavor.TRADITIONAL) !== DocumentFlavor.UNSPECIFIED
+ )),
+ recalculate: vi.fn(() => {
+ skeleton.calculate();
+ return skeleton;
+ }),
+ };
+ const viewport = {
+ scrollX: 24,
+ scrollY: 6_400,
+ viewportScrollX: 48,
+ viewportScrollY: 12_800,
+ scrollByViewportDeltaVal: vi.fn(),
+ calcViewportInfo: vi.fn(() => ({
+ viewBound: options?.viewBound ?? {
+ bottom: 1_000,
+ left: 0,
+ right: 1_500,
+ top: 0,
+ },
+ })),
};
- const unitId = options?.unitId ?? 'doc-unit';
const context = {
unitId,
unit: {
@@ -142,17 +304,23 @@ function createControllerFixture(options?: {
documentStyle: {
documentFlavor: options?.documentFlavor ?? DocumentFlavor.TRADITIONAL,
},
+ drawings: options?.drawings,
})),
},
scene: {
+ width: 1_500,
+ height: 1_000,
attachControl: vi.fn(),
onMouseWheel$: { subscribeEvent: vi.fn() },
addLayer: vi.fn(),
addObjects: vi.fn(),
enableLayerCache: vi.fn(),
transformByState: vi.fn(),
+ getViewport: vi.fn(() => viewport),
+ getParent: vi.fn(() => options?.sceneParent),
},
engine: {
+ beginFrame$: options?.engineBeginFrame$,
canvasColorService,
runRenderLoop: vi.fn(),
stopRenderLoop: vi.fn(),
@@ -160,7 +328,7 @@ function createControllerFixture(options?: {
getCanvasEle: vi.fn(() => canvasElement),
})),
},
- mainComponent: undefined as { width: number } | undefined,
+ mainComponent: undefined as { width: number; height: number } | undefined,
components: new Map(),
activated$: new Subject<boolean>(),
};
@@ -183,28 +351,101 @@ function createControllerFixture(options?: {
};
const selectionManager = {
refreshSelection: vi.fn(),
+ getActiveTextRange: vi.fn(() => options?.activeRange),
+ getSelectionInfo: vi.fn(() => ({
+ isEditing: options?.selectionIsEditing ?? (options?.activeRange != null),
+ rectRanges: [],
+ textRanges: options?.activeRange == null ? [] : [options.activeRange],
+ })),
+ };
+ const selectionRenderService = {
+ __attachScrollEvent: vi.fn(),
+ isOnPointerEvent: false,
+ onCompositionstart$: compositionStart$,
+ onCompositionend$: compositionEnd$,
};
+ const backScrollController = {
+ scrollToRange: vi.fn(),
+ };
+ const renderManagerService = {
+ getRenderUnitById: vi.fn(() => ({
+ with: vi.fn((token) => token === DocBackScrollRenderController
+ ? backScrollController
+ : skeletonManager),
+ })),
+ };
+ const layoutInteractionService = new DocLayoutInteractionService();
+ const layoutExecutorService = {
+ getExecutor: vi.fn(() => options?.useWorker ? {} : null),
+ getExecutorStatus: vi.fn(() => ({ state: 'active' })),
+ recoverExecutor: vi.fn(() => Promise.resolve()),
+ completeRecovery: vi.fn(),
+ recordHydrationDuration: vi.fn(),
+ startLayout: vi.fn((identity: IDocLayoutMountIdentity, _options: unknown, _budgetMs: number) => {
+ options?.onWorkerStart?.(layoutInteractionService);
+ if (!options?.workerCompletes) {
+ return new Promise(() => {});
+ }
+ const result = {
+ status: DocLayoutSessionStatus.ACCEPTED,
+ step: {
+ ...identity,
+ modelRevision: 1,
+ metricsRevision: 1,
+ publication: { pages: [] },
+ progress: {
+ generation: 2,
+ publicationRevision: 1,
+ didPublish: true,
+ didPublishAnchor: true,
+ publishedPageCount: 20,
+ reason: 'edit',
+ mode: 'paginated',
+ complete: true,
+ cancelled: false,
+ anchorReady: true,
+ laidOutThrough: 20_000,
+ stableLaidOutThrough: 20_000,
+ pageCount: 20,
+ processedBlockCount: 100,
+ totalBlockCount: 100,
+ estimatedPageCount: 20,
+ estimatedHeight: 18_000,
+ elapsedTime: 20,
+ maxBlockDuration: 3,
+ interactionWindowComplete: false,
+ },
+ },
+ };
+ return options.workerCompletionPromise
+ ? options.workerCompletionPromise.then(() => result)
+ : Promise.resolve(result);
+ }),
+ stepLayout: vi.fn(),
+ publishBacklog: vi.fn(),
+ cancelLayout: vi.fn(() => Promise.resolve()),
+ disposeLayoutMount: vi.fn(() => Promise.resolve()),
+ };
const Controller = DocRenderController as unknown as new (...args: unknown[]) => DocRenderController;
const controller = new Controller(
context,
commandService,
- { __attachScrollEvent: vi.fn() },
+ selectionRenderService,
skeletonManager,
{
isEditor: vi.fn(() => editorRenderConfig != null),
getEditor: vi.fn(() => null),
getEditorRenderConfig: vi.fn(() => editorRenderConfig),
},
- {
- getRenderUnitById: vi.fn(() => ({
- with: vi.fn(() => skeletonManager),
- })),
- },
+ renderManagerService,
{
getCurrentUnitOfType: vi.fn(() => ({
getUnitId: vi.fn(() => unitId),
})),
+ getFocusedUnit: vi.fn(() => ({
+ getUnitId: vi.fn(() => options?.focusedUnitId ?? unitId),
+ })),
},
pageLayoutService,
selectionManager,
@@ -215,7 +456,10 @@ function createControllerFixture(options?: {
align: options?.fitToWidth?.align ?? 'center',
})),
},
- { currentTheme$, darkMode$ }
+ { currentTheme$, darkMode$ },
+ layoutExecutorService,
+ layoutInteractionService,
+ { error: vi.fn(), warn: vi.fn() }
);
return {
@@ -227,8 +471,15 @@ function createControllerFixture(options?: {
currentTheme$,
darkMode$,
skeletonManager,
+ viewport,
+ backScrollController,
pageLayoutService,
selectionManager,
+ selectionRenderService,
+ compositionStart$,
+ compositionEnd$,
+ layoutExecutorService,
+ layoutInteractionService,
};
}
@@ -292,7 +543,87 @@ describe('doc render controller', () => {
});
});
- it('refreshes page layout and selection after rich text mutations resize the document', () => {
+ it('treats a layout rerender without an explicit anchor as invalidated from the document start', () => {
+ const { controller, skeletonManager } = createControllerFixture();
+ const skeleton = skeletonManager.getSkeleton();
+
+ controller.reRender('doc-unit');
+
+ expect(skeleton.startIncrementalLayout).toHaveBeenCalledWith(expect.objectContaining({
+ anchor: 0,
+ reason: 'edit',
+ }));
+
+ controller.dispose();
+ });
+
+ it('restarts an incomplete initial layout when a non-interactive rerender has no anchor', () => {
+ const { controller, skeletonManager } = createControllerFixture({ hasCompleteLayout: false });
+ const skeleton = skeletonManager.getSkeleton();
+
+ controller.reRender('doc-unit');
+
+ expect(skeleton.startIncrementalLayout).toHaveBeenCalledWith(expect.objectContaining({
+ reason: 'initial',
+ }));
+ expect(skeleton.startIncrementalLayout).not.toHaveBeenCalledWith(expect.objectContaining({
+ anchor: 0,
+ }));
+
+ controller.dispose();
+ });
+
+ it('publishes the initial interaction window on Main before handing the tail to the Worker', async () => {
+ const { controller, layoutExecutorService, skeletonManager } = createControllerFixture({
+ useWorker: true,
+ hasCompleteLayout: false,
+ initialSkeletonDataMissing: true,
+ pages: Array.from({ length: 5 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: Array.from({ length: 5 }, (_, pageIndex) => ({
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: pageIndex === 0,
+ interactionWindowComplete: pageIndex === 4,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: pageIndex + 1,
+ })),
+ });
+ const skeleton = skeletonManager.getSkeleton();
+
+ skeletonManager.currentSkeletonBefore$.next(skeleton);
+
+ expect(skeleton.startIncrementalLayout).toHaveBeenCalledTimes(1);
+ expect(skeleton.startIncrementalLayout).toHaveBeenCalledWith(expect.objectContaining({
+ reason: 'initial',
+ }));
+ expect(skeleton.beginExternalLayout).not.toHaveBeenCalled();
+
+ for (let pageIndex = 0; pageIndex < 5; pageIndex++) {
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+ }
+
+ await vi.waitFor(() => {
+ expect(skeleton.beginExternalLayout).toHaveBeenCalledWith({
+ reason: 'initial',
+ protectedRange: {
+ mode: 'paginated',
+ startPageIndex: 0,
+ endPageIndex: 4,
+ },
+ });
+ });
+ expect(layoutExecutorService.startLayout).toHaveBeenCalledTimes(1);
+
+ controller.dispose();
+ });
+
+ it('refreshes page layout and selection after rich text mutations resize the document', async () => {
const { commandCallbacks, pageLayoutService, selectionManager } = createControllerFixture();
commandCallbacks[0]({
@@ -301,33 +632,1454 @@ describe('doc render controller', () => {
unitId: 'doc-unit',
actions: [],
},
- } as unknown as ICommandInfo);
+ } satisfies ICommandInfo);
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
expect(pageLayoutService.calculatePagePosition).toHaveBeenCalledTimes(1);
expect(selectionManager.refreshSelection).toHaveBeenCalledTimes(1);
});
- it('coalesces synchronous changeset mutations into one document render', async () => {
- const { commandCallbacks, pageLayoutService, selectionManager, skeletonManager } = createControllerFixture();
+ it('coalesces synchronous changeset mutations into one incremental document layout', async () => {
+ const { commandCallbacks, skeletonManager } = createControllerFixture();
const mutation = {
id: RichTextEditingMutation.id,
params: {
unitId: 'doc-unit',
actions: [],
},
- } as unknown as ICommandInfo;
+ } satisfies ICommandInfo;
commandCallbacks[0](mutation, { fromChangeset: true });
commandCallbacks[0](mutation, { fromChangeset: true });
commandCallbacks[0](mutation, { fromChangeset: true });
expect(skeletonManager.getSkeleton().calculate).not.toHaveBeenCalled();
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).not.toHaveBeenCalled();
await Promise.resolve();
- expect(skeletonManager.getSkeleton().calculate).toHaveBeenCalledTimes(1);
- expect(pageLayoutService.calculatePagePosition).toHaveBeenCalledTimes(1);
+ expect(skeletonManager.getSkeleton().calculate).not.toHaveBeenCalled();
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not start document layout when an overlay-only drawing moves', () => {
+ const { commandCallbacks, skeletonManager } = createControllerFixture({
+ drawings: {
+ 'drawing-1': {
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ },
+ },
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: JSONX.getInstance().replaceOp(
+ ['drawings', 'drawing-1', 'docTransform', 'positionH'],
+ { posOffset: 10 },
+ { posOffset: 20 }
+ ),
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).not.toHaveBeenCalled();
+ expect(skeletonManager.recalculate).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ PositionedObjectLayoutType.INLINE,
+ PositionedObjectLayoutType.WRAP_SQUARE,
+ PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM,
+ ])('reflows when a layout-participating drawing moves (layout type %s)', (layoutType) => {
+ const { commandCallbacks, skeletonManager } = createControllerFixture({
+ drawings: {
+ 'drawing-1': { layoutType },
+ },
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: JSONX.getInstance().replaceOp(
+ ['drawings', 'drawing-1', 'docTransform', 'positionV'],
+ { posOffset: 10 },
+ { posOffset: 20 }
+ ),
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).toHaveBeenCalledTimes(1);
+ });
+
+ it('reflows when a drawing switches between wrapping and overlay layout', () => {
+ const { commandCallbacks, skeletonManager } = createControllerFixture({
+ drawings: {
+ 'drawing-1': {
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ },
+ },
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: JSONX.getInstance().replaceOp(
+ ['drawings', 'drawing-1', 'layoutType'],
+ PositionedObjectLayoutType.WRAP_SQUARE,
+ PositionedObjectLayoutType.WRAP_NONE
+ ),
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not recompute global page positions while synchronously reaching the edit anchor', () => {
+ const { commandCallbacks, pageLayoutService, selectionManager } = createControllerFixture({
+ layoutProgress: [
+ {
+ complete: false,
+ anchorReady: false,
+ elapsedTime: 1,
+ },
+ {
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: true,
+ elapsedTime: 2,
+ },
+ ],
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+
+ expect(pageLayoutService.calculatePagePosition).not.toHaveBeenCalled();
+ expect(selectionManager.refreshSelection).toHaveBeenCalledTimes(1);
+ });
+
+ it('refreshes selection without repositioning the document from a stable incomplete anchor page', async () => {
+ const { commandCallbacks, pageLayoutService, selectionManager } = createControllerFixture({
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ elapsedTime: 1,
+ }],
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+
+ expect(pageLayoutService.calculatePagePosition).not.toHaveBeenCalled();
+ expect(selectionManager.refreshSelection).toHaveBeenCalledTimes(1);
+ });
+
+ it('publishes the edited page on the main thread before handing the tail to the Worker', async () => {
+ const { commandCallbacks, controller, layoutExecutorService, selectionManager, skeletonManager } = createControllerFixture({
+ useWorker: true,
+ pages: Array.from({ length: 5 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: Array.from({ length: 5 }, (_, pageIndex) => ({
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: pageIndex === 0,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: pageIndex + 1,
+ })),
+ });
+ const skeleton = skeletonManager.getSkeleton();
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeleton.startIncrementalLayout).toHaveBeenCalledTimes(1);
+ expect(skeleton.startIncrementalLayout).toHaveBeenCalledWith(expect.objectContaining({
+ reuseUnaffectedTail: false,
+ }));
+ expect(skeleton.beginExternalLayout).not.toHaveBeenCalled();
+
+ for (let pageIndex = 0; pageIndex < 5; pageIndex++) {
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+ }
+
expect(selectionManager.refreshSelection).toHaveBeenCalledTimes(1);
+ expect(skeleton.beginExternalLayout).not.toHaveBeenCalled();
+
+ await vi.waitFor(() => {
+ expect(skeleton.beginExternalLayout).toHaveBeenCalledWith({
+ reason: 'edit',
+ protectedRange: {
+ mode: 'paginated',
+ startPageIndex: 0,
+ endPageIndex: 4,
+ },
+ });
+ });
+ expect(layoutExecutorService.startLayout).toHaveBeenCalledTimes(1);
+
+ controller.dispose();
+ });
+
+ it('does not rebuild the active Main selection when the Worker only publishes the unprotected tail', async () => {
+ const { commandCallbacks, controller, selectionManager } = createControllerFixture({
+ useWorker: true,
+ workerCompletes: true,
+ pages: Array.from({ length: 5 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: Array.from({ length: 5 }, (_, pageIndex) => ({
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: pageIndex === 0,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: pageIndex + 1,
+ })),
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+
+ await vi.waitFor(() => {
+ expect(selectionManager.refreshSelection).toHaveBeenCalledTimes(1);
+ });
+ await new Promise<void>((resolve) => setTimeout(resolve, 180));
+ await vi.waitFor(() => {
+ expect(selectionManager.refreshSelection).toHaveBeenCalledTimes(1);
+ });
+
+ controller.dispose();
+ });
+
+ it('defers the final Worker publication while a document menu interaction is active', async () => {
+ vi.useFakeTimers();
+ let releaseInteraction: (() => void) | undefined;
+ let completeWorker: (() => void) | undefined;
+ try {
+ const workerCompletionPromise = new Promise<void>((resolve) => {
+ completeWorker = resolve;
+ });
+ const { commandCallbacks, controller, skeletonManager } = createControllerFixture({
+ useWorker: true,
+ workerCompletes: true,
+ workerCompletionPromise,
+ onWorkerStart: (layoutInteractionService) => {
+ const interaction = layoutInteractionService.beginInteraction();
+ releaseInteraction = () => interaction.dispose();
+ },
+ pages: Array.from({ length: 5 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: true,
+ interactionWindowComplete: true,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: 5,
+ }],
+ });
+ const skeleton = skeletonManager.getSkeleton();
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+
+ await vi.advanceTimersByTimeAsync(150);
+ completeWorker?.();
+ await vi.advanceTimersByTimeAsync(1_000);
+
+ expect(skeleton.applyLayoutPublication).not.toHaveBeenCalled();
+
+ releaseInteraction?.();
+ await vi.advanceTimersByTimeAsync(100);
+ expect(skeleton.applyLayoutPublication).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(50);
+ await vi.advanceTimersByTimeAsync(16);
+ expect(skeleton.applyLayoutPublication).toHaveBeenCalledTimes(1);
+
+ controller.dispose();
+ } finally {
+ releaseInteraction?.();
+ vi.useRealTimers();
+ }
+ });
+
+ it('rebuilds a divergent protected selection as an active editing selection', async () => {
+ const { commandCallbacks, controller, selectionManager } = createControllerFixture({
+ useWorker: true,
+ workerCompletes: true,
+ workerReplacesProtectedPages: true,
+ activeRange: {
+ startOffset: 2_630,
+ endOffset: 2_630,
+ isActive: true,
+ },
+ pages: Array.from({ length: 5 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: Array.from({ length: 5 }, (_, pageIndex) => ({
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: pageIndex === 0,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: pageIndex + 1,
+ })),
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+
+ await new Promise<void>((resolve) => setTimeout(resolve, 180));
+ await vi.waitFor(() => {
+ expect(selectionManager.refreshSelection).toHaveBeenLastCalledWith({
+ unitId: 'doc-unit',
+ subUnitId: 'doc-unit',
+ }, true);
+ });
+
+ controller.dispose();
+ });
+
+ it('does not scroll a programmatic Worker mutation without an active editing selection', async () => {
+ const { commandCallbacks, controller, selectionManager, viewport } = createControllerFixture({
+ useWorker: true,
+ workerCompletes: true,
+ workerReplacesProtectedPages: true,
+ activeRange: {
+ startOffset: 2_630,
+ endOffset: 2_630,
+ isActive: true,
+ },
+ selectionIsEditing: false,
+ anchorPage: 0,
+ anchorPageAfterPublication: 1,
+ pages: Array.from({ length: 5 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: true,
+ elapsedTime: 1,
+ pageCount: 5,
+ publishedPageCount: 1,
+ }],
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ textRanges: null,
+ actions: ['body', {
+ et: 'text-x',
+ e: [
+ { t: 'r', len: 10 },
+ { t: 'i', len: 1, body: { dataStream: 'B' } },
+ ],
+ }],
+ },
+ } satisfies ICommandInfo);
+
+ await new Promise<void>((resolve) => setTimeout(resolve, 180));
+
+ expect(viewport.scrollByViewportDeltaVal).not.toHaveBeenCalled();
+ expect(selectionManager.refreshSelection).toHaveBeenLastCalledWith({
+ unitId: 'doc-unit',
+ subUnitId: 'doc-unit',
+ }, false);
+
+ controller.dispose();
+ });
+
+ it('protects the Main continuous block window before handing a Modern tail to the Worker', async () => {
+ const { commandCallbacks, controller, layoutExecutorService, skeletonManager } = createControllerFixture({
+ documentFlavor: DocumentFlavor.MODERN,
+ useWorker: true,
+ activeRange: {
+ startOffset: 300,
+ endOffset: 300,
+ isActive: true,
+ },
+ layoutProgress: [20, 21, 22, 24].map((processedBlockCount, index) => ({
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: index === 0,
+ elapsedTime: 1,
+ laidOutThrough: 500,
+ stableLaidOutThrough: 480,
+ mode: 'continuous',
+ pageCount: 1,
+ publishedPageCount: 1,
+ processedBlockCount,
+ totalBlockCount: 100,
+ })),
+ });
+ const skeleton = skeletonManager.getSkeleton();
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeleton.startIncrementalLayout).toHaveBeenCalledTimes(1);
+ await vi.waitFor(() => {
+ expect(skeleton.beginExternalLayout).toHaveBeenCalledWith({
+ reason: 'edit',
+ protectedRange: {
+ mode: 'continuous',
+ startOffset: 300,
+ endOffset: 480,
+ },
+ });
+ });
+ expect(layoutExecutorService.startLayout).toHaveBeenCalledTimes(1);
+
+ controller.dispose();
+ });
+
+ it('uses a sole post-edit range as the foreground caret anchor without requiring isActive', () => {
+ const { commandCallbacks, controller, skeletonManager } = createControllerFixture({
+ documentFlavor: DocumentFlavor.MODERN,
+ useWorker: true,
+ activeRange: {
+ startOffset: 300,
+ endOffset: 300,
+ isActive: true,
+ },
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: true,
+ elapsedTime: 1,
+ laidOutThrough: 301,
+ stableLaidOutThrough: 300,
+ mode: 'continuous',
+ pageCount: 1,
+ publishedPageCount: 1,
+ processedBlockCount: 20,
+ totalBlockCount: 100,
+ }],
+ });
+ const skeleton = skeletonManager.getSkeleton();
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ textRanges: [{
+ startOffset: 301,
+ endOffset: 301,
+ collapsed: true,
+ }],
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeleton.startIncrementalLayout).toHaveBeenCalledWith(expect.objectContaining({
+ anchor: 301,
+ priorityAnchor: 301,
+ }));
+
+ controller.dispose();
+ });
+
+ it('protects the visible Modern continuous suffix instead of a fixed block count', () => {
+ const { commandCallbacks, controller, skeletonManager } = createControllerFixture({
+ documentFlavor: DocumentFlavor.MODERN,
+ useWorker: true,
+ viewBound: { bottom: 400, left: 0, right: 1_000, top: 0 },
+ pages: [{
+ marginTop: 20,
+ pageWidth: 640,
+ pageHeight: Number.POSITIVE_INFINITY,
+ sections: [{
+ top: 0,
+ columns: [{
+ lines: [
+ { ed: 120, top: 100 },
+ { ed: 360, top: 380 },
+ { ed: 900, top: 760 },
+ { ed: 1_200, top: 900 },
+ ],
+ }],
+ }],
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ }],
+ activeRange: {
+ startOffset: 300,
+ endOffset: 300,
+ isActive: true,
+ },
+ });
+ const skeleton = skeletonManager.getSkeleton();
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ textRanges: [{
+ startOffset: 301,
+ endOffset: 301,
+ collapsed: true,
+ }],
+ actions: ['body', {
+ et: 'text-x',
+ e: [
+ { t: 'r', len: 300 },
+ { t: 'i', len: 1, body: { dataStream: 'A' } },
+ ],
+ }],
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeleton.startIncrementalLayout).toHaveBeenCalledWith(expect.objectContaining({
+ reason: 'edit',
+ foregroundEndOffset: 901,
+ }));
+ controller.dispose();
+ });
+
+ it('does not hand the interaction window to the Worker during IME composition', async () => {
+ vi.useFakeTimers();
+ try {
+ const { commandCallbacks, compositionEnd$, compositionStart$, controller, layoutExecutorService } = createControllerFixture({
+ useWorker: true,
+ pages: Array.from({ length: 5 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: true,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: 1,
+ }, {
+ complete: false,
+ anchorReady: true,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: 5,
+ }],
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+ await vi.advanceTimersByTimeAsync(0);
+ compositionStart$.next({});
+ await vi.advanceTimersByTimeAsync(1_000);
+
+ expect(layoutExecutorService.startLayout).not.toHaveBeenCalled();
+
+ compositionEnd$.next({});
+ await vi.advanceTimersByTimeAsync(149);
+ expect(layoutExecutorService.startLayout).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(layoutExecutorService.startLayout).toHaveBeenCalledTimes(1);
+
+ controller.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not hand the interaction window to the Worker during pointer selection', async () => {
+ vi.useFakeTimers();
+ try {
+ const { commandCallbacks, controller, layoutExecutorService, selectionRenderService } = createControllerFixture({
+ useWorker: true,
+ pages: Array.from({ length: 5 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: true,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: 1,
+ }, {
+ complete: false,
+ anchorReady: true,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: 5,
+ }],
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+ selectionRenderService.isOnPointerEvent = true;
+ await vi.advanceTimersByTimeAsync(600);
+
+ expect(layoutExecutorService.startLayout).not.toHaveBeenCalled();
+
+ selectionRenderService.isOnPointerEvent = false;
+ await vi.advanceTimersByTimeAsync(149);
+ expect(layoutExecutorService.startLayout).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(layoutExecutorService.startLayout).toHaveBeenCalledTimes(1);
+
+ controller.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('continues starting Worker tail computation while a document menu interaction is active', async () => {
+ vi.useFakeTimers();
+ try {
+ const { commandCallbacks, controller, layoutExecutorService, layoutInteractionService } = createControllerFixture({
+ useWorker: true,
+ pages: Array.from({ length: 5 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: true,
+ interactionWindowComplete: true,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: 5,
+ }],
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+ const interaction = layoutInteractionService.beginInteraction();
+
+ await vi.advanceTimersByTimeAsync(150);
+
+ expect(layoutExecutorService.startLayout).toHaveBeenCalledTimes(1);
+
+ interaction.dispose();
+ controller.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('discards a pending Worker handoff when a newer local edit arrives', async () => {
+ vi.useFakeTimers();
+ try {
+ const { commandCallbacks, controller, layoutExecutorService } = createControllerFixture({
+ useWorker: true,
+ pages: Array.from({ length: 5 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: Array.from({ length: 4 }, (_, index) => ({
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: index % 2 === 0,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: index % 2 === 0 ? 1 : 5,
+ })),
+ });
+ const mutation = {
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo;
+
+ commandCallbacks[0](mutation);
+ await vi.advanceTimersByTimeAsync(100);
+ commandCallbacks[0](mutation);
+ await vi.advanceTimersByTimeAsync(149);
+ expect(layoutExecutorService.startLayout).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+
+ expect(layoutExecutorService.startLayout).toHaveBeenCalledTimes(1);
+
+ controller.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('composes a Worker edit batch from its earliest dirty anchor', async () => {
+ vi.useFakeTimers();
+ try {
+ const { commandCallbacks, controller, layoutExecutorService } = createControllerFixture({
+ useWorker: true,
+ pages: Array.from({ length: 12 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: Array.from({ length: 3 }, () => ({
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: true,
+ interactionWindowComplete: true,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: 5,
+ })),
+ });
+ const mutations = [{
+ retain: 2_630,
+ text: '现在',
+ range: 2_632,
+ }, {
+ retain: 2_632,
+ text: '\r',
+ range: 2_633,
+ }, {
+ retain: 2_633,
+ text: 'ISSUE-ENTER',
+ range: 2_644,
+ }];
+
+ for (const mutation of mutations) {
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ textRanges: [{
+ startOffset: mutation.range,
+ endOffset: mutation.range,
+ collapsed: true,
+ isActive: true,
+ }],
+ actions: ['body', {
+ et: 'text-x',
+ e: [
+ { t: 'r', len: mutation.retain },
+ { t: 'i', len: mutation.text.length, body: { dataStream: mutation.text } },
+ ],
+ }],
+ },
+ } satisfies ICommandInfo);
+ }
+
+ await vi.advanceTimersByTimeAsync(150);
+
+ expect(layoutExecutorService.startLayout).toHaveBeenCalledTimes(1);
+ expect(layoutExecutorService.startLayout.mock.calls[0][1]).toEqual({
+ reason: 'edit',
+ anchor: 2_630,
+ priorityAnchor: 2_630,
+ invalidation: {
+ oldStart: 2_630,
+ oldEnd: 2_630,
+ newEnd: 2_644,
+ },
+ });
+
+ controller.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('restarts the Worker handoff quiet window when the user keeps interacting', async () => {
+ vi.useFakeTimers();
+ try {
+ const { commandCallbacks, controller, layoutExecutorService } = createControllerFixture({
+ useWorker: true,
+ pages: Array.from({ length: 12 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: true,
+ interactionWindowComplete: true,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: 5,
+ }],
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ textRanges: [{
+ startOffset: 2_631,
+ endOffset: 2_631,
+ collapsed: true,
+ isActive: true,
+ }],
+ actions: ['body', {
+ et: 'text-x',
+ e: [
+ { t: 'r', len: 2_630 },
+ { t: 'i', len: 1, body: { dataStream: 'A' } },
+ ],
+ }],
+ },
+ } satisfies ICommandInfo);
+
+ await vi.advanceTimersByTimeAsync(100);
+ document.dispatchEvent(new KeyboardEvent('keydown'));
+ await vi.advanceTimersByTimeAsync(149);
+ expect(layoutExecutorService.startLayout).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(1);
+ expect(layoutExecutorService.startLayout).toHaveBeenCalledOnce();
+
+ controller.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('derives the incremental anchor from a body TextX edit when text ranges are absent', async () => {
+ const { backScrollController, commandCallbacks, selectionManager, skeletonManager, viewport } = createControllerFixture();
+ document.dispatchEvent(new KeyboardEvent('keydown'));
+ viewport.scrollX = 0;
+ viewport.scrollY = 900;
+ viewport.viewportScrollX = 0;
+ viewport.viewportScrollY = 1_800;
+ document.dispatchEvent(new Event('beforeinput'));
+ selectionManager.refreshSelection.mockImplementation(() => {
+ viewport.scrollX = 0;
+ viewport.scrollY = 1_200;
+ viewport.viewportScrollX = 0;
+ viewport.viewportScrollY = 2_400;
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ textRanges: null,
+ actions: ['body', {
+ et: 'text-x',
+ e: [
+ { t: 'r', len: 1_792 },
+ { t: 'i', len: 1, body: { dataStream: 'Z' } },
+ ],
+ }],
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).toHaveBeenCalledWith({
+ reason: 'edit',
+ anchor: 1_792,
+ invalidation: {
+ oldStart: 1_792,
+ oldEnd: 1_792,
+ newEnd: 1_793,
+ },
+ });
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+ expect(viewport.scrollByViewportDeltaVal).not.toHaveBeenCalled();
+ // The foreground skeleton is sufficient to paint the edited glyph, but its
+ // page coordinates are not stable until the background pass reaches a page
+ // boundary. Never back-scroll with those transient coordinates.
+ expect(backScrollController.scrollToRange).not.toHaveBeenCalled();
+ });
+
+ it('uses the pretransformed local caret when a remote edit still carries sender ranges', () => {
+ const { commandCallbacks, controller, skeletonManager } = createControllerFixture({
+ useWorker: true,
+ activeRange: {
+ startOffset: 9_001,
+ endOffset: 9_001,
+ isActive: true,
+ },
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ textRanges: [{
+ startOffset: 11,
+ endOffset: 11,
+ isActive: true,
+ }],
+ actions: ['body', {
+ et: 'text-x',
+ e: [
+ { t: 'r', len: 10 },
+ { t: 'i', len: 1, body: { dataStream: 'B' } },
+ ],
+ }],
+ },
+ } satisfies ICommandInfo, { fromCollab: true });
+
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).toHaveBeenCalledWith({
+ reason: 'edit',
+ anchor: 9_001,
+ priorityAnchor: 9_001,
+ invalidation: {
+ oldStart: 10,
+ oldEnd: 10,
+ newEnd: 11,
+ },
+ preserveInteractionWindow: true,
+ reuseUnaffectedTail: false,
+ });
+
+ controller.dispose();
+ });
+
+ it('uses the post-edit text range before the selection-manager microtask runs', () => {
+ const { commandCallbacks, controller, skeletonManager } = createControllerFixture({
+ useWorker: true,
+ activeRange: {
+ startOffset: 100,
+ endOffset: 100,
+ isActive: true,
+ },
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ textRanges: [{
+ startOffset: 101,
+ endOffset: 101,
+ isActive: true,
+ }],
+ actions: ['body', {
+ et: 'text-x',
+ e: [
+ { t: 'r', len: 100 },
+ { t: 'i', len: 1, body: { dataStream: 'A' } },
+ ],
+ }],
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).toHaveBeenCalledWith({
+ reason: 'edit',
+ anchor: 100,
+ priorityAnchor: 101,
+ invalidation: {
+ oldStart: 100,
+ oldEnd: 100,
+ newEnd: 101,
+ },
+ preserveInteractionWindow: false,
+ reuseUnaffectedTail: false,
+ });
+
+ controller.dispose();
+ });
+
+ it('leaves a local post-edit caret to the original mutation microtask', () => {
+ const { commandCallbacks, controller, selectionManager } = createControllerFixture({
+ useWorker: true,
+ activeRange: {
+ startOffset: 100,
+ endOffset: 100,
+ isActive: true,
+ },
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: true,
+ elapsedTime: 1,
+ }],
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ trigger: 'keyboard',
+ textRanges: [{
+ startOffset: 101,
+ endOffset: 101,
+ isActive: true,
+ }],
+ actions: ['body', {
+ et: 'text-x',
+ e: [
+ { t: 'r', len: 100 },
+ { t: 'i', len: 1, body: { dataStream: 'A' } },
+ ],
+ }],
+ },
+ } satisfies ICommandInfo);
+
+ expect(selectionManager.refreshSelection).not.toHaveBeenCalled();
+ controller.dispose();
+ });
+
+ it('keeps the local caret editing after the foreground layout completes across a page', async () => {
+ const { commandCallbacks, controller, selectionManager } = createControllerFixture({
+ useWorker: true,
+ workerCompletes: true,
+ activeRange: {
+ startOffset: 100,
+ endOffset: 100,
+ isActive: true,
+ },
+ pages: Array.from({ length: 5 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: true,
+ interactionWindowComplete: true,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: 5,
+ }],
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ trigger: 'keyboard',
+ textRanges: [{
+ startOffset: 101,
+ endOffset: 101,
+ isActive: true,
+ }],
+ actions: ['body', {
+ et: 'text-x',
+ e: [
+ { t: 'r', len: 100 },
+ { t: 'i', len: 1, body: { dataStream: 'A' } },
+ ],
+ }],
+ },
+ } satisfies ICommandInfo);
+ await new Promise<void>((resolve) => setTimeout(resolve, 180));
+ await vi.waitFor(() => {
+ expect(selectionManager.refreshSelection).toHaveBeenCalledTimes(1);
+ });
+
+ expect(selectionManager.refreshSelection).toHaveBeenCalledWith({
+ unitId: 'doc-unit',
+ subUnitId: 'doc-unit',
+ }, true);
+ controller.dispose();
+ });
+
+ it('refreshes the transformed local caret for a remote mutation', () => {
+ const { commandCallbacks, controller, selectionManager } = createControllerFixture({
+ useWorker: true,
+ activeRange: {
+ startOffset: 9_000,
+ endOffset: 9_000,
+ isActive: true,
+ },
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: true,
+ elapsedTime: 1,
+ }],
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ trigger: 'collaboration',
+ textRanges: [{
+ startOffset: 11,
+ endOffset: 11,
+ isActive: true,
+ }],
+ actions: ['body', {
+ et: 'text-x',
+ e: [
+ { t: 'r', len: 10 },
+ { t: 'i', len: 1, body: { dataStream: 'B' } },
+ ],
+ }],
+ },
+ } satisfies ICommandInfo, { fromCollab: true });
+
+ expect(selectionManager.refreshSelection).toHaveBeenCalledWith({
+ unitId: 'doc-unit',
+ subUnitId: 'doc-unit',
+ }, true);
+ controller.dispose();
+ });
+
+ it('keeps the caret at the same viewport offset after editing state ends while a remote edit moves it to a later page', async () => {
+ const { commandCallbacks, controller, viewport } = createControllerFixture({
+ useWorker: true,
+ workerCompletes: true,
+ anchorPage: 1,
+ anchorPageAfterPublication: 3,
+ selectionIsEditing: false,
+ activeRange: {
+ startOffset: 9_000,
+ endOffset: 9_000,
+ isActive: true,
+ },
+ pages: Array.from({ length: 20 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: Array.from({ length: 5 }, (_, pageIndex) => ({
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: pageIndex === 0,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: pageIndex + 2,
+ })),
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ isSync: true,
+ textRanges: null,
+ actions: ['body', {
+ et: 'text-x',
+ e: [
+ { t: 'r', len: 10 },
+ { t: 'i', len: 1, body: { dataStream: 'B' } },
+ ],
+ }],
+ },
+ } satisfies ICommandInfo);
+
+ for (let pageIndex = 0; pageIndex < 5; pageIndex++) {
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+ }
+ await new Promise<void>((resolve) => setTimeout(resolve, 180));
+
+ expect(viewport.scrollByViewportDeltaVal).toHaveBeenCalledWith({
+ viewportScrollX: 0,
+ viewportScrollY: 1_800,
+ });
+
+ controller.dispose();
+ });
+
+ it('keeps UNSPECIFIED editor mutations on the synchronous layout path', () => {
+ const { commandCallbacks, skeletonManager } = createControllerFixture({
+ documentFlavor: DocumentFlavor.UNSPECIFIED,
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeletonManager.recalculate).toHaveBeenCalledTimes(1);
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).not.toHaveBeenCalled();
+ });
+
+ it('keeps document mutations on the historical synchronous path without an incremental executor', () => {
+ const { commandCallbacks, skeletonManager } = createControllerFixture({
+ supportsIncrementalLayout: false,
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeletonManager.recalculate).toHaveBeenCalledTimes(1);
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).not.toHaveBeenCalled();
+ });
+
+ it('does not back-scroll a nested table anchor from a partial layout', async () => {
+ const { backScrollController, commandCallbacks } = createControllerFixture({
+ anchorPage: -1,
+ anchorPageType: 3,
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ textRanges: null,
+ actions: ['body', {
+ et: 'text-x',
+ e: [
+ { t: 'r', len: 1_688 },
+ { t: 'i', len: 1, body: { dataStream: 'T' } },
+ ],
+ }],
+ },
+ } satisfies ICommandInfo);
+
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+ expect(backScrollController.scrollToRange).not.toHaveBeenCalled();
+ });
+
+ it('keeps non-editor UNSPECIFIED mutations on the synchronous layout path', () => {
+ const { commandCallbacks, skeletonManager } = createControllerFixture({
+ documentFlavor: DocumentFlavor.UNSPECIFIED,
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeletonManager.recalculate).toHaveBeenCalledTimes(1);
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).not.toHaveBeenCalled();
+ });
+
+ it('reserves estimated traditional tail height while background layout is incomplete', async () => {
+ const { commandCallbacks, context } = createControllerFixture({
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ elapsedTime: 8,
+ estimatedPageCount: 20,
+ estimatedHeight: 18_000,
+ processedBlockCount: 10,
+ totalBlockCount: 200,
+ }],
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+
+ expect(context.mainComponent?.height).toBe(18_420);
+ expect(context.scene.transformByState).toHaveBeenCalledWith(expect.objectContaining({ height: 18_420 }));
+ });
+
+ it('uses the first published page width instead of the default scene width on first open', async () => {
+ const { context, skeletonManager } = createControllerFixture({
+ hasCompleteLayout: false,
+ initialSkeletonDataMissing: true,
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ elapsedTime: 8,
+ estimatedPageCount: 20,
+ estimatedHeight: 18_000,
+ }],
+ });
+ skeletonManager.currentSkeletonBefore$.next(skeletonManager.getSkeleton());
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+
+ expect(context.mainComponent?.width).toBe(640);
+ expect(context.mainComponent?.height).toBe(18_420);
+ expect(context.scene.transformByState).toHaveBeenCalledWith({ width: 640, height: 18_420 });
+ });
+
+ it('does not publish Worker geometry before the render container can commit an interactive frame', async () => {
+ const engineBeginFrame$ = new Subject<number>();
+ const sceneParent = { width: 1, height: 1 };
+ const { pageLayoutService, skeletonManager } = createControllerFixture({
+ engineBeginFrame$,
+ sceneParent,
+ useWorker: true,
+ workerCompletes: true,
+ hasCompleteLayout: false,
+ initialSkeletonDataMissing: true,
+ pages: Array.from({ length: 5 }, () => ({
+ pageWidth: 640,
+ pageHeight: 900,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ })),
+ layoutProgress: Array.from({ length: 5 }, (_, pageIndex) => ({
+ complete: false,
+ anchorReady: true,
+ didPublishAnchor: pageIndex === 0,
+ interactionWindowComplete: pageIndex === 4,
+ elapsedTime: 1,
+ pageCount: 20,
+ publishedPageCount: pageIndex + 1,
+ })),
+ });
+
+ skeletonManager.currentSkeletonBefore$.next(skeletonManager.getSkeleton());
+ engineBeginFrame$.next(1);
+
+ expect(skeletonManager.getSkeleton().applyLayoutPublication).not.toHaveBeenCalled();
+ expect(pageLayoutService.calculatePagePosition).not.toHaveBeenCalled();
+ expect(skeletonManager.getSkeleton().beginExternalLayout).not.toHaveBeenCalled();
+
+ sceneParent.width = 1_280;
+ sceneParent.height = 900;
+ for (let frame = 2; frame <= 6; frame++) {
+ engineBeginFrame$.next(frame);
+ }
+ await vi.waitFor(() => {
+ expect(skeletonManager.getSkeleton().beginExternalLayout).toHaveBeenCalledTimes(1);
+ });
+ engineBeginFrame$.next(7);
+
+ expect(skeletonManager.getSkeleton().applyLayoutPublication).toHaveBeenCalledTimes(1);
+ expect(pageLayoutService.calculatePagePosition).toHaveBeenCalled();
+ });
+
+ it('preserves only the vertical flow extent from the last complete layout', async () => {
+ const { commandCallbacks, context } = createControllerFixture({
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ elapsedTime: 8,
+ estimatedPageCount: 20,
+ estimatedHeight: 18_000,
+ }],
+ });
+ if (context.mainComponent != null) {
+ context.mainComponent.width = 1_500;
+ context.mainComponent.height = 20_000;
+ }
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+
+ expect(context.mainComponent?.width).toBe(640);
+ expect(context.mainComponent?.height).toBe(20_000);
+ });
+
+ it('refreshes selection for the foreground anchor and final layout only', () => {
+ vi.useFakeTimers();
+ vi.stubGlobal('requestIdleCallback', (callback: IdleRequestCallback) => setTimeout(() => callback({
+ didTimeout: false,
+ timeRemaining: () => 12,
+ }), 0));
+ vi.stubGlobal('cancelIdleCallback', (id: number) => clearTimeout(id));
+ const { commandCallbacks, pageLayoutService, selectionManager } = createControllerFixture({
+ layoutProgress: [
+ { complete: false, anchorReady: true, elapsedTime: 8 },
+ { complete: false, anchorReady: true, elapsedTime: 16 },
+ { complete: true, anchorReady: true, elapsedTime: 24 },
+ ],
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+ vi.runAllTimers();
+
+ expect(pageLayoutService.calculatePagePosition).toHaveBeenCalledTimes(1);
+ expect(selectionManager.refreshSelection).toHaveBeenCalledTimes(2);
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
});
it('keeps modern doc width anchored to page width when a table grows wider than the text column', () => {
diff --git a/packages/docs-ui/src/controllers/components.controller.ts b/packages/docs-ui/src/controllers/components.controller.ts
index f5b56dae69..dcbc6d29e9 100644
--- a/packages/docs-ui/src/controllers/components.controller.ts
+++ b/packages/docs-ui/src/controllers/components.controller.ts
@@ -68,6 +68,7 @@ import {
UnorderIcon,
} from '@univerjs/icons';
import { ComponentManager, IconManager } from '@univerjs/ui';
+import { DOC_LAYOUT_RECOVERY_COMPONENT, DocLayoutRecovery } from '../views/DocLayoutRecovery';
import { FLOAT_MENU_COMPONENT_KEY, FloatToolbar } from '../views/float-toolbar/FloatToolbar';
import { COMPONENT_DOC_HEADER_FOOTER_PANEL } from '../views/header-footer/panel/component-name';
import { DocHeaderFooterPanel } from '../views/header-footer/panel/DocHeaderFooterPanel';
@@ -233,6 +234,7 @@ export class ComponentsController extends Disposable {
[DOC_TABLE_BLOCK_MENU_COMPONENT_KEY, TableBlockMenu],
[FLOAT_MENU_COMPONENT_KEY, FloatToolbar],
[PAGE_SETTING_COMPONENT_ID, PageSettings],
+ [DOC_LAYOUT_RECOVERY_COMPONENT, DocLayoutRecovery],
] as const).forEach(([key, comp]) => {
this.disposeWithMe(
this._componentManager.register(key, comp)
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-canvas-popup-layout-interaction.controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-canvas-popup-layout-interaction.controller.spec.ts
new file mode 100644
index 0000000000..f1f73755e1
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-canvas-popup-layout-interaction.controller.spec.ts
@@ -0,0 +1,65 @@
+/**
+ * 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 { BehaviorSubject } from 'rxjs';
+import { describe, expect, it } from 'vitest';
+import { DocLayoutInteractionService } from '../../../services/doc-layout-interaction.service';
+import { DocCanvasPopupLayoutInteractionController } from '../doc-canvas-popup-layout-interaction.controller';
+
+describe('DocCanvasPopupLayoutInteractionController', () => {
+ it('holds the layout interaction while its render unit owns a popup', () => {
+ const popupUnits$ = new BehaviorSubject<ReadonlySet<string>>(new Set());
+ const interactionService = new DocLayoutInteractionService();
+ const controller = new DocCanvasPopupLayoutInteractionController(
+ { unitId: 'doc-1' },
+ { popupUnits$ },
+ interactionService
+ );
+
+ popupUnits$.next(new Set(['doc-2']));
+ expect(interactionService.isActive).toBe(false);
+
+ popupUnits$.next(new Set(['doc-1', 'doc-2']));
+ expect(interactionService.isActive).toBe(true);
+
+ popupUnits$.next(new Set(['doc-1']));
+ expect(interactionService.isActive).toBe(true);
+
+ popupUnits$.next(new Set());
+ expect(interactionService.isActive).toBe(false);
+
+ controller.dispose();
+ interactionService.dispose();
+ popupUnits$.complete();
+ });
+
+ it('releases the layout interaction when its render controller is disposed', () => {
+ const popupUnits$ = new BehaviorSubject<ReadonlySet<string>>(new Set(['doc-1']));
+ const interactionService = new DocLayoutInteractionService();
+ const controller = new DocCanvasPopupLayoutInteractionController(
+ { unitId: 'doc-1' },
+ { popupUnits$ },
+ interactionService
+ );
+
+ expect(interactionService.isActive).toBe(true);
+
+ controller.dispose();
+ expect(interactionService.isActive).toBe(false);
+ interactionService.dispose();
+ popupUnits$.complete();
+ });
+});
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-layout-recovery.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-layout-recovery.render-controller.spec.ts
new file mode 100644
index 0000000000..d0dc4fa93d
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-layout-recovery.render-controller.spec.ts
@@ -0,0 +1,49 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// @vitest-environment jsdom
+
+import { describe, expect, it, vi } from 'vitest';
+import { acquireDocLayoutRecoveryInteractionLock } from '../doc-layout-recovery.render-controller';
+
+describe('document layout recovery interaction lock', () => {
+ it('blocks pointer and shortcut input until recovery completes, then restores prior canvas state', () => {
+ const canvas = document.createElement('canvas');
+ canvas.style.pointerEvents = 'auto';
+ canvas.style.opacity = '0.8';
+ canvas.setAttribute('aria-busy', 'mixed');
+ const blurSelection = vi.fn();
+ const releaseShortcuts = vi.fn();
+ const shortcutService = {
+ forceDisable: vi.fn(() => ({ dispose: releaseShortcuts })),
+ };
+
+ const lock = acquireDocLayoutRecoveryInteractionLock(canvas, shortcutService, blurSelection);
+
+ expect(blurSelection).toHaveBeenCalledOnce();
+ expect(shortcutService.forceDisable).toHaveBeenCalledOnce();
+ expect(canvas.style.pointerEvents).toBe('none');
+ expect(canvas.style.opacity).toBe('0.55');
+ expect(canvas.getAttribute('aria-busy')).toBe('true');
+
+ lock.dispose();
+
+ expect(releaseShortcuts).toHaveBeenCalledOnce();
+ expect(canvas.style.pointerEvents).toBe('auto');
+ expect(canvas.style.opacity).toBe('0.8');
+ expect(canvas.getAttribute('aria-busy')).toBe('mixed');
+ });
+});
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-resize.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-resize.render-controller.spec.ts
index dbf072742f..98c7bbe8ac 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-resize.render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-resize.render-controller.spec.ts
@@ -17,7 +17,21 @@
import { EventSubject } from '@univerjs/core';
import { Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
-import { DocResizeRenderController } from '../doc-resize.render-controller';
+import { DocResizeRenderController, hasRenderableDocSkeleton } from '../doc-resize.render-controller';
+
+describe('hasRenderableDocSkeleton', () => {
+ it('rejects missing and empty skeletons', () => {
+ expect(hasRenderableDocSkeleton(undefined)).toBe(false);
+ expect(hasRenderableDocSkeleton({ getSkeleton: () => null })).toBe(false);
+ expect(hasRenderableDocSkeleton({ getSkeleton: () => ({ getSkeletonData: () => ({ pages: [] }) }) })).toBe(false);
+ });
+
+ it('accepts a skeleton with at least one page', () => {
+ expect(hasRenderableDocSkeleton({
+ getSkeleton: () => ({ getSkeletonData: () => ({ pages: [{}] }) }),
+ })).toBe(true);
+ });
+});
describe('DocResizeRenderController', () => {
it('refreshes page layout and text selection after sidebar layout changes', async () => {
@@ -31,6 +45,9 @@ describe('DocResizeRenderController', () => {
engine: {
onTransformChange$: new EventSubject(),
},
+ mainComponent: {
+ getSkeleton: () => ({ getSkeletonData: () => ({ pages: [{}] }) }),
+ },
} as never,
{ calculatePagePosition } as never,
{ refreshSelection } 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 8e2df9e4db..8eabebdfb6 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
@@ -101,6 +101,7 @@ function createController(options: { readonly?: boolean; hasEditor?: boolean; pr
const docSelectionRenderService = {
removeAllRanges: vi.fn(),
addDocRanges: vi.fn(),
+ replaceDocRanges: vi.fn(),
textSelectionInner$,
focus: vi.fn(),
__onPointDown: vi.fn(),
@@ -193,8 +194,7 @@ describe('DocSelectionRenderController', () => {
refreshSelection$.next({ unitId: 'doc-1', docRanges, isEditing: true, options: { segmentId: 'header' } });
textSelectionInner$.next([{ startOffset: 3, endOffset: 4 }]);
- expect(docSelectionRenderService.removeAllRanges).toHaveBeenCalledTimes(1);
- expect(docSelectionRenderService.addDocRanges).toHaveBeenCalledWith(docRanges, true, { segmentId: 'header' });
+ expect(docSelectionRenderService.replaceDocRanges).toHaveBeenCalledWith(docRanges, true, { segmentId: 'header' });
expect(docSelectionManagerService.__replaceTextRangesWithNoRefresh).toHaveBeenCalledWith(
[{ startOffset: 3, endOffset: 4 }],
{ unitId: 'doc-1', subUnitId: 'doc-1' }
diff --git a/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts
index 894785d800..6707c36299 100644
--- a/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ITextRange, Nullable } from '@univerjs/core';
-import type { Documents, INodePosition, IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import type { DocumentDataModel, ITextRangeParam, Nullable } from '@univerjs/core';
import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, Inject, RxDisposable } from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
+import * as EngineRender from '@univerjs/engine-render';
import { takeUntil } from 'rxjs';
import { VIEWPORT_KEY } from '../../basics/docs-view-key';
import { IEditorService } from '../../services/editor/editor-manager.service';
@@ -26,9 +26,11 @@ import { getAnchorBounding } from '../../services/selection/text-range';
const ANCHOR_WIDTH = 1.5;
-export class DocBackScrollRenderController extends RxDisposable implements IRenderModule {
+export class DocBackScrollRenderController extends RxDisposable implements EngineRender.IRenderModule {
+ private _pendingSelectionScrollFrame: number | null = null;
+
constructor(
- private readonly _context: IRenderContext<DocumentDataModel>,
+ private readonly _context: EngineRender.IRenderContext<DocumentDataModel>,
@Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,
@IEditorService private readonly _editorService: IEditorService,
@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService
@@ -54,35 +56,144 @@ export class DocBackScrollRenderController extends RxDisposable implements IRend
return;
}
+ this._scheduleScrollToSelection();
+ });
+ }
+
+ override dispose(): void {
+ if (this._pendingSelectionScrollFrame != null && typeof cancelAnimationFrame !== 'undefined') {
+ cancelAnimationFrame(this._pendingSelectionScrollFrame);
+ }
+ this._pendingSelectionScrollFrame = null;
+ super.dispose();
+ }
+
+ private _scheduleScrollToSelection(): void {
+ if (typeof requestAnimationFrame === 'undefined') {
+ this._scrollToSelection();
+ return;
+ }
+
+ if (this._pendingSelectionScrollFrame != null) {
+ cancelAnimationFrame(this._pendingSelectionScrollFrame);
+ }
+ this._pendingSelectionScrollFrame = requestAnimationFrame(() => {
+ this._pendingSelectionScrollFrame = null;
this._scrollToSelection();
});
}
- scrollToRange(range: ITextRange) {
+ scrollToRange(range: ITextRangeParam) {
const skeleton = this._docSkeletonManagerService.getSkeleton();
if (!skeleton) {
return;
}
- const { startOffset } = range;
- const anchorNodePosition = skeleton.findNodePositionByCharIndex(startOffset);
+ const { startOffset, segmentId, segmentPage } = range;
+ const anchorNodePosition = skeleton.findNodePositionByCharIndex(
+ startOffset,
+ true,
+ segmentId ?? '',
+ segmentPage ?? -1
+ );
+ if (anchorNodePosition == null) {
+ const pageIndex = skeleton.findBodyPageIndexByCharIndex(startOffset);
+ const page = skeleton.getSkeletonData()?.pages[pageIndex];
+ if (page?.isMaterializationPlaceholder) {
+ this._scrollToPage(pageIndex);
+ this._scheduleScrollToMaterializedRange(range);
+ }
+ return;
+ }
+
+ const pages = skeleton.getSkeletonData()?.pages;
+ const rootPageIndex = anchorNodePosition.pageType === EngineRender.DocumentSkeletonPageType.HEADER ||
+ anchorNodePosition.pageType === EngineRender.DocumentSkeletonPageType.FOOTER ||
+ (anchorNodePosition.pageType === EngineRender.DocumentSkeletonPageType.CELL && pages?.[anchorNodePosition.page] == null)
+ ? anchorNodePosition.segmentPage
+ : anchorNodePosition.page;
+ const rootPage = pages?.[rootPageIndex];
+ if (rootPage == null || rootPage.isLayoutPlaceholder) {
+ return;
+ }
+
+ this.scrollToNode(anchorNodePosition);
+ }
+
+ private _scheduleScrollToMaterializedRange(range: ITextRangeParam, attempt = 0): void {
+ if (typeof requestAnimationFrame === 'undefined' || attempt >= 120) {
+ return;
+ }
+ if (this._pendingSelectionScrollFrame != null) {
+ cancelAnimationFrame(this._pendingSelectionScrollFrame);
+ }
+ this._pendingSelectionScrollFrame = requestAnimationFrame(() => {
+ this._pendingSelectionScrollFrame = null;
+ const skeleton = this._docSkeletonManagerService.getSkeleton();
+ const pageIndex = skeleton.findBodyPageIndexByCharIndex(range.startOffset);
+ if (skeleton.getSkeletonData()?.pages[pageIndex]?.isMaterializationPlaceholder) {
+ this._scheduleScrollToMaterializedRange(range, attempt + 1);
+ return;
+ }
+ this.scrollToRange(range);
+ });
+ }
- anchorNodePosition && this.scrollToNode(anchorNodePosition);
+ private _scrollToPage(pageIndex: number): void {
+ const { mainComponent, scene } = this._context;
+ const skeleton = this._docSkeletonManagerService.getSkeleton();
+ const pages = skeleton.getSkeletonData()?.pages;
+ if (!(mainComponent instanceof EngineRender.Documents) || pages == null || pages[pageIndex] == null) {
+ return;
+ }
+ const viewportMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+ if (viewportMain == null) {
+ return;
+ }
+ const {
+ docsLeft,
+ docsTop,
+ pageLayoutType = EngineRender.PageLayoutType.VERTICAL,
+ pageMarginLeft,
+ pageMarginTop,
+ } = mainComponent.getOffsetConfig();
+ let pageLeft = docsLeft;
+ let pageTop = docsTop;
+ for (let index = 0; index < pageIndex; index++) {
+ if (pageLayoutType === EngineRender.PageLayoutType.HORIZONTAL) {
+ pageLeft += pages[index].pageWidth + pageMarginLeft;
+ } else {
+ pageTop += pages[index].pageHeight + pageMarginTop;
+ }
+ }
+ const viewBound = viewportMain.calcViewportInfo().viewBound;
+ const offsetX = pageLayoutType === EngineRender.PageLayoutType.HORIZONTAL
+ ? pageLeft - viewBound.left
+ : 0;
+ const offsetY = pageLayoutType === EngineRender.PageLayoutType.HORIZONTAL
+ ? 0
+ : pageTop - viewBound.top;
+ viewportMain.scrollByBarDeltaValue(
+ viewportMain.transViewportScroll2ScrollValue(offsetX, offsetY)
+ );
}
- scrollToNode(startNodePosition: Nullable<INodePosition>) {
+ scrollToNode(startNodePosition: Nullable<EngineRender.INodePosition>) {
const { unitId, scene, mainComponent } = this._context;
const skeleton = this._docSkeletonManagerService.getSkeleton();
- if (mainComponent == null || skeleton == null) {
+ if (!(mainComponent instanceof EngineRender.Documents) || skeleton == null) {
return;
}
- const documentOffsetConfig = (mainComponent as Documents).getOffsetConfig();
+ const documentOffsetConfig = mainComponent.getOffsetConfig();
const { docsLeft, docsTop } = documentOffsetConfig;
const convertor = new NodePositionConvertToCursor(documentOffsetConfig, skeleton);
const { contentBoxPointGroup } = convertor.getRangePointData(startNodePosition, startNodePosition);
+ if (contentBoxPointGroup.length === 0) {
+ return;
+ }
const { left: aLeft, top: aTop, height } = getAnchorBounding(contentBoxPointGroup);
@@ -132,12 +243,15 @@ export class DocBackScrollRenderController extends RxDisposable implements IRend
return;
}
- const { collapsed, startNodePosition } = activeTextRange;
+ const { collapsed } = activeTextRange;
if (!collapsed) {
return;
}
- this.scrollToNode(startNodePosition);
+ // Incremental publication replaces page and line objects. Resolve the
+ // current position from stable document offsets instead of reusing a
+ // cached node path from an older skeleton generation.
+ this.scrollToRange(activeTextRange);
}
}
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-canvas-popup-layout-interaction.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-canvas-popup-layout-interaction.controller.ts
new file mode 100644
index 0000000000..e99b8d6419
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-canvas-popup-layout-interaction.controller.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 { DocumentDataModel, IDisposable } from '@univerjs/core';
+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import { Disposable, Inject } from '@univerjs/core';
+import { DocLayoutInteractionService } from '../../services/doc-layout-interaction.service';
+import { DocCanvasPopManagerService } from '../../services/doc-popup-manager.service';
+
+/** Keeps a document skeleton stable while one of its canvas popups is mounted. */
+export class DocCanvasPopupLayoutInteractionController extends Disposable implements IRenderModule {
+ private _layoutInteraction: IDisposable | null = null;
+
+ constructor(
+ private readonly _context: Pick<IRenderContext<DocumentDataModel>, 'unitId'>,
+ @Inject(DocCanvasPopManagerService) private readonly _canvasPopupManagerService: Pick<DocCanvasPopManagerService, 'popupUnits$'>,
+ @Inject(DocLayoutInteractionService) private readonly _docLayoutInteractionService: DocLayoutInteractionService
+ ) {
+ super();
+
+ this.disposeWithMe(this._canvasPopupManagerService.popupUnits$.subscribe((popupUnits) => {
+ if (popupUnits.has(this._context.unitId)) {
+ this._layoutInteraction ??= this._docLayoutInteractionService.beginInteraction();
+ } else {
+ this._endInteraction();
+ }
+ }));
+ }
+
+ override dispose(): void {
+ this._endInteraction();
+ super.dispose();
+ }
+
+ private _endInteraction(): void {
+ this._layoutInteraction?.dispose();
+ this._layoutInteraction = null;
+ }
+}
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-layout-recovery.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-layout-recovery.render-controller.ts
new file mode 100644
index 0000000000..9a6af12120
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-layout-recovery.render-controller.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, IDisposable } from '@univerjs/core';
+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import { Inject, RxDisposable, toDisposable } from '@univerjs/core';
+import { DocLayoutExecutorService, DocLayoutExecutorState } from '@univerjs/docs';
+import { IShortcutService } from '@univerjs/ui';
+import { takeUntil } from 'rxjs';
+import { DocCanvasPopManagerService } from '../../services/doc-popup-manager.service';
+import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';
+import { DOC_LAYOUT_RECOVERY_COMPONENT } from '../../views/DocLayoutRecovery';
+
+export function acquireDocLayoutRecoveryInteractionLock(
+ canvas: HTMLElement,
+ shortcutService: Pick<IShortcutService, 'forceDisable'>,
+ blurSelection: () => void
+): IDisposable {
+ const previousPointerEvents = canvas.style.pointerEvents;
+ const previousOpacity = canvas.style.opacity;
+ const previousAriaBusy = canvas.getAttribute('aria-busy');
+ const shortcutLock = shortcutService.forceDisable();
+
+ blurSelection();
+ canvas.style.pointerEvents = 'none';
+ canvas.style.opacity = '0.55';
+ canvas.setAttribute('aria-busy', 'true');
+
+ return toDisposable(() => {
+ shortcutLock.dispose();
+ canvas.style.pointerEvents = previousPointerEvents;
+ canvas.style.opacity = previousOpacity;
+ if (previousAriaBusy == null) {
+ canvas.removeAttribute('aria-busy');
+ } else {
+ canvas.setAttribute('aria-busy', previousAriaBusy);
+ }
+ });
+}
+
+export class DocLayoutRecoveryRenderController extends RxDisposable implements IRenderModule {
+ private _popup: IDisposable | null = null;
+ private _interactionLock: IDisposable | null = null;
+ private _visible = false;
+
+ constructor(
+ private readonly _context: IRenderContext<DocumentDataModel>,
+ @Inject(DocLayoutExecutorService) private readonly _layoutExecutorService: DocLayoutExecutorService,
+ @Inject(DocCanvasPopManagerService) private readonly _docPopupManagerService: DocCanvasPopManagerService,
+ @Inject(DocSelectionRenderService) private readonly _docSelectionRenderService: DocSelectionRenderService,
+ @IShortcutService private readonly _shortcutService: IShortcutService
+ ) {
+ super();
+
+ this._layoutExecutorService.executorStatus$.pipe(takeUntil(this.dispose$)).subscribe((status) => {
+ const recovering = status.state === DocLayoutExecutorState.RECOVERING &&
+ status.recoveryUnitId === this._context.unitId;
+ if (recovering) {
+ this._show();
+ } else {
+ this._hide();
+ }
+ });
+ }
+
+ override dispose(): void {
+ this._hide();
+ super.dispose();
+ }
+
+ private _show(): void {
+ if (this._visible) {
+ return;
+ }
+
+ const canvas = this._context.engine.getCanvasElement();
+ this._visible = true;
+
+ try {
+ this._interactionLock = acquireDocLayoutRecoveryInteractionLock(
+ canvas,
+ this._shortcutService,
+ () => this._docSelectionRenderService.blur()
+ );
+ this._popup = this._docPopupManagerService.attachPopupToRect(
+ () => ({
+ left: this._context.scene.width / 2,
+ right: this._context.scene.width / 2,
+ top: this._context.scene.height / 2,
+ bottom: this._context.scene.height / 2,
+ }),
+ {
+ componentKey: DOC_LAYOUT_RECOVERY_COMPONENT,
+ customActive: true,
+ direction: 'vertical-center',
+ zIndex: 1021,
+ },
+ this._context.unitId
+ );
+ } catch {
+ this._restoreInteraction();
+ }
+ }
+
+ private _hide(): void {
+ if (!this._visible) {
+ return;
+ }
+
+ this._popup?.dispose();
+ this._popup = null;
+ this._restoreInteraction();
+ }
+
+ private _restoreInteraction(): void {
+ this._interactionLock?.dispose();
+ this._interactionLock = null;
+ this._visible = false;
+ }
+}
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-resize.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-resize.render-controller.ts
index 216f55400f..cd3f1eaaa7 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc-resize.render-controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-resize.render-controller.ts
@@ -22,6 +22,23 @@ import { animationFrameScheduler, observeOn, throttleTime } from 'rxjs';
import { DocPageLayoutService } from '../../services/doc-page-layout.service';
import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';
+export function hasRenderableDocSkeleton(component: unknown): boolean {
+ if (typeof component !== 'object' || component == null ||
+ !('getSkeleton' in component) || typeof component.getSkeleton !== 'function') {
+ return false;
+ }
+
+ const skeleton = component.getSkeleton();
+ if (typeof skeleton !== 'object' || skeleton == null ||
+ !('getSkeletonData' in skeleton) || typeof skeleton.getSkeletonData !== 'function') {
+ return false;
+ }
+
+ const skeletonData = skeleton.getSkeletonData();
+ return typeof skeletonData === 'object' && skeletonData != null &&
+ 'pages' in skeletonData && Array.isArray(skeletonData.pages) && skeletonData.pages.length > 0;
+}
+
// REFACTOR: @JOCS, move to new-docs package.
export class DocResizeRenderController extends Disposable implements IRenderModule {
constructor(
@@ -58,6 +75,12 @@ export class DocResizeRenderController extends Disposable implements IRenderModu
return;
}
+ // Keep the default document component offscreen until the first stable
+ // publication supplies real geometry, avoiding a left-aligned blank flash.
+ if (!hasRenderableDocSkeleton(this._context.mainComponent)) {
+ return;
+ }
+
this._docPageLayoutService.calculatePagePosition();
this._docSelectionRenderService.refreshRanges();
this._textSelectionManagerService.refreshSelection();
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 3d651a093f..6594dd3874 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
@@ -94,8 +94,7 @@ export class DocSelectionRenderController extends Disposable implements IRenderM
if (unitId !== this._context.unitId) {
return;
}
- this._docSelectionRenderService.removeAllRanges();
- this._docSelectionRenderService.addDocRanges(docRanges, isEditing, options);
+ this._docSelectionRenderService.replaceDocRanges(docRanges, isEditing, options);
})
);
}
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 de2da0b3d3..bba708cef2 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
@@ -14,22 +14,374 @@
* limitations under the License.
*/
-import type { DocumentDataModel, EventState, ICommandInfo, IExecutionOptions, Nullable } from '@univerjs/core';
+import type { DocumentDataModel, EventState, ICommandInfo, IDocDrawingBase, IExecutionOptions, JSONXActions, Nullable } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
-import type { DocumentSkeleton, IDocumentSkeletonPage, IRenderContext, IRenderModule, IWheelEvent } from '@univerjs/engine-render';
-import { DocumentFlavor, ICommandService, Inject, isInternalEditorID, IUniverInstanceService, RxDisposable, ThemeService, UniverInstanceType } from '@univerjs/core';
-import { DocSelectionManagerService, DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
+import type { DocumentSkeleton, IDocumentLayoutInvalidation, IDocumentLayoutPageRange, IDocumentLayoutProgress, IDocumentLayoutProtectedRange, IDocumentSkeletonPage, IRenderContext, IRenderModule, IWheelEvent } from '@univerjs/engine-render';
+import { DocumentFlavor, ICommandService, ILogService, Inject, isInternalEditorID, IUniverInstanceService, JSON1, PositionedObjectLayoutType, RxDisposable, TextX, TextXActionType, ThemeService, Tools, UniverInstanceType } from '@univerjs/core';
+import { DocLayoutExecutorService, DocSelectionManagerService, DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { DocBackground, Documents, IRenderManagerService, Layer, PageLayoutType, ScrollBar, Viewport } from '@univerjs/engine-render';
-import { combineLatest, takeUntil } from 'rxjs';
+import { combineLatest, fromEvent, merge, take, takeUntil } from 'rxjs';
import { DOCS_COMPONENT_BACKGROUND_LAYER_INDEX, DOCS_COMPONENT_DEFAULT_Z_INDEX, DOCS_COMPONENT_HEADER_LAYER_INDEX, DOCS_COMPONENT_MAIN_LAYER_INDEX, DOCS_VIEW_KEY, VIEWPORT_KEY } from '../../basics/docs-view-key';
+import { DocLayoutCoordinatorService } from '../../services/doc-layout-coordinator.service';
+import { DocLayoutInteractionService } from '../../services/doc-layout-interaction.service';
import { DocPageLayoutService } from '../../services/doc-page-layout.service';
import { resolveDocRenderBackground } from '../../services/doc-render-background';
import { DocViewScaleService } from '../../services/doc-view-scale';
import { IEditorService } from '../../services/editor/editor-manager.service';
+import { NodePositionConvertToCursor } from '../../services/selection/convert-text-range';
import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';
+import { getAnchorBounding } from '../../services/selection/text-range';
+
+function getBodyTextXActions(actions: JSONXActions, segmentId?: string): unknown[] | undefined {
+ if (segmentId || actions == null || actions.length !== 2 || actions[0] !== 'body') {
+ return undefined;
+ }
+
+ const editComponent = actions[1];
+ if (
+ typeof editComponent !== 'object' ||
+ editComponent == null ||
+ !('et' in editComponent) ||
+ editComponent.et !== TextX.name ||
+ !('e' in editComponent) ||
+ !Array.isArray(editComponent.e)
+ ) {
+ return undefined;
+ }
+
+ return editComponent.e;
+}
+
+function getTextXActionLength(action: unknown): number | undefined {
+ if (typeof action !== 'object' || action == null || !('t' in action) || !('len' in action)) {
+ return undefined;
+ }
+ return typeof action.len === 'number' && Number.isFinite(action.len) && action.len >= 0
+ ? action.len
+ : undefined;
+}
+
+function isPlainTextXRetain(action: object & { t: unknown }): boolean {
+ return action.t === TextXActionType.RETAIN &&
+ !('body' in action) &&
+ !('oldBody' in action) &&
+ !('coverType' in action);
+}
+
+function getBodyMutationInvalidation(
+ actions: JSONXActions,
+ segmentId?: string
+): IDocumentLayoutInvalidation | undefined {
+ const textActions = getBodyTextXActions(actions, segmentId);
+ if (textActions == null) {
+ return undefined;
+ }
+
+ let oldOffset = 0;
+ let newOffset = 0;
+ let invalidation: IDocumentLayoutInvalidation | undefined;
+ let sawTrailingRetain = false;
+ for (const action of textActions) {
+ const length = getTextXActionLength(action);
+ if (length == null || typeof action !== 'object' || action == null || !('t' in action)) {
+ return undefined;
+ }
+
+ if (isPlainTextXRetain(action)) {
+ oldOffset += length;
+ newOffset += length;
+ sawTrailingRetain ||= invalidation != null;
+ continue;
+ }
+ if (sawTrailingRetain) {
+ // Multiple disjoint edits need more than one offset transform. Fall
+ // back to ordinary suffix pagination instead of reusing a wrong tail.
+ return undefined;
+ }
+
+ invalidation ??= {
+ oldStart: oldOffset,
+ oldEnd: oldOffset,
+ newEnd: newOffset,
+ };
+ switch (action.t) {
+ case TextXActionType.RETAIN:
+ oldOffset += length;
+ newOffset += length;
+ break;
+ case TextXActionType.INSERT:
+ newOffset += length;
+ break;
+ case TextXActionType.DELETE:
+ oldOffset += length;
+ break;
+ default:
+ return undefined;
+ }
+ invalidation.oldEnd = oldOffset;
+ invalidation.newEnd = newOffset;
+ }
+
+ return invalidation;
+}
+
+interface IDrawingLayoutTransition {
+ before?: PositionedObjectLayoutType;
+ after?: PositionedObjectLayoutType;
+}
+
+function isPositionedObjectLayoutType(value: unknown): value is PositionedObjectLayoutType {
+ switch (value) {
+ case PositionedObjectLayoutType.INLINE:
+ case PositionedObjectLayoutType.WRAP_NONE:
+ case PositionedObjectLayoutType.WRAP_POLYGON:
+ case PositionedObjectLayoutType.WRAP_SQUARE:
+ case PositionedObjectLayoutType.WRAP_THROUGH:
+ case PositionedObjectLayoutType.WRAP_TIGHT:
+ case PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM:
+ return true;
+ default:
+ return false;
+ }
+}
+
+function getDrawingLayoutType(value: unknown): PositionedObjectLayoutType | undefined {
+ if (typeof value !== 'object' || value == null || !('layoutType' in value)) {
+ return undefined;
+ }
+
+ const layoutType = value.layoutType;
+ return isPositionedObjectLayoutType(layoutType) ? layoutType : undefined;
+}
+
+function isRichTextEditingMutationParams(value: unknown): value is IRichTextEditingMutationParams {
+ return typeof value === 'object' && value != null &&
+ 'unitId' in value && typeof value.unitId === 'string' &&
+ 'actions' in value && (value.actions == null || Array.isArray(value.actions));
+}
+
+function doesMutationScheduleLocalSelectionUpdate(
+ params: IRichTextEditingMutationParams,
+ isRemoteMutation: boolean
+): boolean {
+ return !isRemoteMutation &&
+ params.isSync !== true &&
+ params.noNeedSetTextRange !== true &&
+ params.trigger != null &&
+ params.textRanges != null;
+}
+
+const EDIT_WORKER_RESUME_DELAY_MS = 150;
+const MATERIALIZED_PAGE_WINDOW_SIZE = 5;
+
+function resolveMaterializedPageAxis(
+ docsComponent: unknown,
+ viewport: Nullable<Viewport>
+): { pageGap: number; vertical: boolean; viewportCenter: number } | null {
+ if (!(docsComponent instanceof Documents) || viewport == null) {
+ return null;
+ }
+ const viewBound = viewport.calcViewportInfo().viewBound;
+ const {
+ docsLeft,
+ docsTop,
+ pageLayoutType = PageLayoutType.VERTICAL,
+ pageMarginLeft,
+ pageMarginTop,
+ } = docsComponent.getOffsetConfig();
+ const vertical = pageLayoutType !== PageLayoutType.HORIZONTAL;
+ return {
+ pageGap: vertical ? pageMarginTop : pageMarginLeft,
+ vertical,
+ viewportCenter: vertical
+ ? (viewBound.top + viewBound.bottom) / 2 - docsTop
+ : (viewBound.left + viewBound.right) / 2 - docsLeft,
+ };
+}
+
+interface IDocLayoutViewportAnchor {
+ offset: number;
+ relativeLeft: number;
+ relativeTop: number;
+}
+
+interface IDocLayoutWorkerHandoff {
+ layoutRequestId: number;
+ run: () => void;
+ waitForInteractionEnd: boolean;
+}
+
+interface IDocLayoutWorkerEditBatch {
+ anchor: number | undefined;
+ invalidation: IDocumentLayoutInvalidation | undefined;
+}
+
+interface IDocLayoutScheduleOptions {
+ reason: 'initial' | 'edit';
+ anchor?: number;
+ priorityAnchor?: number;
+ invalidation?: IDocumentLayoutInvalidation;
+}
+
+function mapPreviousOffsetToCurrent(
+ offset: number,
+ invalidation: IDocumentLayoutInvalidation | undefined
+): number {
+ if (invalidation == null || offset < invalidation.oldStart) {
+ return offset;
+ }
+ if (offset >= invalidation.oldEnd) {
+ return offset + invalidation.newEnd - invalidation.oldEnd;
+ }
+ return invalidation.newEnd;
+}
+
+function mergeDocumentLayoutInvalidations(
+ previous: IDocumentLayoutInvalidation | undefined,
+ current: IDocumentLayoutInvalidation | undefined
+): IDocumentLayoutInvalidation | undefined {
+ if (previous == null || current == null) {
+ return undefined;
+ }
+
+ const previousDelta = previous.newEnd - previous.oldEnd;
+ const mapCurrentToPrevious = (offset: number): number => {
+ if (offset < previous.oldStart) {
+ return offset;
+ }
+ if (offset < previous.newEnd) {
+ return previous.oldStart;
+ }
+ return offset - previousDelta;
+ };
+ const oldStart = Math.min(previous.oldStart, mapCurrentToPrevious(current.oldStart));
+ const oldEnd = Math.max(previous.oldEnd, mapCurrentToPrevious(current.oldEnd));
+ const currentDelta = current.newEnd - current.oldEnd;
+ return {
+ oldStart,
+ oldEnd,
+ newEnd: oldEnd + previousDelta + currentDelta,
+ };
+}
+
+function findContinuousLayoutEndOffset(
+ page: IDocumentSkeletonPage,
+ documentTop: number,
+ viewportTop: number,
+ viewportBottom: number
+): number | undefined {
+ const protectedBottom = viewportBottom + Math.max(0, viewportBottom - viewportTop);
+ let endOffset: number | undefined;
+
+ for (const section of page.sections) {
+ for (const column of section.columns) {
+ const localBottom = protectedBottom - documentTop - page.marginTop - section.top;
+ let low = 0;
+ let high = column.lines.length;
+ while (low < high) {
+ const middle = low + Math.floor((high - low) / 2);
+ if (column.lines[middle].top <= localBottom) {
+ low = middle + 1;
+ } else {
+ high = middle;
+ }
+ }
+ const lastVisibleLine = column.lines[low - 1];
+ if (lastVisibleLine != null) {
+ endOffset = Math.max(endOffset ?? lastVisibleLine.ed, lastVisibleLine.ed);
+ }
+ }
+ }
+
+ return endOffset;
+}
+
+type DocLayoutCoordinatorCallbacks = Parameters<DocLayoutCoordinatorService['schedule']>[2];
+
+/**
+ * Returns false only when a mutation is proven to touch overlay-only drawings.
+ *
+ * WRAP_NONE drawings are positioned independently from text, so moving, resizing,
+ * rotating, or switching them between front/behind text must refresh drawing
+ * geometry without starting a document layout generation. Every uncertain case
+ * remains conservative and reflows.
+ */
+export function doesDocMutationRequireLayout(
+ actions: JSONXActions,
+ drawings: Record<string, IDocDrawingBase> | undefined
+): boolean {
+ if (actions == null || !Array.isArray(actions) || actions.length === 0) {
+ return true;
+ }
+
+ const transitions = new Map<string, IDrawingLayoutTransition>();
+ let sawComponent = false;
+ let drawingOnly = true;
+
+ try {
+ const cursor = JSON1.type.readCursor(actions);
+ cursor.traverse(null, (component) => {
+ sawComponent = true;
+ const path = cursor.getPath();
+ const drawingId = path[1];
+ if (path[0] !== 'drawings' || typeof drawingId !== 'string') {
+ drawingOnly = false;
+ return;
+ }
+
+ const transition = transitions.get(drawingId) ?? {};
+ if (path.length === 2) {
+ transition.before = getDrawingLayoutType(component.r);
+ transition.after = getDrawingLayoutType(component.i);
+ } else if (path.length === 3 && path[2] === 'layoutType') {
+ transition.before = isPositionedObjectLayoutType(component.r)
+ ? component.r
+ : transition.before;
+ transition.after = isPositionedObjectLayoutType(component.i)
+ ? component.i
+ : transition.after;
+ }
+ transitions.set(drawingId, transition);
+ });
+ } catch {
+ return true;
+ }
+
+ if (!sawComponent || !drawingOnly || transitions.size === 0) {
+ return true;
+ }
+
+ for (const [drawingId, transition] of transitions) {
+ const currentLayoutType = drawings?.[drawingId]?.layoutType;
+ const before = transition.before ?? currentLayoutType;
+ const after = transition.after ?? currentLayoutType;
+ if (
+ before == null ||
+ after == null ||
+ before !== PositionedObjectLayoutType.WRAP_NONE ||
+ after !== PositionedObjectLayoutType.WRAP_NONE
+ ) {
+ return true;
+ }
+ }
+
+ return false;
+}
export class DocRenderController extends RxDisposable implements IRenderModule {
private _changesetRenderScheduled = false;
+ private readonly _layoutCoordinator: DocLayoutCoordinatorService;
+ private _layoutRequestId = 0;
+ private _workerHandoffTimer: ReturnType<typeof setTimeout> | null = null;
+ private _workerPresentationResumeTimer: ReturnType<typeof setTimeout> | null = null;
+ private _pendingWorkerHandoff: IDocLayoutWorkerHandoff | null = null;
+ private _pendingWorkerEditBatch: IDocLayoutWorkerEditBatch | null = null;
+ private _isImeComposing = false;
+ private _recoveryViewportAnchor: IDocLayoutViewportAnchor | null = null;
+ private _pendingMaterializedPageRange: IDocumentLayoutPageRange | null = null;
+ private _isMaterializingPages = false;
+ private _reservedLayoutWidth = 0;
+ private _reservedLayoutHeight = 0;
constructor(
private readonly _context: IRenderContext<DocumentDataModel>,
@@ -42,19 +394,70 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
@Inject(DocPageLayoutService) private readonly _docPageLayoutService: DocPageLayoutService,
@Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,
@Inject(DocViewScaleService) private readonly _docViewScaleService: DocViewScaleService,
- @Inject(ThemeService) private readonly _themeService: ThemeService
+ @Inject(ThemeService) private readonly _themeService: ThemeService,
+ @Inject(DocLayoutExecutorService) private readonly _docLayoutExecutorService: DocLayoutExecutorService,
+ @Inject(DocLayoutInteractionService) private readonly _docLayoutInteractionService: DocLayoutInteractionService,
+ @ILogService private readonly _logService: ILogService
) {
super();
+ this._layoutCoordinator = new DocLayoutCoordinatorService((callback) =>
+ this._scheduleVisualFrame(callback));
+ this.disposeWithMe(this._layoutCoordinator);
+
this._addNewRender();
this._initRenderRefresh();
this._initCommandListener();
+ this._initInteractionLayoutProtection();
this._initThemeListener();
}
- reRender(unitId: string) {
+ private _scheduleVisualFrame(callback: () => void): () => void {
+ const beginFrame$ = this._context.engine.beginFrame$;
+ if (beginFrame$ == null) {
+ const frameId = requestAnimationFrame(callback);
+ return () => cancelAnimationFrame(frameId);
+ }
+
+ let disposed = false;
+ let unsubscribe: (() => void) | null = null;
+ const schedule = () => {
+ const subscription = beginFrame$.pipe(take(1)).subscribe(() => {
+ if (disposed) {
+ return;
+ }
+
+ const parent = this._context.scene.getParent();
+ if (parent == null || parent.width <= 1 || parent.height <= 1) {
+ schedule();
+ return;
+ }
+ callback();
+ });
+ unsubscribe = () => subscription.unsubscribe();
+ };
+ schedule();
+
+ return () => {
+ disposed = true;
+ unsubscribe?.();
+ };
+ }
+
+ reRender(
+ unitId: string,
+ anchor?: number,
+ invalidation?: IDocumentLayoutInvalidation,
+ priorityAnchor?: number,
+ refreshMainSelection = true,
+ preserveInactiveViewportAnchor = false
+ ) {
const docSkeletonManagerService = this._renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService);
- const skeleton = docSkeletonManagerService?.getSkeleton();
+ if (!docSkeletonManagerService) {
+ return;
+ }
+
+ const skeleton = docSkeletonManagerService.getSkeleton();
if (!skeleton) {
return;
}
@@ -65,18 +468,885 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
return;
}
- skeleton.calculate();
+ if (!docSkeletonManagerService.supportsIncrementalLayout()) {
+ docSkeletonManagerService.recalculate();
+ return;
+ }
+
+ const hasExplicitEditAnchor = anchor != null || priorityAnchor != null || invalidation != null;
+ const layoutOptions: IDocLayoutScheduleOptions = !skeleton.hasCompleteLayout() && !hasExplicitEditAnchor
+ ? { reason: 'initial' }
+ : { reason: 'edit', anchor: anchor ?? 0, priorityAnchor, invalidation };
+ this._scheduleLayout(
+ unitId,
+ skeleton,
+ layoutOptions,
+ refreshMainSelection,
+ preserveInactiveViewportAnchor
+ );
+ }
+
+ override dispose(): void {
+ this._layoutRequestId++;
+ if (this._workerHandoffTimer != null) {
+ clearTimeout(this._workerHandoffTimer);
+ this._workerHandoffTimer = null;
+ }
+ if (this._workerPresentationResumeTimer != null) {
+ clearTimeout(this._workerPresentationResumeTimer);
+ this._workerPresentationResumeTimer = null;
+ }
+ this._pendingWorkerHandoff = null;
+ this._pendingWorkerEditBatch = null;
+ this._pendingMaterializedPageRange = null;
+ this._recoveryViewportAnchor = null;
+ super.dispose();
+ }
+
+ refreshCustomBlockPresentation(unitId: string): boolean {
+ const skeleton = this._renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService)?.getSkeleton();
+ if (skeleton == null) {
+ return false;
+ }
+
+ const result = skeleton.refreshCustomBlockPresentationViewports();
+ if (result.didRefresh) {
+ this._context.mainComponent?.makeDirty(true);
+ this._context.components.get(DOCS_VIEW_KEY.BACKGROUND)?.makeDirty(true);
+ }
+
+ return !result.requiresLayout;
+ }
+
+ private _scheduleLayout(
+ unitId: string,
+ skeleton: DocumentSkeleton,
+ options: IDocLayoutScheduleOptions,
+ refreshMainSelection = true,
+ preserveInactiveViewportAnchor = false
+ ) {
+ const layoutRequestId = ++this._layoutRequestId;
+ this._cancelWorkerHandoff();
+ const isInitialLayout = options.reason === 'initial';
+ const docsComponent = this._context.mainComponent;
+ if (!(docsComponent instanceof Documents)) {
+ return;
+ }
+ this._prepareReservedLayoutExtent(skeleton, docsComponent);
+
+ const mainThreadCallbacks = this._createLayoutCallbacks(
+ unitId,
+ skeleton,
+ options,
+ refreshMainSelection,
+ true,
+ preserveInactiveViewportAnchor,
+ undefined,
+ false
+ );
+ if (this._docLayoutExecutorService.getExecutor() == null) {
+ this._pendingWorkerEditBatch = null;
+ this._layoutCoordinator.schedule(skeleton, options, mainThreadCallbacks);
+ return;
+ }
+ const workerOptions = isInitialLayout
+ ? options
+ : this._accumulateWorkerEditBatch(options);
+ if (isInitialLayout) {
+ this._pendingWorkerEditBatch = null;
+ this._scheduleInitialInteractionWindow(
+ layoutRequestId,
+ unitId,
+ skeleton,
+ options,
+ workerOptions,
+ mainThreadCallbacks,
+ preserveInactiveViewportAnchor
+ );
+ return;
+ }
+
+ this._scheduleMainInteractionWindow(
+ layoutRequestId,
+ unitId,
+ skeleton,
+ options,
+ workerOptions,
+ mainThreadCallbacks,
+ refreshMainSelection,
+ preserveInactiveViewportAnchor
+ );
+ }
+
+ private _scheduleInitialInteractionWindow(
+ layoutRequestId: number,
+ unitId: string,
+ skeleton: DocumentSkeleton,
+ options: IDocLayoutScheduleOptions,
+ workerOptions: IDocLayoutScheduleOptions,
+ mainThreadCallbacks: DocLayoutCoordinatorCallbacks,
+ preserveInactiveViewportAnchor: boolean
+ ): void {
+ this._layoutCoordinator.schedule(skeleton, options, {
+ onProgress: mainThreadCallbacks.onProgress,
+ onForegroundReady: (progress) => {
+ if (progress.complete) {
+ return;
+ }
+
+ const protectedRange = this._resolveProtectedRange(skeleton, 0, progress);
+ this._queueWorkerHandoff(layoutRequestId, () => {
+ this._scheduleWorkerLayout(
+ layoutRequestId,
+ unitId,
+ skeleton,
+ options,
+ workerOptions,
+ protectedRange,
+ mainThreadCallbacks,
+ preserveInactiveViewportAnchor
+ );
+ });
+ },
+ });
+ }
+
+ private _prepareReservedLayoutExtent(skeleton: DocumentSkeleton, docsComponent: Documents): void {
+ if (skeleton.hasCompleteLayout()) {
+ // Editing keeps the previous complete document extent along the flow
+ // axis. The scene is a viewport and may still have its 1500px default,
+ // so it must never seed document geometry.
+ this._reservedLayoutWidth = Math.max(this._reservedLayoutWidth, docsComponent.width || 0);
+ this._reservedLayoutHeight = Math.max(this._reservedLayoutHeight, docsComponent.height || 0);
+ } else {
+ // First-open layout has no stable extent to preserve. Let the first
+ // published page establish its real cross-axis size immediately.
+ this._reservedLayoutWidth = 0;
+ this._reservedLayoutHeight = 0;
+ }
+ }
+
+ private _scheduleMainInteractionWindow(
+ layoutRequestId: number,
+ unitId: string,
+ skeleton: DocumentSkeleton,
+ options: IDocLayoutScheduleOptions,
+ workerOptions: IDocLayoutScheduleOptions,
+ mainThreadCallbacks: DocLayoutCoordinatorCallbacks,
+ refreshMainSelection: boolean,
+ preserveInactiveViewportAnchor: boolean
+ ): void {
+ // A local post-edit caret stays inside the mutation's new range, so Main
+ // must rebuild from the mutation start (notably when Enter splits a
+ // paragraph). A transformed local caret outside that range identifies a
+ // remote edit; keep protecting the local interaction page in that case.
+ const priorityAnchorBelongsToMutation = options.priorityAnchor != null &&
+ options.invalidation != null &&
+ options.priorityAnchor >= options.invalidation.oldStart &&
+ options.priorityAnchor <= options.invalidation.newEnd;
+ const interactionAnchor = priorityAnchorBelongsToMutation
+ ? options.anchor
+ : options.priorityAnchor ?? options.anchor;
+ let interactionViewportAnchor = priorityAnchorBelongsToMutation
+ ? null
+ : this._captureViewportAnchor(
+ skeleton,
+ options.priorityAnchor,
+ options.invalidation
+ );
+ const foregroundEndOffset = this._resolveContinuousForegroundEndOffset(
+ skeleton,
+ options.invalidation
+ );
+ this._layoutCoordinator.schedule(skeleton, {
+ ...options,
+ anchor: interactionAnchor,
+ foregroundEndOffset,
+ preserveInteractionWindow: interactionAnchor != null && interactionAnchor !== options.anchor,
+ // The authoritative Worker recomputes the suffix after the protected
+ // interaction window. Deep-cloning and shifting the complete previous
+ // tail on Main would duplicate that work in the input task and turns a
+ // one-page edit into an O(document pages) operation.
+ reuseUnaffectedTail: false,
+ }, {
+ onProgress: (progress, publication) => {
+ mainThreadCallbacks.onProgress(progress, publication);
+ if (
+ interactionViewportAnchor != null &&
+ (progress.didPublishAnchor || progress.complete)
+ ) {
+ this._restoreViewportAnchor(skeleton, interactionViewportAnchor);
+ interactionViewportAnchor = null;
+ }
+ },
+ onForegroundReady: (progress) => {
+ this._refreshSelectionAfterForegroundLayout(unitId, refreshMainSelection);
+ const protectedRange = this._resolveProtectedRange(
+ skeleton,
+ options.priorityAnchor ?? options.anchor,
+ progress
+ );
+ this._queueWorkerHandoff(layoutRequestId, () => {
+ this._scheduleWorkerLayout(
+ layoutRequestId,
+ unitId,
+ skeleton,
+ options,
+ workerOptions,
+ protectedRange,
+ mainThreadCallbacks,
+ preserveInactiveViewportAnchor
+ );
+ });
+ },
+ });
+ }
+
+ private _refreshSelectionAfterForegroundLayout(unitId: string, refreshMainSelection: boolean): void {
+ if (refreshMainSelection) {
+ return;
+ }
+
+ // RichTextEditingMutation advances the logical range in a microtask. The
+ // foreground window can replace its adjacent page afterwards, so rebuild
+ // the caret before handing the remaining suffix to the Worker.
+ this._refreshPagePositionAndSelection(this._getActiveEditingRange(unitId) != null);
+ }
+
+ private _resolveContinuousForegroundEndOffset(
+ skeleton: DocumentSkeleton,
+ invalidation: IDocumentLayoutInvalidation | undefined
+ ): number | undefined {
+ if (this._context.unit.getSnapshot().documentStyle.documentFlavor !== DocumentFlavor.MODERN) {
+ return undefined;
+ }
+
+ const page = skeleton.getSkeletonData()?.pages[0];
+ const docsComponent = this._context.mainComponent;
+ const viewport = this._context.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+ if (page == null || !(docsComponent instanceof Documents) || viewport == null) {
+ return undefined;
+ }
+
+ const viewBound = viewport.calcViewportInfo().viewBound;
+ if (!Number.isFinite(viewBound.top) || !Number.isFinite(viewBound.bottom)) {
+ return undefined;
+ }
+
+ const previousEndOffset = findContinuousLayoutEndOffset(
+ page,
+ docsComponent.getOffsetConfig().docsTop,
+ viewBound.top,
+ viewBound.bottom
+ );
+ return previousEndOffset == null
+ ? undefined
+ : mapPreviousOffsetToCurrent(previousEndOffset, invalidation);
+ }
+
+ private _createLayoutCallbacks(
+ unitId: string,
+ skeleton: DocumentSkeleton,
+ options: IDocLayoutScheduleOptions,
+ refreshIncompleteAnchorSelection: boolean,
+ refreshCompleteSelection: boolean,
+ preserveInactiveViewportAnchor: boolean,
+ layoutRequestId: number | undefined,
+ deferCompleteDuringInteraction: boolean
+ ): DocLayoutCoordinatorCallbacks {
+ const isInitialLayout = options.reason === 'initial';
+ return {
+ onProgress: (progress, publication) => this._handleLayoutProgress(
+ unitId,
+ skeleton,
+ options,
+ progress,
+ publication,
+ isInitialLayout,
+ refreshIncompleteAnchorSelection,
+ refreshCompleteSelection,
+ preserveInactiveViewportAnchor,
+ layoutRequestId,
+ deferCompleteDuringInteraction
+ ),
+ };
+ }
+
+ private _handleLayoutProgress(
+ unitId: string,
+ skeleton: DocumentSkeleton,
+ options: IDocLayoutScheduleOptions,
+ progress: IDocumentLayoutProgress,
+ publication: Parameters<DocumentSkeleton['applyLayoutPublication']>[0] | null | undefined,
+ isInitialLayout: boolean,
+ refreshIncompleteAnchorSelection: boolean,
+ refreshCompleteSelection: boolean,
+ preserveInactiveViewportAnchor: boolean,
+ layoutRequestId: number | undefined,
+ deferCompleteDuringInteraction: boolean
+ ): void {
+ if (!progress.didPublish) {
+ return;
+ }
+ if (
+ deferCompleteDuringInteraction &&
+ progress.complete &&
+ publication != null &&
+ layoutRequestId != null &&
+ this._docLayoutInteractionService.isActive
+ ) {
+ this._queueWorkerHandoff(
+ layoutRequestId,
+ () => this._handleLayoutProgress(
+ unitId,
+ skeleton,
+ options,
+ progress,
+ publication,
+ isInitialLayout,
+ refreshIncompleteAnchorSelection,
+ refreshCompleteSelection,
+ preserveInactiveViewportAnchor,
+ layoutRequestId,
+ false
+ ),
+ true
+ );
+ return;
+ }
+ const completionViewportAnchor = this._captureCompletionViewportAnchor(
+ unitId,
+ skeleton,
+ publication != null && progress.complete && !isInitialLayout,
+ preserveInactiveViewportAnchor
+ );
+ const applyResult = this._applyLayoutPublication(unitId, skeleton, publication, progress);
- // REFACTOR: @Jocs, should not use scroll bar to indicate a Zen Editor. refactor after support modern doc.
const editorRenderConfig = this._editorService.getEditorRenderConfig(unitId);
if (editorRenderConfig && !editorRenderConfig.scrollBar) {
- this._context.mainComponent?.makeDirty();
+ this._markDocumentRenderDirty();
+ return;
+ }
+
+ this._recalculateSizeBySkeleton(skeleton, progress);
+ if (progress.complete) {
+ this._completeLayoutPresentation(
+ unitId,
+ skeleton,
+ completionViewportAnchor,
+ refreshCompleteSelection,
+ refreshIncompleteAnchorSelection,
+ applyResult?.didReplaceProtectedPages === true
+ );
+ } else if (isInitialLayout) {
+ this._refreshPagePosition();
+ } else if (progress.didPublishAnchor && refreshIncompleteAnchorSelection) {
+ // The foreground pass replaces edited line and glyph objects. Rebuild
+ // the caret from stable document offsets without moving the viewport.
+ this._textSelectionManagerService.refreshSelection(
+ { unitId, subUnitId: unitId },
+ this._getActiveEditingRange(unitId) != null
+ );
+ }
+
+ // Size, translation and content belong to one visual publication.
+ this._markDocumentRenderDirty();
+ }
+
+ private _applyLayoutPublication(
+ unitId: string,
+ skeleton: DocumentSkeleton,
+ publication: Parameters<DocumentSkeleton['applyLayoutPublication']>[0] | null | undefined,
+ progress: IDocumentLayoutProgress
+ ): ReturnType<DocumentSkeleton['applyLayoutPublication']> | null {
+ if (publication == null) {
+ return null;
+ }
+
+ const hydrationStartedAt = Tools.now();
+ try {
+ const materializedPageRange = progress.mode === 'paginated'
+ ? this._resolveMaterializedPageRange(skeleton, progress.publishedPageCount)
+ : undefined;
+ return skeleton.applyLayoutPublication(publication, progress, materializedPageRange);
+ } finally {
+ this._docLayoutExecutorService.recordHydrationDuration(
+ unitId,
+ Tools.now() - hydrationStartedAt
+ );
+ }
+ }
+
+ private _completeLayoutPresentation(
+ unitId: string,
+ skeleton: DocumentSkeleton,
+ completionViewportAnchor: IDocLayoutViewportAnchor | null,
+ refreshCompleteSelection: boolean,
+ preserveEditingSelection: boolean,
+ didReplaceProtectedPages: boolean
+ ): void {
+ this._docLayoutExecutorService.completeRecovery(unitId);
+ if (refreshCompleteSelection || didReplaceProtectedPages) {
+ const isEditing = preserveEditingSelection ||
+ didReplaceProtectedPages ||
+ this._getActiveEditingRange(unitId) != null;
+ this._refreshPagePositionAndSelection(isEditing);
+ } else {
+ this._refreshPagePosition();
+ }
+ this._restoreViewportAnchor(skeleton, completionViewportAnchor);
+ this._restoreRecoveryViewportAnchor(skeleton);
+ }
+ private _scheduleWorkerLayout(
+ layoutRequestId: number,
+ unitId: string,
+ skeleton: DocumentSkeleton,
+ options: IDocLayoutScheduleOptions,
+ workerOptions: IDocLayoutScheduleOptions,
+ protectedRange: IDocumentLayoutProtectedRange | undefined,
+ mainThreadCallbacks: DocLayoutCoordinatorCallbacks,
+ preserveInactiveViewportAnchor: boolean,
+ allowRecovery = true
+ ): void {
+ if (layoutRequestId !== this._layoutRequestId) {
return;
}
- this._recalculateSizeBySkeleton(skeleton);
- this._refreshPagePositionAndSelection();
+ this._layoutCoordinator.scheduleWorker(
+ unitId,
+ skeleton,
+ this._docLayoutExecutorService,
+ workerOptions,
+ protectedRange,
+ {
+ ...this._createLayoutCallbacks(
+ unitId,
+ skeleton,
+ options,
+ false,
+ false,
+ preserveInactiveViewportAnchor,
+ layoutRequestId,
+ true
+ ),
+ onComplete: () => {
+ if (layoutRequestId === this._layoutRequestId) {
+ this._pendingWorkerEditBatch = null;
+ }
+ },
+ },
+ (error) => this._handleWorkerLayoutFailure(
+ layoutRequestId,
+ unitId,
+ skeleton,
+ options,
+ workerOptions,
+ protectedRange,
+ mainThreadCallbacks,
+ preserveInactiveViewportAnchor,
+ allowRecovery,
+ error
+ )
+ );
+ }
+
+ private _handleWorkerLayoutFailure(
+ layoutRequestId: number,
+ unitId: string,
+ skeleton: DocumentSkeleton,
+ options: IDocLayoutScheduleOptions,
+ workerOptions: IDocLayoutScheduleOptions,
+ protectedRange: IDocumentLayoutProtectedRange | undefined,
+ mainThreadCallbacks: DocLayoutCoordinatorCallbacks,
+ preserveInactiveViewportAnchor: boolean,
+ allowRecovery: boolean,
+ error: unknown
+ ): void {
+ if (!allowRecovery) {
+ this._logService.error('[DocRenderController]: Worker layout failed; using main-thread layout.', error);
+ this._layoutCoordinator.schedule(skeleton, options, mainThreadCallbacks);
+ return;
+ }
+
+ this._recoveryViewportAnchor = this._captureViewportAnchor(
+ skeleton,
+ options.priorityAnchor ?? options.anchor,
+ options.invalidation
+ );
+ const diagnostic = error instanceof Error ? error.message : String(error);
+ this._logService.warn('[DocRenderController]: restarting the document layout Worker after a fatal layout failure.', error);
+ this._docLayoutExecutorService.recoverExecutor(unitId, diagnostic).then(() => {
+ this._scheduleWorkerLayout(
+ layoutRequestId,
+ unitId,
+ skeleton,
+ options,
+ workerOptions,
+ protectedRange,
+ mainThreadCallbacks,
+ preserveInactiveViewportAnchor,
+ false
+ );
+ }).catch((recoveryError: unknown) => {
+ this._logService.error('[DocRenderController]: document layout Worker recovery failed; using main-thread layout.', recoveryError);
+ this._layoutCoordinator.schedule(skeleton, options, mainThreadCallbacks);
+ });
+ }
+
+ private _accumulateWorkerEditBatch(options: {
+ reason: 'initial' | 'edit';
+ anchor?: number;
+ priorityAnchor?: number;
+ invalidation?: IDocumentLayoutInvalidation;
+ }): typeof options {
+ const pending = this._pendingWorkerEditBatch;
+ this._pendingWorkerEditBatch = pending == null
+ ? {
+ anchor: options.anchor,
+ invalidation: options.invalidation,
+ }
+ : {
+ anchor: pending.anchor == null || options.anchor == null
+ ? undefined
+ : Math.min(pending.anchor, options.anchor),
+ // The Worker is still based on the preceding complete model. Compose
+ // every pending scalar edit into one conservative changed span so
+ // IME commits and continued typing retain an exact tail offset delta.
+ // A structurally ambiguous mutation remains undefined and therefore
+ // keeps the canonical full-suffix fallback.
+ invalidation: mergeDocumentLayoutInvalidations(
+ pending.invalidation,
+ options.invalidation
+ ),
+ };
+
+ return {
+ ...options,
+ anchor: this._pendingWorkerEditBatch.anchor,
+ priorityAnchor: this._pendingWorkerEditBatch.anchor,
+ invalidation: this._pendingWorkerEditBatch.invalidation,
+ };
+ }
+
+ private _initInteractionLayoutProtection(): void {
+ this._docLayoutInteractionService.active$
+ .pipe(takeUntil(this.dispose$))
+ .subscribe((active) => {
+ if (active) {
+ if (this._workerPresentationResumeTimer != null) {
+ clearTimeout(this._workerPresentationResumeTimer);
+ this._workerPresentationResumeTimer = null;
+ }
+ this._layoutCoordinator.setWorkerPresentationPaused(true);
+ if (this._pendingWorkerHandoff?.waitForInteractionEnd && this._workerHandoffTimer != null) {
+ clearTimeout(this._workerHandoffTimer);
+ this._workerHandoffTimer = null;
+ }
+ return;
+ }
+
+ this._workerPresentationResumeTimer = setTimeout(() => {
+ this._workerPresentationResumeTimer = null;
+ if (!this._docLayoutInteractionService.isActive) {
+ this._layoutCoordinator.setWorkerPresentationPaused(false);
+ }
+ }, EDIT_WORKER_RESUME_DELAY_MS);
+ this._startWorkerHandoffTimer();
+ });
+ this._docSelectionRenderService.onCompositionstart$
+ .pipe(takeUntil(this.dispose$))
+ .subscribe((config) => {
+ if (config == null) {
+ return;
+ }
+
+ this._isImeComposing = true;
+ if (this._workerHandoffTimer != null) {
+ clearTimeout(this._workerHandoffTimer);
+ this._workerHandoffTimer = null;
+ }
+ this._layoutCoordinator.cancel();
+ });
+ this._docSelectionRenderService.onCompositionend$
+ .pipe(takeUntil(this.dispose$))
+ .subscribe((config) => {
+ if (config == null) {
+ return;
+ }
+
+ this._isImeComposing = false;
+ this._startWorkerHandoffTimer();
+ });
+ }
+
+ private _queueWorkerHandoff(layoutRequestId: number, run: () => void, waitForInteractionEnd = false): void {
+ this._cancelWorkerHandoff();
+ this._pendingWorkerHandoff = { layoutRequestId, run, waitForInteractionEnd };
+ this._startWorkerHandoffTimer();
+ }
+
+ private _startWorkerHandoffTimer(): void {
+ if (
+ this._pendingWorkerHandoff == null ||
+ this._workerHandoffTimer != null ||
+ this._isImeComposing ||
+ (this._pendingWorkerHandoff.waitForInteractionEnd && this._docLayoutInteractionService.isActive)
+ ) {
+ return;
+ }
+
+ this._workerHandoffTimer = setTimeout(() => {
+ this._workerHandoffTimer = null;
+ const handoff = this._pendingWorkerHandoff;
+ if (handoff == null) {
+ return;
+ }
+ if (handoff.layoutRequestId !== this._layoutRequestId) {
+ this._pendingWorkerHandoff = null;
+ return;
+ }
+ if (
+ this._isImeComposing ||
+ (handoff.waitForInteractionEnd && this._docLayoutInteractionService.isActive) ||
+ this._docSelectionRenderService.isOnPointerEvent
+ ) {
+ this._startWorkerHandoffTimer();
+ return;
+ }
+
+ this._pendingWorkerHandoff = null;
+ handoff.run();
+ }, EDIT_WORKER_RESUME_DELAY_MS);
+ }
+
+ private _deferWorkerHandoff(): void {
+ if (this._pendingWorkerHandoff == null) {
+ return;
+ }
+ if (this._workerHandoffTimer != null) {
+ clearTimeout(this._workerHandoffTimer);
+ this._workerHandoffTimer = null;
+ }
+ this._startWorkerHandoffTimer();
+ }
+
+ private _cancelWorkerHandoff(): void {
+ if (this._workerHandoffTimer != null) {
+ clearTimeout(this._workerHandoffTimer);
+ this._workerHandoffTimer = null;
+ }
+ this._pendingWorkerHandoff = null;
+ }
+
+ private _resolveProtectedRange(
+ skeleton: DocumentSkeleton,
+ anchor: number | undefined,
+ progress: IDocumentLayoutProgress
+ ): IDocumentLayoutProtectedRange | undefined {
+ if (progress.mode === 'continuous') {
+ if (progress.stableLaidOutThrough < 0) {
+ return undefined;
+ }
+
+ return {
+ mode: 'continuous',
+ startOffset: Math.max(0, Math.min(anchor ?? progress.stableLaidOutThrough, progress.stableLaidOutThrough)),
+ endOffset: progress.stableLaidOutThrough,
+ };
+ }
+
+ const pages = skeleton.getSkeletonData()?.pages;
+ if (pages == null || pages.length === 0 || progress.publishedPageCount <= 0) {
+ return undefined;
+ }
+
+ const publishedEndPageIndex = Math.min(progress.publishedPageCount, pages.length) - 1;
+ let startPageIndex = anchor == null
+ ? Math.max(0, publishedEndPageIndex - 4)
+ : skeleton.findNodePositionByCharIndex(anchor)?.page ?? -1;
+ if (startPageIndex < 0 || startPageIndex > publishedEndPageIndex) {
+ startPageIndex = Math.max(0, publishedEndPageIndex - 4);
+ }
+
+ while (
+ startPageIndex <= publishedEndPageIndex &&
+ (pages[startPageIndex]?.isLayoutPlaceholder || pages[startPageIndex]?.isMaterializationPlaceholder)
+ ) {
+ startPageIndex++;
+ }
+ if (startPageIndex > publishedEndPageIndex) {
+ return undefined;
+ }
+
+ return {
+ mode: 'paginated',
+ startPageIndex,
+ endPageIndex: publishedEndPageIndex,
+ };
+ }
+
+ private _resolveMaterializedPageRange(
+ skeleton: DocumentSkeleton,
+ publishedPageCount?: number
+ ): IDocumentLayoutPageRange | undefined {
+ if (this._context.unit.getSnapshot().documentStyle.documentFlavor !== DocumentFlavor.TRADITIONAL) {
+ return undefined;
+ }
+ const pages = skeleton.getSkeletonData()?.pages;
+ const docsComponent = this._context.mainComponent;
+ const viewport = this._context.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+ const pageAxis = resolveMaterializedPageAxis(docsComponent, viewport);
+ if (pages == null || pages.length === 0 || pageAxis == null) {
+ return undefined;
+ }
+ const { pageGap, vertical, viewportCenter } = pageAxis;
+ let pageStart = 0;
+ let pageIndex = 0;
+ for (; pageIndex < pages.length; pageIndex++) {
+ const page = pages[pageIndex];
+ const pageExtent = vertical ? page.pageHeight : page.pageWidth;
+ if (viewportCenter <= pageStart + pageExtent) {
+ break;
+ }
+ pageStart += pageExtent + pageGap;
+ }
+ const availablePageCount = Math.max(pages.length, publishedPageCount ?? 0);
+ if (pageIndex >= pages.length && availablePageCount > pages.length) {
+ const lastPage = pages.at(-1);
+ const estimatedExtent = vertical ? lastPage?.pageHeight : lastPage?.pageWidth;
+ if (estimatedExtent != null && estimatedExtent + pageGap > 0) {
+ pageIndex += Math.floor(Math.max(0, viewportCenter - pageStart) / (estimatedExtent + pageGap));
+ }
+ }
+ pageIndex = Math.max(0, Math.min(pageIndex, availablePageCount - 1));
+ const preferredStart = Math.max(0, pageIndex - 1);
+ const endPageIndex = Math.min(
+ availablePageCount - 1,
+ preferredStart + MATERIALIZED_PAGE_WINDOW_SIZE - 1
+ );
+ return {
+ startPageIndex: Math.max(0, endPageIndex - MATERIALIZED_PAGE_WINDOW_SIZE + 1),
+ endPageIndex,
+ };
+ }
+
+ private _queueMaterializedPageRange(range: IDocumentLayoutPageRange): void {
+ this._pendingMaterializedPageRange = range;
+ if (this._isMaterializingPages) {
+ return;
+ }
+ this._isMaterializingPages = true;
+ this._materializePendingPageRanges().catch((error: unknown) => {
+ this._logService.warn('[DocRenderController]: failed to materialize a document page.', error);
+ }).finally(() => {
+ this._isMaterializingPages = false;
+ if (this._pendingMaterializedPageRange != null) {
+ this._queueMaterializedPageRange(this._pendingMaterializedPageRange);
+ }
+ });
+ }
+
+ private async _materializePendingPageRanges(): Promise<void> {
+ while (this._pendingMaterializedPageRange != null) {
+ const range = this._pendingMaterializedPageRange;
+ this._pendingMaterializedPageRange = null;
+ const requestId = this._layoutRequestId;
+ const skeleton = this._docSkeletonManagerService.getSkeleton();
+ if (skeleton == null) {
+ return;
+ }
+ for (let pageIndex = range.startPageIndex; pageIndex <= range.endPageIndex; pageIndex++) {
+ if (!skeleton.getSkeletonData()?.pages[pageIndex]?.isMaterializationPlaceholder) {
+ continue;
+ }
+ const result = await this._layoutCoordinator.getWorkerPage(pageIndex);
+ if (requestId !== this._layoutRequestId || result == null) {
+ return;
+ }
+ if (result.page == null) {
+ continue;
+ }
+ const hydrationStartedAt = Tools.now();
+ try {
+ skeleton.applyLayoutPagePublication(result.page, range);
+ } finally {
+ this._docLayoutExecutorService.recordHydrationDuration(
+ this._context.unitId,
+ Tools.now() - hydrationStartedAt
+ );
+ }
+ this._markDocumentRenderDirty();
+ }
+ }
+ }
+
+ private _captureViewportAnchor(
+ skeleton: DocumentSkeleton,
+ offset: number | undefined,
+ invalidation: IDocumentLayoutInvalidation | undefined
+ ): IDocLayoutViewportAnchor | null {
+ if (offset == null) {
+ return null;
+ }
+ const previousOffset = invalidation == null || offset < invalidation.oldStart
+ ? offset
+ : offset < invalidation.newEnd
+ ? invalidation.oldStart
+ : offset - (invalidation.newEnd - invalidation.oldEnd);
+ const position = skeleton.findNodePositionByCharIndex(previousOffset);
+ const docsComponent = this._context.mainComponent;
+ const viewport = this._context.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+ if (position == null || !(docsComponent instanceof Documents) || viewport == null) {
+ return null;
+ }
+
+ const offsetConfig = docsComponent.getOffsetConfig();
+ const convertor = new NodePositionConvertToCursor(offsetConfig, skeleton);
+ const { contentBoxPointGroup } = convertor.getRangePointData(position, position);
+ const anchor = getAnchorBounding(contentBoxPointGroup);
+ const viewBound = viewport.calcViewportInfo().viewBound;
+ return {
+ offset,
+ relativeLeft: anchor.left + offsetConfig.docsLeft - viewBound.left,
+ relativeTop: anchor.top + offsetConfig.docsTop - viewBound.top,
+ };
+ }
+
+ private _restoreRecoveryViewportAnchor(skeleton: DocumentSkeleton): void {
+ const captured = this._recoveryViewportAnchor;
+ if (captured == null) {
+ return;
+ }
+ this._recoveryViewportAnchor = null;
+
+ this._restoreViewportAnchor(skeleton, captured);
+ }
+
+ private _restoreViewportAnchor(
+ skeleton: DocumentSkeleton,
+ captured: IDocLayoutViewportAnchor | null
+ ): void {
+ if (captured == null) {
+ return;
+ }
+
+ const position = skeleton.findNodePositionByCharIndex(captured.offset);
+ const docsComponent = this._context.mainComponent;
+ const viewport = this._context.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+ if (position == null || !(docsComponent instanceof Documents) || viewport == null) {
+ return;
+ }
+
+ const offsetConfig = docsComponent.getOffsetConfig();
+ const convertor = new NodePositionConvertToCursor(offsetConfig, skeleton);
+ const { contentBoxPointGroup } = convertor.getRangePointData(position, position);
+ const anchor = getAnchorBounding(contentBoxPointGroup);
+ const viewBound = viewport.calcViewportInfo().viewBound;
+ viewport.scrollByViewportDeltaVal({
+ viewportScrollX: anchor.left + offsetConfig.docsLeft - viewBound.left - captured.relativeLeft,
+ viewportScrollY: anchor.top + offsetConfig.docsTop - viewBound.top - captured.relativeTop,
+ });
}
private _addNewRender() {
@@ -91,42 +1361,13 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
});
scene.attachControl();
-
- scene.onMouseWheel$.subscribeEvent((evt: unknown, state: EventState) => {
- const currentDocUnit = this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);
- if (currentDocUnit?.getUnitId() !== this._context.unitId) {
- return;
- }
-
- const e = evt as IWheelEvent;
- if (e.ctrlKey) {
- const deltaFactor = Math.abs(e.deltaX);
- let scrollNum = deltaFactor < 40 ? 0.2 : deltaFactor < 80 ? 0.4 : 0.2;
- scrollNum *= e.deltaY > 0 ? -1 : 1;
- if (scene.scaleX < 1) {
- scrollNum /= 2;
- }
-
- if (scene.scaleX + scrollNum > 4) {
- scene.scale(4, 4);
- } else if (scene.scaleX + scrollNum < 0.1) {
- scene.scale(0.1, 0.1);
- } else {
- // const value = e.deltaY > 0 ? 0.1 : -0.1;
- // scene.scaleBy(scrollNum, scrollNum);
- e.preventDefault();
- }
- } else {
- viewMain.onMouseWheel(e, state);
- }
- });
+ this._initViewportInteraction(viewMain);
// TODO@wzhudev: this shouldn't be a config, because we may render different units at the same time.
// @jikkai: hasScroll has never been set before, so I commented it out.
// const hasScroll = this._configService.getConfig('hasScroll') as Nullable<boolean>;
// if (hasScroll !== false) {
- // eslint-disable-next-line no-new
- new ScrollBar(viewMain, {
+ const _scrollBar = new ScrollBar(viewMain, {
enableHorizontal: this._shouldEnableHorizontalScrollBar(),
});
// }
@@ -153,6 +1394,69 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
this._docSelectionRenderService.__attachScrollEvent();
}
+ private _initViewportInteraction(viewMain: Viewport): void {
+ const { scene } = this._context;
+
+ const pointerDownSubscription = scene.onPointerDown$?.subscribeEvent(() => {
+ this._deferWorkerHandoff();
+ this._layoutCoordinator.deferBackgroundWork();
+ });
+ if (pointerDownSubscription != null) {
+ this.disposeWithMe(pointerDownSubscription);
+ }
+ this.disposeWithMe(viewMain.onScrollAfter$.subscribeEvent(() => {
+ const skeleton = this._docSkeletonManagerService.getSkeleton();
+ const range = skeleton == null ? undefined : this._resolveMaterializedPageRange(skeleton);
+ if (range != null) {
+ this._queueMaterializedPageRange(range);
+ }
+ }));
+ if (typeof document !== 'undefined') {
+ this.disposeWithMe(merge(
+ fromEvent(document, 'keydown', { capture: true }),
+ fromEvent(document, 'beforeinput', { capture: true })
+ ).pipe(
+ takeUntil(this.dispose$)
+ ).subscribe(() => {
+ const currentDocUnit = this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);
+ if (currentDocUnit?.getUnitId() === this._context.unitId) {
+ this._deferWorkerHandoff();
+ this._layoutCoordinator.deferBackgroundWork();
+ }
+ }));
+ }
+
+ scene.onMouseWheel$.subscribeEvent((event: IWheelEvent, state: EventState) => {
+ const currentDocUnit = this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);
+ if (currentDocUnit?.getUnitId() !== this._context.unitId) {
+ return;
+ }
+
+ this._deferWorkerHandoff();
+ this._layoutCoordinator.deferBackgroundWork();
+ if (event.ctrlKey) {
+ const deltaFactor = Math.abs(event.deltaX);
+ let scrollNum = deltaFactor < 40 ? 0.2 : deltaFactor < 80 ? 0.4 : 0.2;
+ scrollNum *= event.deltaY > 0 ? -1 : 1;
+ if (scene.scaleX < 1) {
+ scrollNum /= 2;
+ }
+
+ if (scene.scaleX + scrollNum > 4) {
+ scene.scale(4, 4);
+ } else if (scene.scaleX + scrollNum < 0.1) {
+ scene.scale(0.1, 0.1);
+ } else {
+ // const value = e.deltaY > 0 ? 0.1 : -0.1;
+ // scene.scaleBy(scrollNum, scrollNum);
+ event.preventDefault();
+ }
+ } else {
+ viewMain.onMouseWheel(event, state);
+ }
+ });
+ }
+
private _shouldEnableHorizontalScrollBar(): boolean {
const options = this._docViewScaleService.getOptions();
return !(options.mode === 'fit-width' && options.target === 'container' && options.align === 'start');
@@ -207,6 +1511,11 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
const { unitId } = this._context;
+ if (skeleton.getSkeletonData() == null) {
+ this._scheduleLayout(unitId, skeleton, { reason: 'initial' });
+ return;
+ }
+
// REFACTOR: @Jocs, should not use scroll bar to indicate a Zen Editor. refactor after support modern doc.
const editorRenderConfig = this._editorService.getEditorRenderConfig(unitId);
if (editorRenderConfig && !editorRenderConfig.scrollBar) {
@@ -222,23 +1531,64 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
private _initCommandListener() {
const updateCommandList = [RichTextEditingMutation.id];
- this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo, options?: IExecutionOptions) => {
+ this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo, executionOptions?: IExecutionOptions) => {
if (!updateCommandList.includes(command.id)) {
return;
}
- const params = command.params as IRichTextEditingMutationParams;
- const { unitId } = params;
+ const params = command.params;
+ if (!isRichTextEditingMutationParams(params)) {
+ return;
+ }
+ const { unitId, textRanges } = params;
if (unitId !== this._context.unitId) {
return;
}
- if (options?.fromChangeset) {
+ if (executionOptions?.fromChangeset) {
this._scheduleChangesetRender();
return;
}
- this.reRender(unitId);
+ if (!doesDocMutationRequireLayout(params.actions, this._context.unit.getSnapshot().drawings)) {
+ return;
+ }
+ const bodyRanges = textRanges?.filter((range) => !range.segmentId) ?? [];
+ const invalidation = getBodyMutationInvalidation(params.actions, params.segmentId);
+ const anchor = invalidation?.oldStart ?? (bodyRanges.length > 0
+ ? Math.min(...bodyRanges.map((range) => range.startOffset))
+ : undefined);
+ const activeRange = this._getActiveEditingRange(unitId);
+ const isRemoteMutation = params.isSync === true || executionOptions?.fromCollab === true;
+ // Local mutations carry the post-edit selection. Prefer it over the
+ // selection manager because the latter is advanced in a microtask after
+ // this command callback. A collaboration payload can still carry the
+ // remote author's ranges, so execution options—not range presence—decide
+ // whether the transformed local caret remains authoritative.
+ const mutationActiveRange = isRemoteMutation
+ ? undefined
+ : bodyRanges.find((range) => range.isActive) ??
+ (bodyRanges.length === 1 ? bodyRanges[0] : undefined);
+ const priorityAnchor = mutationActiveRange?.endOffset ?? activeRange?.endOffset;
+ // RichTextEditingMutation preserves the original Main input
+ // contract by applying its local post-edit range in a microtask.
+ // Rebuilding the old active range during the synchronous anchor
+ // pass makes the caret visibly jump backward before that microtask.
+ // Remote/direct mutations do not schedule this local range update
+ // and therefore still need the render controller refresh.
+ const hasPendingLocalSelectionUpdate = doesMutationScheduleLocalSelectionUpdate(
+ params,
+ isRemoteMutation
+ );
+
+ this.reRender(
+ unitId,
+ anchor,
+ invalidation,
+ priorityAnchor,
+ !hasPendingLocalSelectionUpdate,
+ isRemoteMutation
+ );
}));
}
@@ -261,39 +1611,125 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
private _initThemeListener() {
this.disposeWithMe(combineLatest([this._themeService.currentTheme$, this._themeService.darkMode$]).pipe(takeUntil(this.dispose$)).subscribe(() => {
this._syncCanvasBackground();
- this._context.mainComponent?.makeDirty(true);
- this._context.components.get(DOCS_VIEW_KEY.BACKGROUND)?.makeDirty(true);
+ this._markDocumentRenderDirty();
}));
}
- private _refreshPagePositionAndSelection() {
+ private _markDocumentRenderDirty(): void {
+ this._context.mainComponent?.makeDirty(true);
+ this._context.components.get(DOCS_VIEW_KEY.BACKGROUND)?.makeDirty(true);
+ }
+
+ private _refreshPagePositionAndSelection(isEditing = false) {
+ this._refreshPagePosition();
+ if (this._isEditorRenderUnit()) {
+ return;
+ }
+
+ const unitId = this._context.unitId;
+ const activeRange = this._getActiveEditingRange(unitId);
+ this._textSelectionManagerService.refreshSelection(
+ { unitId, subUnitId: unitId },
+ isEditing && activeRange != null
+ );
+ }
+
+ private _getFocusedSelectionInfo(unitId: string) {
+ if (this._univerInstanceService.getFocusedUnit()?.getUnitId() !== unitId) {
+ return;
+ }
+
+ return this._textSelectionManagerService.getSelectionInfo({
+ unitId,
+ subUnitId: unitId,
+ });
+ }
+
+ private _getActiveEditingRange(unitId: string) {
+ const selectionInfo = this._getFocusedSelectionInfo(unitId);
+ if (selectionInfo?.isEditing !== true) {
+ return;
+ }
+
+ return selectionInfo.textRanges.find((range) => range.isActive);
+ }
+
+ private _getActiveRange(unitId: string) {
+ const selectionInfo = this._getFocusedSelectionInfo(unitId);
+ return selectionInfo?.textRanges.find((range) => range.isActive);
+ }
+
+ private _captureCompletionViewportAnchor(
+ unitId: string,
+ skeleton: DocumentSkeleton,
+ shouldCapture: boolean,
+ preserveInactiveViewportAnchor: boolean
+ ): IDocLayoutViewportAnchor | null {
+ if (!shouldCapture || this._recoveryViewportAnchor != null) {
+ return null;
+ }
+
+ const selectionInfo = this._getFocusedSelectionInfo(unitId);
+ if (selectionInfo?.isEditing !== true && !preserveInactiveViewportAnchor) {
+ return null;
+ }
+
+ const activeRange = selectionInfo?.textRanges.find((range) => range.isActive);
+ if (activeRange == null || activeRange.segmentId) {
+ return null;
+ }
+
+ return this._captureViewportAnchor(skeleton, activeRange.endOffset, undefined);
+ }
+
+ private _refreshPagePosition() {
if (this._isEditorRenderUnit()) {
return;
}
this._docPageLayoutService.calculatePagePosition();
- this._textSelectionManagerService.refreshSelection();
}
- private _recalculateSizeBySkeleton(skeleton: DocumentSkeleton) {
+ private _recalculateSizeBySkeleton(skeleton: DocumentSkeleton, progress?: IDocumentLayoutProgress | null) {
const { mainComponent, scene, unitId, components } = this._context;
-
const docsComponent = mainComponent as Documents;
-
const docBackground = components.get(DOCS_VIEW_KEY.BACKGROUND) as DocBackground;
-
const pages = skeleton.getSkeletonData()?.pages;
if (pages == null) {
return;
}
- let width = 0;
- let height = 0;
+ const documentFlavor = this._context.unit.getSnapshot().documentStyle.documentFlavor;
+ this._syncCanvasBackground(documentFlavor);
+ const measured = this._measureDocumentExtent(pages, docsComponent, documentFlavor);
+ const layoutProgress = progress ?? skeleton.getLayoutProgress?.() ?? null;
+ const { width, height } = this._reserveDocumentExtent(
+ measured,
+ pages,
+ docsComponent,
+ documentFlavor,
+ layoutProgress
+ );
- const docDataModel = this._context.unit;
+ docsComponent.resize(width, height);
+ docBackground.resize(width, height);
- const documentFlavor = docDataModel.getSnapshot().documentStyle.documentFlavor;
- this._syncCanvasBackground(documentFlavor);
+ const editorRenderConfig = this._editorService.getEditorRenderConfig(unitId);
+ if (
+ (!editorRenderConfig || editorRenderConfig.scrollBar) &&
+ (scene.width !== width || scene.height !== height)
+ ) {
+ scene.transformByState({ width, height });
+ }
+ }
+
+ private _measureDocumentExtent(
+ pages: IDocumentSkeletonPage[],
+ docsComponent: Documents,
+ documentFlavor: DocumentFlavor | undefined
+ ): { width: number; height: number } {
+ let width = 0;
+ let height = 0;
for (let i = 0, len = pages.length; i < len; i++) {
const page = pages[i];
@@ -326,16 +1762,44 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
height = Math.max(height, pageHeight);
}
}
+ return { width, height };
+ }
- docsComponent.resize(width, height);
- docBackground.resize(width, height);
-
- const editorRenderConfig = this._editorService.getEditorRenderConfig(unitId);
+ private _reserveDocumentExtent(
+ measured: { width: number; height: number },
+ pages: IDocumentSkeletonPage[],
+ docsComponent: Documents,
+ documentFlavor: DocumentFlavor | undefined,
+ layoutProgress: IDocumentLayoutProgress | null
+ ): { width: number; height: number } {
+ let { width, height } = measured;
+ if (layoutProgress != null && !layoutProgress.complete && pages.length > 0) {
+ const firstPage = pages[0];
+ if (documentFlavor === DocumentFlavor.MODERN) {
+ this._reservedLayoutHeight = Math.max(
+ this._reservedLayoutHeight,
+ layoutProgress.estimatedHeight + docsComponent.pageMarginTop * 2
+ );
+ } else if (docsComponent.pageLayoutType === PageLayoutType.VERTICAL) {
+ const estimatedHeight = layoutProgress.estimatedPageCount *
+ (firstPage.pageHeight + docsComponent.pageMarginTop) + docsComponent.pageMarginTop;
+ this._reservedLayoutHeight = Math.max(this._reservedLayoutHeight, estimatedHeight);
+ } else {
+ const estimatedWidth = layoutProgress.estimatedPageCount *
+ (firstPage.pageWidth + docsComponent.pageMarginLeft);
+ this._reservedLayoutWidth = Math.max(this._reservedLayoutWidth, estimatedWidth);
+ }
- // REFACTOR: @JOCS show not use scrollBar to indicate it's a Zen Editor.
- if (!editorRenderConfig || editorRenderConfig.scrollBar) {
- scene.transformByState({ width, height });
+ if (documentFlavor === DocumentFlavor.MODERN || docsComponent.pageLayoutType === PageLayoutType.VERTICAL) {
+ height = Math.max(height, this._reservedLayoutHeight);
+ } else {
+ width = Math.max(width, this._reservedLayoutWidth);
+ }
+ } else {
+ this._reservedLayoutWidth = width;
+ this._reservedLayoutHeight = height;
}
+ return { width, height };
}
private _syncCanvasBackground(documentFlavor = this._context.unit.getSnapshot().documentStyle.documentFlavor) {
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index 7dcd0c8fd3..ed79abb8df 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -242,6 +242,7 @@ export {
} from './services/doc-event-manager.service';
export type { IBulletBound, IMutiPageParagraphBound } from './services/doc-event-manager.service';
export { DocIMEInputManagerService } from './services/doc-ime-input-manager.service';
+export { DocLayoutInteractionService } from './services/doc-layout-interaction.service';
export { SetDocInputStyleCommand } from './services/doc-menu-style.service';
export type { ISetDocInputStyleCommandParams } from './services/doc-menu-style.service';
export { DocPageLayoutService } from './services/doc-page-layout.service';
diff --git a/packages/docs-ui/src/locale/ar-SA.ts b/packages/docs-ui/src/locale/ar-SA.ts
index b39ed3b055..5b8fda2de1 100644
--- a/packages/docs-ui/src/locale/ar-SA.ts
+++ b/packages/docs-ui/src/locale/ar-SA.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: 'جارٍ استعادة تخطيط المستند…',
+ },
toolbar: {
font: 'خط',
fontSize: 'حجم الخط',
diff --git a/packages/docs-ui/src/locale/ca-ES.ts b/packages/docs-ui/src/locale/ca-ES.ts
index 6f48c9d503..5d63442c74 100644
--- a/packages/docs-ui/src/locale/ca-ES.ts
+++ b/packages/docs-ui/src/locale/ca-ES.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: 'S’està restaurant el disseny del document…',
+ },
toolbar: {
font: 'Tipus de lletra',
fontSize: 'Mida de lletra',
diff --git a/packages/docs-ui/src/locale/de-DE.ts b/packages/docs-ui/src/locale/de-DE.ts
index fbc3ef5ef5..c5305f3eff 100644
--- a/packages/docs-ui/src/locale/de-DE.ts
+++ b/packages/docs-ui/src/locale/de-DE.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: 'Dokumentlayout wird wiederhergestellt…',
+ },
toolbar: {
font: 'Schriftart',
fontSize: 'Schriftgröße',
diff --git a/packages/docs-ui/src/locale/en-US.ts b/packages/docs-ui/src/locale/en-US.ts
index 5607110f2a..67cf3c15aa 100644
--- a/packages/docs-ui/src/locale/en-US.ts
+++ b/packages/docs-ui/src/locale/en-US.ts
@@ -16,6 +16,9 @@
const locale = {
'docs-ui': {
+ layout: {
+ recovering: 'Restoring document layout…',
+ },
toolbar: {
font: 'Font',
fontSize: 'Font size',
diff --git a/packages/docs-ui/src/locale/es-ES.ts b/packages/docs-ui/src/locale/es-ES.ts
index 432aeeaf2b..48b11982c2 100644
--- a/packages/docs-ui/src/locale/es-ES.ts
+++ b/packages/docs-ui/src/locale/es-ES.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: 'Restaurando el diseño del documento…',
+ },
toolbar: {
font: 'Fuente',
fontSize: 'Tamaño de fuente',
diff --git a/packages/docs-ui/src/locale/fa-IR.ts b/packages/docs-ui/src/locale/fa-IR.ts
index f5df5e2ca4..5ec9532468 100644
--- a/packages/docs-ui/src/locale/fa-IR.ts
+++ b/packages/docs-ui/src/locale/fa-IR.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: 'در حال بازیابی صفحه‌آرایی سند…',
+ },
toolbar: {
font: 'فونت',
fontSize: 'اندازه فونت',
diff --git a/packages/docs-ui/src/locale/fr-FR.ts b/packages/docs-ui/src/locale/fr-FR.ts
index 83bd61e260..51e5ef1027 100644
--- a/packages/docs-ui/src/locale/fr-FR.ts
+++ b/packages/docs-ui/src/locale/fr-FR.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: 'Restauration de la mise en page du document…',
+ },
toolbar: {
font: 'Police',
fontSize: 'Taille de la police',
diff --git a/packages/docs-ui/src/locale/id-ID.ts b/packages/docs-ui/src/locale/id-ID.ts
index 440517bc61..f269762e37 100644
--- a/packages/docs-ui/src/locale/id-ID.ts
+++ b/packages/docs-ui/src/locale/id-ID.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: 'Memulihkan tata letak dokumen…',
+ },
toolbar: {
font: 'Font',
fontSize: 'Ukuran font',
diff --git a/packages/docs-ui/src/locale/it-IT.ts b/packages/docs-ui/src/locale/it-IT.ts
index 9a2dd9c718..704ca1839d 100644
--- a/packages/docs-ui/src/locale/it-IT.ts
+++ b/packages/docs-ui/src/locale/it-IT.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: 'Ripristino del layout del documento…',
+ },
toolbar: {
font: 'Carattere',
fontSize: 'Dimensione carattere',
diff --git a/packages/docs-ui/src/locale/ja-JP.ts b/packages/docs-ui/src/locale/ja-JP.ts
index 0dcf59379e..ed3a035a41 100644
--- a/packages/docs-ui/src/locale/ja-JP.ts
+++ b/packages/docs-ui/src/locale/ja-JP.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: 'ドキュメントのレイアウトを復元しています…',
+ },
toolbar: {
font: 'フォント',
fontSize: 'フォントサイズ',
diff --git a/packages/docs-ui/src/locale/ko-KR.ts b/packages/docs-ui/src/locale/ko-KR.ts
index febe838d56..6245c7e73a 100644
--- a/packages/docs-ui/src/locale/ko-KR.ts
+++ b/packages/docs-ui/src/locale/ko-KR.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: '문서 레이아웃을 복구하는 중…',
+ },
toolbar: {
font: '글꼴',
fontSize: '글꼴 크기',
diff --git a/packages/docs-ui/src/locale/pl-PL.ts b/packages/docs-ui/src/locale/pl-PL.ts
index 5118c74e61..4f8ff905d0 100644
--- a/packages/docs-ui/src/locale/pl-PL.ts
+++ b/packages/docs-ui/src/locale/pl-PL.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: 'Przywracanie układu dokumentu…',
+ },
toolbar: {
font: 'Czcionka',
fontSize: 'Rozmiar czcionki',
diff --git a/packages/docs-ui/src/locale/pt-BR.ts b/packages/docs-ui/src/locale/pt-BR.ts
index eb0ba86321..f852de20a3 100644
--- a/packages/docs-ui/src/locale/pt-BR.ts
+++ b/packages/docs-ui/src/locale/pt-BR.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: 'Restaurando o layout do documento…',
+ },
toolbar: {
font: 'Fonte',
fontSize: 'Tamanho da fonte',
diff --git a/packages/docs-ui/src/locale/ru-RU.ts b/packages/docs-ui/src/locale/ru-RU.ts
index 376c85e01d..c1fdb97808 100644
--- a/packages/docs-ui/src/locale/ru-RU.ts
+++ b/packages/docs-ui/src/locale/ru-RU.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: 'Восстановление макета документа…',
+ },
toolbar: {
font: 'Шрифт',
fontSize: 'Размер шрифта',
diff --git a/packages/docs-ui/src/locale/sk-SK.ts b/packages/docs-ui/src/locale/sk-SK.ts
index 127de25752..0035b63321 100644
--- a/packages/docs-ui/src/locale/sk-SK.ts
+++ b/packages/docs-ui/src/locale/sk-SK.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: 'Obnovuje sa rozloženie dokumentu…',
+ },
toolbar: {
font: 'Písmo',
fontSize: 'Veľkosť písma',
diff --git a/packages/docs-ui/src/locale/vi-VN.ts b/packages/docs-ui/src/locale/vi-VN.ts
index 58fa0a02c6..b47204404d 100644
--- a/packages/docs-ui/src/locale/vi-VN.ts
+++ b/packages/docs-ui/src/locale/vi-VN.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: 'Đang khôi phục bố cục tài liệu…',
+ },
toolbar: {
font: 'Phông chữ',
fontSize: 'Cỡ chữ',
diff --git a/packages/docs-ui/src/locale/zh-CN.ts b/packages/docs-ui/src/locale/zh-CN.ts
index 8843964a77..1b4b27db5b 100644
--- a/packages/docs-ui/src/locale/zh-CN.ts
+++ b/packages/docs-ui/src/locale/zh-CN.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: '正在恢复文档排版…',
+ },
toolbar: {
font: '字体',
fontSize: '字号',
diff --git a/packages/docs-ui/src/locale/zh-HK.ts b/packages/docs-ui/src/locale/zh-HK.ts
index 12ff197a71..86b5d07eb6 100644
--- a/packages/docs-ui/src/locale/zh-HK.ts
+++ b/packages/docs-ui/src/locale/zh-HK.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: '正在恢復文件排版…',
+ },
toolbar: {
font: '字型',
fontSize: '字號',
diff --git a/packages/docs-ui/src/locale/zh-TW.ts b/packages/docs-ui/src/locale/zh-TW.ts
index 14a6f0d7e9..d4822db0c6 100644
--- a/packages/docs-ui/src/locale/zh-TW.ts
+++ b/packages/docs-ui/src/locale/zh-TW.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ layout: {
+ recovering: '正在復原文件排版…',
+ },
toolbar: {
font: '字體',
fontSize: '字號',
diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.ts
index 5bb07d7e94..17bbfee331 100644
--- a/packages/docs-ui/src/plugin.ts
+++ b/packages/docs-ui/src/plugin.ts
@@ -154,12 +154,14 @@ import { DocParagraphSettingController } from './controllers/doc-paragraph-setti
import { DocSectionSettingController } from './controllers/doc-section-setting.controller';
import { DocTableController } from './controllers/doc-table.controller';
import { DocBackScrollRenderController } from './controllers/render-controllers/back-scroll.render-controller';
+import { DocCanvasPopupLayoutInteractionController } from './controllers/render-controllers/doc-canvas-popup-layout-interaction.controller';
import { DocChecklistRenderController } from './controllers/render-controllers/doc-checklist.render-controller';
import { DocClipboardController } from './controllers/render-controllers/doc-clipboard.controller';
import { DocContextMenuRenderController } from './controllers/render-controllers/doc-contextmenu.render-controller';
import { DocEditorBridgeController } from './controllers/render-controllers/doc-editor-bridge.controller';
import { DocIMEInputController } from './controllers/render-controllers/doc-ime-input.controller';
import { DocInputController } from './controllers/render-controllers/doc-input.controller';
+import { DocLayoutRecoveryRenderController } from './controllers/render-controllers/doc-layout-recovery.render-controller';
import {
DocParagraphPlaceholderRenderController,
} from './controllers/render-controllers/doc-paragraph-placeholder.render-controller';
@@ -178,6 +180,7 @@ import { DocAutoFormatService } from './services/doc-auto-format.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';
+import { DocLayoutInteractionService } from './services/doc-layout-interaction.service';
import { DocMenuStyleService, SetDocInputStyleCommand } from './services/doc-menu-style.service';
import { DocPageLayoutService } from './services/doc-page-layout.service';
import { DocParagraphMenuService } from './services/doc-paragraph-menu.service';
@@ -482,6 +485,8 @@ export class UniverDocsUIPlugin extends Plugin {
[DocInterceptorService],
[DocViewScaleService],
[DocPageLayoutService],
+ [DocLayoutInteractionService],
+ [DocCanvasPopupLayoutInteractionController],
[DocIMEInputManagerService],
[DocRenderController],
[DocZoomRenderController],
@@ -505,6 +510,7 @@ export class UniverDocsUIPlugin extends Plugin {
[DocClipboardController],
[DocInputController],
[DocIMEInputController],
+ [DocLayoutRecoveryRenderController],
[DocEditorBridgeController],
] as Dependency[]).forEach((m) => {
this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, m);
diff --git a/packages/docs-ui/src/services/__tests__/doc-layout-coordinator.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-layout-coordinator.service.spec.ts
new file mode 100644
index 0000000000..0b65910dfe
--- /dev/null
+++ b/packages/docs-ui/src/services/__tests__/doc-layout-coordinator.service.spec.ts
@@ -0,0 +1,1120 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// @vitest-environment jsdom
+
+import type { IDocLayoutMountIdentity, IDocLayoutStartResult } from '@univerjs/docs';
+import type { IDocumentLayoutProgress } from '@univerjs/engine-render';
+import type { DocumentLayoutSchedulingSkeleton } from '../doc-layout-coordinator.service';
+import { DocLayoutSessionStatus } from '@univerjs/docs';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DocLayoutCoordinatorService } from '../doc-layout-coordinator.service';
+
+function createProgress(overrides: Partial<IDocumentLayoutProgress>): IDocumentLayoutProgress {
+ return {
+ generation: 1,
+ publicationRevision: 0,
+ didPublish: false,
+ didPublishAnchor: false,
+ publishedPageCount: 0,
+ reason: 'edit',
+ mode: 'paginated',
+ complete: false,
+ cancelled: false,
+ anchorReady: false,
+ laidOutThrough: 0,
+ stableLaidOutThrough: 0,
+ pageCount: 1,
+ processedBlockCount: 1,
+ totalBlockCount: 10,
+ estimatedPageCount: 1,
+ estimatedHeight: 800,
+ elapsedTime: 1,
+ maxBlockDuration: 1,
+ interactionWindowComplete: false,
+ ...overrides,
+ };
+}
+
+describe('DocLayoutCoordinatorService', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>
+ window.setTimeout(() => callback(performance.now()), 0));
+ vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id));
+ vi.stubGlobal('requestIdleCallback', (callback: IdleRequestCallback) =>
+ window.setTimeout(() => callback({ didTimeout: false, timeRemaining: () => 10 }), 0));
+ vi.stubGlobal('cancelIdleCallback', (id: number) => window.clearTimeout(id));
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ });
+
+ it('uses foreground slices until the anchor is ready and then finishes in idle slices', () => {
+ const steps = [
+ createProgress({ anchorReady: false }),
+ createProgress({ anchorReady: true, laidOutThrough: 40 }),
+ createProgress({ anchorReady: true, laidOutThrough: 100, complete: true }),
+ ];
+ const skeleton = {
+ startIncrementalLayout: vi.fn(() => 1),
+ stepIncrementalLayout: vi.fn(() => steps.shift()!),
+ cancelIncrementalLayout: vi.fn(),
+ } satisfies DocumentLayoutSchedulingSkeleton;
+ const onProgress = vi.fn();
+ const onComplete = vi.fn();
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.schedule(skeleton, { reason: 'edit', anchor: 30 }, { onProgress, onComplete });
+ vi.runAllTimers();
+
+ expect(skeleton.stepIncrementalLayout).toHaveBeenCalledTimes(3);
+ expect(onProgress).toHaveBeenCalledTimes(3);
+ expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({ complete: true }));
+ coordinator.dispose();
+ });
+
+ it('finishes the edited anchor synchronously one atomic block at a time', () => {
+ const requestAnimationFrameSpy = vi.fn((callback: FrameRequestCallback) =>
+ window.setTimeout(() => callback(performance.now()), 0));
+ vi.stubGlobal('requestAnimationFrame', requestAnimationFrameSpy);
+ const steps = [
+ createProgress({ anchorReady: false, laidOutThrough: 10 }),
+ createProgress({ anchorReady: false, laidOutThrough: 20 }),
+ createProgress({ anchorReady: true, laidOutThrough: 40 }),
+ createProgress({ anchorReady: true, laidOutThrough: 80, complete: true }),
+ ];
+ const skeleton = {
+ startIncrementalLayout: vi.fn(() => 1),
+ stepIncrementalLayout: vi.fn(() => steps.shift()!),
+ cancelIncrementalLayout: vi.fn(),
+ } satisfies DocumentLayoutSchedulingSkeleton;
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.schedule(skeleton, { reason: 'edit', anchor: 30 }, { onProgress: vi.fn() });
+
+ expect(skeleton.stepIncrementalLayout).toHaveBeenCalledTimes(3);
+ expect(skeleton.stepIncrementalLayout).toHaveBeenNthCalledWith(1, 1, 0);
+ expect(skeleton.stepIncrementalLayout).toHaveBeenNthCalledWith(2, 1, 0);
+ expect(skeleton.stepIncrementalLayout).toHaveBeenNthCalledWith(3, 1, 0);
+ vi.runAllTimers();
+
+ expect(skeleton.stepIncrementalLayout).toHaveBeenCalledTimes(4);
+ expect(requestAnimationFrameSpy).not.toHaveBeenCalled();
+ coordinator.dispose();
+ });
+
+ it('lets the shell paint once before starting an initial layout', () => {
+ const requestAnimationFrameSpy = vi.fn((callback: FrameRequestCallback) =>
+ window.setTimeout(() => callback(performance.now()), 0));
+ vi.stubGlobal('requestAnimationFrame', requestAnimationFrameSpy);
+ const skeleton = {
+ startIncrementalLayout: vi.fn(() => 1),
+ stepIncrementalLayout: vi.fn(() => createProgress({ reason: 'initial', complete: true, anchorReady: true })),
+ cancelIncrementalLayout: vi.fn(),
+ } satisfies DocumentLayoutSchedulingSkeleton;
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.schedule(skeleton, { reason: 'initial' }, { onProgress: vi.fn() });
+ vi.runAllTimers();
+
+ expect(requestAnimationFrameSpy).toHaveBeenCalledTimes(1);
+ coordinator.dispose();
+ });
+
+ it('keeps a bounded interaction window on the main thread before handing off the tail', () => {
+ const steps = [
+ createProgress({
+ anchorReady: true,
+ didPublish: true,
+ didPublishAnchor: true,
+ publishedPageCount: 3,
+ pageCount: 20,
+ }),
+ createProgress({
+ anchorReady: true,
+ didPublish: true,
+ publishedPageCount: 4,
+ pageCount: 20,
+ }),
+ createProgress({
+ anchorReady: true,
+ didPublish: true,
+ publishedPageCount: 5,
+ pageCount: 20,
+ }),
+ createProgress({
+ anchorReady: true,
+ didPublish: true,
+ publishedPageCount: 7,
+ pageCount: 20,
+ }),
+ ];
+ const skeleton = {
+ startIncrementalLayout: vi.fn(() => 1),
+ stepIncrementalLayout: vi.fn(() => steps.shift()!),
+ cancelIncrementalLayout: vi.fn(),
+ } satisfies DocumentLayoutSchedulingSkeleton;
+ const onForegroundReady = vi.fn();
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.schedule(skeleton, {
+ reason: 'edit',
+ anchor: 30,
+ foregroundWindowSize: 5,
+ foregroundBudgetMs: 1_000,
+ }, {
+ onProgress: vi.fn(),
+ onForegroundReady,
+ });
+ vi.runAllTimers();
+
+ expect(skeleton.stepIncrementalLayout).toHaveBeenCalledTimes(4);
+ expect(onForegroundReady).toHaveBeenCalledTimes(1);
+ expect(onForegroundReady).toHaveBeenCalledWith(expect.objectContaining({ publishedPageCount: 7 }));
+ coordinator.dispose();
+ });
+
+ it('clamps the main-thread interaction window to three through five pages', () => {
+ const createSchedulingSkeleton = () => {
+ const steps = Array.from({ length: 10 }, (_, index) => createProgress({
+ anchorReady: true,
+ didPublish: true,
+ didPublishAnchor: index === 0,
+ publishedPageCount: index + 1,
+ pageCount: 20,
+ }));
+ return {
+ startIncrementalLayout: vi.fn(() => 1),
+ stepIncrementalLayout: vi.fn(() => steps.shift()!),
+ cancelIncrementalLayout: vi.fn(),
+ } satisfies DocumentLayoutSchedulingSkeleton;
+ };
+ const coordinator = new DocLayoutCoordinatorService();
+ const oversizedSkeleton = createSchedulingSkeleton();
+ const undersizedSkeleton = createSchedulingSkeleton();
+
+ coordinator.schedule(oversizedSkeleton, {
+ reason: 'edit',
+ anchor: 30,
+ foregroundWindowSize: 100,
+ foregroundBudgetMs: 1_000,
+ }, {
+ onProgress: vi.fn(),
+ onForegroundReady: vi.fn(),
+ });
+ vi.runAllTimers();
+ expect(oversizedSkeleton.stepIncrementalLayout).toHaveBeenCalledTimes(5);
+
+ coordinator.schedule(undersizedSkeleton, {
+ reason: 'edit',
+ anchor: 30,
+ foregroundWindowSize: 1,
+ foregroundBudgetMs: 1_000,
+ }, {
+ onProgress: vi.fn(),
+ onForegroundReady: vi.fn(),
+ });
+ vi.runAllTimers();
+ expect(undersizedSkeleton.stepIncrementalLayout).toHaveBeenCalledTimes(3);
+
+ coordinator.dispose();
+ });
+
+ it('hands off immediately when Main seals a page whose last paragraph continues in Worker', () => {
+ const progress = createProgress({
+ anchorReady: true,
+ didPublish: true,
+ didPublishAnchor: true,
+ publishedPageCount: 3,
+ pageCount: 20,
+ interactionWindowComplete: true,
+ });
+ const skeleton = {
+ startIncrementalLayout: vi.fn(() => 1),
+ stepIncrementalLayout: vi.fn(() => progress),
+ cancelIncrementalLayout: vi.fn(),
+ } satisfies DocumentLayoutSchedulingSkeleton;
+ const onForegroundReady = vi.fn();
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.schedule(skeleton, {
+ reason: 'edit',
+ anchor: 30,
+ foregroundWindowSize: 5,
+ foregroundBudgetMs: 1_000,
+ }, {
+ onProgress: vi.fn(),
+ onForegroundReady,
+ });
+
+ expect(skeleton.stepIncrementalLayout).toHaveBeenCalledTimes(1);
+ expect(skeleton.cancelIncrementalLayout).toHaveBeenCalledWith(1);
+ expect(onForegroundReady).toHaveBeenCalledWith(progress);
+ coordinator.dispose();
+ });
+
+ it('hands a completed Main edit to Worker before publishing completion', () => {
+ const progress = createProgress({
+ anchorReady: true,
+ didPublish: true,
+ didPublishAnchor: true,
+ publishedPageCount: 3,
+ pageCount: 3,
+ complete: true,
+ });
+ const skeleton = {
+ startIncrementalLayout: vi.fn(() => 1),
+ stepIncrementalLayout: vi.fn(() => progress),
+ cancelIncrementalLayout: vi.fn(),
+ } satisfies DocumentLayoutSchedulingSkeleton;
+ const onProgress = vi.fn();
+ const onComplete = vi.fn();
+ const onForegroundReady = vi.fn();
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.schedule(skeleton, {
+ reason: 'edit',
+ anchor: 30,
+ }, {
+ onProgress,
+ onComplete,
+ onForegroundReady,
+ });
+
+ expect(skeleton.cancelIncrementalLayout).toHaveBeenCalledWith(1);
+ expect(onProgress).toHaveBeenCalledWith(expect.objectContaining({ complete: false }));
+ expect(onForegroundReady).toHaveBeenCalledWith(progress);
+ expect(onComplete).not.toHaveBeenCalled();
+ coordinator.dispose();
+ });
+
+ it('counts continuous blocks instead of physical pages for the Modern interaction window', () => {
+ const steps = [20, 21, 22, 24].map((processedBlockCount, index) => createProgress({
+ mode: 'continuous',
+ anchorReady: true,
+ didPublish: true,
+ didPublishAnchor: index === 0,
+ publishedPageCount: 1,
+ processedBlockCount,
+ totalBlockCount: 100,
+ }));
+ const skeleton = {
+ startIncrementalLayout: vi.fn(() => 1),
+ stepIncrementalLayout: vi.fn(() => steps.shift()!),
+ cancelIncrementalLayout: vi.fn(),
+ } satisfies DocumentLayoutSchedulingSkeleton;
+ const onForegroundReady = vi.fn();
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.schedule(skeleton, {
+ reason: 'edit',
+ anchor: 300,
+ foregroundWindowSize: 5,
+ foregroundBudgetMs: 1_000,
+ }, {
+ onProgress: vi.fn(),
+ onForegroundReady,
+ });
+ vi.runAllTimers();
+
+ expect(skeleton.stepIncrementalLayout).toHaveBeenCalledTimes(4);
+ expect(onForegroundReady).toHaveBeenCalledWith(expect.objectContaining({
+ mode: 'continuous',
+ processedBlockCount: 24,
+ }));
+ coordinator.dispose();
+ });
+
+ it('protects the visible Modern suffix through its viewport offset before Worker handoff', () => {
+ const steps = [
+ createProgress({
+ mode: 'continuous',
+ anchorReady: true,
+ didPublish: true,
+ didPublishAnchor: true,
+ processedBlockCount: 20,
+ stableLaidOutThrough: 320,
+ }),
+ createProgress({
+ mode: 'continuous',
+ anchorReady: true,
+ didPublish: true,
+ processedBlockCount: 21,
+ stableLaidOutThrough: 480,
+ }),
+ createProgress({
+ mode: 'continuous',
+ anchorReady: true,
+ didPublish: true,
+ processedBlockCount: 22,
+ stableLaidOutThrough: 720,
+ }),
+ ];
+ const skeleton = {
+ startIncrementalLayout: vi.fn(() => 1),
+ stepIncrementalLayout: vi.fn(() => steps.shift()!),
+ cancelIncrementalLayout: vi.fn(),
+ } satisfies DocumentLayoutSchedulingSkeleton;
+ const onForegroundReady = vi.fn();
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.schedule(skeleton, {
+ reason: 'edit',
+ anchor: 300,
+ foregroundEndOffset: 720,
+ foregroundBudgetMs: 1_000,
+ }, {
+ onProgress: vi.fn(),
+ onForegroundReady,
+ });
+ vi.runAllTimers();
+
+ expect(skeleton.stepIncrementalLayout).toHaveBeenCalledTimes(3);
+ expect(onForegroundReady).toHaveBeenCalledWith(expect.objectContaining({
+ mode: 'continuous',
+ processedBlockCount: 22,
+ stableLaidOutThrough: 720,
+ }));
+ coordinator.dispose();
+ });
+
+ it('cancels the previous generation when a new edit is scheduled', () => {
+ const skeleton = {
+ startIncrementalLayout: vi.fn()
+ .mockReturnValueOnce(1)
+ .mockReturnValueOnce(2),
+ stepIncrementalLayout: vi.fn()
+ .mockReturnValueOnce(createProgress({ generation: 1, anchorReady: true }))
+ .mockReturnValueOnce(createProgress({ generation: 2, complete: true, anchorReady: true })),
+ cancelIncrementalLayout: vi.fn(),
+ } satisfies DocumentLayoutSchedulingSkeleton;
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.schedule(skeleton, { reason: 'edit', anchor: 10 }, { onProgress: vi.fn() });
+ coordinator.schedule(skeleton, { reason: 'edit', anchor: 11 }, { onProgress: vi.fn() });
+
+ expect(skeleton.cancelIncrementalLayout).toHaveBeenCalledWith(1);
+ vi.runAllTimers();
+ expect(skeleton.stepIncrementalLayout).toHaveBeenCalledWith(2, 0);
+ coordinator.dispose();
+ });
+
+ it('crosses a timer boundary before chaining background idle work', () => {
+ const requestIdle = vi.fn((callback: IdleRequestCallback) =>
+ window.setTimeout(() => callback({ didTimeout: false, timeRemaining: () => 10 }), 0));
+ vi.stubGlobal('requestIdleCallback', requestIdle);
+ const skeleton = {
+ startIncrementalLayout: vi.fn(() => 1),
+ stepIncrementalLayout: vi.fn()
+ .mockReturnValueOnce(createProgress({ anchorReady: true }))
+ .mockReturnValueOnce(createProgress({ anchorReady: true, complete: true })),
+ cancelIncrementalLayout: vi.fn(),
+ } satisfies DocumentLayoutSchedulingSkeleton;
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.schedule(skeleton, { reason: 'initial' }, { onProgress: vi.fn() });
+
+ expect(requestIdle).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(3);
+ expect(requestIdle).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(requestIdle).toHaveBeenCalledTimes(1);
+
+ vi.runAllTimers();
+ coordinator.dispose();
+ });
+
+ it('publishes at most one already-computed page per background task before calculating more', () => {
+ const skeleton = {
+ startIncrementalLayout: vi.fn(() => 1),
+ stepIncrementalLayout: vi.fn()
+ .mockReturnValueOnce(createProgress({
+ anchorReady: true,
+ didPublish: true,
+ publishedPageCount: 1,
+ }))
+ .mockReturnValueOnce(createProgress({
+ anchorReady: true,
+ didPublish: true,
+ publishedPageCount: 3,
+ }))
+ .mockReturnValueOnce(createProgress({
+ anchorReady: true,
+ complete: true,
+ didPublish: true,
+ publishedPageCount: 4,
+ })),
+ publishIncrementalLayoutBacklog: vi.fn()
+ .mockReturnValueOnce(createProgress({
+ anchorReady: true,
+ didPublish: true,
+ publishedPageCount: 2,
+ }))
+ .mockReturnValue(createProgress({
+ anchorReady: true,
+ didPublish: false,
+ publishedPageCount: 2,
+ })),
+ cancelIncrementalLayout: vi.fn(),
+ } satisfies DocumentLayoutSchedulingSkeleton;
+ const publications: number[] = [];
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.schedule(skeleton, { reason: 'initial' }, {
+ onProgress: (progress) => publications.push(progress.publishedPageCount),
+ });
+ vi.runAllTimers();
+
+ expect(publications).toEqual([1, 2, 3, 4]);
+ expect(skeleton.publishIncrementalLayoutBacklog).toHaveBeenCalledTimes(3);
+ coordinator.dispose();
+ });
+
+ it('resumes an edited document tail after the input quiet period', () => {
+ const requestIdle = vi.fn((callback: IdleRequestCallback) =>
+ window.setTimeout(() => callback({ didTimeout: false, timeRemaining: () => 10 }), 0));
+ vi.stubGlobal('requestIdleCallback', requestIdle);
+ const skeleton = {
+ startIncrementalLayout: vi.fn(() => 1),
+ stepIncrementalLayout: vi.fn()
+ .mockReturnValueOnce(createProgress({ anchorReady: true }))
+ .mockReturnValueOnce(createProgress({ anchorReady: true, complete: true })),
+ cancelIncrementalLayout: vi.fn(),
+ } satisfies DocumentLayoutSchedulingSkeleton;
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.schedule(skeleton, { reason: 'edit', anchor: 100 }, { onProgress: vi.fn() });
+
+ vi.advanceTimersByTime(119);
+ expect(requestIdle).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(requestIdle).toHaveBeenCalledTimes(1);
+
+ vi.runAllTimers();
+ coordinator.dispose();
+ });
+
+ it('defers an active background tail when the user interacts', () => {
+ const requestIdle = vi.fn((callback: IdleRequestCallback) =>
+ window.setTimeout(() => callback({ didTimeout: false, timeRemaining: () => 10 }), 0));
+ vi.stubGlobal('requestIdleCallback', requestIdle);
+ const skeleton = {
+ startIncrementalLayout: vi.fn(() => 1),
+ stepIncrementalLayout: vi.fn()
+ .mockReturnValueOnce(createProgress({ anchorReady: true }))
+ .mockReturnValueOnce(createProgress({ anchorReady: true, complete: true })),
+ cancelIncrementalLayout: vi.fn(),
+ } satisfies DocumentLayoutSchedulingSkeleton;
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.schedule(skeleton, { reason: 'initial' }, { onProgress: vi.fn() });
+ coordinator.deferBackgroundWork();
+
+ vi.advanceTimersByTime(3);
+ expect(requestIdle).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(requestIdle).toHaveBeenCalledTimes(1);
+
+ vi.runAllTimers();
+ coordinator.dispose();
+ });
+
+ it('keeps Worker background layout moving when the browser has no idle period', async () => {
+ const requestIdle = vi.fn(() => 1);
+ vi.stubGlobal('requestIdleCallback', requestIdle);
+ let identity: IDocLayoutMountIdentity = {
+ unitId: 'doc-worker-background',
+ mountId: '',
+ mountEpoch: 0,
+ viewportEpoch: 0,
+ };
+ const executorService = {
+ startLayout: vi.fn(async (requestIdentity: IDocLayoutMountIdentity): Promise<IDocLayoutStartResult> => {
+ identity = requestIdentity;
+ return {
+ status: DocLayoutSessionStatus.ACCEPTED,
+ step: {
+ ...requestIdentity,
+ progress: createProgress({
+ generation: 7,
+ mode: 'continuous',
+ didPublish: true,
+ anchorReady: true,
+ processedBlockCount: 63,
+ totalBlockCount: 6_264,
+ }),
+ publication: null,
+ modelRevision: 3,
+ metricsRevision: 5,
+ },
+ };
+ }),
+ stepLayout: vi.fn(async () => ({
+ ...identity,
+ progress: createProgress({
+ generation: 7,
+ mode: 'continuous',
+ didPublish: true,
+ anchorReady: true,
+ complete: true,
+ processedBlockCount: 6_264,
+ totalBlockCount: 6_264,
+ }),
+ publication: null,
+ modelRevision: 3,
+ metricsRevision: 5,
+ })),
+ publishBacklog: vi.fn(async () => ({
+ ...identity,
+ progress: createProgress({
+ generation: 7,
+ mode: 'continuous',
+ anchorReady: true,
+ processedBlockCount: 63,
+ totalBlockCount: 6_264,
+ }),
+ publication: null,
+ modelRevision: 3,
+ metricsRevision: 5,
+ })),
+ getLayoutPage: vi.fn(),
+ cancelLayout: vi.fn(async () => {}),
+ disposeLayoutMount: vi.fn(async () => {}),
+ };
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.scheduleWorker(
+ 'doc-worker-background',
+ { beginExternalLayout: vi.fn(), cancelExternalLayout: vi.fn() },
+ executorService,
+ { reason: 'initial' },
+ undefined,
+ { onProgress: vi.fn() },
+ vi.fn()
+ );
+ await vi.runAllTimersAsync();
+
+ expect(requestIdle).not.toHaveBeenCalled();
+ expect(executorService.stepLayout).toHaveBeenCalledTimes(1);
+ coordinator.dispose();
+ });
+
+ it('does not advance Worker computation past an unpublished backlog while input is pending', async () => {
+ const isInputPending = vi.fn()
+ .mockReturnValueOnce(false)
+ .mockReturnValueOnce(true)
+ .mockReturnValue(false);
+ vi.stubGlobal('navigator', {
+ scheduling: { isInputPending },
+ });
+ let identity: IDocLayoutMountIdentity = {
+ unitId: 'doc-worker-pending-input',
+ mountId: '',
+ mountEpoch: 0,
+ viewportEpoch: 0,
+ };
+ const executorService = {
+ startLayout: vi.fn(async (requestIdentity: IDocLayoutMountIdentity): Promise<IDocLayoutStartResult> => {
+ identity = requestIdentity;
+ return {
+ status: DocLayoutSessionStatus.ACCEPTED,
+ step: {
+ ...requestIdentity,
+ progress: createProgress({
+ generation: 7,
+ didPublish: true,
+ anchorReady: true,
+ publishedPageCount: 1,
+ pageCount: 3,
+ }),
+ publication: null,
+ modelRevision: 3,
+ metricsRevision: 5,
+ },
+ };
+ }),
+ stepLayout: vi.fn(async () => ({
+ ...identity,
+ progress: createProgress({
+ generation: 7,
+ didPublish: true,
+ anchorReady: true,
+ complete: true,
+ publishedPageCount: 3,
+ pageCount: 3,
+ }),
+ publication: null,
+ modelRevision: 3,
+ metricsRevision: 5,
+ })),
+ publishBacklog: vi.fn(async () => ({
+ ...identity,
+ progress: createProgress({
+ generation: 7,
+ didPublish: true,
+ anchorReady: true,
+ complete: true,
+ publishedPageCount: 2,
+ pageCount: 2,
+ }),
+ publication: null,
+ modelRevision: 3,
+ metricsRevision: 5,
+ })),
+ getLayoutPage: vi.fn(),
+ cancelLayout: vi.fn(async () => {}),
+ disposeLayoutMount: vi.fn(async () => {}),
+ };
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.scheduleWorker(
+ 'doc-worker-pending-input',
+ { beginExternalLayout: vi.fn(), cancelExternalLayout: vi.fn() },
+ executorService,
+ { reason: 'initial' },
+ undefined,
+ { onProgress: vi.fn() },
+ vi.fn()
+ );
+ await vi.runAllTimersAsync();
+
+ expect(executorService.publishBacklog).toHaveBeenCalledTimes(1);
+ expect(executorService.stepLayout).not.toHaveBeenCalled();
+ coordinator.dispose();
+ });
+
+ it('keeps an external presentation barrier until Worker pages are published', async () => {
+ const requestAnimationFrameSpy = vi.fn((callback: FrameRequestCallback) =>
+ window.setTimeout(() => callback(performance.now()), 0));
+ vi.stubGlobal('requestAnimationFrame', requestAnimationFrameSpy);
+ const firstProgress = createProgress({
+ generation: 7,
+ didPublish: true,
+ anchorReady: true,
+ didPublishAnchor: true,
+ publishedPageCount: 1,
+ });
+ const progress = [
+ createProgress({
+ generation: 7,
+ didPublish: true,
+ anchorReady: true,
+ complete: true,
+ publishedPageCount: 2,
+ pageCount: 2,
+ }),
+ ];
+ let identity: IDocLayoutMountIdentity = {
+ unitId: 'doc-1',
+ mountId: '',
+ mountEpoch: 0,
+ viewportEpoch: 0,
+ };
+ const executorService = {
+ startLayout: vi.fn(async (requestIdentity: IDocLayoutMountIdentity): Promise<IDocLayoutStartResult> => {
+ identity = requestIdentity;
+ return {
+ status: DocLayoutSessionStatus.ACCEPTED,
+ step: {
+ ...requestIdentity,
+ progress: firstProgress,
+ publication: null,
+ modelRevision: 3,
+ metricsRevision: 5,
+ },
+ };
+ }),
+ stepLayout: vi.fn(async () => ({
+ ...identity,
+ progress: progress.shift()!,
+ publication: null,
+ modelRevision: 3,
+ metricsRevision: 5,
+ })),
+ publishBacklog: vi.fn(async () => ({
+ ...identity,
+ progress: createProgress({
+ generation: 7,
+ anchorReady: true,
+ didPublish: false,
+ publishedPageCount: 1,
+ }),
+ publication: null,
+ modelRevision: 3,
+ metricsRevision: 5,
+ })),
+ getLayoutPage: vi.fn(),
+ cancelLayout: vi.fn(async () => {}),
+ disposeLayoutMount: vi.fn(async () => {}),
+ };
+ const skeleton = {
+ beginExternalLayout: vi.fn(),
+ cancelExternalLayout: vi.fn(),
+ };
+ const onProgress = vi.fn();
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.scheduleWorker(
+ 'doc-1',
+ skeleton,
+ executorService,
+ { reason: 'edit', anchor: 12 },
+ undefined,
+ { onProgress },
+ vi.fn()
+ );
+
+ expect(skeleton.beginExternalLayout).toHaveBeenCalledWith({
+ reason: 'edit',
+ protectedRange: undefined,
+ });
+ await vi.runAllTimersAsync();
+ expect(executorService.startLayout).toHaveBeenCalledTimes(1);
+ expect(executorService.startLayout).toHaveBeenCalledWith(
+ {
+ unitId: 'doc-1',
+ mountId: expect.stringMatching(/^docs-layout-mount-/),
+ mountEpoch: 1,
+ viewportEpoch: 1,
+ },
+ { reason: 'edit', anchor: 12 },
+ 32
+ );
+ expect(executorService.publishBacklog).toHaveBeenCalledTimes(1);
+ expect(executorService.stepLayout).toHaveBeenCalledTimes(1);
+ expect(requestAnimationFrameSpy).toHaveBeenCalledTimes(2);
+ expect(onProgress).toHaveBeenCalledTimes(2);
+ expect(skeleton.cancelExternalLayout).not.toHaveBeenCalled();
+ coordinator.dispose();
+ expect(executorService.disposeLayoutMount).toHaveBeenCalledWith({
+ unitId: 'doc-1',
+ mountId: expect.stringMatching(/^docs-layout-mount-/),
+ mountEpoch: 1,
+ viewportEpoch: 1,
+ });
+ });
+
+ it('commits a Worker publication only inside the configured visual frame', async () => {
+ const visualFrames: Array<() => void> = [];
+ const scheduleVisualFrame = vi.fn((callback: () => void) => {
+ visualFrames.push(callback);
+ return () => {
+ const index = visualFrames.indexOf(callback);
+ if (index >= 0) {
+ visualFrames.splice(index, 1);
+ }
+ };
+ });
+ const executorService = {
+ startLayout: vi.fn(async (identity: IDocLayoutMountIdentity): Promise<IDocLayoutStartResult> => ({
+ status: DocLayoutSessionStatus.ACCEPTED,
+ step: {
+ ...identity,
+ progress: createProgress({
+ generation: 11,
+ didPublish: true,
+ anchorReady: true,
+ complete: true,
+ }),
+ publication: null,
+ modelRevision: 0,
+ metricsRevision: 1,
+ },
+ })),
+ stepLayout: vi.fn(),
+ publishBacklog: vi.fn(),
+ getLayoutPage: vi.fn(),
+ cancelLayout: vi.fn(async () => {}),
+ disposeLayoutMount: vi.fn(async () => {}),
+ };
+ const skeleton = {
+ beginExternalLayout: vi.fn(),
+ cancelExternalLayout: vi.fn(),
+ };
+ const onProgress = vi.fn();
+ const coordinator = new DocLayoutCoordinatorService(scheduleVisualFrame);
+
+ coordinator.scheduleWorker(
+ 'doc-frame-commit',
+ skeleton,
+ executorService,
+ { reason: 'initial' },
+ undefined,
+ { onProgress },
+ vi.fn()
+ );
+ await vi.waitFor(() => expect(scheduleVisualFrame).toHaveBeenCalledTimes(1));
+
+ expect(onProgress).not.toHaveBeenCalled();
+ coordinator.setWorkerPresentationPaused(true);
+ coordinator.setWorkerPresentationPaused(false);
+ expect(scheduleVisualFrame).toHaveBeenCalledTimes(1);
+ visualFrames.shift()?.();
+ await Promise.resolve();
+
+ expect(onProgress).toHaveBeenCalledTimes(1);
+ expect(onProgress).toHaveBeenCalledWith(
+ expect.objectContaining({ generation: 11, complete: true }),
+ null
+ );
+ coordinator.dispose();
+ });
+
+ it('keeps an in-flight Worker publication when scrolling defers background work', async () => {
+ const visualFrames: Array<() => void> = [];
+ const scheduleVisualFrame = vi.fn((callback: () => void) => {
+ visualFrames.push(callback);
+ return () => {
+ const index = visualFrames.indexOf(callback);
+ if (index >= 0) {
+ visualFrames.splice(index, 1);
+ }
+ };
+ });
+ const executorService = {
+ startLayout: vi.fn(async (identity: IDocLayoutMountIdentity): Promise<IDocLayoutStartResult> => ({
+ status: DocLayoutSessionStatus.ACCEPTED,
+ step: {
+ ...identity,
+ progress: createProgress({
+ generation: 13,
+ didPublish: true,
+ anchorReady: true,
+ publishedPageCount: 1,
+ pageCount: 3,
+ }),
+ publication: null,
+ modelRevision: 0,
+ metricsRevision: 1,
+ },
+ })),
+ stepLayout: vi.fn(),
+ publishBacklog: vi.fn(async (identity: IDocLayoutMountIdentity) => ({
+ ...identity,
+ progress: createProgress({
+ generation: 13,
+ didPublish: true,
+ anchorReady: true,
+ publishedPageCount: 2,
+ pageCount: 3,
+ }),
+ publication: null,
+ modelRevision: 0,
+ metricsRevision: 1,
+ })),
+ getLayoutPage: vi.fn(),
+ cancelLayout: vi.fn(async () => {}),
+ disposeLayoutMount: vi.fn(async () => {}),
+ };
+ const onProgress = vi.fn();
+ const coordinator = new DocLayoutCoordinatorService(scheduleVisualFrame);
+
+ coordinator.scheduleWorker(
+ 'doc-scroll-publication',
+ { beginExternalLayout: vi.fn(), cancelExternalLayout: vi.fn() },
+ executorService,
+ { reason: 'initial' },
+ undefined,
+ { onProgress },
+ vi.fn()
+ );
+ await vi.waitFor(() => expect(visualFrames).toHaveLength(1));
+ visualFrames.shift()?.();
+ await Promise.resolve();
+ await vi.advanceTimersByTimeAsync(4);
+ await vi.waitFor(() => expect(visualFrames).toHaveLength(1));
+
+ coordinator.deferBackgroundWork();
+
+ expect(visualFrames).toHaveLength(1);
+ expect(onProgress).toHaveBeenCalledTimes(1);
+ visualFrames.shift()?.();
+ await Promise.resolve();
+
+ expect(onProgress).toHaveBeenCalledTimes(2);
+ coordinator.dispose();
+ });
+
+ it('holds a Worker publication until the document interaction releases it', async () => {
+ const visualFrames: Array<() => void> = [];
+ const scheduleVisualFrame = vi.fn((callback: () => void) => {
+ visualFrames.push(callback);
+ return () => {
+ const index = visualFrames.indexOf(callback);
+ if (index >= 0) {
+ visualFrames.splice(index, 1);
+ }
+ };
+ });
+ const executorService = {
+ startLayout: vi.fn(async (identity: IDocLayoutMountIdentity): Promise<IDocLayoutStartResult> => ({
+ status: DocLayoutSessionStatus.ACCEPTED,
+ step: {
+ ...identity,
+ progress: createProgress({
+ generation: 12,
+ didPublish: true,
+ anchorReady: true,
+ complete: true,
+ }),
+ publication: null,
+ modelRevision: 0,
+ metricsRevision: 1,
+ },
+ })),
+ stepLayout: vi.fn(),
+ publishBacklog: vi.fn(),
+ getLayoutPage: vi.fn(),
+ cancelLayout: vi.fn(async () => {}),
+ disposeLayoutMount: vi.fn(async () => {}),
+ };
+ const skeleton = {
+ beginExternalLayout: vi.fn(),
+ cancelExternalLayout: vi.fn(),
+ };
+ const onProgress = vi.fn();
+ const coordinator = new DocLayoutCoordinatorService(scheduleVisualFrame);
+
+ coordinator.setWorkerPresentationPaused(true);
+ coordinator.scheduleWorker(
+ 'doc-interaction-publication',
+ skeleton,
+ executorService,
+ { reason: 'edit', anchor: 5 },
+ undefined,
+ { onProgress },
+ vi.fn()
+ );
+ await vi.waitFor(() => expect(executorService.startLayout).toHaveBeenCalledTimes(1));
+
+ expect(scheduleVisualFrame).not.toHaveBeenCalled();
+ expect(onProgress).not.toHaveBeenCalled();
+
+ coordinator.setWorkerPresentationPaused(false);
+ expect(scheduleVisualFrame).toHaveBeenCalledTimes(1);
+ visualFrames.shift()?.();
+ await Promise.resolve();
+
+ expect(onProgress).toHaveBeenCalledTimes(1);
+ coordinator.dispose();
+ });
+
+ it('ignores a late Worker start result after the mounted document is disposed', async () => {
+ let resolveStart: (result: IDocLayoutStartResult) => void = () => {};
+ let startIdentity: IDocLayoutMountIdentity = {
+ unitId: 'doc-late',
+ mountId: '',
+ mountEpoch: 0,
+ viewportEpoch: 0,
+ };
+ const executorService = {
+ startLayout: vi.fn((requestIdentity: IDocLayoutMountIdentity) => {
+ startIdentity = requestIdentity;
+ return new Promise<IDocLayoutStartResult>((resolve) => {
+ resolveStart = resolve;
+ });
+ }),
+ stepLayout: vi.fn(),
+ publishBacklog: vi.fn(),
+ getLayoutPage: vi.fn(),
+ cancelLayout: vi.fn(async () => {}),
+ disposeLayoutMount: vi.fn(async () => {}),
+ };
+ const skeleton = {
+ beginExternalLayout: vi.fn(),
+ cancelExternalLayout: vi.fn(),
+ };
+ const onProgress = vi.fn();
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.scheduleWorker(
+ 'doc-late',
+ skeleton,
+ executorService,
+ { reason: 'initial' },
+ undefined,
+ { onProgress },
+ vi.fn()
+ );
+ coordinator.dispose();
+ resolveStart({
+ status: DocLayoutSessionStatus.ACCEPTED,
+ step: {
+ ...startIdentity,
+ progress: createProgress({ generation: 9, didPublish: true, anchorReady: true }),
+ publication: null,
+ modelRevision: 0,
+ metricsRevision: 1,
+ },
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(onProgress).not.toHaveBeenCalled();
+ expect(skeleton.cancelExternalLayout).toHaveBeenCalledTimes(1);
+ expect(executorService.disposeLayoutMount).toHaveBeenCalledWith(startIdentity);
+ expect(executorService.cancelLayout).toHaveBeenCalledWith({
+ ...startIdentity,
+ generation: 9,
+ });
+ });
+
+ it('closes the external presentation barrier when a Worker publication is rejected', async () => {
+ const publicationError = new Error('continuation checkpoint mismatch');
+ const executorService = {
+ startLayout: vi.fn(async (identity: IDocLayoutMountIdentity): Promise<IDocLayoutStartResult> => ({
+ status: DocLayoutSessionStatus.ACCEPTED,
+ step: {
+ ...identity,
+ progress: createProgress({ generation: 9, didPublish: true, anchorReady: true }),
+ publication: null,
+ modelRevision: 0,
+ metricsRevision: 1,
+ },
+ })),
+ stepLayout: vi.fn(),
+ publishBacklog: vi.fn(),
+ getLayoutPage: vi.fn(),
+ cancelLayout: vi.fn(async () => {}),
+ disposeLayoutMount: vi.fn(async () => {}),
+ };
+ const skeleton = {
+ beginExternalLayout: vi.fn(),
+ cancelExternalLayout: vi.fn(),
+ };
+ const onError = vi.fn();
+ const coordinator = new DocLayoutCoordinatorService();
+
+ coordinator.scheduleWorker(
+ 'doc-rejected',
+ skeleton,
+ executorService,
+ { reason: 'edit' },
+ undefined,
+ { onProgress: () => { throw publicationError; } },
+ onError
+ );
+ await vi.runAllTimersAsync();
+ await vi.waitFor(() => {
+ expect(skeleton.cancelExternalLayout).toHaveBeenCalledTimes(1);
+ expect(onError).toHaveBeenCalledWith(publicationError);
+ });
+ coordinator.dispose();
+ });
+});
diff --git a/packages/docs-ui/src/services/__tests__/doc-layout-interaction.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-layout-interaction.service.spec.ts
new file mode 100644
index 0000000000..083604f114
--- /dev/null
+++ b/packages/docs-ui/src/services/__tests__/doc-layout-interaction.service.spec.ts
@@ -0,0 +1,51 @@
+/**
+ * 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, vi } from 'vitest';
+import { DocLayoutInteractionService } from '../doc-layout-interaction.service';
+
+describe('DocLayoutInteractionService', () => {
+ it('keeps the render protected until every overlapping interaction ends', () => {
+ const service = new DocLayoutInteractionService();
+ const activeStates: boolean[] = [];
+ service.active$.subscribe((active) => activeStates.push(active));
+
+ const menuInteraction = service.beginInteraction();
+ const dragInteraction = service.beginInteraction();
+ menuInteraction.dispose();
+ menuInteraction.dispose();
+
+ expect(service.isActive).toBe(true);
+ expect(activeStates).toEqual([false, true]);
+
+ dragInteraction.dispose();
+
+ expect(service.isActive).toBe(false);
+ expect(activeStates).toEqual([false, true, false]);
+ });
+
+ it('releases active interactions when the render is disposed', () => {
+ const service = new DocLayoutInteractionService();
+ const complete = vi.fn();
+ service.active$.subscribe({ complete });
+ service.beginInteraction();
+
+ service.dispose();
+
+ expect(service.isActive).toBe(false);
+ expect(complete).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
index b4bdd807d8..a64519bbd8 100644
--- a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
@@ -37,6 +37,7 @@ import {
getTableBlockMenuHoverRect,
getTableHorizontalViewportGeometry,
} from '../doc-event-manager.service';
+import { DocLayoutInteractionService } from '../doc-layout-interaction.service';
import { DocParagraphMenuService } from '../doc-paragraph-menu.service';
describe('DocParagraphMenuService', () => {
@@ -411,6 +412,29 @@ describe('DocParagraphMenuService', () => {
expect(replaceDocRanges).not.toHaveBeenCalled();
});
+ it('protects layout while the paragraph menu is actively used', () => {
+ const layoutInteractionService = new DocLayoutInteractionService();
+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));
+ const service = createService({
+ attachPopupToRect,
+ dataStream: 'Body\r',
+ layoutInteractionService,
+ });
+
+ service.showParagraphMenu(createParagraphBound({
+ paragraphStart: 0,
+ paragraphEnd: 4,
+ startIndex: 4,
+ }));
+ service.setParagraphMenuActive(true);
+
+ expect(layoutInteractionService.isActive).toBe(true);
+
+ service.setParagraphMenuActive(false);
+
+ expect(layoutInteractionService.isActive).toBe(false);
+ });
+
it('does not show paragraph menus while a table rect selection is active', () => {
const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));
const service = createService({
@@ -756,6 +780,21 @@ describe('DocParagraphMenuService', () => {
expect(service.activeTarget).toBeNull();
});
+ it('protects layout for the full block drag lifetime', () => {
+ const layoutInteractionService = new DocLayoutInteractionService();
+ const service = createService({
+ attachPopupToRect: vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() })),
+ dataStream: 'Title\r',
+ layoutInteractionService,
+ });
+
+ service.setBlockMenuDragging(true);
+ expect(layoutInteractionService.isActive).toBe(true);
+
+ service.setBlockMenuDragging(false);
+ expect(layoutInteractionService.isActive).toBe(false);
+ });
+
it('hides the paragraph menu on keyboard input', () => {
const dispose = vi.fn();
const keydown$ = new Subject();
@@ -1313,6 +1352,7 @@ function createService(options: {
isOnPointerEvent?: boolean;
inputBefore$?: Subject<unknown>;
keydown$?: Subject<unknown>;
+ layoutInteractionService?: DocLayoutInteractionService;
replaceDocRanges?: ReturnType<typeof vi.fn>;
scrollAfter$?: { subscribeEvent: (callback: (event: { scrollY: number }) => void) => { dispose: () => void } };
selectionStart$?: Subject<unknown>;
@@ -1398,7 +1438,8 @@ function createService(options: {
value: options.getPermissionValue?.(permissionId) ?? options.canEdit ?? true,
}),
permissionPointUpdate$: new Subject(),
- } as never
+ } as never,
+ options.layoutInteractionService ?? new DocLayoutInteractionService()
);
}
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 a75ef760d4..35e25bcf1e 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
@@ -101,7 +101,6 @@ class TestRenderManagerService {
getSkeleton: () => skeleton,
};
}
-
throw new Error(`Unexpected render dependency: ${String(token)}`);
},
};
@@ -230,6 +229,39 @@ describe('DocCanvasPopManagerService', () => {
expect(renderManagerService.getInjector).toHaveBeenCalledTimes(1);
});
+ it('publishes popup ownership until the last popup for a document is disposed', () => {
+ const { service } = createService();
+ const popupUnits: string[][] = [];
+ const subscription = service.popupUnits$.subscribe((units) => {
+ popupUnits.push(Array.from(units).sort());
+ });
+
+ const first = service.attachPopupToRect(
+ { left: 10, right: 110, top: 20, bottom: 40 },
+ { componentKey: 'first-popup' },
+ 'doc-1'
+ );
+ const second = service.attachPopupToRect(
+ { left: 10, right: 110, top: 20, bottom: 40 },
+ { componentKey: 'second-popup' },
+ 'doc-1'
+ );
+ const other = service.attachPopupToRect(
+ { left: 10, right: 110, top: 20, bottom: 40 },
+ { componentKey: 'other-popup' },
+ 'doc-2'
+ );
+
+ first.dispose();
+ expect(popupUnits.at(-1)).toEqual(['doc-1', 'doc-2']);
+ second.dispose();
+ expect(popupUnits.at(-1)).toEqual(['doc-2']);
+ other.dispose();
+ expect(popupUnits.at(-1)).toEqual([]);
+
+ subscription.unsubscribe();
+ });
+
it('uses embedded unit creation metadata when the render has no scene ownership flag', () => {
const { service, popupService, renderManagerService, univerInstanceService } = createService();
renderManagerService.isMainScene = undefined;
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 456acf2ae6..82a8ecd1c7 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
@@ -43,6 +43,7 @@ import { ComponentManager } from '@univerjs/ui';
import { Subject } from 'rxjs';
import { describe, expect, it } from 'vitest';
import { EmbedRuntimeFocusCoordinator, IDocEmbedRuntimeFocusCoordinator } from '../doc-embed-integration.service';
+import { DocLayoutInteractionService } from '../doc-layout-interaction.service';
import { DocCanvasPopManagerService } from '../doc-popup-manager.service';
import { DocFloatMenuService } from '../float-menu.service';
import { DocSelectionRenderService } from '../selection/doc-selection-render.service';
@@ -103,6 +104,7 @@ function createActiveFloatMenuHarness(
injector.add([ICommandService, { useClass: CommandService }]);
injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
injector.add([DocSelectionManagerService]);
+ injector.add([DocLayoutInteractionService]);
injector.add([DocCanvasPopManagerService, { useClass: RecordingDocCanvasPopManagerServiceCtor }]);
injector.add([ComponentManager]);
injector.add([DocSelectionRenderService, { useClass: ActiveDocSelectionRenderServiceCtor }]);
@@ -136,6 +138,7 @@ describe('DocFloatMenuService', () => {
injector.add([ICommandService, { useClass: CommandService }]);
injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
injector.add([DocSelectionManagerService]);
+ injector.add([DocLayoutInteractionService]);
injector.add([DocCanvasPopManagerService, { useClass: InertDocCanvasPopManagerServiceCtor }]);
injector.add([ComponentManager]);
injector.add([DocSelectionRenderService, { useClass: InertDocSelectionRenderServiceCtor }]);
@@ -155,6 +158,7 @@ describe('DocFloatMenuService', () => {
injector.add([ICommandService, { useClass: CommandService }]);
injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
injector.add([DocSelectionManagerService]);
+ injector.add([DocLayoutInteractionService]);
injector.add([DocCanvasPopManagerService, { useClass: RecordingDocCanvasPopManagerServiceCtor }]);
injector.add([ComponentManager]);
injector.add([DocSelectionRenderService, { useClass: ActiveDocSelectionRenderServiceCtor }]);
@@ -203,14 +207,17 @@ describe('DocFloatMenuService', () => {
}, { unitId, subUnitId: unitId });
const popupService = injector.get(DocCanvasPopManagerService) as unknown as RecordingDocCanvasPopManagerService;
+ const layoutInteractionService = injector.get(DocLayoutInteractionService);
expect(popupService.ranges).toEqual(['0:5']);
expect(popupService.offsets).toEqual([[0, 10]]);
expect(service.floatMenu).toMatchObject({ start: 0, end: 5 });
+ expect(layoutInteractionService.isActive).toBe(true);
const selectionRenderService = injector.get(DocSelectionRenderService) as unknown as ActiveDocSelectionRenderService;
selectionRenderService.emitSelectionStart();
expect(service.floatMenu).toBeNull();
expect(popupService.disposedCount).toBe(1);
+ expect(layoutInteractionService.isActive).toBe(false);
});
it('hides the floating toolbar when document edit permission is revoked', () => {
@@ -260,6 +267,7 @@ describe('DocFloatMenuService', () => {
injector.add([ICommandService, { useClass: CommandService }]);
injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
injector.add([DocSelectionManagerService]);
+ injector.add([DocLayoutInteractionService]);
injector.add([DocCanvasPopManagerService, { useClass: RecordingDocCanvasPopManagerServiceCtor }]);
injector.add([ComponentManager]);
injector.add([DocSelectionRenderService, { useClass: ActiveDocSelectionRenderServiceCtor }]);
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 a8a6c2e0c3..8a2ee0e4ff 100644
--- a/packages/docs-ui/src/services/doc-event-manager.service.ts
+++ b/packages/docs-ui/src/services/doc-event-manager.service.ts
@@ -24,6 +24,7 @@ import type {
IDocumentSkeletonLineContext,
IDocumentSkeletonPage,
IDocumentSkeletonSection,
+ IDocumentSkeletonTableCellGeometry,
IRenderContext,
IRenderModule,
} from '@univerjs/engine-render';
@@ -327,6 +328,12 @@ export interface ITableCellBound {
tableId: string;
}
+interface ITableCellGeometryEntry {
+ cellGeometry: IDocumentSkeletonTableCellGeometry;
+ pageIndex: number;
+ segmentId?: string;
+}
+
const TABLE_BLOCK_MENU_HOVER_GUTTER_LEFT = 72;
const TABLE_BLOCK_MENU_HOVER_GUTTER_TOP = 42;
@@ -441,6 +448,7 @@ export class DocEventManagerService extends Disposable implements IRenderModule
private _customRangeDirty = true;
private _bulletDirty = true;
private _paragraphDirty = true;
+ private _tableBoundsDirty = true;
/**
* cache the bounding of custom ranges,
@@ -459,10 +467,13 @@ export class DocEventManagerService extends Disposable implements IRenderModule
private _paragraphBounds: Map<number, IMutiPageParagraphBound> = new Map();
private _paragraphLeftBounds: IMutiPageParagraphBound[] = [];
private _tableParagraphBounds: Map<string, ITableParagraphBound[]> = new Map();
+ private _tableParagraphBoundsByIndex: Map<number, ITableParagraphBound> = new Map();
private _segmentParagraphBounds: Map<string, Map<number, IMutiPageParagraphBound[]>> = new Map();
private _tableViewportSignature = '';
private _tableCellBounds: Map<string, ITableCellBound[]> = new Map();
+ private _tableCellGeometries: Map<string, ITableCellGeometryEntry[]> = new Map();
+ private _tableCellPages = new Set<number>();
private _tableBounds: Map<string, ITableBound> = new Map();
private get _skeleton() {
@@ -508,6 +519,7 @@ export class DocEventManagerService extends Disposable implements IRenderModule
this._customRangeDirty = true;
this._bulletDirty = true;
this._paragraphDirty = true;
+ this._tableBoundsDirty = true;
}));
this.disposeWithMe(
@@ -517,6 +529,7 @@ export class DocEventManagerService extends Disposable implements IRenderModule
this._customRangeDirty = true;
this._bulletDirty = true;
this._paragraphDirty = true;
+ this._tableBoundsDirty = true;
})
);
@@ -527,6 +540,7 @@ export class DocEventManagerService extends Disposable implements IRenderModule
this._customRangeDirty = true;
this._bulletDirty = true;
this._paragraphDirty = true;
+ this._tableBoundsDirty = true;
})
);
}
@@ -815,7 +829,6 @@ export class DocEventManagerService extends Disposable implements IRenderModule
return this._context.unit.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.paragraphs?.find((paragraph) => paragraph.startIndex === startIndex);
}
- // eslint-disable-next-line max-lines-per-function
private _buildParagraphBoundsBySegment(segmentId?: string) {
const skeletonData = this._skeleton.getSkeletonData();
const documents = this._documents;
@@ -824,7 +837,6 @@ export class DocEventManagerService extends Disposable implements IRenderModule
return null;
}
- // eslint-disable-next-line max-lines-per-function
const calc = (pages: IDocumentSkeletonPage[]) => {
const paragraphMap: Map<number, IMutiPageParagraphBound> = new Map();
@@ -880,71 +892,6 @@ export class DocEventManagerService extends Disposable implements IRenderModule
);
});
- for (const tableContext of documentSkeletonTableIterator(pages, {
- docsLeft: documentOffsetConfig.docsLeft,
- docsTop: documentOffsetConfig.docsTop,
- pageMarginTop: documentOffsetConfig.pageMarginTop,
- unitId: this._context.unitId,
- })) {
- const tableId = tableContext.tableId;
- const sourceTableId = getTableIdAndSliceIndex(tableId).tableId;
- const tableViewport = getTableHorizontalViewportGeometry(
- tableContext.tableRect.left,
- tableContext.table.width,
- getDocsTableRenderViewport(this._context.unitId, sourceTableId)
- );
- this._tableBounds.set(tableId, {
- rect: {
- ...tableContext.tableRect,
- right: tableViewport.visibleRight,
- },
- pageIndex: tableContext.pageIndex,
- tableId,
- });
-
- for (const cellGeometry of tableContext.cells) {
- const cell = cellGeometry.cell;
- const cellContentWidth = (cell.pageWidth ?? 0) - (cell.marginLeft ?? 0) - (cell.marginRight ?? 0);
- const bounds = calcDocParagraphPositions(cell.sections, cellGeometry.pageTop, cellGeometry.pageLeft, cellContentWidth)
- .map((bound) => clipParagraphBoundHorizontally(bound, cellGeometry.clipLeft, cellGeometry.clipRight))
- .filter((bound): bound is ICustomRangeBoundBase => bound != null);
- let arr = this._tableParagraphBounds.get(tableId);
- if (!arr) {
- arr = [];
- this._tableParagraphBounds.set(tableId, arr);
- }
-
- arr.push(...bounds.map((bound) => ({
- rect: bound.rect,
- paragraphStart: bound.paragraphStart,
- paragraphEnd: bound.paragraphEnd,
- startIndex: bound.startIndex,
- pageIndex: tableContext.pageIndex,
- segmentId,
- rowIndex: cellGeometry.rowIndex,
- colIndex: cellGeometry.columnIndex,
- firstLine: bound.fisrtLine,
- tableId,
- }))
- );
-
- let cellBounds = this._tableCellBounds.get(tableId);
-
- if (!cellBounds) {
- cellBounds = [];
- this._tableCellBounds.set(tableId, cellBounds);
- }
-
- cellBounds.push({
- rect: cellGeometry.cellRect,
- pageIndex: tableContext.pageIndex,
- rowIndex: cellGeometry.rowIndex,
- colIndex: cellGeometry.columnIndex,
- tableId,
- });
- }
- }
-
return paragraphMap;
};
@@ -960,15 +907,12 @@ export class DocEventManagerService extends Disposable implements IRenderModule
}
private _buildParagraphBounds() {
- const tableViewportSignature = this._getTableViewportSignature();
- if (!this._paragraphDirty && this._tableViewportSignature === tableViewportSignature) {
+ if (!this._paragraphDirty) {
return;
}
this._paragraphDirty = false;
- this._tableViewportSignature = tableViewportSignature;
this._tableParagraphBounds = new Map();
- this._tableCellBounds = new Map();
- this._tableBounds = new Map();
+ this._tableParagraphBoundsByIndex = new Map();
this._paragraphBounds = this._buildParagraphBoundsBySegment() ?? new Map();
this._paragraphLeftBounds = Array.from(this._paragraphBounds.values()).map((bound) => ({
...bound,
@@ -994,23 +938,199 @@ export class DocEventManagerService extends Disposable implements IRenderModule
});
}
- private _calcActiveParagraph(evt: { x: number; y: number }): Nullable<IMutiPageParagraphBound> {
- this._buildParagraphBounds();
+ private _buildTableBounds() {
+ const tableViewportSignature = this._getTableViewportSignature();
+ if (!this._tableBoundsDirty && this._tableViewportSignature === tableViewportSignature) {
+ return;
+ }
+
+ this._tableBoundsDirty = false;
+ this._tableViewportSignature = tableViewportSignature;
+ this._tableBounds = new Map();
+ this._tableCellBounds = new Map();
+ this._tableCellGeometries = new Map();
+ this._tableCellPages = new Set();
+ this._tableParagraphBounds = new Map();
+ this._tableParagraphBoundsByIndex = new Map();
+
+ const skeletonData = this._skeleton.getSkeletonData();
+ const pages = skeletonData?.pages;
+ if (!pages) {
+ return;
+ }
+ const { docsLeft, docsTop, pageMarginTop } = this._documents.getOffsetConfig();
+ for (const tableContext of documentSkeletonTableIterator(pages, {
+ docsLeft,
+ docsTop,
+ includeCells: false,
+ pageMarginTop,
+ skeFooters: skeletonData.skeFooters,
+ skeHeaders: skeletonData.skeHeaders,
+ unitId: this._context.unitId,
+ })) {
+ const tableId = tableContext.tableId;
+ const sourceTableId = getTableIdAndSliceIndex(tableId).tableId;
+ const tableViewport = getTableHorizontalViewportGeometry(
+ tableContext.tableRect.left,
+ tableContext.table.width,
+ getDocsTableRenderViewport(this._context.unitId, sourceTableId)
+ );
+ this._tableBounds.set(tableId, {
+ rect: {
+ ...tableContext.tableRect,
+ right: tableViewport.visibleRight,
+ },
+ pageIndex: tableContext.pageIndex,
+ tableId,
+ });
+ }
+ }
+
+ private _buildTableCellsForPage(pageIndex: number): void {
+ if (this._tableCellPages.has(pageIndex)) {
+ return;
+ }
+
+ const skeletonData = this._skeleton.getSkeletonData();
+ const page = skeletonData?.pages[pageIndex];
+ if (!skeletonData || !page) {
+ return;
+ }
+
+ this._tableCellPages.add(pageIndex);
+ const { docsLeft, docsTop, pageMarginTop } = this._documents.getOffsetConfig();
+ const pageTop = skeletonData.pages.slice(0, pageIndex).reduce((top, previousPage) =>
+ top + (previousPage.pageHeight === Infinity ? 0 : previousPage.pageHeight) + pageMarginTop, 0);
+ const contexts = documentSkeletonTableIterator([page], {
+ docsLeft,
+ docsTop: docsTop + pageTop,
+ includeCells: true,
+ pageMarginTop,
+ skeFooters: skeletonData.skeFooters,
+ skeHeaders: skeletonData.skeHeaders,
+ unitId: this._context.unitId,
+ });
+
+ for (const tableContext of contexts) {
+ const tableId = tableContext.tableId;
+ const segmentId = tableContext.source === 'header'
+ ? tableContext.rootPage.headerId
+ : tableContext.source === 'footer'
+ ? tableContext.rootPage.footerId
+ : undefined;
+ const cellGeometries = this._tableCellGeometries.get(tableId) ?? [];
+ const cellBounds = this._tableCellBounds.get(tableId) ?? [];
+ for (const cellGeometry of tableContext.cells) {
+ cellGeometries.push({ cellGeometry, pageIndex, segmentId });
+ cellBounds.push({
+ rect: cellGeometry.cellRect,
+ pageIndex,
+ rowIndex: cellGeometry.rowIndex,
+ colIndex: cellGeometry.columnIndex,
+ tableId,
+ });
+ }
+ this._tableCellGeometries.set(tableId, cellGeometries);
+ this._tableCellBounds.set(tableId, cellBounds);
+ }
+ }
+
+ private _buildTableCellsForDocumentRange(startIndex: number, endIndex: number): void {
+ const body = this._context.unit.getSelfOrHeaderFooterModel()?.getBody();
+ const tableIds = new Set(
+ (body?.tables ?? [])
+ .filter((table) => endIndex >= table.startIndex && startIndex < table.endIndex)
+ .map((table) => table.tableId)
+ );
+ if (tableIds.size === 0) {
+ this._tableBounds.forEach((bound) => this._buildTableCellsForPage(bound.pageIndex));
+ return;
+ }
+
+ this._tableBounds.forEach((bound, tableId) => {
+ if (tableIds.has(getTableIdAndSliceIndex(tableId).tableId)) {
+ this._buildTableCellsForPage(bound.pageIndex);
+ }
+ });
+ }
+
+ private _getTableParagraphBoundsForCell(
+ tableId: string,
+ rowIndex: number,
+ colIndex: number,
+ pageIndex: number
+ ): ITableParagraphBound[] {
+ const cached = this._tableParagraphBounds.get(tableId)?.filter((bound) =>
+ bound.pageIndex === pageIndex && bound.rowIndex === rowIndex && bound.colIndex === colIndex
+ );
+ if (cached?.length) {
+ return cached;
+ }
+
+ const entry = this._tableCellGeometries.get(tableId)?.find((item) =>
+ item.pageIndex === pageIndex &&
+ item.cellGeometry.rowIndex === rowIndex &&
+ item.cellGeometry.columnIndex === colIndex
+ );
+ if (!entry) {
+ return [];
+ }
+
+ const { cellGeometry, segmentId } = entry;
+ const cell = cellGeometry.cell;
+ const cellContentWidth = (cell.pageWidth ?? 0) - (cell.marginLeft ?? 0) - (cell.marginRight ?? 0);
+ const paragraphBounds: ITableParagraphBound[] = calcDocParagraphPositions(
+ cell.sections,
+ cellGeometry.pageTop,
+ cellGeometry.pageLeft,
+ cellContentWidth
+ )
+ .map((bound) => clipParagraphBoundHorizontally(bound, cellGeometry.clipLeft, cellGeometry.clipRight))
+ .filter((bound): bound is ICustomRangeBoundBase => bound != null)
+ .map((bound) => ({
+ rect: bound.rect,
+ paragraphStart: bound.paragraphStart,
+ paragraphEnd: bound.paragraphEnd,
+ startIndex: bound.startIndex,
+ pageIndex,
+ segmentId,
+ rowIndex,
+ colIndex,
+ firstLine: bound.fisrtLine,
+ tableId,
+ }));
+
+ const retained = (this._tableParagraphBounds.get(tableId) ?? []).filter((bound) =>
+ bound.pageIndex !== pageIndex || bound.rowIndex !== rowIndex || bound.colIndex !== colIndex
+ );
+ retained.push(...paragraphBounds);
+ this._tableParagraphBounds.set(tableId, retained);
+ paragraphBounds.forEach((bound) => this._tableParagraphBoundsByIndex.set(bound.startIndex, bound));
+ return paragraphBounds;
+ }
+
+ private _calcActiveParagraph(evt: { x: number; y: number }): Nullable<IMutiPageParagraphBound> {
const { x, y } = evt;
+ this._buildTableBounds();
const table = Array.from(this._tableBounds.values()).find((bound) => isPointInRect(x, y, getTableBlockMenuHoverRect(bound.rect)));
this._hoverTable$.next(table);
if (table) {
+ this._buildTableCellsForPage(table.pageIndex);
const tableCell = this._tableCellBounds.get(table.tableId)?.find((bound) => isPointInRect(x, y, bound.rect));
this._hoverTableCell$.next(tableCell);
if (!tableCell) {
return null;
}
- const paragraphs = this._tableParagraphBounds.get(tableCell.tableId)
- ?.filter((bound) => bound.colIndex === tableCell.colIndex && bound.rowIndex === tableCell.rowIndex);
+ const paragraphs = this._getTableParagraphBoundsForCell(
+ tableCell.tableId,
+ tableCell.rowIndex,
+ tableCell.colIndex,
+ tableCell.pageIndex
+ );
const paragraph = paragraphs?.find((bound) => isPointInRect(x, y, bound.rect));
return paragraph && {
...paragraph,
@@ -1018,6 +1138,7 @@ export class DocEventManagerService extends Disposable implements IRenderModule
};
}
+ this._buildParagraphBounds();
return getMostSpecificParagraphBound([...this._paragraphBounds.values()].filter((bound) =>
bound.rects.some((rect) => isPointInRect(x, y, rect))
));
@@ -1036,12 +1157,21 @@ export class DocEventManagerService extends Disposable implements IRenderModule
}
get tableBounds() {
- this._buildParagraphBounds();
+ this._buildTableBounds();
return this._tableBounds;
}
findTableCellBound(tableId: string, rowIndex: number, colIndex: number, pageIndex?: number) {
- this._buildParagraphBounds();
+ this._buildTableBounds();
+ if (pageIndex != null) {
+ this._buildTableCellsForPage(pageIndex);
+ } else {
+ this._tableBounds.forEach((bound, id) => {
+ if (getTableIdAndSliceIndex(id).tableId === getTableIdAndSliceIndex(tableId).tableId) {
+ this._buildTableCellsForPage(bound.pageIndex);
+ }
+ });
+ }
return this._tableCellBounds.get(tableId)?.find((bound) => (
bound.rowIndex === rowIndex &&
bound.colIndex === colIndex &&
@@ -1050,12 +1180,35 @@ export class DocEventManagerService extends Disposable implements IRenderModule
}
findParagraphBoundByIndex(index: number) {
- this._buildParagraphBounds();
- const tableParagraph = Array.from(this._tableParagraphBounds.values()).flat().find((bound) => bound.startIndex === index);
+ this._buildTableBounds();
+ this._buildTableCellsForDocumentRange(index, index);
+ let tableParagraph = this._tableParagraphBoundsByIndex.get(index);
+ if (!tableParagraph) {
+ for (const [tableId, entries] of this._tableCellGeometries) {
+ for (const entry of entries) {
+ const { st, ed } = entry.cellGeometry.cell;
+ if (st != null && ed != null && (index < st || index > ed)) {
+ continue;
+ }
+
+ this._getTableParagraphBoundsForCell(
+ tableId,
+ entry.cellGeometry.rowIndex,
+ entry.cellGeometry.columnIndex,
+ entry.pageIndex
+ );
+ tableParagraph = this._tableParagraphBoundsByIndex.get(index);
+ if (tableParagraph) {
+ return tableParagraph;
+ }
+ }
+ }
+ }
if (tableParagraph) {
return tableParagraph;
}
+ this._buildParagraphBounds();
const paragraph = this._paragraphBounds.get(index);
if (paragraph) {
return paragraph;
@@ -1063,8 +1216,24 @@ export class DocEventManagerService extends Disposable implements IRenderModule
}
findParagraphBoundsInRange(startIndex: number, endIndex: number): IMutiPageParagraphBound[] {
+ this._buildTableBounds();
+ this._buildTableCellsForDocumentRange(startIndex, endIndex);
this._buildParagraphBounds();
+ for (const [tableId, entries] of this._tableCellGeometries) {
+ entries
+ .filter((item) => {
+ const { st, ed } = item.cellGeometry.cell;
+ return st == null || ed == null || (endIndex >= st && startIndex <= ed);
+ })
+ .forEach((entry) => this._getTableParagraphBoundsForCell(
+ tableId,
+ entry.cellGeometry.rowIndex,
+ entry.cellGeometry.columnIndex,
+ entry.pageIndex
+ ));
+ }
+
const bodyBounds = [...this._paragraphBounds.values()];
const tableBounds = Array.from(this._tableParagraphBounds.values()).flat().map((bound) => ({
rect: bound.rect,
@@ -1081,10 +1250,22 @@ export class DocEventManagerService extends Disposable implements IRenderModule
}
private _getTableViewportSignature(): string {
+ if (this._tableBounds.size > 0) {
+ const tableIds = new Set<string>();
+ this._tableBounds.forEach((_bound, tableId) => tableIds.add(getTableIdAndSliceIndex(tableId).tableId));
+ return Array.from(tableIds).map((tableId) => {
+ const viewport = getDocsTableRenderViewport(this._context.unitId, tableId);
+ return viewport
+ ? `${tableId}:${viewport.contentWidth}:${viewport.viewportWidth}:${viewport.scrollLeft}`
+ : `${tableId}:none`;
+ }).join('|');
+ }
+
const pages = this._skeleton.getSkeletonData()?.pages ?? [];
const signatures: string[] = [];
for (const tableContext of documentSkeletonTableIterator(pages, {
+ includeCells: false,
pageMarginTop: this._documents.getOffsetConfig().pageMarginTop,
resolveViewport: false,
unitId: this._context.unitId,
diff --git a/packages/docs-ui/src/services/doc-layout-coordinator.service.ts b/packages/docs-ui/src/services/doc-layout-coordinator.service.ts
new file mode 100644
index 0000000000..b4554c53aa
--- /dev/null
+++ b/packages/docs-ui/src/services/doc-layout-coordinator.service.ts
@@ -0,0 +1,940 @@
+/**
+ * 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 { DocLayoutExecutorService, IDocLayoutMountIdentity, IDocLayoutPageResult, IDocLayoutStartOptions, IDocLayoutStepResult } from '@univerjs/docs';
+import type { DocumentLayoutReason, DocumentSkeleton, IDocumentLayoutProgress, IDocumentLayoutProtectedRange } from '@univerjs/engine-render';
+import { Disposable } from '@univerjs/core';
+import { DocLayoutSessionStatus } from '@univerjs/docs';
+
+const FOREGROUND_BUDGET_MS = 8;
+const WORKER_FOREGROUND_BUDGET_MS = 32;
+const WORKER_BACKGROUND_BUDGET_MS = 128;
+const BACKGROUND_BUDGET_MS = 12;
+const BACKGROUND_YIELD_MS = 4;
+const BACKGROUND_RESUME_DELAY_MS = 4;
+const EDIT_BACKGROUND_RESUME_DELAY_MS = 120;
+const MIN_EDIT_FOREGROUND_WINDOW_SIZE = 3;
+const MAX_EDIT_FOREGROUND_WINDOW_SIZE = 5;
+const EDIT_FOREGROUND_WINDOW_SIZE = MAX_EDIT_FOREGROUND_WINDOW_SIZE;
+const EDIT_FOREGROUND_BUDGET_MS = 28;
+let docLayoutMountSequence = 0;
+
+interface IInputPendingSchedulingHost {
+ scheduling: {
+ isInputPending: (options?: { includeContinuous?: boolean }) => boolean;
+ };
+}
+
+function hasInputPendingScheduling(value: object): value is IInputPendingSchedulingHost {
+ if (!('scheduling' in value)) {
+ return false;
+ }
+
+ const scheduling = value.scheduling;
+ return typeof scheduling === 'object' && scheduling != null &&
+ 'isInputPending' in scheduling && typeof scheduling.isInputPending === 'function';
+}
+
+function hasPendingUserInput(): boolean {
+ if (typeof navigator === 'undefined') {
+ return false;
+ }
+
+ return hasInputPendingScheduling(navigator) &&
+ navigator.scheduling.isInputPending({ includeContinuous: true });
+}
+
+export interface IDocLayoutCoordinatorCallbacks {
+ onProgress: (progress: IDocumentLayoutProgress, publication?: IDocLayoutStepResult['publication']) => void;
+ onComplete?: (progress: IDocumentLayoutProgress) => void;
+ onForegroundReady?: (progress: IDocumentLayoutProgress) => void;
+}
+
+interface IScheduledLayoutBase {
+ callbacks: IDocLayoutCoordinatorCallbacks;
+ backgroundResumeDelayMs: number;
+ nextBackgroundDelayMs: number;
+ anchorReady: boolean;
+}
+
+function getBackgroundResumeDelay(reason: DocumentLayoutReason): number {
+ return reason === 'edit' ? EDIT_BACKGROUND_RESUME_DELAY_MS : BACKGROUND_RESUME_DELAY_MS;
+}
+
+function normalizeEditForegroundWindowSize(size: number | undefined): number {
+ const normalizedSize = Math.floor(size ?? EDIT_FOREGROUND_WINDOW_SIZE);
+ return Math.min(
+ MAX_EDIT_FOREGROUND_WINDOW_SIZE,
+ Math.max(MIN_EDIT_FOREGROUND_WINDOW_SIZE, normalizedSize)
+ );
+}
+
+interface IScheduledMainThreadLayout extends IScheduledLayoutBase {
+ executor: 'main-thread';
+ skeleton: DocumentLayoutSchedulingSkeleton;
+ generation: number;
+ foregroundStarted: boolean;
+ foregroundBudgetMs: number;
+ foregroundElapsedMs: number;
+ foregroundWindowSize: number;
+ foregroundTargetProgressCount: number | null;
+ foregroundEndOffset: number | null;
+ waitForAnimationFrame: boolean;
+}
+
+export type DocumentLayoutSchedulingSkeleton = Pick<
+ DocumentSkeleton,
+ 'startIncrementalLayout' | 'stepIncrementalLayout' | 'cancelIncrementalLayout'
+> & Partial<Pick<DocumentSkeleton, 'publishIncrementalLayoutBacklog'>>;
+
+type DocumentLayoutSchedulingOptions = NonNullable<Parameters<DocumentSkeleton['startIncrementalLayout']>[0]> & {
+ reason: DocumentLayoutReason;
+ foregroundWindowSize?: number;
+ foregroundBudgetMs?: number;
+ foregroundEndOffset?: number;
+};
+
+type DocLayoutSchedulingExecutor = Pick<
+ DocLayoutExecutorService,
+ 'startLayout' | 'stepLayout' | 'publishBacklog' | 'getLayoutPage' | 'cancelLayout' | 'disposeLayoutMount'
+>;
+
+type ExternalLayoutPresentation = Pick<DocumentSkeleton, 'beginExternalLayout' | 'cancelExternalLayout'>;
+
+interface IScheduledWorkerLayout extends IScheduledLayoutBase {
+ executor: 'worker';
+ unitId: string;
+ mountId: string;
+ mountEpoch: number;
+ viewportEpoch: number;
+ skeleton: ExternalLayoutPresentation;
+ executorService: DocLayoutSchedulingExecutor;
+ options: IDocLayoutStartOptions;
+ generation: number | null;
+ modelRevision: number | null;
+ metricsRevision: number | null;
+ onError: (error: unknown) => void;
+}
+
+type IScheduledLayout = IScheduledMainThreadLayout | IScheduledWorkerLayout;
+
+export type DocLayoutVisualFrameScheduler = (callback: () => void) => () => void;
+
+function scheduleAnimationFrame(callback: () => void): () => void {
+ if (typeof requestAnimationFrame === 'function') {
+ const frameId = requestAnimationFrame(callback);
+ return () => cancelAnimationFrame(frameId);
+ }
+
+ const timerId = setTimeout(callback, 0);
+ return () => clearTimeout(timerId);
+}
+
+interface IPendingWorkerPresentation {
+ cancel: () => void;
+ resume: () => void;
+}
+
+/**
+ * Cooperative presentation scheduler for interactive document layout.
+ *
+ * The coordinator owns only timing and cancellation. The selected executor owns
+ * layout state; both executors publish the same generation/step contract.
+ */
+export class DocLayoutCoordinatorService extends Disposable {
+ private readonly _mountId = `docs-layout-mount-${++docLayoutMountSequence}`;
+ private _mountEpoch = 0;
+ private _viewportEpoch = 0;
+ private _workerMount: {
+ unitId: string;
+ executorService: DocLayoutSchedulingExecutor;
+ onError: (error: unknown) => void;
+ mountEpoch: number;
+ viewportEpoch: number;
+ } | null = null;
+
+ private _scheduledLayout: IScheduledLayout | null = null;
+ private _animationFrameId: number | null = null;
+ private _idleCallbackId: number | null = null;
+ private _fallbackTimerId: ReturnType<typeof setTimeout> | null = null;
+ private _pendingWorkerPresentation: IPendingWorkerPresentation | null = null;
+ private _workerPresentationPaused = false;
+
+ constructor(
+ private readonly _scheduleVisualFrame: DocLayoutVisualFrameScheduler = scheduleAnimationFrame
+ ) {
+ super();
+ }
+
+ schedule(
+ skeleton: DocumentLayoutSchedulingSkeleton,
+ options: DocumentLayoutSchedulingOptions,
+ callbacks: IDocLayoutCoordinatorCallbacks
+ ): number {
+ this.cancel();
+
+ const generation = skeleton.startIncrementalLayout(options);
+ const backgroundResumeDelayMs = getBackgroundResumeDelay(options.reason);
+ this._scheduledLayout = {
+ executor: 'main-thread',
+ skeleton,
+ generation,
+ callbacks,
+ backgroundResumeDelayMs,
+ nextBackgroundDelayMs: backgroundResumeDelayMs,
+ anchorReady: false,
+ foregroundStarted: false,
+ foregroundBudgetMs: options.foregroundBudgetMs ?? EDIT_FOREGROUND_BUDGET_MS,
+ foregroundElapsedMs: 0,
+ foregroundWindowSize: normalizeEditForegroundWindowSize(options.foregroundWindowSize),
+ foregroundTargetProgressCount: null,
+ foregroundEndOffset: options.foregroundEndOffset ?? null,
+ waitForAnimationFrame: options.reason !== 'edit',
+ };
+ // Rich-text mutations update their logical selection in a microtask after the
+ // command has completed. Advance the edited anchor on the main thread before
+ // returning from the command callback so that the existing selection refresh
+ // closes over the newly committed skeleton, just as it did before background
+ // layout was introduced. A zero budget advances exactly one atomic block, so
+ // stop as soon as the anchor is publishable instead of spending the whole
+ // interaction-window budget in the command turn. Modern continuous layout
+ // then spends only the remaining budget on its visible suffix; any work
+ // still needed to reach that viewport boundary remains cooperatively scheduled.
+ if (options.reason === 'edit') {
+ this._scheduledLayout.foregroundStarted = true;
+ while (this._scheduledLayout != null && !this._scheduledLayout.anchorReady) {
+ this._runSlice(0, false, false);
+ }
+ const foregroundLayout = this._scheduledLayout;
+ if (
+ foregroundLayout?.executor === 'main-thread' &&
+ foregroundLayout.foregroundEndOffset != null &&
+ foregroundLayout.foregroundElapsedMs < foregroundLayout.foregroundBudgetMs
+ ) {
+ this._runSlice(
+ foregroundLayout.foregroundBudgetMs - foregroundLayout.foregroundElapsedMs,
+ false,
+ false
+ );
+ }
+ const scheduledLayout = this._scheduledLayout;
+ if (scheduledLayout != null) {
+ if (scheduledLayout.callbacks.onForegroundReady != null) {
+ this._scheduleForeground();
+ } else {
+ this._scheduleBackground();
+ }
+ }
+ } else {
+ // Initial layout still yields one frame so the application shell can paint.
+ this._scheduleForeground();
+ }
+
+ return generation;
+ }
+
+ scheduleWorker(
+ unitId: string,
+ skeleton: ExternalLayoutPresentation,
+ executorService: DocLayoutSchedulingExecutor,
+ options: IDocLayoutStartOptions,
+ protectedRange: IDocumentLayoutProtectedRange | undefined,
+ callbacks: IDocLayoutCoordinatorCallbacks,
+ onError: (error: unknown) => void
+ ): void {
+ this.cancel();
+ const previousMount = this._workerMount;
+ if (previousMount != null && (
+ previousMount.unitId !== unitId ||
+ previousMount.executorService !== executorService
+ )) {
+ previousMount.executorService.disposeLayoutMount({
+ unitId: previousMount.unitId,
+ mountId: this._mountId,
+ mountEpoch: previousMount.mountEpoch,
+ viewportEpoch: previousMount.viewportEpoch,
+ }).catch(onError);
+ }
+ if (
+ previousMount == null ||
+ previousMount.unitId !== unitId ||
+ previousMount.executorService !== executorService
+ ) {
+ this._mountEpoch++;
+ }
+ const viewportEpoch = ++this._viewportEpoch;
+ this._workerMount = {
+ unitId,
+ executorService,
+ onError,
+ mountEpoch: this._mountEpoch,
+ viewportEpoch,
+ };
+ skeleton.beginExternalLayout({
+ reason: options.reason,
+ protectedRange,
+ });
+ const backgroundResumeDelayMs = getBackgroundResumeDelay(options.reason);
+ this._scheduledLayout = {
+ executor: 'worker',
+ unitId,
+ mountId: this._mountId,
+ mountEpoch: this._mountEpoch,
+ viewportEpoch,
+ skeleton,
+ executorService,
+ options,
+ generation: null,
+ modelRevision: null,
+ metricsRevision: null,
+ callbacks,
+ onError,
+ backgroundResumeDelayMs,
+ nextBackgroundDelayMs: backgroundResumeDelayMs,
+ anchorReady: false,
+ };
+ // Posting a Worker request is non-blocking, so start the synchronized
+ // mutation + anchor-page transaction in the current command turn. Only
+ // additional foreground slices cross task boundaries.
+ this._runSlice(WORKER_FOREGROUND_BUDGET_MS, false);
+ }
+
+ async getWorkerPage(pageIndex: number): Promise<IDocLayoutPageResult | null> {
+ const workerMount = this._workerMount;
+ if (workerMount == null) {
+ return null;
+ }
+ const result = await workerMount.executorService.getLayoutPage({
+ unitId: workerMount.unitId,
+ mountId: this._mountId,
+ mountEpoch: workerMount.mountEpoch,
+ viewportEpoch: workerMount.viewportEpoch,
+ pageIndex,
+ });
+ if (
+ this._workerMount !== workerMount ||
+ result.unitId !== workerMount.unitId ||
+ result.mountId !== this._mountId ||
+ result.mountEpoch !== workerMount.mountEpoch ||
+ result.viewportEpoch !== workerMount.viewportEpoch
+ ) {
+ return null;
+ }
+ return result;
+ }
+
+ deferBackgroundWork(): void {
+ const scheduledLayout = this._scheduledLayout;
+ if (scheduledLayout == null || !scheduledLayout.anchorReady) {
+ return;
+ }
+
+ scheduledLayout.nextBackgroundDelayMs = scheduledLayout.backgroundResumeDelayMs;
+ if (scheduledLayout.executor === 'worker') {
+ // Worker computation does not block the Main thread. More importantly,
+ // its transport cursor advances before the visual-frame publication is
+ // committed. Cancelling that pending publication here would drop a page
+ // permanently and make every later page index sparse on Main.
+ return;
+ }
+ this._cancelCallbacks();
+ this._scheduleBackground();
+ }
+
+ setWorkerPresentationPaused(paused: boolean): void {
+ if (this._workerPresentationPaused === paused) {
+ return;
+ }
+
+ this._workerPresentationPaused = paused;
+ if (!paused) {
+ this._pendingWorkerPresentation?.resume();
+ }
+ }
+
+ cancel(): void {
+ const scheduledLayout = this._scheduledLayout;
+ if (scheduledLayout != null) {
+ if (scheduledLayout.executor === 'main-thread') {
+ scheduledLayout.skeleton.cancelIncrementalLayout(scheduledLayout.generation);
+ } else if (scheduledLayout.generation != null) {
+ scheduledLayout.executorService.cancelLayout({
+ unitId: scheduledLayout.unitId,
+ mountId: scheduledLayout.mountId,
+ mountEpoch: scheduledLayout.mountEpoch,
+ viewportEpoch: scheduledLayout.viewportEpoch,
+ generation: scheduledLayout.generation,
+ }).catch(scheduledLayout.onError);
+ }
+ if (scheduledLayout.executor === 'worker') {
+ scheduledLayout.skeleton.cancelExternalLayout();
+ }
+ }
+ this._scheduledLayout = null;
+ this._cancelCallbacks();
+ }
+
+ override dispose(): void {
+ this.cancel();
+ const workerMount = this._workerMount;
+ this._workerMount = null;
+ if (workerMount != null) {
+ workerMount.executorService.disposeLayoutMount({
+ unitId: workerMount.unitId,
+ mountId: this._mountId,
+ mountEpoch: workerMount.mountEpoch,
+ viewportEpoch: workerMount.viewportEpoch,
+ }).catch(workerMount.onError);
+ }
+ super.dispose();
+ }
+
+ private _scheduleForeground(): void {
+ if (
+ this._scheduledLayout == null ||
+ this._animationFrameId != null ||
+ this._fallbackTimerId != null
+ ) {
+ return;
+ }
+
+ if (this._scheduledLayout.executor === 'worker') {
+ // Worker computation cannot block input on the main thread. Advance the
+ // priority page across zero-delay task boundaries instead of paying one
+ // animation frame per RPC slice; each response still yields to queued
+ // input before the next request, while the caret page can converge in a
+ // single visual frame.
+ this._fallbackTimerId = setTimeout(() => {
+ this._fallbackTimerId = null;
+ this._runSlice(WORKER_FOREGROUND_BUDGET_MS, false);
+ }, 0);
+ return;
+ }
+
+ const scheduledLayout = this._scheduledLayout;
+ if (scheduledLayout.foregroundStarted || !scheduledLayout.waitForAnimationFrame) {
+ this._fallbackTimerId = setTimeout(() => {
+ this._fallbackTimerId = null;
+ if (this._scheduledLayout !== scheduledLayout) {
+ return;
+ }
+ scheduledLayout.foregroundStarted = true;
+ this._runSlice(FOREGROUND_BUDGET_MS, false);
+ }, 0);
+ return;
+ }
+
+ if (typeof requestAnimationFrame === 'function') {
+ this._animationFrameId = requestAnimationFrame(() => {
+ this._animationFrameId = null;
+ if (this._scheduledLayout !== scheduledLayout) {
+ return;
+ }
+ scheduledLayout.foregroundStarted = true;
+ this._runSlice(FOREGROUND_BUDGET_MS, false);
+ });
+ return;
+ }
+
+ this._fallbackTimerId = setTimeout(() => {
+ this._fallbackTimerId = null;
+ if (this._scheduledLayout !== scheduledLayout) {
+ return;
+ }
+ scheduledLayout.foregroundStarted = true;
+ this._runSlice(FOREGROUND_BUDGET_MS, false);
+ }, 0);
+ }
+
+ private _scheduleBackground(): void {
+ if (this._scheduledLayout == null || this._idleCallbackId != null || this._fallbackTimerId != null) {
+ return;
+ }
+
+ // Always cross a timer boundary before requesting more idle work. Chaining
+ // requestIdleCallback directly can consume every idle period while a long
+ // document is opening, leaving input and browser tasks with no useful gap.
+ const delay = this._scheduledLayout.nextBackgroundDelayMs;
+ this._scheduledLayout.nextBackgroundDelayMs = BACKGROUND_YIELD_MS;
+ this._fallbackTimerId = setTimeout(() => {
+ this._fallbackTimerId = null;
+ const scheduledLayout = this._scheduledLayout;
+ if (scheduledLayout == null) {
+ return;
+ }
+
+ // Worker computation does not consume the main thread's idle budget.
+ // Waiting for requestIdleCallback here can starve forever while the
+ // loading skeleton keeps Canvas animating. Preserve the timer boundary
+ // and input-pending check, then let the Worker advance independently;
+ // its geometry is still committed only inside a visual frame.
+ if (scheduledLayout.executor === 'worker') {
+ if (hasPendingUserInput()) {
+ this._scheduleBackground();
+ return;
+ }
+ this._runSlice(WORKER_BACKGROUND_BUDGET_MS, true);
+ return;
+ }
+
+ if (typeof requestIdleCallback === 'function') {
+ this._idleCallbackId = requestIdleCallback((deadline) => {
+ this._idleCallbackId = null;
+ if (hasPendingUserInput()) {
+ this._scheduleBackground();
+ return;
+ }
+
+ const availableTime = deadline.timeRemaining();
+ const budget = availableTime > 0
+ ? Math.min(BACKGROUND_BUDGET_MS, Math.max(1, availableTime))
+ : FOREGROUND_BUDGET_MS;
+ this._runSlice(budget, true);
+ });
+ return;
+ }
+
+ this._runSlice(FOREGROUND_BUDGET_MS, true);
+ }, delay);
+ }
+
+ private _runSlice(
+ budgetMs: number,
+ publishOneBacklogPage: boolean,
+ scheduleContinuation = true
+ ): void {
+ const scheduledLayout = this._scheduledLayout;
+ if (scheduledLayout == null) {
+ return;
+ }
+
+ if (scheduledLayout.executor === 'worker') {
+ this._runWorkerSlice(scheduledLayout, budgetMs, publishOneBacklogPage).catch((error: unknown) => {
+ if (this._scheduledLayout !== scheduledLayout) {
+ return;
+ }
+ scheduledLayout.skeleton.cancelExternalLayout();
+ this._scheduledLayout = null;
+ this._cancelCallbacks();
+ scheduledLayout.onError(error);
+ });
+ return;
+ }
+
+ this._runMainThreadSlice(
+ scheduledLayout,
+ budgetMs,
+ publishOneBacklogPage,
+ scheduleContinuation
+ );
+ }
+
+ private _runMainThreadSlice(
+ scheduledLayout: IScheduledMainThreadLayout,
+ budgetMs: number,
+ publishOneBacklogPage: boolean,
+ scheduleContinuation: boolean
+ ): void {
+ if (this._publishMainThreadBacklog(scheduledLayout, publishOneBacklogPage, scheduleContinuation)) {
+ return;
+ }
+
+ const foregroundStepStartedAt = performance.now();
+ const progress = scheduledLayout.skeleton.stepIncrementalLayout(scheduledLayout.generation, budgetMs);
+ scheduledLayout.foregroundElapsedMs += performance.now() - foregroundStepStartedAt;
+ if (this._scheduledLayout !== scheduledLayout) {
+ return;
+ }
+ if (progress.cancelled) {
+ this._scheduledLayout = null;
+ this._cancelCallbacks();
+ return;
+ }
+
+ scheduledLayout.anchorReady = progress.anchorReady;
+ const publishedProgress = progress.complete && scheduledLayout.callbacks.onForegroundReady != null
+ ? { ...progress, complete: false }
+ : progress;
+ scheduledLayout.callbacks.onProgress(publishedProgress);
+
+ // A completed Main interaction pass still has to hand the committed model
+ // revision to the Worker. Otherwise edits that fit inside one Main slice
+ // leave the Worker baseline stale forever and the next canonical layout
+ // starts from an obsolete document snapshot.
+ if (this._finishForegroundWindow(scheduledLayout, progress, scheduleContinuation)) {
+ return;
+ }
+
+ if (progress.complete) {
+ this._scheduledLayout = null;
+ scheduledLayout.callbacks.onComplete?.(progress);
+ return;
+ }
+
+ if (scheduleContinuation) {
+ if (scheduledLayout.anchorReady) {
+ this._scheduleBackground();
+ } else {
+ this._scheduleForeground();
+ }
+ }
+ }
+
+ private _publishMainThreadBacklog(
+ scheduledLayout: IScheduledMainThreadLayout,
+ publishOneBacklogPage: boolean,
+ scheduleContinuation: boolean
+ ): boolean {
+ if (
+ !publishOneBacklogPage ||
+ !scheduledLayout.anchorReady ||
+ hasPendingUserInput() ||
+ typeof scheduledLayout.skeleton.publishIncrementalLayoutBacklog !== 'function'
+ ) {
+ return false;
+ }
+
+ const backlogProgress = scheduledLayout.skeleton.publishIncrementalLayoutBacklog(
+ scheduledLayout.generation
+ );
+ if (this._scheduledLayout !== scheduledLayout || backlogProgress.cancelled) {
+ return true;
+ }
+ if (!backlogProgress.didPublish) {
+ return false;
+ }
+
+ scheduledLayout.anchorReady = backlogProgress.anchorReady;
+ scheduledLayout.callbacks.onProgress(backlogProgress);
+ if (backlogProgress.complete) {
+ this._scheduledLayout = null;
+ scheduledLayout.callbacks.onComplete?.(backlogProgress);
+ return true;
+ }
+
+ // A visual publication owns this task. Yield before exposing the next
+ // page so Canvas can paint genuinely progressive pagination.
+ if (scheduleContinuation) {
+ this._scheduleBackground();
+ }
+ return true;
+ }
+
+ private _finishForegroundWindow(
+ scheduledLayout: IScheduledMainThreadLayout,
+ progress: IDocumentLayoutProgress,
+ scheduleContinuation: boolean
+ ): boolean {
+ const onForegroundReady = scheduledLayout.callbacks.onForegroundReady;
+ if (onForegroundReady == null) {
+ return false;
+ }
+
+ if (progress.complete) {
+ this._completeForegroundWindow(scheduledLayout, progress, onForegroundReady);
+ return true;
+ }
+
+ const progressCount = progress.mode === 'continuous'
+ ? progress.processedBlockCount
+ : progress.publishedPageCount;
+ if (progress.didPublishAnchor && progress.interactionWindowComplete) {
+ this._completeForegroundWindow(scheduledLayout, progress, onForegroundReady);
+ return true;
+ }
+ if (progress.didPublishAnchor && scheduledLayout.foregroundTargetProgressCount == null) {
+ scheduledLayout.foregroundTargetProgressCount = progressCount +
+ Math.max(0, scheduledLayout.foregroundWindowSize - 1);
+ }
+ const target = scheduledLayout.foregroundTargetProgressCount;
+ if (target == null) {
+ return false;
+ }
+
+ const foregroundReady = progress.mode === 'continuous' && scheduledLayout.foregroundEndOffset != null
+ ? progress.stableLaidOutThrough >= scheduledLayout.foregroundEndOffset
+ : progressCount >= target ||
+ scheduledLayout.foregroundElapsedMs >= scheduledLayout.foregroundBudgetMs;
+ if (!foregroundReady) {
+ if (scheduleContinuation) {
+ this._scheduleForeground();
+ }
+ return true;
+ }
+
+ // The budget is soft because a table or paragraph block is the smallest
+ // atomic layout unit. For Modern, it limits only the synchronous command
+ // turn; later foreground tasks still protect the viewport before handoff.
+ this._completeForegroundWindow(scheduledLayout, progress, onForegroundReady);
+ return true;
+ }
+
+ private _completeForegroundWindow(
+ scheduledLayout: IScheduledMainThreadLayout,
+ progress: IDocumentLayoutProgress,
+ onForegroundReady: NonNullable<IDocLayoutCoordinatorCallbacks['onForegroundReady']>
+ ): void {
+ this._scheduledLayout = null;
+ scheduledLayout.skeleton.cancelIncrementalLayout(scheduledLayout.generation);
+ this._cancelCallbacks();
+ onForegroundReady(progress);
+ }
+
+ private async _runWorkerSlice(
+ scheduledLayout: IScheduledWorkerLayout,
+ budgetMs: number,
+ publishOneBacklogPage: boolean
+ ): Promise<void> {
+ if (scheduledLayout.generation == null && await this._startWorkerLayout(scheduledLayout, budgetMs)) {
+ return;
+ }
+
+ if (await this._publishWorkerBacklog(scheduledLayout, publishOneBacklogPage)) {
+ return;
+ }
+
+ const result = await scheduledLayout.executorService.stepLayout({
+ ...this._getWorkerIdentity(scheduledLayout),
+ generation: this._getWorkerGeneration(scheduledLayout),
+ budgetMs,
+ });
+ this._assertWorkerResultIdentity(scheduledLayout, result);
+ this._assertWorkerResultRevisions(scheduledLayout, result, 'step');
+ if (this._scheduledLayout !== scheduledLayout || result.progress.cancelled) {
+ return;
+ }
+
+ if (!await this._publishWorkerResult(scheduledLayout, result)) {
+ return;
+ }
+ if (result.progress.complete) {
+ return;
+ }
+
+ if (scheduledLayout.anchorReady) {
+ this._scheduleBackground();
+ } else {
+ this._scheduleForeground();
+ }
+ }
+
+ private async _startWorkerLayout(
+ scheduledLayout: IScheduledWorkerLayout,
+ budgetMs: number
+ ): Promise<boolean> {
+ const startResult = await scheduledLayout.executorService.startLayout(
+ this._getWorkerIdentity(scheduledLayout),
+ scheduledLayout.options,
+ budgetMs
+ );
+ if (this._scheduledLayout !== scheduledLayout) {
+ if (startResult?.status === DocLayoutSessionStatus.ACCEPTED) {
+ await scheduledLayout.executorService.cancelLayout({
+ unitId: startResult.step.unitId,
+ mountId: startResult.step.mountId,
+ mountEpoch: startResult.step.mountEpoch,
+ viewportEpoch: startResult.step.viewportEpoch,
+ generation: startResult.step.progress.generation,
+ });
+ }
+ return true;
+ }
+ if (startResult?.status !== DocLayoutSessionStatus.ACCEPTED) {
+ throw new Error('The document layout Worker could not start a synchronized session.');
+ }
+
+ this._assertWorkerResultIdentity(scheduledLayout, startResult.step);
+ scheduledLayout.generation = startResult.step.progress.generation;
+ scheduledLayout.modelRevision = startResult.step.modelRevision;
+ scheduledLayout.metricsRevision = startResult.step.metricsRevision;
+ if (startResult.step.progress.cancelled) {
+ return true;
+ }
+
+ if (!await this._publishWorkerResult(scheduledLayout, startResult.step)) {
+ return true;
+ }
+ if (startResult.step.progress.complete || scheduledLayout.anchorReady) {
+ if (!startResult.step.progress.complete) {
+ this._scheduleBackground();
+ }
+ return true;
+ }
+ return false;
+ }
+
+ private async _publishWorkerBacklog(
+ scheduledLayout: IScheduledWorkerLayout,
+ publishOneBacklogPage: boolean
+ ): Promise<boolean> {
+ if (!publishOneBacklogPage || !scheduledLayout.anchorReady) {
+ return false;
+ }
+ if (hasPendingUserInput()) {
+ // Do not advance the Worker past an unpublished page while input is
+ // pending. Incremental layout can temporarily merge page fragments;
+ // stepping here would advance the transport cursor beyond geometry
+ // that has not been delivered and create a sparse Main skeleton.
+ this._scheduleBackground();
+ return true;
+ }
+
+ const backlogResult = await scheduledLayout.executorService.publishBacklog({
+ ...this._getWorkerIdentity(scheduledLayout),
+ generation: this._getWorkerGeneration(scheduledLayout),
+ });
+ this._assertWorkerResultIdentity(scheduledLayout, backlogResult);
+ this._assertWorkerResultRevisions(scheduledLayout, backlogResult, 'backlog');
+ if (this._scheduledLayout !== scheduledLayout || backlogResult.progress.cancelled) {
+ return true;
+ }
+ if (!backlogResult.progress.didPublish) {
+ return false;
+ }
+
+ if (!await this._publishWorkerResult(scheduledLayout, backlogResult)) {
+ return true;
+ }
+ if (!backlogResult.progress.complete) {
+ // Match the Main path: one visible page publication per task.
+ this._scheduleBackground();
+ }
+ return true;
+ }
+
+ private _assertWorkerResultRevisions(
+ scheduledLayout: IScheduledWorkerLayout,
+ result: IDocLayoutStepResult,
+ phase: 'backlog' | 'step'
+ ): void {
+ if (result.modelRevision !== scheduledLayout.modelRevision) {
+ throw new Error(`The document layout Worker returned a stale ${phase} model revision.`);
+ }
+ if (result.metricsRevision !== scheduledLayout.metricsRevision) {
+ throw new Error(`The document layout Worker returned stale ${phase} Custom Block metrics.`);
+ }
+ }
+
+ private _publishWorkerResult(
+ scheduledLayout: IScheduledWorkerLayout,
+ result: IDocLayoutStepResult
+ ): Promise<boolean> {
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ let cancelFrame: (() => void) | null = null;
+ const settle = (committed: boolean) => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ resolve(committed);
+ };
+ const cancel = () => {
+ cancelFrame?.();
+ cancelFrame = null;
+ settle(false);
+ };
+ const commit = () => {
+ if (settled || cancelFrame != null) {
+ return;
+ }
+ if (this._workerPresentationPaused) {
+ this._pendingWorkerPresentation = { cancel, resume: commit };
+ return;
+ }
+
+ cancelFrame = this._scheduleVisualFrame(() => {
+ cancelFrame = null;
+ if (this._workerPresentationPaused) {
+ this._pendingWorkerPresentation = { cancel, resume: commit };
+ return;
+ }
+ this._pendingWorkerPresentation = null;
+ if (this._scheduledLayout !== scheduledLayout) {
+ settle(false);
+ return;
+ }
+
+ try {
+ scheduledLayout.anchorReady = result.progress.anchorReady;
+ scheduledLayout.callbacks.onProgress(result.progress, result.publication);
+ if (result.progress.complete) {
+ this._scheduledLayout = null;
+ scheduledLayout.callbacks.onComplete?.(result.progress);
+ }
+ settle(true);
+ } catch (error) {
+ if (!settled) {
+ settled = true;
+ reject(error);
+ }
+ }
+ });
+ this._pendingWorkerPresentation = { cancel, resume: commit };
+ };
+ commit();
+ });
+ }
+
+ private _getWorkerIdentity(scheduledLayout: IScheduledWorkerLayout): IDocLayoutMountIdentity {
+ return {
+ unitId: scheduledLayout.unitId,
+ mountId: scheduledLayout.mountId,
+ mountEpoch: scheduledLayout.mountEpoch,
+ viewportEpoch: scheduledLayout.viewportEpoch,
+ };
+ }
+
+ private _getWorkerGeneration(scheduledLayout: IScheduledWorkerLayout): number {
+ if (scheduledLayout.generation == null) {
+ throw new Error('The document layout Worker session has not started.');
+ }
+ return scheduledLayout.generation;
+ }
+
+ private _assertWorkerResultIdentity(
+ scheduledLayout: IScheduledWorkerLayout,
+ result: IDocLayoutStepResult
+ ): void {
+ if (
+ result.unitId !== scheduledLayout.unitId ||
+ result.mountId !== scheduledLayout.mountId ||
+ result.mountEpoch !== scheduledLayout.mountEpoch ||
+ result.viewportEpoch !== scheduledLayout.viewportEpoch ||
+ (scheduledLayout.generation != null && result.progress.generation !== scheduledLayout.generation)
+ ) {
+ throw new Error('The document layout Worker returned a stale publication identity.');
+ }
+ }
+
+ private _cancelCallbacks(): void {
+ if (this._animationFrameId != null && typeof cancelAnimationFrame === 'function') {
+ cancelAnimationFrame(this._animationFrameId);
+ }
+ if (this._idleCallbackId != null && typeof cancelIdleCallback === 'function') {
+ cancelIdleCallback(this._idleCallbackId);
+ }
+ if (this._fallbackTimerId != null) {
+ clearTimeout(this._fallbackTimerId);
+ }
+ this._pendingWorkerPresentation?.cancel();
+
+ this._animationFrameId = null;
+ this._idleCallbackId = null;
+ this._fallbackTimerId = null;
+ this._pendingWorkerPresentation = null;
+ }
+}
diff --git a/packages/docs-ui/src/services/doc-layout-interaction.service.ts b/packages/docs-ui/src/services/doc-layout-interaction.service.ts
new file mode 100644
index 0000000000..3ccb134177
--- /dev/null
+++ b/packages/docs-ui/src/services/doc-layout-interaction.service.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 { IDisposable } from '@univerjs/core';
+import { Disposable } from '@univerjs/core';
+import { BehaviorSubject } from 'rxjs';
+
+/**
+ * Coordinates render-scoped interactions that require the current document
+ * skeleton to stay stable until the interaction ends.
+ */
+export class DocLayoutInteractionService extends Disposable {
+ private readonly _active$ = new BehaviorSubject(false);
+ private _interactionCount = 0;
+
+ readonly active$ = this._active$.asObservable();
+
+ get isActive(): boolean {
+ return this._interactionCount > 0;
+ }
+
+ beginInteraction(): IDisposable {
+ this.ensureNotDisposed();
+ this._interactionCount++;
+ if (this._interactionCount === 1) {
+ this._active$.next(true);
+ }
+
+ let disposed = false;
+ return {
+ dispose: () => {
+ if (disposed) {
+ return;
+ }
+
+ disposed = true;
+ if (this._disposed) {
+ return;
+ }
+ this._interactionCount--;
+ if (this._interactionCount === 0) {
+ this._active$.next(false);
+ }
+ },
+ };
+ }
+
+ override dispose(): void {
+ if (this._disposed) {
+ return;
+ }
+
+ if (this._interactionCount > 0) {
+ this._interactionCount = 0;
+ this._active$.next(false);
+ }
+ this._active$.complete();
+ super.dispose();
+ }
+}
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 80ff760a32..02085c611b 100644
--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ICustomBlock, ICustomTable, IDocumentBlockRange, INeedCheckDisposable, Nullable } from '@univerjs/core';
+import type { DocumentDataModel, ICustomBlock, ICustomTable, IDisposable, IDocumentBlockRange, INeedCheckDisposable, Nullable } from '@univerjs/core';
import type { IBoundRectNoAngle, IRenderContext, IRenderModule, ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IMutiPageParagraphBound, ITableBound, ITableParagraphBound } from './doc-event-manager.service';
import type { IEditorInputConfig } from './selection/doc-selection-render.service';
@@ -28,6 +28,7 @@ import {
DOC_TABLE_BLOCK_MENU_COMPONENT_KEY,
} from '../views/paragraph-menu/component-keys';
import { DocEventManagerService } from './doc-event-manager.service';
+import { DocLayoutInteractionService } from './doc-layout-interaction.service';
import {
calcDocRangePositions,
DocCanvasPopManagerService,
@@ -127,6 +128,8 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
private _isBlockMenuDragging = false;
private _isSlashMenuActive = false;
private _slashMenuRequestNonce = 0;
+ private _menuInteraction: IDisposable | null = null;
+ private _dragInteraction: IDisposable | null = null;
get activeParagraph() {
return this._paragraphMenu?.paragraph;
@@ -138,6 +141,12 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
setBlockMenuDragging(isDragging: boolean) {
this._isBlockMenuDragging = isDragging;
+ if (isDragging) {
+ this._dragInteraction ??= this._docLayoutInteractionService.beginInteraction();
+ } else {
+ this._dragInteraction?.dispose();
+ this._dragInteraction = null;
+ }
}
get isBlockMenuDragging() {
@@ -152,7 +161,8 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
@Inject(DocSkeletonManagerService) private _docSkeletonManagerService: DocSkeletonManagerService,
@Inject(DocFloatMenuService) private _floatMenuService: DocFloatMenuService,
@Inject(DocSelectionRenderService) private _docSelectionRenderService: DocSelectionRenderService,
- @IPermissionService private readonly _permissionService: IPermissionService
+ @IPermissionService private readonly _permissionService: IPermissionService,
+ @Inject(DocLayoutInteractionService) private _docLayoutInteractionService: DocLayoutInteractionService
) {
super();
@@ -234,6 +244,12 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
if (this._paragraphMenu) {
this._paragraphMenu.active = active;
}
+ if (active && this._paragraphMenu) {
+ this._menuInteraction ??= this._docLayoutInteractionService.beginInteraction();
+ } else {
+ this._menuInteraction?.dispose();
+ this._menuInteraction = null;
+ }
}
private _init() {
@@ -683,6 +699,8 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
if (this._paragraphMenu && ((this._paragraphMenu.disposable.canDispose() || force))) {
this._paragraphMenu.disposable.dispose();
this._paragraphMenu = null;
+ this._menuInteraction?.dispose();
+ this._menuInteraction = null;
this._isSlashMenuActive = false;
this._slashMenuRequest$.next(null);
this._activeTarget$.next(null);
@@ -700,6 +718,14 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
);
}
+ override dispose(): void {
+ this._menuInteraction?.dispose();
+ this._menuInteraction = null;
+ this._dragInteraction?.dispose();
+ this._dragInteraction = null;
+ super.dispose();
+ }
+
private _buildParagraphMenuTarget(paragraph: IMutiPageParagraphBound): IDocBlockMenuTarget | null {
const body = this._context.unit.getBody();
const dataStream = body?.dataStream ?? '';
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 6a75a79ef2..23c90f220a 100644
--- a/packages/docs-ui/src/services/doc-popup-manager.service.ts
+++ b/packages/docs-ui/src/services/doc-popup-manager.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { INeedCheckDisposable, Injector, ITextRangeParam } from '@univerjs/core';
+import type { IDisposable, INeedCheckDisposable, Injector, ITextRangeParam } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { BaseObject, Documents, IBoundRectNoAngle, IRender, Scene } from '@univerjs/engine-render';
import type { IPopup } from '@univerjs/ui';
@@ -129,6 +129,10 @@ export const calcDocRangePositions = (range: ITextRangeParam, currentRender: IRe
};
export class DocCanvasPopManagerService extends Disposable {
+ private readonly _popupCountByUnit = new Map<string, number>();
+ private readonly _popupUnits$ = new BehaviorSubject<ReadonlySet<string>>(new Set());
+ readonly popupUnits$ = this._popupUnits$.asObservable();
+
constructor(
@Inject(ICanvasPopupService) private readonly _globalPopupManagerService: ICanvasPopupService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@@ -138,6 +142,40 @@ export class DocCanvasPopManagerService extends Disposable {
super();
}
+ override dispose(): void {
+ this._popupCountByUnit.clear();
+ this._popupUnits$.next(new Set());
+ this._popupUnits$.complete();
+ super.dispose();
+ }
+
+ private _beginPopupActivity(unitId: string): IDisposable {
+ this._popupCountByUnit.set(unitId, (this._popupCountByUnit.get(unitId) ?? 0) + 1);
+ this._publishPopupUnits();
+
+ let disposed = false;
+ return {
+ dispose: () => {
+ if (disposed) {
+ return;
+ }
+ disposed = true;
+
+ const count = this._popupCountByUnit.get(unitId) ?? 0;
+ if (count <= 1) {
+ this._popupCountByUnit.delete(unitId);
+ } else {
+ this._popupCountByUnit.set(unitId, count - 1);
+ }
+ this._publishPopupUnits();
+ },
+ };
+ }
+
+ private _publishPopupUnits(): void {
+ this._popupUnits$.next(new Set(this._popupCountByUnit.keys()));
+ }
+
private _shouldUpdateForCommand(commandInfo: { id: string; params?: unknown }, unitId: string): boolean {
if (commandInfo.id !== SetDocZoomRatioOperation.id && commandInfo.id !== RichTextEditingMutation.id) {
return false;
@@ -292,12 +330,14 @@ export class DocCanvasPopManagerService extends Disposable {
anchorRect$: position$,
canvasElement: currentRender.engine.getCanvasElement(),
});
+ const popupActivity = this._beginPopupActivity(unitId);
return {
dispose: () => {
popupManagerService.removePopup(id);
position$.complete();
disposable.dispose();
+ popupActivity.dispose();
},
canDispose: () => popupManagerService.activePopupId !== id,
};
@@ -328,12 +368,14 @@ export class DocCanvasPopManagerService extends Disposable {
anchorRect$: position$,
canvasElement: currentRender.engine.getCanvasElement(),
});
+ const popupActivity = this._beginPopupActivity(unitId);
return {
dispose: () => {
popupManagerService.removePopup(id);
position$.complete();
disposable.dispose();
+ popupActivity.dispose();
},
canDispose: () => popupManagerService.activePopupId !== id,
};
@@ -380,12 +422,14 @@ export class DocCanvasPopManagerService extends Disposable {
: direction,
canvasElement: currentRender.engine.getCanvasElement(),
});
+ const popupActivity = this._beginPopupActivity(unitId);
return {
dispose: () => {
popupManagerService.removePopup(id);
bounds$.complete();
disposable.dispose();
+ popupActivity.dispose();
},
canDispose: () => popupManagerService.activePopupId !== id,
};
diff --git a/packages/docs-ui/src/services/float-menu.service.ts b/packages/docs-ui/src/services/float-menu.service.ts
index f4514b81fd..784b67088b 100644
--- a/packages/docs-ui/src/services/float-menu.service.ts
+++ b/packages/docs-ui/src/services/float-menu.service.ts
@@ -35,6 +35,7 @@ import { DocSelectionManagerService, getDocumentPermissionValue } from '@univerj
import { UnitAction } from '@univerjs/protocol';
import { FLOAT_MENU_COMPONENT_KEY } from '../views/float-toolbar/FloatToolbar';
import { IDocEmbedRuntimeFocusCoordinator } from './doc-embed-integration.service';
+import { DocLayoutInteractionService } from './doc-layout-interaction.service';
import { DocCanvasPopManagerService } from './doc-popup-manager.service';
import { DocSelectionRenderService } from './selection/doc-selection-render.service';
@@ -67,6 +68,7 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {
@Inject(DocSelectionRenderService) private readonly _docSelectionRenderService: DocSelectionRenderService,
@IContextService private readonly _contextService: IContextService,
@IPermissionService private readonly _permissionService: IPermissionService,
+ @Inject(DocLayoutInteractionService) private readonly _docLayoutInteractionService: DocLayoutInteractionService,
@Optional(IDocEmbedRuntimeFocusCoordinator) private readonly _embedRuntimeFocusCoordinator?: IDocEmbedRuntimeFocusCoordinator
) {
super();
@@ -214,16 +216,21 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {
return;
}
+ const popup = this._docCanvasPopManagerService.attachPopupToRange(
+ range,
+ {
+ componentKey: FLOAT_MENU_COMPONENT_KEY,
+ direction: range.direction === 'backward' || isInSameLine((range as ITextRangeWithStyle).startNodePosition, (range as ITextRangeWithStyle).endNodePosition) ? 'top-center' : 'bottom-center',
+ offset: [0, 10],
+ },
+ unitId
+ );
+ const layoutInteraction = this._docLayoutInteractionService.beginInteraction();
this._floatMenu = {
- disposable: this._docCanvasPopManagerService.attachPopupToRange(
- range,
- {
- componentKey: FLOAT_MENU_COMPONENT_KEY,
- direction: range.direction === 'backward' || isInSameLine((range as ITextRangeWithStyle).startNodePosition, (range as ITextRangeWithStyle).endNodePosition) ? 'top-center' : 'bottom-center',
- offset: [0, 10],
- },
- unitId
- ),
+ disposable: toDisposable(() => {
+ popup.dispose();
+ layoutInteraction.dispose();
+ }),
start: range.startOffset,
end: range.endOffset,
};
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 cda36b9611..e8f4e57516 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
@@ -83,6 +83,8 @@ interface IFakeTextRange {
style?: { strokeWidth: number };
segmentId?: string;
segmentPage?: number;
+ startOffset?: number;
+ endOffset?: number;
}
interface IFakeRectRange {
@@ -123,9 +125,11 @@ interface IServiceHarness {
_isEmpty(): boolean;
_getCanvasOffset(): { left: number; top: number };
_moving(moveOffsetX: number, moveOffsetY: number): void;
+ _isAnotherEditorFocused: Mock<() => boolean>;
_updateInputPosition(): void;
addDocRanges(ranges: Array<Record<string, unknown>>, isEditing?: boolean, options?: Record<string, boolean>): void;
cancelPointerSelection(): void;
+ replaceDocRanges(ranges: Array<Record<string, unknown>>, isEditing?: boolean, options?: Record<string, boolean>): boolean;
setCursorManually(evtOffsetX: number, evtOffsetY: number): void;
}
@@ -196,6 +200,7 @@ function createService() {
_getAllRectRanges: vi.fn(() => ['serialized-rect']),
_findNodeByCoord: vi.fn(),
_getNodePosition: vi.fn(),
+ _isAnotherEditorFocused: vi.fn(() => false),
focus: vi.fn(),
}, DocSelectionRenderService.prototype) as IServiceHarness;
@@ -447,6 +452,19 @@ describe('doc selection render service internals', () => {
expect(service.focus).toHaveBeenCalledTimes(1);
});
+ it('does not steal focus from another editor when input anchor is unavailable', () => {
+ const { service } = createService();
+ service._isAnotherEditorFocused.mockReturnValue(true);
+ service._rangeList = [createTextRange({
+ getAnchor: vi.fn(() => null),
+ isActive: vi.fn(() => true),
+ })];
+
+ service._updateInputPosition();
+
+ expect(service.focus).not.toHaveBeenCalled();
+ });
+
it('creates a text range from anchor position with current skeleton and segment context', () => {
const { service } = createService();
const oldText = createTextRange();
@@ -658,6 +676,32 @@ describe('doc selection render service internals', () => {
expect(service._rangeList).toEqual([cursorRange]);
});
+ it('keeps the rendered caret when its replacement page is not resolved yet', () => {
+ const { service } = createService();
+ const currentCaret = createTextRange({
+ collapsed: true,
+ startOffset: 34,
+ endOffset: 34,
+ });
+ const unresolvedCaret = createTextRange({
+ collapsed: true,
+ });
+ service._rangeList = [currentCaret];
+ cursorConvertToTextRangeMock.mockReturnValueOnce(unresolvedCaret);
+
+ const replaced = service.replaceDocRanges([{
+ startOffset: 35,
+ endOffset: 35,
+ collapsed: true,
+ }], true);
+
+ expect(replaced).toBe(false);
+ expect(service._rangeList).toEqual([currentCaret]);
+ expect(currentCaret.dispose).not.toHaveBeenCalled();
+ expect(unresolvedCaret.dispose).toHaveBeenCalledTimes(1);
+ expect(service._textSelectionInner$.next).not.toHaveBeenCalled();
+ });
+
it('deactivates structural carets when document ranges contain a visible selection', () => {
const { service } = createService();
const leadingCaret = createTextRange({ collapsed: true });
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 4292a0f1d4..63a2b50b75 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
@@ -15,7 +15,7 @@
*/
import type { DocumentDataModel, Nullable } from '@univerjs/core';
-import type { Documents, Engine, IDocSelectionInnerParam, IFindNodeRestrictions, IMouseEvent, INodeInfo, INodePosition, IPointerEvent, IRenderContext, IRenderModule, IScrollObserverParam, ISuccinctDocRangeParam, ITextRangeWithStyle, ITextSelectionStyle } from '@univerjs/engine-render';
+import type { Documents, DocumentSkeleton, Engine, IDocSelectionInnerParam, IFindNodeRestrictions, IMouseEvent, INodeInfo, INodePosition, IPointerEvent, IRenderContext, IRenderModule, IScrollObserverParam, ISuccinctDocRangeParam, ITextRangeWithStyle, ITextSelectionStyle } from '@univerjs/engine-render';
import type { Subscription } from 'rxjs';
import type { RectRange } from './rect-range';
import { DataStreamTreeTokenType, DOC_RANGE_TYPE, ILogService, Inject, isInternalEditorID, IUniverInstanceService, Optional, RxDisposable, UniverInstanceType } from '@univerjs/core';
@@ -241,8 +241,52 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
this._selectionStyle = style;
}
+ replaceDocRanges(ranges: ISuccinctDocRangeParam[], isEditing = true, options?: { [key: string]: boolean }): boolean {
+ return this.addDocRanges(ranges, isEditing, options, true);
+ }
+
+ private _canResolveCollapsedRanges(
+ ranges: ISuccinctDocRangeParam[],
+ scene: IRenderContext<DocumentDataModel>['scene'],
+ document: Documents,
+ docSkeleton: DocumentSkeleton
+ ): boolean {
+ for (const range of ranges) {
+ if (range.rangeType === DOC_RANGE_TYPE.RECT || range.startOffset !== range.endOffset) {
+ continue;
+ }
+
+ const textRange = cursorConvertToTextRange(
+ scene,
+ {
+ ...range,
+ segmentId: this._currentSegmentId,
+ segmentPage: this._currentSegmentPage,
+ style: range.style ?? this._selectionStyle,
+ },
+ docSkeleton,
+ document
+ );
+ if (textRange == null) {
+ return false;
+ }
+ const resolved = textRange.startOffset != null && textRange.endOffset != null;
+ textRange.dispose();
+ if (!resolved) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
// eslint-disable-next-line max-lines-per-function
- addDocRanges(ranges: ISuccinctDocRangeParam[], isEditing = true, options?: { [key: string]: boolean }) {
+ addDocRanges(
+ ranges: ISuccinctDocRangeParam[],
+ isEditing = true,
+ options?: { [key: string]: boolean },
+ replace = false
+ ): boolean {
const {
_currentSegmentId: segmentId,
_currentSegmentPage: segmentPage,
@@ -251,6 +295,12 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
const { scene, mainComponent } = this._context;
const document = mainComponent as Documents;
const docSkeleton = this._docSkeletonManagerService.getSkeleton();
+ if (replace && !this._canResolveCollapsedRanges(ranges, scene, document, docSkeleton)) {
+ return false;
+ }
+ if (replace) {
+ this.removeAllRanges();
+ }
const generalAddRange = (
startOffset: number,
@@ -282,7 +332,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
};
for (const range of ranges) {
- const { startOffset, endOffset, rangeType, startNodePosition, endNodePosition } = range as ITextRangeWithStyle;
+ const { startOffset, endOffset, rangeType, startNodePosition, endNodePosition } = range;
const rangeStyle = range.style ?? style;
if (rangeType !== DOC_RANGE_TYPE.RECT && startOffset === endOffset) {
@@ -371,8 +421,9 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
options,
});
- if (!ranges.length || options?.shouldFocus === false) return;
+ if (!ranges.length || options?.shouldFocus === false) return true;
this._updateInputPosition(options?.forceFocus);
+ return true;
}
setCursorManually(evtOffsetX: number, evtOffsetY: number) {
@@ -1061,7 +1112,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
const anchor = activeRangeInstance?.getAnchor();
if (!anchor || (anchor && !anchor.visible) || this.activeViewPort == null) {
- if (this._shouldPreserveExternalFocus()) {
+ if (this._shouldPreserveExternalFocus() || (!forceFocus && this._isAnotherEditorFocused())) {
return;
}
this.focus();
@@ -1534,6 +1585,13 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
return this._embedInteractionBoundaryService?.hasRecentInteractionFor?.(currentEmbedOwner, ownerDocument) === true;
}
+ private _isAnotherEditorFocused(): boolean {
+ const activeElement = this._getOwnerDocument().activeElement;
+ return activeElement instanceof HTMLElement &&
+ activeElement !== this._input &&
+ activeElement.dataset.uComp === this._input.dataset.uComp;
+ }
+
private _containsCurrentEmbedRuntimeElement(element: HTMLElement): boolean {
const currentEmbedOwner = this._getCurrentEmbedOwner();
if (!currentEmbedOwner) {
diff --git a/packages/docs-ui/src/views/DocLayoutRecovery.tsx b/packages/docs-ui/src/views/DocLayoutRecovery.tsx
new file mode 100644
index 0000000000..f2d0c7ce52
--- /dev/null
+++ b/packages/docs-ui/src/views/DocLayoutRecovery.tsx
@@ -0,0 +1,43 @@
+/**
+ * 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 { LocaleService } from '@univerjs/core';
+import { LoadingMultiIcon } from '@univerjs/icons';
+import { useDependency } from '@univerjs/ui';
+
+export const DOC_LAYOUT_RECOVERY_COMPONENT = 'DOC_LAYOUT_RECOVERY_COMPONENT';
+
+export function DocLayoutRecovery() {
+ const localeService = useDependency(LocaleService);
+
+ return (
+ <div
+ aria-live="polite"
+ className="
+ univer-flex univer-items-center univer-gap-2 univer-rounded-lg univer-bg-white univer-px-4 univer-py-3
+ univer-text-sm univer-text-gray-700 univer-shadow-lg
+ dark:univer-bg-gray-800 dark:univer-text-gray-200
+ "
+ role="status"
+ >
+ <LoadingMultiIcon
+ aria-hidden
+ className="univer-size-5 univer-animate-spin univer-text-violet-500"
+ />
+ <span>{localeService.t('docs-ui.layout.recovering')}</span>
+ </div>
+ );
+}
diff --git a/packages/docs/package.json b/packages/docs/package.json
index 53ea1c4561..2476167a1c 100644
--- a/packages/docs/package.json
+++ b/packages/docs/package.json
@@ -80,7 +80,8 @@
"dependencies": {
"@univerjs/core": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/protocol": "workspace:*"
+ "@univerjs/protocol": "workspace:*",
+ "@univerjs/rpc": "workspace:*"
},
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
diff --git a/packages/docs/src/__tests__/docs.integration.spec.ts b/packages/docs/src/__tests__/docs.integration.spec.ts
index e85ca1f494..fbc28887ff 100644
--- a/packages/docs/src/__tests__/docs.integration.spec.ts
+++ b/packages/docs/src/__tests__/docs.integration.spec.ts
@@ -36,6 +36,7 @@ import { SetTextSelectionsOperation } from '../commands/operations/text-selectio
import { UniverDocsPlugin } from '../plugin';
import { DocInterceptorService } from '../services/doc-interceptor/doc-interceptor.service';
import { DOC_INTERCEPTOR_POINT } from '../services/doc-interceptor/interceptor-const';
+import { DocLayoutExecutorService } from '../services/doc-layout-executor.service';
import { DocSelectionManagerService } from '../services/doc-selection-manager.service';
import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
import { DocStateChangeManagerService } from '../services/doc-state-change-manager.service';
@@ -57,7 +58,8 @@ function registerRenderManagerForDoc(
const skeletonManager = new DocSkeletonManagerService(
context,
injector.get(LocaleService),
- univerInstanceService
+ univerInstanceService,
+ injector.get(DocLayoutExecutorService)
);
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
@@ -384,6 +386,7 @@ describe('docs integration', () => {
});
it('builds skeleton/view-model and applies interceptors for custom ranges', () => {
+ injector.add([DocLayoutExecutorService]);
const doc = univer.createUnit<IDocumentData, DocumentDataModel>(
UniverInstanceType.UNIVER_DOC,
createTestDocData('doc-3')
@@ -400,7 +403,8 @@ describe('docs integration', () => {
const skeletonManager = new DocSkeletonManagerService(
context,
injector.get(LocaleService),
- univerInstanceService
+ univerInstanceService,
+ injector.get(DocLayoutExecutorService)
);
const viewModelManager = new DocViewModelManagerService(context, univerInstanceService);
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 4cbb80a182..ad59317456 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,7 @@
* limitations under the License.
*/
-import { BlockType, 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';
@@ -235,7 +235,7 @@ describe('core editing commands', () => {
expect(testBed.doc.getSnapshot().footers?.['footer-1'].body.dataStream).toBe('Y\r\n');
});
- it('rejects invalid rich text mutations in header segments and rolls them back', () => {
+ it('rejects invalid rich text mutations after validating a structure-preserving header edit', () => {
testBed.univer.dispose();
testBed = createTestBed({
id: 'test',
@@ -258,8 +258,20 @@ describe('core editing commands', () => {
});
commandService = testBed.get(ICommandService);
+ expect(commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: 'test',
+ segmentId: 'header-1',
+ body: { dataStream: 'X' },
+ range: {
+ startOffset: 0,
+ endOffset: 0,
+ collapsed: true,
+ segmentId: 'header-1',
+ },
+ })).toBe(true);
+
const actions = JSONX.getInstance().editOp([
- { t: TextXActionType.RETAIN, len: 4 },
+ { t: TextXActionType.RETAIN, len: 5 },
{ t: TextXActionType.DELETE, len: 2 },
], getRichTextEditPath(testBed.doc, 'header-1'));
@@ -269,7 +281,77 @@ describe('core editing commands', () => {
actions,
textRanges: null,
})).toThrow('[DocStructure] header header-1');
- expect(testBed.doc.getSnapshot().headers?.['header-1'].body.dataStream).toBe('Head\r\n');
+ expect(testBed.doc.getSnapshot().headers?.['header-1'].body.dataStream).toBe('XHead\r\n');
+ });
+
+ it('allows structure-preserving text edits in documents with legacy orphan custom-block tokens', () => {
+ testBed.univer.dispose();
+ testBed = createTestBed({
+ id: 'test',
+ body: {
+ dataStream: 'A\b\r\n',
+ paragraphs: [{ startIndex: 2, paragraphId: 'body' }],
+ sectionBreaks: [{ sectionId: 'section_fixture_109', startIndex: 3 }],
+ },
+ documentStyle: {},
+ });
+ commandService = testBed.get(ICommandService);
+
+ expect(commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: 'test',
+ body: { dataStream: 'X' },
+ range: {
+ startOffset: 1,
+ endOffset: 1,
+ collapsed: true,
+ },
+ })).toBe(true);
+ expect(testBed.doc.getBody()?.dataStream).toBe('AX\b\r\n');
+ });
+
+ it('inserts a paragraph around imported DOCX raw custom blocks without rolling back Enter', () => {
+ testBed.univer.dispose();
+ testBed = createTestBed({
+ id: 'test',
+ body: {
+ dataStream: `A${DataStreamTreeTokenType.CUSTOM_BLOCK}B${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 3, paragraphId: 'body' }],
+ sectionBreaks: [{ sectionId: 'section_fixture_110', startIndex: 4 }],
+ docxRawCustomBlocks: [{
+ startIndex: 1,
+ blockId: 'raw-footnote-1',
+ blockType: 1,
+ docxRawXml: '<w:footnoteReference w:id="1"/>',
+ }],
+ },
+ documentStyle: {},
+ });
+ commandService = testBed.get(ICommandService);
+
+ expect(commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: 'test',
+ body: {
+ dataStream: DataStreamTreeTokenType.PARAGRAPH,
+ paragraphs: [{ startIndex: 0, paragraphId: 'inserted' }],
+ },
+ range: {
+ startOffset: 2,
+ endOffset: 2,
+ collapsed: true,
+ },
+ })).toBe(true);
+ expect(testBed.doc.getBody()).toMatchObject({
+ dataStream: `A${DataStreamTreeTokenType.CUSTOM_BLOCK}${DataStreamTreeTokenType.PARAGRAPH}B${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 2 },
+ { startIndex: 4 },
+ ],
+ sectionBreaks: [{ sectionId: 'section_fixture_110', startIndex: 5 }],
+ docxRawCustomBlocks: [{
+ startIndex: 1,
+ blockId: 'raw-footnote-1',
+ }],
+ });
});
it('expands deletion to whole custom entities', () => {
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
new file mode 100644
index 0000000000..d253d1b59d
--- /dev/null
+++ b/packages/docs/src/commands/mutations/__tests__/core-editing.mutation.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 { describe, expect, it } from 'vitest';
+import { transformDocumentTextRanges } from '../core-editing.mutation';
+
+describe('transformDocumentTextRanges', () => {
+ it('moves an active body caret through an insertion with right priority', () => {
+ expect(transformDocumentTextRanges(['body', {
+ et: 'text-x',
+ e: [
+ { t: 'r', len: 10 },
+ { t: 'i', len: 6, body: { dataStream: 'REMOTE' } },
+ ],
+ }], [{
+ startOffset: 14,
+ endOffset: 14,
+ collapsed: true,
+ isActive: true,
+ segmentId: '',
+ }])).toEqual([expect.objectContaining({
+ startOffset: 20,
+ endOffset: 20,
+ collapsed: true,
+ isActive: true,
+ })]);
+ });
+
+ it('treats an omitted segment id as the document body', () => {
+ expect(transformDocumentTextRanges(['body', {
+ et: 'text-x',
+ e: [
+ { t: 'i', len: 6, body: { dataStream: 'REMOTE' } },
+ ],
+ }], [{
+ startOffset: 14,
+ endOffset: 14,
+ collapsed: true,
+ isActive: true,
+ }])).toEqual([expect.objectContaining({
+ startOffset: 20,
+ endOffset: 20,
+ collapsed: true,
+ isActive: true,
+ })]);
+ });
+
+ it('does not move a body selection through a header mutation', () => {
+ const range = {
+ startOffset: 14,
+ endOffset: 18,
+ collapsed: false,
+ segmentId: '',
+ };
+ expect(transformDocumentTextRanges(['header-1', 'body', {
+ et: 'text-x',
+ e: [{ t: 'i', len: 6, body: { dataStream: 'REMOTE' } }],
+ }], [range])).toEqual([range]);
+ });
+});
diff --git a/packages/docs/src/commands/mutations/core-editing.mutation-id.ts b/packages/docs/src/commands/mutations/core-editing.mutation-id.ts
new file mode 100644
index 0000000000..a54473830f
--- /dev/null
+++ b/packages/docs/src/commands/mutations/core-editing.mutation-id.ts
@@ -0,0 +1,17 @@
+/**
+ * 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 RICH_TEXT_EDITING_MUTATION_ID = 'doc.mutation.rich-text-editing';
diff --git a/packages/docs/src/commands/mutations/core-editing.mutation.ts b/packages/docs/src/commands/mutations/core-editing.mutation.ts
index 6d8c09f590..c40a13e058 100644
--- a/packages/docs/src/commands/mutations/core-editing.mutation.ts
+++ b/packages/docs/src/commands/mutations/core-editing.mutation.ts
@@ -14,14 +14,23 @@
* limitations under the License.
*/
-import type { DocumentDataModel, IExecutionOptions, IMutation, IMutationCommonParams, JSONXActions, Nullable } from '@univerjs/core';
-import type { ITextRangeWithStyle } from '@univerjs/engine-render';
+import type { DocumentDataModel, IExecutionOptions, IMutation, IMutationCommonParams, JSONXActions, Nullable, TPriority } from '@univerjs/core';
+import type { DocumentViewModel, ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IDocStateChangeInfo } from '../../services/doc-state-emit.service';
-import { CommandType, IUniverInstanceService, JSONX, UniverInstanceType, validateDocBodyStructure } from '@univerjs/core';
+import {
+ CommandType,
+
+ IUniverInstanceService,
+ JSONX,
+
+ UniverInstanceType,
+} from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
import { DocSelectionManagerService } from '../../services/doc-selection-manager.service';
import { DocSkeletonManagerService } from '../../services/doc-skeleton-manager.service';
import { DocStateEmitService } from '../../services/doc-state-emit.service';
+import { RICH_TEXT_EDITING_MUTATION_ID } from './core-editing.mutation-id';
+import { validateDocStructureMutation } from './doc-structure-mutation-validation';
export enum DocHistoryAction {
DeleteChart = 'delete-chart',
@@ -55,41 +64,128 @@ export interface IRichTextEditingMutationParams extends IMutationCommonParams {
syncer?: string;
}
-const RichTextEditingMutationId = 'doc.mutation.rich-text-editing';
+function extractDocumentBodyActions(actions: JSONXActions, segmentId: string): Nullable<JSONXActions> {
+ if (!Array.isArray(actions)) {
+ return;
+ }
+ const bodyActions = actions.indexOf('body') > -1
+ ? actions
+ : actions.find((action) => Array.isArray(action) && action.indexOf('body') > -1);
+ if (!Array.isArray(bodyActions)) {
+ return;
+ }
-function getSegmentType(documentDataModel: DocumentDataModel, segmentId: string) {
- if (!segmentId) {
- return 'body' as const;
+ const bodyIndex = bodyActions.indexOf('body');
+ if (bodyIndex === -1) {
+ return;
}
+ const actionSegmentId = bodyIndex === 0 ? '' : bodyActions[bodyIndex - 1];
+ return actionSegmentId === segmentId ? bodyActions.slice(bodyIndex) : undefined;
+}
- const { headers, footers } = documentDataModel.getSnapshot();
- if (headers?.[segmentId]) {
- return 'header' as const;
+/**
+ * Transforms document selections through the same JSONX actions applied by a rich-text mutation.
+ * Collaboration and rendering use this shared offset rule so the Main interaction window follows
+ * the transformed local caret before an authoritative background layout is published.
+ */
+export function transformDocumentTextRanges(
+ actions: JSONXActions,
+ textRanges: ITextRangeWithStyle[],
+ priority: TPriority = 'right'
+): ITextRangeWithStyle[] {
+ if (textRanges.length === 0) {
+ return [];
}
- if (footers?.[segmentId]) {
- return 'footer' as const;
+ const segmentId = textRanges[0].segmentId ?? '';
+
+ const bodyActions = extractDocumentBodyActions(actions, segmentId);
+ if (bodyActions == null) {
+ return textRanges;
}
- return 'body' as const;
+ return textRanges.map((textRange) => {
+ const startOffset = JSONX.transformPosition(bodyActions, textRange.startOffset, priority);
+ const endOffset = JSONX.transformPosition(bodyActions, textRange.endOffset, priority);
+ return {
+ ...textRange,
+ startOffset,
+ endOffset,
+ collapsed: startOffset === endOffset,
+ };
+ });
}
-function assertValidDocBodyStructure(documentDataModel: DocumentDataModel, segmentId: string) {
- const segmentModel = documentDataModel.getSelfOrHeaderFooterModel(segmentId);
- const body = segmentModel?.getBody();
- if (!body) {
+function applyValidatedDocumentActions(
+ documentDataModel: DocumentDataModel,
+ segmentId: string,
+ actions: JSONXActions
+): { undoActions: JSONXActions; preservesStructure: boolean } {
+ const undoActions = JSONX.invertWithDoc(actions, documentDataModel.getSnapshot());
+ documentDataModel.apply(actions);
+ try {
+ return {
+ undoActions,
+ preservesStructure: validateDocStructureMutation(documentDataModel, segmentId, actions, undoActions),
+ };
+ } catch (error) {
+ documentDataModel.apply(undoActions);
+ throw error;
+ }
+}
+
+function resetDocumentViewModel(
+ documentViewModel: DocumentViewModel | null | undefined,
+ documentDataModel: DocumentDataModel,
+ segmentId: string,
+ actions: JSONXActions,
+ preservesStructure: boolean
+): void {
+ if (documentViewModel == null) {
return;
}
+ const didResetIncrementally = segmentId === '' && preservesStructure &&
+ documentViewModel.resetByValidatedTextMutation(documentDataModel, actions);
+ if (!didResetIncrementally) {
+ documentViewModel.reset(documentDataModel);
+ }
+}
- const segmentType = getSegmentType(documentDataModel, segmentId);
- const issues = validateDocBodyStructure(body, { segmentType, segmentId: segmentId || undefined });
- if (!issues.length) {
+function scheduleDocumentSelectionUpdate(
+ selectionManager: DocSelectionManagerService,
+ params: IRichTextEditingMutationParams,
+ isSync: boolean
+): void {
+ const { unitId, textRanges, trigger, noNeedSetTextRange, isEditing = true } = params;
+ if (noNeedSetTextRange || textRanges == null || trigger == null || isSync) {
return;
}
+ queueMicrotask(() => {
+ const selectionTarget = { unitId, subUnitId: unitId };
+ const currentSelection = selectionManager.getSelectionInfo(selectionTarget);
+ if (currentSelection == null) {
+ selectionManager.replaceDocRanges(textRanges, selectionTarget, isEditing, params.options);
+ return;
+ }
+
+ const logicalTextRanges = textRanges.map((textRange, index) => ({
+ ...textRange,
+ collapsed: textRange.startOffset === textRange.endOffset,
+ isActive: index === textRanges.length - 1,
+ }));
- const detail = issues.map((issue) => `${issue.code}${issue.index == null ? '' : `@${issue.index}`}`).join(', ');
- const segmentLabel = segmentId ? `${segmentType} ${segmentId}` : segmentType;
- throw new Error(`[DocStructure] ${segmentLabel}: ${detail}`);
+ // The logical range advances with the mutation even if its new physical
+ // page has not been published yet. Keeping that intent in the model lets
+ // the render layer retry the same caret after foreground pagination.
+ selectionManager.replaceSelectionInfoWithoutRefresh({
+ ...currentSelection,
+ textRanges: logicalTextRanges,
+ rectRanges: [],
+ isEditing,
+ options: params.options,
+ }, selectionTarget);
+ selectionManager.refreshSelection(selectionTarget, isEditing);
+ });
}
/**
@@ -97,11 +193,10 @@ function assertValidDocBodyStructure(documentDataModel: DocumentDataModel, segme
* send to undo redo service (will be used by the triggering command).
*/
export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams, IRichTextEditingMutationParams> = {
- id: RichTextEditingMutationId,
+ id: RICH_TEXT_EDITING_MUTATION_ID,
type: CommandType.MUTATION,
- // eslint-disable-next-line max-lines-per-function
handler: (accessor, params, options?: IExecutionOptions) => {
const {
unitId,
@@ -112,13 +207,12 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
trigger,
noHistory,
isCompositionEnd,
- noNeedSetTextRange,
debounce,
isEditing = true,
isSync: paramsIsSync,
syncer,
} = params;
- const isSync = paramsIsSync || options?.fromCollab || options?.fromChangeset;
+ const isSync = Boolean(paramsIsSync || options?.fromCollab || options?.fromChangeset);
const univerInstanceService = accessor.get(IUniverInstanceService);
const renderManagerService = accessor.get(IRenderManagerService);
const docStateEmitService = accessor.get(DocStateEmitService);
@@ -147,29 +241,18 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
};
}
- // Step 1: Update Doc Data Model.
- const undoActions = JSONX.invertWithDoc(actions, documentDataModel.getSnapshot());
- documentDataModel.apply(actions);
- try {
- assertValidDocBodyStructure(documentDataModel, segmentId);
- } catch (error) {
- documentDataModel.apply(undoActions);
- throw error;
- }
+ const { undoActions, preservesStructure } = applyValidatedDocumentActions(
+ documentDataModel,
+ segmentId,
+ actions
+ );
- // Step 2: Update Doc View Model.
- documentViewModel?.reset(documentDataModel);
- // Step 3: Update cursor & selection.
- // Make sure update cursor & selection after doc skeleton is calculated.
- if (!noNeedSetTextRange && textRanges && trigger != null && !isSync) {
- queueMicrotask(() => {
- docSelectionManagerService.replaceDocRanges(textRanges, { unitId, subUnitId: unitId }, isEditing, params.options);
- });
- }
+ resetDocumentViewModel(documentViewModel, documentDataModel, segmentId, actions, preservesStructure);
+ scheduleDocumentSelectionUpdate(docSelectionManagerService, params, isSync);
// Step 4: Emit state change event.
const changeState: IDocStateChangeInfo = {
- commandId: RichTextEditingMutationId,
+ commandId: RICH_TEXT_EDITING_MUTATION_ID,
unitId,
segmentId,
trigger,
diff --git a/packages/docs/src/commands/mutations/doc-structure-mutation-validation.ts b/packages/docs/src/commands/mutations/doc-structure-mutation-validation.ts
new file mode 100644
index 0000000000..761ada43d2
--- /dev/null
+++ b/packages/docs/src/commands/mutations/doc-structure-mutation-validation.ts
@@ -0,0 +1,193 @@
+/**
+ * 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, JSONXActions, JSONXPath } from '@univerjs/core';
+import {
+ DataStreamTreeTokenType,
+
+ getRichTextEditPath,
+
+ JSON1,
+
+ TextX,
+ TextXActionType,
+ validateDocBodyStructure,
+} from '@univerjs/core';
+
+const STRUCTURAL_BODY_FIELDS = [
+ 'paragraphs',
+ 'sectionBreaks',
+ 'customBlocks',
+ 'docxRawCustomBlocks',
+ 'docxRawBlocks',
+ 'docxExportExcludedRanges',
+ 'tables',
+ 'columnGroups',
+ 'blockRanges',
+] satisfies Array<keyof IDocumentBody>;
+const STRUCTURAL_DATA_STREAM_TOKENS = new Set<string>([
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.SECTION_BREAK,
+ DataStreamTreeTokenType.TABLE_START,
+ DataStreamTreeTokenType.TABLE_ROW_START,
+ DataStreamTreeTokenType.TABLE_CELL_START,
+ DataStreamTreeTokenType.TABLE_CELL_END,
+ DataStreamTreeTokenType.TABLE_ROW_END,
+ DataStreamTreeTokenType.TABLE_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_START,
+ DataStreamTreeTokenType.COLUMN_START,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_END,
+ DataStreamTreeTokenType.BLOCK_START,
+ DataStreamTreeTokenType.BLOCK_END,
+ DataStreamTreeTokenType.CUSTOM_BLOCK,
+]);
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value != null && !Array.isArray(value);
+}
+
+function containsStructuralToken(dataStream: string): boolean {
+ for (let index = 0; index < dataStream.length; index++) {
+ if (STRUCTURAL_DATA_STREAM_TOKENS.has(dataStream[index])) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+function isStructurePreservingBody(value: unknown): boolean {
+ if (!isRecord(value)) {
+ return false;
+ }
+
+ const dataStream = value.dataStream;
+ if (dataStream != null && (typeof dataStream !== 'string' || containsStructuralToken(dataStream))) {
+ return false;
+ }
+
+ return STRUCTURAL_BODY_FIELDS.every((field) => {
+ const metadata = value[field];
+ return metadata == null || (Array.isArray(metadata) && metadata.length === 0);
+ });
+}
+
+function isStructurePreservingTextXEdit(value: unknown): boolean {
+ if (!Array.isArray(value)) {
+ return false;
+ }
+
+ return value.every((action) => {
+ if (!isRecord(action) || typeof action.len !== 'number' || !Number.isFinite(action.len)) {
+ return false;
+ }
+
+ if (action.t === TextXActionType.DELETE) {
+ return true;
+ }
+
+ if (action.t === TextXActionType.INSERT) {
+ return isStructurePreservingBody(action.body);
+ }
+
+ return action.t === TextXActionType.RETAIN &&
+ (action.body == null || isStructurePreservingBody(action.body));
+ });
+}
+
+function pathsEqual(left: JSONXPath, right: JSONXPath): boolean {
+ return left.length === right.length && left.every((item, index) => item === right[index]);
+}
+
+function isStructurePreservingJSONXEdit(actions: JSONXActions, expectedPath: JSONXPath): boolean {
+ const cursor = JSON1.type.readCursor(actions);
+ let hasTextEdit = false;
+ let isStructurePreserving = true;
+
+ cursor.traverse(null, (component) => {
+ if (!isStructurePreserving) {
+ return;
+ }
+
+ const componentKeys = Object.keys(component);
+ if (
+ component.et !== TextX.id ||
+ componentKeys.some((key) => key !== 'et' && key !== 'e') ||
+ !pathsEqual(cursor.getPath(), expectedPath)
+ ) {
+ isStructurePreserving = false;
+ return;
+ }
+
+ const edit: unknown = component.e;
+ hasTextEdit = true;
+ isStructurePreserving = isStructurePreservingTextXEdit(edit);
+ });
+
+ return hasTextEdit && isStructurePreserving;
+}
+
+function getSegmentType(documentDataModel: DocumentDataModel, segmentId: string): 'body' | 'header' | 'footer' {
+ if (!segmentId) {
+ return 'body';
+ }
+
+ const { headers, footers } = documentDataModel.getSnapshot();
+ if (headers?.[segmentId]) {
+ return 'header';
+ }
+
+ if (footers?.[segmentId]) {
+ return 'footer';
+ }
+
+ return 'body';
+}
+
+function assertValidDocBodyStructure(documentDataModel: DocumentDataModel, segmentId: string): void {
+ const segmentModel = documentDataModel.getSelfOrHeaderFooterModel(segmentId);
+ const body = segmentModel?.getBody();
+ if (!body) {
+ return;
+ }
+
+ const segmentType = getSegmentType(documentDataModel, segmentId);
+ const issues = validateDocBodyStructure(body, { segmentType, segmentId: segmentId || undefined });
+ if (!issues.length) {
+ return;
+ }
+
+ const detail = issues.map((issue) => `${issue.code}${issue.index == null ? '' : `@${issue.index}`}`).join(', ');
+ const segmentLabel = segmentId ? `${segmentType} ${segmentId}` : segmentType;
+ throw new Error(`[DocStructure] ${segmentLabel}: ${detail}`);
+}
+
+export function validateDocStructureMutation(
+ documentDataModel: DocumentDataModel,
+ segmentId: string,
+ actions: JSONXActions,
+ undoActions: JSONXActions
+): boolean {
+ const editPath = getRichTextEditPath(documentDataModel, segmentId);
+ const preservesStructure =
+ isStructurePreservingJSONXEdit(actions, editPath) &&
+ isStructurePreservingJSONXEdit(undoActions, editPath);
+
+ if (!preservesStructure) {
+ assertValidDocBodyStructure(documentDataModel, segmentId);
+ }
+ return preservesStructure;
+}
diff --git a/packages/docs/src/facade/__tests__/create-test-bed.ts b/packages/docs/src/facade/__tests__/create-test-bed.ts
index fed2264806..1e32d662b4 100644
--- a/packages/docs/src/facade/__tests__/create-test-bed.ts
+++ b/packages/docs/src/facade/__tests__/create-test-bed.ts
@@ -196,6 +196,7 @@ export function createTestBed(documentConfig?: IDocumentData): ITestBed {
with: <T>() => ({
getViewModel: () => ({
reset: () => undefined,
+ resetByValidatedTextMutation: () => false,
}),
}) as T,
activate: () => undefined,
diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.ts
index 9cfe0aef23..bfb334f151 100644
--- a/packages/docs/src/index.ts
+++ b/packages/docs/src/index.ts
@@ -40,7 +40,7 @@ export type { ISetSectionHeaderFooterLinkCommandParams } from './commands/comman
export { UpdateDocumentParagraphStyleCommand } from './commands/commands/update-document-paragraph-style.command';
export { DeleteDocumentSectionBreakCommand, InsertDocumentColumnBreakCommand, InsertDocumentSectionBreakCommand, UpdateDocumentSectionCommand } from './commands/commands/update-document-section.command';
export type { IDeleteDocumentSectionBreakCommandParams, IDocumentSectionConfig, IDocumentSectionUpdate, IInsertDocumentColumnBreakCommandParams, IInsertDocumentSectionBreakCommandParams, IUpdateDocumentSectionCommandParams } from './commands/commands/update-document-section.command';
-export { DocHistoryAction, RichTextEditingMutation } from './commands/mutations/core-editing.mutation';
+export { DocHistoryAction, RichTextEditingMutation, transformDocumentTextRanges } from './commands/mutations/core-editing.mutation';
export type { IRichTextEditingMutationParams } from './commands/mutations/core-editing.mutation';
export { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';
export type { ISetTextSelectionsOperationParams } from './commands/operations/text-selection.operation';
@@ -63,6 +63,8 @@ export type {
IDocsCustomBlockMutationParams,
IEmbedDocsCustomBlockData,
} from './embed-host-anchor';
+export { DocsLayoutWorkerCapabilityError, DocsLayoutWorkerClientService, startDocsLayoutWorker, UniverDocsLayoutWorkerPlugin } from './layout-worker';
+export type { IDocsLayoutWorkerCapabilities, IDocsLayoutWorkerFontProbe, IDocsLayoutWorkerRuntime, IUniverDocsLayoutWorkerConfig } from './layout-worker';
export { UniverDocsPlugin } from './plugin';
export { DocBlockMoveValidatorService } from './services/doc-block-move-validator.service';
export type {
@@ -76,6 +78,30 @@ export { DocContentInsertService } from './services/doc-content-insert.service';
export type { IDocContentInsertRange } from './services/doc-content-insert.service';
export { DocInterceptorService } from './services/doc-interceptor/doc-interceptor.service';
export { DOC_INTERCEPTOR_POINT } from './services/doc-interceptor/interceptor-const';
+export {
+ DocLayoutExecutorService,
+ DocLayoutExecutorState,
+ DocLayoutExecutorType,
+ DocLayoutSessionStatus,
+} from './services/doc-layout-executor.service';
+export type {
+ IDocLayoutCancelRequest,
+ IDocLayoutCreateSessionRequest,
+ IDocLayoutDisposeMountRequest,
+ IDocLayoutDisposeSessionRequest,
+ IDocLayoutExecutor,
+ IDocLayoutExecutorStatus,
+ IDocLayoutMountIdentity,
+ IDocLayoutMutationProjection,
+ IDocLayoutPageRequest,
+ IDocLayoutPageResult,
+ IDocLayoutPerformanceMetrics,
+ IDocLayoutStartOptions,
+ IDocLayoutStartRequest,
+ IDocLayoutStartResult,
+ IDocLayoutStepRequest,
+ IDocLayoutStepResult,
+} from './services/doc-layout-executor.service';
export {
DOC_SELECTION_OPTION_PRESERVE_CARET,
DocSelectionManagerService,
diff --git a/packages/docs/src/layout-worker/__tests__/performance-tracker.spec.ts b/packages/docs/src/layout-worker/__tests__/performance-tracker.spec.ts
new file mode 100644
index 0000000000..0f57ca8c6f
--- /dev/null
+++ b/packages/docs/src/layout-worker/__tests__/performance-tracker.spec.ts
@@ -0,0 +1,79 @@
+/**
+ * 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 { DocsLayoutWorkerPerformanceTracker } from '../performance-tracker';
+
+describe('DocsLayoutWorkerPerformanceTracker', () => {
+ it('separates snapshot, mutation, and published patch transfer samples by unit', () => {
+ const tracker = new DocsLayoutWorkerPerformanceTracker();
+
+ tracker.recordRequest({
+ method: 'createSession',
+ args: [{ unitId: 'doc-1', snapshot: { id: 'doc-1' } }],
+ }, 4);
+ tracker.recordRequest({
+ method: 'startLayout',
+ args: [{ unitId: 'doc-1', mutations: [] }],
+ }, 5);
+ tracker.recordRequest({
+ method: 'startLayout',
+ args: [{ unitId: 'doc-1', mutations: [{ modelRevision: 1 }] }],
+ }, 6);
+ tracker.recordResponse({
+ data: {
+ unitId: 'doc-1',
+ publication: { pages: [] },
+ },
+ }, 7);
+ tracker.recordResponse({
+ data: {
+ status: 'accepted',
+ step: {
+ unitId: 'doc-1',
+ publication: { pages: [] },
+ },
+ },
+ }, 8);
+ tracker.recordResponse({
+ data: {
+ unitId: 'doc-2',
+ publication: { pages: [] },
+ },
+ }, 9);
+
+ expect(tracker.getMetrics('doc-1')).toEqual({
+ mutationTransferMs: [6],
+ patchTransferMs: [7, 8],
+ snapshotTransferMs: [4],
+ });
+ expect(tracker.getMetrics('doc-2').patchTransferMs).toEqual([9]);
+
+ tracker.reset('doc-1');
+ expect(tracker.getMetrics('doc-1')).toEqual({
+ mutationTransferMs: [],
+ patchTransferMs: [],
+ snapshotTransferMs: [],
+ });
+
+ tracker.resetAll();
+ expect(tracker.getMetrics('doc-2')).toEqual({
+ mutationTransferMs: [],
+ patchTransferMs: [],
+ snapshotTransferMs: [],
+ });
+ });
+});
diff --git a/packages/docs/src/layout-worker/__tests__/worker-runtime.spec.ts b/packages/docs/src/layout-worker/__tests__/worker-runtime.spec.ts
new file mode 100644
index 0000000000..829a2d7bfa
--- /dev/null
+++ b/packages/docs/src/layout-worker/__tests__/worker-runtime.spec.ts
@@ -0,0 +1,408 @@
+/**
+ * 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 {
+ createDocumentModelWithStyle,
+ DocumentFlavor,
+ LocaleType,
+ ObjectRelativeFromH,
+ ObjectRelativeFromV,
+ PositionedObjectLayoutType,
+} from '@univerjs/core';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { DocLayoutSessionStatus } from '../../services/doc-layout-executor.service';
+import { DocsLayoutWorkerPerformanceTracker } from '../performance-tracker';
+import { DocsLayoutWorkerRuntime } from '../worker';
+
+function stubOffscreenCanvas(): void {
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText(content: string) {
+ return {
+ width: content.length * 7,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 2,
+ };
+ },
+ };
+ }
+ });
+}
+
+describe('DocsLayoutWorkerRuntime', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('lays out a snapshot and enforces sequential model revisions', async () => {
+ stubOffscreenCanvas();
+
+ const sourceModel = createDocumentModelWithStyle('First page\fSecond page\fThird page\r', {});
+ sourceModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.TRADITIONAL });
+ sourceModel.updateDocumentDataPageSize(240, 180);
+ sourceModel.updateDocumentDataMargin({ t: 10, r: 10, b: 10, l: 10 });
+ const performanceTracker = new DocsLayoutWorkerPerformanceTracker();
+ const runtime = new DocsLayoutWorkerRuntime(performanceTracker);
+ const unitId = sourceModel.getUnitId();
+ const mountIdentity = { mountEpoch: 1, viewportEpoch: 1 };
+
+ await runtime.createSession({
+ unitId,
+ sessionEpoch: 1,
+ snapshot: structuredClone(sourceModel.getSnapshot()),
+ modelRevision: 1,
+ locale: LocaleType.EN_US,
+ localeData: {},
+ direction: 'ltr',
+ });
+
+ await expect(runtime.getCapabilities()).resolves.toMatchObject({
+ protocolVersion: 3,
+ executor: 'worker',
+ offscreenCanvas: true,
+ structuredClone: true,
+ fontProbe: {
+ font: '16px Arial',
+ width: expect.any(Number),
+ },
+ });
+
+ const start = await runtime.startLayout({
+ ...mountIdentity,
+ unitId,
+ mountId: 'mount-1',
+ metricsRevision: 1,
+ baseRevision: 1,
+ modelRevision: 1,
+ mutations: [],
+ customBlockViewports: {},
+ reason: 'initial',
+ budgetMs: 0,
+ });
+ if (start.status !== DocLayoutSessionStatus.ACCEPTED) {
+ throw new Error('Expected the Worker layout session to start.');
+ }
+
+ let result = start.step;
+ const publications = [result.publication];
+ for (let step = 0; step < 1_000 && !result.progress.complete; step++) {
+ result = await runtime.stepLayout({
+ ...mountIdentity,
+ unitId,
+ mountId: 'mount-1',
+ generation: start.step.progress.generation,
+ budgetMs: 0,
+ });
+ publications.push(result.publication);
+ }
+
+ expect(result.progress.complete).toBe(true);
+ expect(result.modelRevision).toBe(1);
+ expect(publications.flatMap((publication) =>
+ publication?.kind === 'page' ? publication.pages : []
+ ).length).toBeGreaterThan(1);
+ expect(() => structuredClone(publications)).not.toThrow();
+ const firstPage = await runtime.getLayoutPage({
+ ...mountIdentity,
+ unitId,
+ mountId: 'mount-1',
+ pageIndex: 0,
+ });
+ expect(firstPage).toMatchObject({
+ ...mountIdentity,
+ unitId,
+ mountId: 'mount-1',
+ page: { pageIndex: 0 },
+ });
+ expect(() => structuredClone(firstPage)).not.toThrow();
+
+ const customBlockModel = createDocumentModelWithStyle('\b\r\n', {});
+ customBlockModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.TRADITIONAL });
+ const customBlockSnapshot = structuredClone(customBlockModel.getSnapshot());
+ customBlockSnapshot.id = 'custom-block-doc';
+ if (customBlockSnapshot.body == null) {
+ throw new Error('Expected a document body.');
+ }
+ customBlockSnapshot.body.customBlocks = [{ startIndex: 0, blockId: 'embed-1' }];
+ customBlockSnapshot.drawings = {
+ 'embed-1': {
+ unitId: customBlockSnapshot.id,
+ subUnitId: customBlockSnapshot.id,
+ drawingId: 'embed-1',
+ drawingType: 1,
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ angle: 0,
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ size: { width: 100, height: 80 },
+ },
+ },
+ };
+ await runtime.createSession({
+ unitId: customBlockSnapshot.id,
+ sessionEpoch: 1,
+ snapshot: customBlockSnapshot,
+ modelRevision: 0,
+ locale: LocaleType.EN_US,
+ localeData: {},
+ direction: 'ltr',
+ });
+ const customBlockStart = await runtime.startLayout({
+ ...mountIdentity,
+ unitId: customBlockSnapshot.id,
+ mountId: 'custom-block-mount',
+ metricsRevision: 1,
+ baseRevision: 0,
+ modelRevision: 0,
+ mutations: [],
+ customBlockViewports: {
+ 'embed-1': { width: 222, height: 111, layoutWidth: 222 },
+ },
+ reason: 'initial',
+ budgetMs: 32,
+ });
+ if (customBlockStart.status !== DocLayoutSessionStatus.ACCEPTED) {
+ throw new Error('Expected the custom block layout session to start.');
+ }
+ expect(JSON.stringify(customBlockStart.step.publication)).toContain('"width":222');
+
+ const secondMountStart = await runtime.startLayout({
+ ...mountIdentity,
+ unitId,
+ mountId: 'mount-2',
+ metricsRevision: 1,
+ baseRevision: 1,
+ modelRevision: 1,
+ mutations: [],
+ customBlockViewports: {},
+ reason: 'initial',
+ budgetMs: 0,
+ });
+ if (secondMountStart.status !== DocLayoutSessionStatus.ACCEPTED) {
+ throw new Error('Expected a second mounted layout session to start.');
+ }
+ const newerViewportStart = await runtime.startLayout({
+ ...mountIdentity,
+ viewportEpoch: 2,
+ unitId,
+ mountId: 'mount-2',
+ metricsRevision: 2,
+ baseRevision: 1,
+ modelRevision: 1,
+ mutations: [],
+ customBlockViewports: {},
+ reason: 'initial',
+ budgetMs: 0,
+ });
+ if (newerViewportStart.status !== DocLayoutSessionStatus.ACCEPTED) {
+ throw new Error('Expected the newer viewport layout to start.');
+ }
+ await expect(runtime.startLayout({
+ ...mountIdentity,
+ unitId,
+ mountId: 'mount-2',
+ metricsRevision: 1,
+ baseRevision: 1,
+ modelRevision: 1,
+ mutations: [],
+ customBlockViewports: {},
+ reason: 'initial',
+ budgetMs: 0,
+ })).resolves.toEqual({ status: DocLayoutSessionStatus.SUPERSEDED });
+ await runtime.disposeLayoutMount({ ...mountIdentity, unitId, mountId: 'mount-2' });
+ await expect(runtime.stepLayout({
+ ...mountIdentity,
+ viewportEpoch: 2,
+ unitId,
+ mountId: 'mount-2',
+ generation: newerViewportStart.step.progress.generation,
+ budgetMs: 0,
+ })).resolves.toEqual(expect.objectContaining({ viewportEpoch: 2 }));
+ await runtime.disposeLayoutMount({ ...mountIdentity, unitId, mountId: 'mount-1' });
+ await expect(runtime.stepLayout({
+ ...mountIdentity,
+ viewportEpoch: 2,
+ unitId,
+ mountId: 'mount-2',
+ generation: newerViewportStart.step.progress.generation,
+ budgetMs: 0,
+ })).resolves.toEqual(expect.objectContaining({ modelRevision: 1 }));
+ await expect(runtime.stepLayout({
+ ...mountIdentity,
+ unitId,
+ mountId: 'mount-1',
+ generation: start.step.progress.generation,
+ budgetMs: 0,
+ })).rejects.toThrow('Document layout Worker mount not found');
+
+ const editedStart = await runtime.startLayout({
+ ...mountIdentity,
+ unitId,
+ mountId: 'mount-1',
+ metricsRevision: 2,
+ baseRevision: 1,
+ modelRevision: 2,
+ mutations: [{ baseRevision: 1, modelRevision: 2, actions: null }],
+ customBlockViewports: {},
+ reason: 'edit',
+ budgetMs: 0,
+ });
+ expect(editedStart.status).toBe(DocLayoutSessionStatus.ACCEPTED);
+ await expect(runtime.startLayout({
+ ...mountIdentity,
+ unitId,
+ mountId: 'mount-1',
+ metricsRevision: 3,
+ baseRevision: 3,
+ modelRevision: 4,
+ mutations: [{ baseRevision: 3, modelRevision: 4, actions: null }],
+ customBlockViewports: {},
+ reason: 'edit',
+ budgetMs: 0,
+ })).resolves.toEqual({
+ status: DocLayoutSessionStatus.RESNAPSHOT_REQUIRED,
+ modelRevision: 2,
+ });
+
+ performanceTracker.recordResponse({
+ data: { unitId, publication: { pages: [] } },
+ }, 5);
+ expect((await runtime.getPerformanceMetrics(unitId)).patchTransferMs).toEqual([5]);
+ await runtime.disposeSession({ unitId, sessionEpoch: 1 });
+ expect((await runtime.getPerformanceMetrics(unitId)).patchTransferMs).toEqual([]);
+ await expect(runtime.startLayout({
+ ...mountIdentity,
+ unitId,
+ mountId: 'mount-1',
+ metricsRevision: 4,
+ baseRevision: 2,
+ modelRevision: 2,
+ mutations: [],
+ customBlockViewports: {},
+ reason: 'edit',
+ budgetMs: 0,
+ })).resolves.toEqual({ status: DocLayoutSessionStatus.NOT_FOUND });
+
+ await runtime.createSession({
+ unitId,
+ sessionEpoch: 2,
+ snapshot: structuredClone(sourceModel.getSnapshot()),
+ modelRevision: 2,
+ locale: LocaleType.EN_US,
+ localeData: {},
+ direction: 'ltr',
+ });
+ await runtime.disposeSession({ unitId, sessionEpoch: 1 });
+ await runtime.createSession({
+ unitId,
+ sessionEpoch: 1,
+ snapshot: structuredClone(sourceModel.getSnapshot()),
+ modelRevision: 1,
+ locale: LocaleType.EN_US,
+ localeData: {},
+ direction: 'ltr',
+ });
+ await expect(runtime.startLayout({
+ ...mountIdentity,
+ mountEpoch: 2,
+ unitId,
+ mountId: 'mount-after-recreate',
+ metricsRevision: 1,
+ baseRevision: 2,
+ modelRevision: 2,
+ mutations: [],
+ customBlockViewports: {},
+ reason: 'initial',
+ budgetMs: 0,
+ })).resolves.toEqual(expect.objectContaining({ status: DocLayoutSessionStatus.ACCEPTED }));
+ await runtime.disposeSession({ unitId, sessionEpoch: 2 });
+
+ runtime.dispose();
+ sourceModel.dispose();
+ customBlockModel.dispose();
+ });
+
+ it('yields after a bounded paragraph batch and observes cancellation before publishing', async () => {
+ stubOffscreenCanvas();
+ const sourceModel = createDocumentModelWithStyle(
+ Array.from({ length: 80 }, (_, index) => `Worker paragraph ${index}\r`).join(''),
+ {}
+ );
+ sourceModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.TRADITIONAL });
+ sourceModel.updateDocumentDataPageSize(240, 180);
+ const runtime = new DocsLayoutWorkerRuntime();
+ const unitId = sourceModel.getUnitId();
+ const identity = {
+ unitId,
+ mountId: 'bounded-worker-layout',
+ mountEpoch: 1,
+ viewportEpoch: 1,
+ };
+ await runtime.createSession({
+ unitId,
+ sessionEpoch: 1,
+ snapshot: structuredClone(sourceModel.getSnapshot()),
+ modelRevision: 0,
+ locale: LocaleType.EN_US,
+ localeData: {},
+ direction: 'ltr',
+ });
+
+ const boundedStart = await runtime.startLayout({
+ ...identity,
+ metricsRevision: 1,
+ baseRevision: 0,
+ modelRevision: 0,
+ mutations: [],
+ customBlockViewports: {},
+ reason: 'initial',
+ budgetMs: 10_000,
+ });
+ if (boundedStart.status !== DocLayoutSessionStatus.ACCEPTED) {
+ throw new Error('Expected the bounded Worker layout session to start.');
+ }
+ expect(boundedStart.step.progress.complete).toBe(false);
+ expect(boundedStart.step.progress.processedBlockCount).toBeLessThanOrEqual(8);
+
+ const cancellingIdentity = { ...identity, mountId: 'cancelled-worker-layout' };
+ const cancellingStart = runtime.startLayout({
+ ...cancellingIdentity,
+ metricsRevision: 1,
+ baseRevision: 0,
+ modelRevision: 0,
+ mutations: [],
+ customBlockViewports: {},
+ reason: 'initial',
+ budgetMs: 10_000,
+ });
+ await runtime.cancelLayout(cancellingIdentity);
+ const cancelledStart = await cancellingStart;
+ if (cancelledStart.status !== DocLayoutSessionStatus.ACCEPTED) {
+ throw new Error('Expected the cancelled Worker layout session to start.');
+ }
+ expect(cancelledStart.step.progress.cancelled).toBe(true);
+ expect(cancelledStart.step.publication).toBeNull();
+
+ runtime.dispose();
+ sourceModel.dispose();
+ });
+});
diff --git a/packages/docs/src/layout-worker/config/config.ts b/packages/docs/src/layout-worker/config/config.ts
new file mode 100644
index 0000000000..e0db36230d
--- /dev/null
+++ b/packages/docs/src/layout-worker/config/config.ts
@@ -0,0 +1,31 @@
+/**
+ * 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_LAYOUT_WORKER_PLUGIN_CONFIG_KEY = 'docs-layout-worker.config';
+
+export const configSymbol = Symbol(DOCS_LAYOUT_WORKER_PLUGIN_CONFIG_KEY);
+
+export const DEFAULT_DOCS_LAYOUT_WORKER_REQUEST_TIMEOUT_MS = 15_000;
+
+export interface IUniverDocsLayoutWorkerConfig {
+ workerFactory?: () => Worker;
+ /** Maximum time allowed for one Worker RPC request before recovery starts. */
+ requestTimeoutMs?: number;
+}
+
+export const defaultPluginDocsLayoutWorkerConfig: IUniverDocsLayoutWorkerConfig = {
+ requestTimeoutMs: DEFAULT_DOCS_LAYOUT_WORKER_REQUEST_TIMEOUT_MS,
+};
diff --git a/packages/docs/src/layout-worker/index.ts b/packages/docs/src/layout-worker/index.ts
new file mode 100644
index 0000000000..28f2e53b23
--- /dev/null
+++ b/packages/docs/src/layout-worker/index.ts
@@ -0,0 +1,283 @@
+/**
+ * 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 { 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 { IDocsLayoutWorkerCapabilities, IDocsLayoutWorkerRuntime } from './protocol';
+import { DependentOn, Disposable, IConfigService, Inject, Injector, merge, Plugin, Tools } from '@univerjs/core';
+import { FontCache } from '@univerjs/engine-render';
+import { ChannelService, toModule } from '@univerjs/rpc';
+import { Observable, shareReplay } from 'rxjs';
+import pkg from '../../package.json';
+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 { DocsLayoutWorkerPerformanceTracker } from './performance-tracker';
+import { DOCS_LAYOUT_WORKER_CHANNEL, DOCS_LAYOUT_WORKER_PROTOCOL_VERSION } from './protocol';
+import { startDocsLayoutWorker } from './worker';
+
+const FONT_METRICS_TOLERANCE = 1;
+
+export class DocsLayoutWorkerCapabilityError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'DocsLayoutWorkerCapabilityError';
+ }
+}
+
+function createDocsLayoutWorkerMessageProtocol(
+ worker: Worker,
+ performanceTracker: DocsLayoutWorkerPerformanceTracker
+): IMessageProtocol {
+ return {
+ send(message: unknown): void {
+ const startedAt = Tools.now();
+ worker.postMessage(message);
+ performanceTracker.recordRequest(message, Tools.now() - startedAt);
+ },
+ onMessage: new Observable<unknown>((subscriber) => {
+ const handler = (event: MessageEvent) => subscriber.next(event.data);
+ worker.addEventListener('message', handler);
+ return () => worker.removeEventListener('message', handler);
+ }).pipe(shareReplay({ bufferSize: 1, refCount: true })),
+ };
+}
+
+export class DocsLayoutWorkerClientService extends Disposable implements IDocLayoutExecutor {
+ readonly type = DocLayoutExecutorType.WORKER;
+ private _worker: Worker | null = null;
+ private _channelService: ChannelService | null = null;
+ private _runtime: IDocsLayoutWorkerRuntime | null = null;
+ private _initialization: Promise<void>;
+ private _initialized = false;
+ private readonly _performanceTracker = new DocsLayoutWorkerPerformanceTracker();
+
+ constructor(
+ private readonly _workerFactory: () => Worker,
+ private readonly _requestTimeoutMs = DEFAULT_DOCS_LAYOUT_WORKER_REQUEST_TIMEOUT_MS
+ ) {
+ super();
+ this._initialization = this._replaceRuntime();
+ }
+
+ initialize(): Promise<void> {
+ return this._initialization;
+ }
+
+ getCapabilities(): Promise<IDocsLayoutWorkerCapabilities> {
+ return this._getRuntime().getCapabilities();
+ }
+
+ async recover(): Promise<void> {
+ this._initialization = this._replaceRuntime();
+ await this._initialization;
+ }
+
+ createSession(request: IDocLayoutCreateSessionRequest): Promise<void> {
+ if (this._initialized) {
+ return this._withTimeout(this._getRuntime().createSession(request), 'create session');
+ }
+
+ const capturedRequest = Tools.deepClone(request);
+ return this._initialization.then(() =>
+ this._withTimeout(this._getRuntime().createSession(capturedRequest), 'create session'));
+ }
+
+ async startLayout(request: IDocLayoutStartRequest): Promise<IDocLayoutStartResult> {
+ await this._initialization;
+ return this._withTimeout(this._getRuntime().startLayout(request), 'start layout');
+ }
+
+ async stepLayout(request: IDocLayoutStepRequest): Promise<IDocLayoutStepResult> {
+ await this._initialization;
+ return this._withTimeout(this._getRuntime().stepLayout(request), 'step layout');
+ }
+
+ async publishBacklog(request: Omit<IDocLayoutStepRequest, 'budgetMs'>): Promise<IDocLayoutStepResult> {
+ await this._initialization;
+ return this._withTimeout(this._getRuntime().publishBacklog(request), 'publish layout backlog');
+ }
+
+ async getLayoutPage(request: IDocLayoutPageRequest): Promise<IDocLayoutPageResult> {
+ await this._initialization;
+ return this._withTimeout(this._getRuntime().getLayoutPage(request), 'get layout page');
+ }
+
+ async cancelLayout(request: IDocLayoutCancelRequest): Promise<void> {
+ await this._initialization;
+ return this._withTimeout(this._getRuntime().cancelLayout(request), 'cancel layout');
+ }
+
+ async getPerformanceMetrics(
+ unitId: string
+ ): Promise<Omit<IDocLayoutPerformanceMetrics, 'hydrationMs'>> {
+ await this._initialization;
+ const workerMetrics = await this._withTimeout(
+ this._getRuntime().getPerformanceMetrics(unitId),
+ 'read performance metrics'
+ );
+ const clientMetrics = this._performanceTracker.getMetrics(unitId);
+ return {
+ mutationTransferMs: clientMetrics.mutationTransferMs,
+ patchTransferMs: workerMetrics.patchTransferMs,
+ snapshotTransferMs: clientMetrics.snapshotTransferMs,
+ };
+ }
+
+ async resetPerformanceMetrics(unitId: string): Promise<void> {
+ await this._initialization;
+ await this._withTimeout(
+ this._getRuntime().resetPerformanceMetrics(unitId),
+ 'reset performance metrics'
+ );
+ this._performanceTracker.reset(unitId);
+ }
+
+ async disposeLayoutMount(request: IDocLayoutDisposeMountRequest): Promise<void> {
+ await this._initialization;
+ return this._withTimeout(this._getRuntime().disposeLayoutMount(request), 'dispose layout mount');
+ }
+
+ async disposeSession(request: IDocLayoutDisposeSessionRequest): Promise<void> {
+ await this._initialization;
+ await this._withTimeout(this._getRuntime().disposeSession(request), 'dispose session');
+ this._performanceTracker.reset(request.unitId);
+ }
+
+ override dispose(): void {
+ this._disposeRuntime();
+ super.dispose();
+ }
+
+ private async _replaceRuntime(): Promise<void> {
+ this._initialized = false;
+ this._disposeRuntime();
+ const worker = this._workerFactory();
+ const channelService = new ChannelService(createDocsLayoutWorkerMessageProtocol(worker, this._performanceTracker));
+ this._worker = worker;
+ this._channelService = channelService;
+ this._runtime = toModule<IDocsLayoutWorkerRuntime>(
+ channelService.requestChannel(DOCS_LAYOUT_WORKER_CHANNEL)
+ );
+ await this._withTimeout(this._verifyCapabilities(), 'verify capabilities');
+ this._initialized = true;
+ }
+
+ private _disposeRuntime(): void {
+ this._initialized = false;
+ this._channelService?.dispose();
+ this._channelService = null;
+ this._runtime = null;
+ this._worker?.terminate();
+ this._worker = null;
+ this._performanceTracker.resetAll();
+ }
+
+ private _getRuntime(): IDocsLayoutWorkerRuntime {
+ if (this._runtime == null) {
+ throw new Error('Document layout Worker runtime is unavailable.');
+ }
+ return this._runtime;
+ }
+
+ private _withTimeout<T>(task: Promise<T>, operation: string): Promise<T> {
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
+ const timeout = new Promise<never>((_resolve, reject) => {
+ timeoutId = setTimeout(() => {
+ reject(new Error(`Document layout Worker timed out while attempting to ${operation}.`));
+ }, this._requestTimeoutMs);
+ });
+ return Promise.race([task, timeout]).finally(() => {
+ if (timeoutId != null) {
+ clearTimeout(timeoutId);
+ }
+ });
+ }
+
+ private async _verifyCapabilities(): Promise<void> {
+ const capabilities = await this.getCapabilities();
+ if (capabilities.protocolVersion !== DOCS_LAYOUT_WORKER_PROTOCOL_VERSION) {
+ throw new DocsLayoutWorkerCapabilityError('Document layout Worker protocol version mismatch.');
+ }
+ if (!capabilities.offscreenCanvas || !capabilities.structuredClone) {
+ throw new DocsLayoutWorkerCapabilityError(
+ 'Document layout Worker requires OffscreenCanvas and structured clone support.'
+ );
+ }
+
+ const mainMetrics = FontCache.getMeasureText(
+ capabilities.fontProbe.content,
+ capabilities.fontProbe.font
+ );
+ const metricPairs = [
+ [mainMetrics.width, capabilities.fontProbe.width],
+ [mainMetrics.actualBoundingBoxAscent, capabilities.fontProbe.actualBoundingBoxAscent],
+ [mainMetrics.actualBoundingBoxDescent, capabilities.fontProbe.actualBoundingBoxDescent],
+ ];
+ if (metricPairs.some(([mainValue, workerValue]) =>
+ !Number.isFinite(mainValue) ||
+ !Number.isFinite(workerValue) ||
+ Math.abs(mainValue - workerValue) > FONT_METRICS_TOLERANCE
+ )) {
+ throw new DocsLayoutWorkerCapabilityError(
+ 'Document layout Worker font metrics differ from the main rendering context.'
+ );
+ }
+ }
+}
+
+@DependentOn(UniverDocsPlugin)
+export class UniverDocsLayoutWorkerPlugin extends Plugin {
+ static override pluginName = 'DOCS_LAYOUT_WORKER_PLUGIN';
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+
+ constructor(
+ private readonly _config: Partial<IUniverDocsLayoutWorkerConfig> = defaultPluginDocsLayoutWorkerConfig,
+ @Inject(Injector) override readonly _injector: Injector,
+ @Inject(DocLayoutExecutorService) private readonly _layoutExecutorService: DocLayoutExecutorService,
+ @IConfigService private readonly _configService: IConfigService
+ ) {
+ super();
+
+ const { ...rest } = merge(
+ {},
+ defaultPluginDocsLayoutWorkerConfig,
+ this._config
+ );
+ this._configService.setConfig(DOCS_LAYOUT_WORKER_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ if (typeof this._config.workerFactory !== 'function') {
+ throw new TypeError('[UniverDocsLayoutWorkerPlugin]: workerFactory is required.');
+ }
+ const requestTimeoutMs = this._config.requestTimeoutMs ?? DEFAULT_DOCS_LAYOUT_WORKER_REQUEST_TIMEOUT_MS;
+ if (!Number.isFinite(requestTimeoutMs) || requestTimeoutMs <= 0) {
+ throw new RangeError('[UniverDocsLayoutWorkerPlugin]: requestTimeoutMs must be a positive finite number.');
+ }
+
+ const client = new DocsLayoutWorkerClientService(this._config.workerFactory, requestTimeoutMs);
+ this._injector.add([DocsLayoutWorkerClientService, { useValue: client }]);
+ this.disposeWithMe(client);
+ this.disposeWithMe(this._layoutExecutorService.register(client));
+ }
+}
+
+export type { IUniverDocsLayoutWorkerConfig } from './config/config';
+export type { IDocsLayoutWorkerCapabilities, IDocsLayoutWorkerFontProbe, IDocsLayoutWorkerRuntime } from './protocol';
+export { startDocsLayoutWorker };
diff --git a/packages/docs/src/layout-worker/performance-tracker.ts b/packages/docs/src/layout-worker/performance-tracker.ts
new file mode 100644
index 0000000000..03fe80991c
--- /dev/null
+++ b/packages/docs/src/layout-worker/performance-tracker.ts
@@ -0,0 +1,115 @@
+/**
+ * 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 { IDocLayoutPerformanceMetrics } from '../services/doc-layout-executor.service';
+
+const PERFORMANCE_SAMPLE_LIMIT = 2048;
+
+type WorkerTransferMetrics = Omit<IDocLayoutPerformanceMetrics, 'hydrationMs'>;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value != null;
+}
+
+function getRequest(message: unknown): { method: string; request: Record<string, unknown> } | null {
+ if (!isRecord(message) || typeof message.method !== 'string' || !Array.isArray(message.args)) {
+ return null;
+ }
+ const request = message.args[0];
+ return isRecord(request) ? { method: message.method, request } : null;
+}
+
+function getPublicationResult(message: unknown): Record<string, unknown> | null {
+ if (!isRecord(message) || !isRecord(message.data)) {
+ return null;
+ }
+ const result = message.data;
+ if (isRecord(result.step)) {
+ return result.step;
+ }
+ return result;
+}
+
+function createTransferMetrics(): WorkerTransferMetrics {
+ return {
+ mutationTransferMs: [],
+ patchTransferMs: [],
+ snapshotTransferMs: [],
+ };
+}
+
+export class DocsLayoutWorkerPerformanceTracker {
+ private readonly _metrics = new Map<string, WorkerTransferMetrics>();
+
+ recordRequest(message: unknown, durationMs: number): void {
+ const requestInfo = getRequest(message);
+ const unitId = requestInfo?.request.unitId;
+ if (requestInfo == null || typeof unitId !== 'string') {
+ return;
+ }
+
+ if (requestInfo.method === 'createSession') {
+ this._append(unitId, 'snapshotTransferMs', durationMs);
+ return;
+ }
+ if (
+ requestInfo.method === 'startLayout' &&
+ Array.isArray(requestInfo.request.mutations) &&
+ requestInfo.request.mutations.length > 0
+ ) {
+ this._append(unitId, 'mutationTransferMs', durationMs);
+ }
+ }
+
+ recordResponse(message: unknown, durationMs: number): void {
+ const result = getPublicationResult(message);
+ if (
+ result == null ||
+ typeof result.unitId !== 'string' ||
+ result.publication == null
+ ) {
+ return;
+ }
+ this._append(result.unitId, 'patchTransferMs', durationMs);
+ }
+
+ getMetrics(unitId: string): WorkerTransferMetrics {
+ const metrics = this._metrics.get(unitId) ?? createTransferMetrics();
+ return {
+ mutationTransferMs: [...metrics.mutationTransferMs],
+ patchTransferMs: [...metrics.patchTransferMs],
+ snapshotTransferMs: [...metrics.snapshotTransferMs],
+ };
+ }
+
+ reset(unitId: string): void {
+ this._metrics.delete(unitId);
+ }
+
+ resetAll(): void {
+ this._metrics.clear();
+ }
+
+ private _append(unitId: string, metric: keyof WorkerTransferMetrics, durationMs: number): void {
+ const metrics = this._metrics.get(unitId) ?? createTransferMetrics();
+ const samples = metrics[metric];
+ samples.push(durationMs);
+ if (samples.length > PERFORMANCE_SAMPLE_LIMIT) {
+ samples.splice(0, samples.length - PERFORMANCE_SAMPLE_LIMIT);
+ }
+ this._metrics.set(unitId, metrics);
+ }
+}
diff --git a/packages/docs/src/layout-worker/protocol.ts b/packages/docs/src/layout-worker/protocol.ts
new file mode 100644
index 0000000000..1d8b9289a3
--- /dev/null
+++ b/packages/docs/src/layout-worker/protocol.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.
+ */
+
+import type { DocLayoutExecutorType, IDocLayoutExecutor } from '../services/doc-layout-executor.service';
+
+export const DOCS_LAYOUT_WORKER_CHANNEL = 'univer.docs-layout-worker';
+export const DOCS_LAYOUT_WORKER_PROTOCOL_VERSION = 3;
+
+export interface IDocsLayoutWorkerFontProbe {
+ content: string;
+ font: string;
+ width: number;
+ actualBoundingBoxAscent: number;
+ actualBoundingBoxDescent: number;
+}
+
+export interface IDocsLayoutWorkerCapabilities {
+ protocolVersion: typeof DOCS_LAYOUT_WORKER_PROTOCOL_VERSION;
+ executor: DocLayoutExecutorType.WORKER;
+ offscreenCanvas: boolean;
+ structuredClone: boolean;
+ fontProbe: IDocsLayoutWorkerFontProbe;
+}
+
+export interface IDocsLayoutWorkerRuntime extends IDocLayoutExecutor {
+ getCapabilities(): Promise<IDocsLayoutWorkerCapabilities>;
+}
diff --git a/packages/docs/src/layout-worker/worker.ts b/packages/docs/src/layout-worker/worker.ts
new file mode 100644
index 0000000000..2a541bcd11
--- /dev/null
+++ b/packages/docs/src/layout-worker/worker.ts
@@ -0,0 +1,418 @@
+/**
+ * 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 { IDocsCustomBlockRenderViewport } from '@univerjs/engine-render';
+import type { IMessageProtocol } from '@univerjs/rpc';
+import type { IDocLayoutCancelRequest, IDocLayoutCreateSessionRequest, IDocLayoutDisposeMountRequest, IDocLayoutDisposeSessionRequest, IDocLayoutMountIdentity, IDocLayoutPageRequest, IDocLayoutPageResult, IDocLayoutPerformanceMetrics, IDocLayoutStartRequest, IDocLayoutStartResult, IDocLayoutStepRequest, IDocLayoutStepResult } from '../services/doc-layout-executor.service';
+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 { DocsLayoutWorkerPerformanceTracker } from './performance-tracker';
+import { DOCS_LAYOUT_WORKER_CHANNEL, DOCS_LAYOUT_WORKER_PROTOCOL_VERSION } from './protocol';
+
+const FONT_PROBE_CONTENT = 'Univer 文档 Worker 0123456789';
+const FONT_PROBE_STYLE = '16px Arial';
+const WORKER_LAYOUT_INTERRUPT_INTERVAL = 8;
+
+function yieldForWorkerMessage(): Promise<void> {
+ return new Promise((resolve) => {
+ requestImmediateMacroTask(() => resolve());
+ });
+}
+
+interface IDocsLayoutWorkerSession {
+ sessionEpoch: number;
+ dataModel: DocumentDataModel;
+ layoutSessions: Map<string, IDocsLayoutWorkerMount>;
+ localeService: LocaleService;
+ modelRevision: number;
+}
+
+interface IDocsLayoutWorkerMount {
+ mountId: string;
+ layoutSession: DocumentLayoutSession;
+ customBlockViewports: Record<string, IDocsCustomBlockRenderViewport>;
+ metricsRevision: number;
+ mountEpoch: number;
+ viewportEpoch: number;
+ activeGeneration: number | null;
+ cancelledGeneration: number | null;
+}
+
+function createDocsLayoutWorkerMessageProtocol(
+ performanceTracker: DocsLayoutWorkerPerformanceTracker
+): IMessageProtocol {
+ return {
+ send(message: unknown): void {
+ const startedAt = Tools.now();
+ postMessage(message);
+ performanceTracker.recordResponse(message, Tools.now() - startedAt);
+ },
+ onMessage: new Observable<unknown>((subscriber) => {
+ const handler = (event: MessageEvent) => subscriber.next(event.data);
+ addEventListener('message', handler);
+ return () => removeEventListener('message', handler);
+ }).pipe(shareReplay({ bufferSize: 1, refCount: true })),
+ };
+}
+
+export class DocsLayoutWorkerRuntime implements IDocsLayoutWorkerRuntime {
+ private readonly _sessions = new Map<string, IDocsLayoutWorkerSession>();
+ readonly type = DocLayoutExecutorType.WORKER;
+
+ constructor(
+ private readonly _performanceTracker = new DocsLayoutWorkerPerformanceTracker()
+ ) {}
+
+ initialize(): Promise<void> {
+ return Promise.resolve();
+ }
+
+ async getCapabilities(): Promise<IDocsLayoutWorkerCapabilities> {
+ const metrics = FontCache.getMeasureText(FONT_PROBE_CONTENT, FONT_PROBE_STYLE);
+ return {
+ protocolVersion: DOCS_LAYOUT_WORKER_PROTOCOL_VERSION,
+ executor: DocLayoutExecutorType.WORKER,
+ offscreenCanvas: typeof OffscreenCanvas !== 'undefined',
+ structuredClone: typeof structuredClone === 'function',
+ fontProbe: {
+ content: FONT_PROBE_CONTENT,
+ font: FONT_PROBE_STYLE,
+ width: metrics.width,
+ actualBoundingBoxAscent: metrics.actualBoundingBoxAscent,
+ actualBoundingBoxDescent: metrics.actualBoundingBoxDescent,
+ },
+ };
+ }
+
+ async recover(): Promise<void> {
+ for (const session of this._sessions.values()) {
+ for (const mount of session.layoutSessions.values()) {
+ mount.layoutSession.dispose();
+ }
+ }
+ this._sessions.clear();
+ }
+
+ async createSession(request: IDocLayoutCreateSessionRequest): Promise<void> {
+ if (typeof OffscreenCanvas === 'undefined') {
+ throw new Error('Document layout Worker requires OffscreenCanvas text measurement support.');
+ }
+
+ const currentSession = this._sessions.get(request.unitId);
+ if (currentSession != null && request.sessionEpoch < currentSession.sessionEpoch) {
+ return;
+ }
+ this._disposeSession(request.unitId);
+
+ const dataModel = new DocumentDataModel(request.snapshot);
+ const localeService = new LocaleService();
+ if (request.localeData != null) {
+ localeService.load({ [request.locale]: request.localeData });
+ }
+ localeService.setLocale(request.locale);
+ localeService.setDirection(request.direction);
+ this._sessions.set(request.unitId, {
+ sessionEpoch: request.sessionEpoch,
+ dataModel,
+ layoutSessions: new Map(),
+ localeService,
+ modelRevision: request.modelRevision,
+ });
+ }
+
+ async startLayout(request: IDocLayoutStartRequest): Promise<IDocLayoutStartResult> {
+ const session = this._sessions.get(request.unitId);
+ if (session == null) {
+ return { status: DocLayoutSessionStatus.NOT_FOUND };
+ }
+
+ if (session.modelRevision !== request.baseRevision) {
+ return {
+ status: DocLayoutSessionStatus.RESNAPSHOT_REQUIRED,
+ modelRevision: session.modelRevision,
+ };
+ }
+
+ if (!this._applyMutations(session, request)) {
+ return {
+ status: DocLayoutSessionStatus.RESNAPSHOT_REQUIRED,
+ modelRevision: session.modelRevision,
+ };
+ }
+
+ let mount = session.layoutSessions.get(request.mountId);
+ if (
+ mount != null && (
+ request.mountEpoch < mount.mountEpoch ||
+ (request.mountEpoch === mount.mountEpoch && request.viewportEpoch < mount.viewportEpoch)
+ )
+ ) {
+ return { status: DocLayoutSessionStatus.SUPERSEDED };
+ }
+ if (mount != null && request.mountEpoch > mount.mountEpoch) {
+ mount.layoutSession.dispose();
+ session.layoutSessions.delete(request.mountId);
+ mount = undefined;
+ }
+ if (mount == null) {
+ mount = {
+ mountId: request.mountId,
+ layoutSession: new DocumentLayoutSession(session.dataModel, session.localeService),
+ customBlockViewports: request.customBlockViewports,
+ metricsRevision: request.metricsRevision,
+ mountEpoch: request.mountEpoch,
+ viewportEpoch: request.viewportEpoch,
+ activeGeneration: null,
+ cancelledGeneration: null,
+ };
+ session.layoutSessions.set(request.mountId, mount);
+ } else {
+ mount.customBlockViewports = request.customBlockViewports;
+ mount.metricsRevision = request.metricsRevision;
+ mount.viewportEpoch = request.viewportEpoch;
+ }
+ const generation = mount.layoutSession.start({
+ reason: request.reason,
+ anchor: request.anchor,
+ priorityAnchor: request.priorityAnchor,
+ invalidation: request.invalidation,
+ });
+ mount.activeGeneration = generation;
+ mount.cancelledGeneration = null;
+ return {
+ status: DocLayoutSessionStatus.ACCEPTED,
+ step: await this._runLayoutStep(session, mount, generation, request.budgetMs),
+ };
+ }
+
+ private _applyMutations(
+ session: IDocsLayoutWorkerSession,
+ request: IDocLayoutStartRequest
+ ): boolean {
+ for (const mutation of request.mutations) {
+ if (
+ mutation.baseRevision !== session.modelRevision ||
+ mutation.modelRevision !== mutation.baseRevision + 1
+ ) {
+ return false;
+ }
+ session.dataModel.apply(mutation.actions);
+ session.modelRevision = mutation.modelRevision;
+ }
+ if (session.modelRevision !== request.modelRevision) {
+ return false;
+ }
+ if (request.mutations.length > 0) {
+ for (const mount of session.layoutSessions.values()) {
+ mount.activeGeneration = null;
+ mount.cancelledGeneration = null;
+ mount.layoutSession.resetDataModel(session.dataModel);
+ }
+ }
+ return true;
+ }
+
+ async stepLayout(request: IDocLayoutStepRequest): Promise<IDocLayoutStepResult> {
+ const session = this._getSession(request.unitId);
+ const mount = this._getLayoutMount(session, request);
+ return await this._runLayoutStep(session, mount, request.generation, request.budgetMs);
+ }
+
+ async publishBacklog(request: Omit<IDocLayoutStepRequest, 'budgetMs'>): Promise<IDocLayoutStepResult> {
+ const session = this._getSession(request.unitId);
+ const mount = this._getLayoutMount(session, request);
+ return this._runWithCustomBlockViewports(session, mount, () => ({
+ ...mount.layoutSession.publishBacklog(request.generation),
+ unitId: request.unitId,
+ mountId: request.mountId,
+ mountEpoch: mount.mountEpoch,
+ viewportEpoch: mount.viewportEpoch,
+ modelRevision: session.modelRevision,
+ metricsRevision: mount.metricsRevision,
+ }));
+ }
+
+ async getLayoutPage(request: IDocLayoutPageRequest): Promise<IDocLayoutPageResult> {
+ const session = this._getSession(request.unitId);
+ const mount = this._getLayoutMount(session, request);
+ return {
+ ...request,
+ modelRevision: session.modelRevision,
+ metricsRevision: mount.metricsRevision,
+ page: mount.layoutSession.getPage(request.pageIndex),
+ };
+ }
+
+ async cancelLayout(request: IDocLayoutCancelRequest): Promise<void> {
+ const mount = this._sessions.get(request.unitId)?.layoutSessions.get(request.mountId);
+ if (
+ mount?.mountEpoch === request.mountEpoch &&
+ mount.viewportEpoch === request.viewportEpoch
+ ) {
+ if (request.generation == null || request.generation === mount.activeGeneration) {
+ mount.cancelledGeneration = request.generation ?? mount.activeGeneration;
+ }
+ mount.layoutSession.cancel(request.generation);
+ }
+ }
+
+ async getPerformanceMetrics(
+ unitId: string
+ ): Promise<Omit<IDocLayoutPerformanceMetrics, 'hydrationMs'>> {
+ return this._performanceTracker.getMetrics(unitId);
+ }
+
+ async resetPerformanceMetrics(unitId: string): Promise<void> {
+ this._performanceTracker.reset(unitId);
+ }
+
+ async disposeLayoutMount(request: IDocLayoutDisposeMountRequest): Promise<void> {
+ const session = this._sessions.get(request.unitId);
+ const mount = session?.layoutSessions.get(request.mountId);
+ if (
+ session == null ||
+ mount == null ||
+ mount.mountEpoch !== request.mountEpoch ||
+ mount.viewportEpoch !== request.viewportEpoch
+ ) {
+ return;
+ }
+
+ session.layoutSessions.delete(request.mountId);
+ mount.activeGeneration = null;
+ mount.layoutSession.dispose();
+ }
+
+ async disposeSession(request: IDocLayoutDisposeSessionRequest): Promise<void> {
+ const session = this._sessions.get(request.unitId);
+ if (session?.sessionEpoch !== request.sessionEpoch) {
+ return;
+ }
+ this._disposeSession(request.unitId);
+ this._performanceTracker.reset(request.unitId);
+ }
+
+ dispose(): void {
+ for (const unitId of this._sessions.keys()) {
+ this._disposeSession(unitId);
+ }
+ this._performanceTracker.resetAll();
+ }
+
+ private _getSession(unitId: string): IDocsLayoutWorkerSession {
+ const session = this._sessions.get(unitId);
+ if (session == null) {
+ throw new Error(`Document layout Worker session not found for unit "${unitId}".`);
+ }
+ return session;
+ }
+
+ private _getLayoutMount(
+ session: IDocsLayoutWorkerSession,
+ request: IDocLayoutMountIdentity
+ ): IDocsLayoutWorkerMount {
+ const mount = session.layoutSessions.get(request.mountId);
+ if (mount == null) {
+ throw new Error(`Document layout Worker mount not found: "${request.mountId}".`);
+ }
+ if (
+ mount.mountEpoch !== request.mountEpoch ||
+ mount.viewportEpoch !== request.viewportEpoch
+ ) {
+ throw new Error(`Document layout Worker rejected a stale mount publication: "${request.mountId}".`);
+ }
+ return mount;
+ }
+
+ private async _runLayoutStep(
+ session: IDocsLayoutWorkerSession,
+ mount: IDocsLayoutWorkerMount,
+ generation: number,
+ budgetMs: number
+ ): Promise<IDocLayoutStepResult> {
+ const result = this._runWithCustomBlockViewports(session, mount, () => ({
+ ...mount.layoutSession.step(generation, budgetMs, WORKER_LAYOUT_INTERRUPT_INTERVAL),
+ unitId: session.dataModel.getUnitId(),
+ mountId: mount.mountId,
+ mountEpoch: mount.mountEpoch,
+ viewportEpoch: mount.viewportEpoch,
+ modelRevision: session.modelRevision,
+ metricsRevision: mount.metricsRevision,
+ }));
+ await yieldForWorkerMessage();
+ if (
+ mount.activeGeneration === generation &&
+ mount.cancelledGeneration !== generation
+ ) {
+ return result;
+ }
+
+ return this._runWithCustomBlockViewports(session, mount, () => ({
+ ...mount.layoutSession.step(generation, 0, 1),
+ unitId: session.dataModel.getUnitId(),
+ mountId: mount.mountId,
+ mountEpoch: mount.mountEpoch,
+ viewportEpoch: mount.viewportEpoch,
+ modelRevision: session.modelRevision,
+ metricsRevision: mount.metricsRevision,
+ }));
+ }
+
+ private _runWithCustomBlockViewports<T>(
+ session: IDocsLayoutWorkerSession,
+ mount: IDocsLayoutWorkerMount,
+ run: () => T
+ ): T {
+ const unregister = setDocsCustomBlockRenderViewportProvider((unitId, blockId) =>
+ unitId === session.dataModel.getUnitId() ? mount.customBlockViewports[blockId] : null
+ );
+ try {
+ return run();
+ } finally {
+ unregister();
+ }
+ }
+
+ private _disposeSession(unitId: string): void {
+ const session = this._sessions.get(unitId);
+ if (session == null) {
+ return;
+ }
+
+ this._sessions.delete(unitId);
+ for (const mount of session.layoutSessions.values()) {
+ mount.activeGeneration = null;
+ mount.layoutSession.dispose();
+ }
+ session.layoutSessions.clear();
+ session.dataModel.dispose();
+ session.localeService.dispose();
+ }
+}
+
+export function startDocsLayoutWorker(): ChannelService {
+ const performanceTracker = new DocsLayoutWorkerPerformanceTracker();
+ const channelService = new ChannelService(createDocsLayoutWorkerMessageProtocol(performanceTracker));
+ channelService.registerChannel(
+ DOCS_LAYOUT_WORKER_CHANNEL,
+ fromModule(new DocsLayoutWorkerRuntime(performanceTracker))
+ );
+ return channelService;
+}
diff --git a/packages/docs/src/plugin.ts b/packages/docs/src/plugin.ts
index cc24634002..30313fcfa0 100644
--- a/packages/docs/src/plugin.ts
+++ b/packages/docs/src/plugin.ts
@@ -41,6 +41,7 @@ import { DocCustomRangeController } from './controllers/custom-range.controller'
import { DocPermissionController } from './controllers/doc-permission.controller';
import { DocBlockMoveValidatorService } from './services/doc-block-move-validator.service';
import { DocContentInsertService } from './services/doc-content-insert.service';
+import { DocLayoutExecutorService } from './services/doc-layout-executor.service';
import { DocSelectionManagerService } from './services/doc-selection-manager.service';
import { DocStateChangeManagerService } from './services/doc-state-change-manager.service';
import { DocStateEmitService } from './services/doc-state-emit.service';
@@ -106,6 +107,7 @@ export class UniverDocsPlugin extends Plugin {
[DocStateChangeManagerService],
[DocBlockMoveValidatorService],
[DocContentInsertService],
+ [DocLayoutExecutorService],
[DocTextResolverService],
[DocCustomRangeController],
[DocPermissionController],
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
new file mode 100644
index 0000000000..9a64d255c6
--- /dev/null
+++ b/packages/docs/src/services/__tests__/doc-layout-executor.service.spec.ts
@@ -0,0 +1,741 @@
+/**
+ * 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 { IDocLayoutExecutor, IDocLayoutMountIdentity, IDocLayoutStartResult } from '../doc-layout-executor.service';
+import {
+
+ DocumentFlavor,
+ ICommandService,
+
+ IUniverInstanceService,
+ JSONX,
+ LifecycleService,
+ LifecycleStages,
+ ObjectRelativeFromH,
+ ObjectRelativeFromV,
+ PositionedObjectLayoutType,
+ TextX,
+ TextXActionType,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ IRenderManagerService,
+ RenderManagerService,
+ setDocsCustomBlockRenderViewportProvider,
+} from '@univerjs/engine-render';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { RichTextEditingMutation } from '../../commands/mutations/core-editing.mutation';
+import { UniverDocsPlugin } from '../../plugin';
+import {
+ DocLayoutExecutorService,
+ DocLayoutExecutorState,
+ DocLayoutExecutorType,
+ DocLayoutSessionStatus,
+
+} from '../doc-layout-executor.service';
+
+function createDocumentData(id: string, documentFlavor: DocumentFlavor): IDocumentData {
+ return {
+ id,
+ body: {
+ dataStream: 'Hello\r\n',
+ paragraphs: [{ paragraphId: 'paragraph-1', startIndex: 5 }],
+ },
+ documentStyle: {
+ documentFlavor,
+ pageSize: { width: 594, height: 840 },
+ },
+ };
+}
+
+function createMountIdentity(mountId = 'mount-1', viewportEpoch = 1): IDocLayoutMountIdentity {
+ return { unitId: 'traditional-doc', mountId, mountEpoch: 1, viewportEpoch };
+}
+
+function createStartResult(
+ modelRevision: number,
+ metricsRevision = 1,
+ identity = createMountIdentity()
+): IDocLayoutStartResult {
+ return {
+ status: DocLayoutSessionStatus.ACCEPTED,
+ step: {
+ ...identity,
+ progress: {
+ generation: 1,
+ publicationRevision: 1,
+ didPublish: true,
+ didPublishAnchor: true,
+ publishedPageCount: 1,
+ reason: 'initial',
+ mode: 'paginated',
+ complete: false,
+ cancelled: false,
+ anchorReady: true,
+ laidOutThrough: 5,
+ stableLaidOutThrough: 4,
+ pageCount: 1,
+ processedBlockCount: 1,
+ totalBlockCount: 1,
+ estimatedPageCount: 1,
+ estimatedHeight: 840,
+ elapsedTime: 1,
+ maxBlockDuration: 1,
+ interactionWindowComplete: false,
+ },
+ publication: null,
+ modelRevision,
+ metricsRevision,
+ },
+ };
+}
+
+function getRequestIdentity(request: IDocLayoutMountIdentity): IDocLayoutMountIdentity {
+ return {
+ unitId: request.unitId,
+ mountId: request.mountId,
+ mountEpoch: request.mountEpoch,
+ viewportEpoch: request.viewportEpoch,
+ };
+}
+
+function createExecutor(): IDocLayoutExecutor {
+ return {
+ type: DocLayoutExecutorType.WORKER,
+ initialize: vi.fn(async () => {}),
+ recover: vi.fn(async () => {}),
+ createSession: vi.fn(async () => {}),
+ startLayout: vi.fn(async (request) =>
+ createStartResult(request.modelRevision, request.metricsRevision, getRequestIdentity(request))),
+ stepLayout: vi.fn(async () => {
+ throw new Error('not used');
+ }),
+ publishBacklog: vi.fn(async () => {
+ throw new Error('not used');
+ }),
+ getLayoutPage: vi.fn(async () => {
+ throw new Error('not used');
+ }),
+ cancelLayout: vi.fn(async () => {}),
+ getPerformanceMetrics: vi.fn(async () => ({
+ mutationTransferMs: [],
+ patchTransferMs: [],
+ snapshotTransferMs: [],
+ })),
+ resetPerformanceMetrics: vi.fn(async () => {}),
+ disposeLayoutMount: vi.fn(async () => {}),
+ disposeSession: vi.fn(async () => {}),
+ };
+}
+
+describe('DocLayoutExecutorService', () => {
+ let univer: Univer;
+
+ beforeEach(() => {
+ univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.get(LifecycleService).stage = LifecycleStages.Starting;
+ univer.registerPlugin(UniverDocsPlugin);
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('owns Worker sessions only for paginated and modern documents', async () => {
+ const injector = univer.__getInjector();
+ const service = injector.get(DocLayoutExecutorService);
+ const executor = createExecutor();
+ const registration = service.register(executor);
+ await vi.waitFor(() => expect(service.getExecutorStatus()).toEqual({
+ state: DocLayoutExecutorState.ACTIVE,
+ executor: DocLayoutExecutorType.WORKER,
+ diagnostic: null,
+ recoveryUnitId: null,
+ }));
+
+ univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createDocumentData('traditional-doc', DocumentFlavor.TRADITIONAL)
+ );
+ univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createDocumentData('modern-doc', DocumentFlavor.MODERN)
+ );
+ univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createDocumentData('editor-doc', DocumentFlavor.UNSPECIFIED)
+ );
+ await vi.waitFor(() => expect(executor.createSession).toHaveBeenCalledTimes(2));
+ expect(executor.createSession).toHaveBeenCalledWith(expect.objectContaining({
+ unitId: 'traditional-doc',
+ sessionEpoch: expect.any(Number),
+ modelRevision: 0,
+ }));
+ expect(executor.createSession).toHaveBeenCalledWith(expect.objectContaining({
+ unitId: 'modern-doc',
+ modelRevision: 0,
+ }));
+
+ const result = await service.startLayout(createMountIdentity(), { reason: 'initial' }, 32);
+ expect(result).toEqual(expect.objectContaining({
+ status: DocLayoutSessionStatus.ACCEPTED,
+ step: expect.objectContaining({ modelRevision: 0 }),
+ }));
+ expect(executor.startLayout).toHaveBeenCalledWith({
+ unitId: 'traditional-doc',
+ mountId: 'mount-1',
+ mountEpoch: 1,
+ viewportEpoch: 1,
+ metricsRevision: 1,
+ baseRevision: 0,
+ modelRevision: 0,
+ mutations: [],
+ customBlockViewports: {},
+ reason: 'initial',
+ budgetMs: 32,
+ });
+ expect(await service.startLayout(
+ { ...createMountIdentity(), unitId: 'editor-doc' },
+ { reason: 'initial' },
+ 32
+ )).toBeNull();
+
+ injector.get(IUniverInstanceService).disposeUnit('traditional-doc');
+ expect(executor.disposeSession).toHaveBeenCalledWith({
+ unitId: 'traditional-doc',
+ sessionEpoch: expect.any(Number),
+ });
+ registration.dispose();
+ });
+
+ it('cancels a deferred snapshot transfer when the document is disposed in the same task', async () => {
+ const injector = univer.__getInjector();
+ const service = injector.get(DocLayoutExecutorService);
+ const executor = createExecutor();
+ service.register(executor);
+
+ univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createDocumentData('traditional-doc', DocumentFlavor.TRADITIONAL)
+ );
+ injector.get(IUniverInstanceService).disposeUnit('traditional-doc');
+ await new Promise<void>((resolve) => setTimeout(resolve, 20));
+
+ expect(executor.createSession).not.toHaveBeenCalled();
+ expect(executor.disposeSession).toHaveBeenCalledWith({
+ unitId: 'traditional-doc',
+ sessionEpoch: expect.any(Number),
+ });
+ });
+
+ it('folds mutations committed before a deferred snapshot transfer into one consistent Worker baseline', async () => {
+ const injector = univer.__getInjector();
+ const service = injector.get(DocLayoutExecutorService);
+ const executor = createExecutor();
+ service.register(executor);
+ univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createDocumentData('traditional-doc', DocumentFlavor.TRADITIONAL)
+ );
+
+ const textX = new TextX();
+ textX.push({ t: TextXActionType.RETAIN, len: 5 });
+ textX.push({
+ t: TextXActionType.INSERT,
+ len: 1,
+ body: { dataStream: 'A' },
+ });
+ injector.get(ICommandService).syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId: 'traditional-doc',
+ actions: JSONX.getInstance().editOp(textX.serialize(), ['body']),
+ textRanges: [],
+ });
+
+ await service.startLayout(createMountIdentity(), { reason: 'edit', anchor: 6 }, 32);
+
+ expect(executor.createSession).toHaveBeenCalledTimes(1);
+ expect(executor.createSession).toHaveBeenCalledWith(expect.objectContaining({
+ modelRevision: 1,
+ snapshot: expect.objectContaining({
+ body: expect.objectContaining({ dataStream: 'HelloA\r\n' }),
+ }),
+ }));
+ expect(executor.startLayout).toHaveBeenCalledWith(expect.objectContaining({
+ baseRevision: 1,
+ modelRevision: 1,
+ mutations: [],
+ }));
+ });
+
+ it('rebases the deferred Worker snapshot after executor initialization completes', async () => {
+ const injector = univer.__getInjector();
+ const service = injector.get(DocLayoutExecutorService);
+ const executor = createExecutor();
+ let resolveInitialization: () => void = () => {};
+ vi.mocked(executor.initialize).mockImplementation(() => new Promise<void>((resolve) => {
+ resolveInitialization = resolve;
+ }));
+ service.register(executor);
+ univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createDocumentData('traditional-doc', DocumentFlavor.TRADITIONAL)
+ );
+ await new Promise<void>((resolve) => setTimeout(resolve, 20));
+ expect(executor.createSession).not.toHaveBeenCalled();
+
+ const textX = new TextX();
+ textX.push({ t: TextXActionType.RETAIN, len: 5 });
+ textX.push({
+ t: TextXActionType.INSERT,
+ len: 1,
+ body: { dataStream: 'A' },
+ });
+ injector.get(ICommandService).syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId: 'traditional-doc',
+ actions: JSONX.getInstance().editOp(textX.serialize(), ['body']),
+ textRanges: [],
+ });
+ resolveInitialization();
+
+ await service.startLayout(createMountIdentity(), { reason: 'edit', anchor: 6 }, 32);
+
+ expect(executor.createSession).toHaveBeenCalledWith(expect.objectContaining({
+ modelRevision: 1,
+ snapshot: expect.objectContaining({
+ body: expect.objectContaining({ dataStream: 'HelloA\r\n' }),
+ }),
+ }));
+ expect(executor.startLayout).toHaveBeenCalledWith(expect.objectContaining({
+ baseRevision: 1,
+ modelRevision: 1,
+ mutations: [],
+ }));
+ });
+
+ it('reports capability initialization failures and unregisters the executor', async () => {
+ const service = univer.__getInjector().get(DocLayoutExecutorService);
+ const executor = createExecutor();
+ vi.mocked(executor.initialize).mockRejectedValue(new Error('font metrics mismatch'));
+
+ service.register(executor);
+
+ await vi.waitFor(() => expect(service.getExecutor()).toBeNull());
+ expect(service.getExecutorStatus()).toEqual({
+ state: DocLayoutExecutorState.FAILED,
+ executor: DocLayoutExecutorType.WORKER,
+ diagnostic: 'font metrics mismatch',
+ recoveryUnitId: null,
+ });
+ });
+
+ it('collects bounded transfer and hydration diagnostics without changing executor results', async () => {
+ const service = univer.__getInjector().get(DocLayoutExecutorService);
+ const executor = createExecutor();
+ vi.mocked(executor.getPerformanceMetrics).mockResolvedValue({
+ mutationTransferMs: [2],
+ patchTransferMs: [3, 4],
+ snapshotTransferMs: [5],
+ });
+ service.register(executor);
+ univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createDocumentData('traditional-doc', DocumentFlavor.TRADITIONAL)
+ );
+ expect(executor.createSession).not.toHaveBeenCalled();
+ await vi.waitFor(() => expect(executor.createSession).toHaveBeenCalledTimes(1));
+
+ service.recordHydrationDuration('traditional-doc', 6);
+ const metrics = await service.getPerformanceMetrics('traditional-doc');
+
+ expect(metrics).toMatchObject({
+ hydrationMs: [6],
+ mutationTransferMs: [2],
+ patchTransferMs: [3, 4],
+ snapshotTransferMs: [5],
+ });
+ await service.resetPerformanceMetrics('traditional-doc');
+ expect(executor.resetPerformanceMetrics).toHaveBeenCalledWith('traditional-doc');
+ expect((await service.getPerformanceMetrics('traditional-doc')).hydrationMs).toEqual([]);
+ });
+
+ it('keeps the affected document in recovery until a canonical layout completes', async () => {
+ const service = univer.__getInjector().get(DocLayoutExecutorService);
+ const executor = createExecutor();
+ service.register(executor);
+ await vi.waitFor(() => expect(service.getExecutorStatus().state).toBe(DocLayoutExecutorState.ACTIVE));
+
+ await service.recoverExecutor('doc-1', 'layout convergence failed');
+
+ expect(executor.recover).toHaveBeenCalledTimes(1);
+ expect(service.getExecutorStatus()).toEqual({
+ state: DocLayoutExecutorState.RECOVERING,
+ executor: DocLayoutExecutorType.WORKER,
+ diagnostic: 'layout convergence failed',
+ recoveryUnitId: 'doc-1',
+ });
+
+ service.completeRecovery('another-doc');
+ expect(service.getExecutorStatus().state).toBe(DocLayoutExecutorState.RECOVERING);
+
+ service.completeRecovery('doc-1');
+ expect(service.getExecutorStatus()).toEqual({
+ state: DocLayoutExecutorState.ACTIVE,
+ executor: DocLayoutExecutorType.WORKER,
+ diagnostic: null,
+ recoveryUnitId: null,
+ });
+ });
+
+ it('projects committed mutations to the Worker in revision order before layout starts', async () => {
+ const injector = univer.__getInjector();
+ const service = injector.get(DocLayoutExecutorService);
+ const executor = createExecutor();
+ service.register(executor);
+ univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createDocumentData('traditional-doc', DocumentFlavor.TRADITIONAL)
+ );
+ await vi.waitFor(() => expect(executor.createSession).toHaveBeenCalledTimes(1));
+
+ const commandService = injector.get(ICommandService);
+ for (const [offset, text] of [[5, 'A'], [6, 'B']] as const) {
+ const textX = new TextX();
+ textX.push({ t: TextXActionType.RETAIN, len: offset });
+ textX.push({
+ t: TextXActionType.INSERT,
+ len: text.length,
+ body: { dataStream: text },
+ });
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId: 'traditional-doc',
+ actions: JSONX.getInstance().editOp(textX.serialize(), ['body']),
+ textRanges: [],
+ });
+ }
+
+ await service.startLayout(createMountIdentity(), { reason: 'edit', anchor: 5 }, 32);
+
+ expect(executor.startLayout).toHaveBeenLastCalledWith({
+ unitId: 'traditional-doc',
+ mountId: 'mount-1',
+ mountEpoch: 1,
+ viewportEpoch: 1,
+ metricsRevision: 1,
+ baseRevision: 0,
+ modelRevision: 2,
+ mutations: [
+ expect.objectContaining({ baseRevision: 0, modelRevision: 1 }),
+ expect.objectContaining({ baseRevision: 1, modelRevision: 2 }),
+ ],
+ customBlockViewports: {},
+ reason: 'edit',
+ anchor: 5,
+ budgetMs: 32,
+ });
+ expect(executor.createSession).toHaveBeenCalledTimes(1);
+ });
+
+ it('re-snapshots before layout when a direct document model mutation bypasses the projected command stream', async () => {
+ const injector = univer.__getInjector();
+ const service = injector.get(DocLayoutExecutorService);
+ const executor = createExecutor();
+ service.register(executor);
+ const model = univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createDocumentData('traditional-doc', DocumentFlavor.TRADITIONAL)
+ );
+ await vi.waitFor(() => expect(executor.createSession).toHaveBeenCalledTimes(1));
+
+ model.updateDocumentStyle({
+ ...model.getDocumentStyle(),
+ marginTop: 123,
+ });
+ await service.startLayout(createMountIdentity(), { reason: 'edit', anchor: 5 }, 32);
+
+ expect(executor.createSession).toHaveBeenCalledTimes(2);
+ expect(executor.createSession).toHaveBeenLastCalledWith(expect.objectContaining({
+ unitId: 'traditional-doc',
+ modelRevision: 0,
+ snapshot: expect.objectContaining({
+ documentStyle: expect.objectContaining({ marginTop: 123 }),
+ }),
+ }));
+ expect(executor.startLayout).toHaveBeenLastCalledWith(expect.objectContaining({
+ baseRevision: 0,
+ modelRevision: 0,
+ mutations: [],
+ }));
+ });
+
+ it('re-snapshots when a direct model mutation lands while a queued Worker start is waiting', async () => {
+ const injector = univer.__getInjector();
+ const service = injector.get(DocLayoutExecutorService);
+ const executor = createExecutor();
+ let resolveInitialSession: () => void = () => {};
+ vi.mocked(executor.createSession)
+ .mockImplementationOnce(() => new Promise<void>((resolve) => {
+ resolveInitialSession = resolve;
+ }))
+ .mockResolvedValue(undefined);
+ service.register(executor);
+ const model = univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createDocumentData('traditional-doc', DocumentFlavor.TRADITIONAL)
+ );
+ await vi.waitFor(() => expect(executor.createSession).toHaveBeenCalledTimes(1));
+
+ const start = service.startLayout(createMountIdentity(), { reason: 'initial' }, 32);
+ model.updateDocumentStyle({
+ ...model.getDocumentStyle(),
+ marginBottom: 456,
+ });
+ resolveInitialSession();
+ await start;
+
+ expect(executor.createSession).toHaveBeenCalledTimes(2);
+ expect(executor.createSession).toHaveBeenLastCalledWith(expect.objectContaining({
+ snapshot: expect.objectContaining({
+ documentStyle: expect.objectContaining({ marginBottom: 456 }),
+ }),
+ }));
+ expect(executor.startLayout).toHaveBeenCalledTimes(1);
+ expect(executor.startLayout).toHaveBeenCalledWith(expect.objectContaining({
+ baseRevision: 0,
+ modelRevision: 0,
+ mutations: [],
+ }));
+ });
+
+ it('preserves paste, undo, redo, remote, and table-format actions in one ordered Worker batch', async () => {
+ const injector = univer.__getInjector();
+ const service = injector.get(DocLayoutExecutorService);
+ const executor = createExecutor();
+ service.register(executor);
+ univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createDocumentData('traditional-doc', DocumentFlavor.TRADITIONAL)
+ );
+ await vi.waitFor(() => expect(executor.createSession).toHaveBeenCalledTimes(1));
+
+ const commandService = injector.get(ICommandService);
+ const pastedText = '大段粘贴内容'.repeat(1_024);
+ const pasteTextX = new TextX();
+ pasteTextX.push({ t: TextXActionType.RETAIN, len: 5 });
+ pasteTextX.push({
+ t: TextXActionType.INSERT,
+ len: pastedText.length,
+ body: { dataStream: pastedText },
+ });
+ const pasteActions = JSONX.getInstance().editOp(pasteTextX.serialize(), ['body']);
+
+ const undoTextX = new TextX();
+ undoTextX.push({ t: TextXActionType.RETAIN, len: 5 });
+ undoTextX.push({ t: TextXActionType.DELETE, len: pastedText.length });
+ const undoActions = JSONX.getInstance().editOp(undoTextX.serialize(), ['body']);
+
+ const redoTextX = new TextX();
+ redoTextX.push({ t: TextXActionType.RETAIN, len: 5 });
+ redoTextX.push({
+ t: TextXActionType.INSERT,
+ len: pastedText.length,
+ body: { dataStream: pastedText },
+ });
+ const redoActions = JSONX.getInstance().editOp(redoTextX.serialize(), ['body']);
+
+ const remoteTextX = new TextX();
+ remoteTextX.push({ t: TextXActionType.RETAIN, len: 5 });
+ remoteTextX.push({
+ t: TextXActionType.INSERT,
+ len: 2,
+ body: { dataStream: '远端' },
+ });
+ const remoteActions = JSONX.getInstance().editOp(remoteTextX.serialize(), ['body']);
+ const tableFormatActions = JSONX.getInstance().insertOp(['tableSource', 'table-1'], {
+ tableId: 'table-1',
+ tableRows: [{ tableCells: [{ backgroundColor: { rgb: '#fff4b9' } }] }],
+ tableColumns: [{}],
+ });
+
+ for (const [actions, textRanges] of [
+ [pasteActions, []],
+ [undoActions, []],
+ [redoActions, []],
+ [remoteActions, null],
+ [tableFormatActions, []],
+ ] as const) {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId: 'traditional-doc',
+ actions,
+ textRanges,
+ });
+ }
+
+ await service.startLayout(createMountIdentity(), { reason: 'edit', anchor: 5 }, 32);
+
+ const request = vi.mocked(executor.startLayout).mock.lastCall?.[0];
+ expect(request).toEqual(expect.objectContaining({
+ baseRevision: 0,
+ modelRevision: 5,
+ reason: 'edit',
+ anchor: 5,
+ }));
+ expect(request?.mutations).toEqual([
+ { baseRevision: 0, modelRevision: 1, actions: pasteActions },
+ { baseRevision: 1, modelRevision: 2, actions: undoActions },
+ { baseRevision: 2, modelRevision: 3, actions: redoActions },
+ { baseRevision: 3, modelRevision: 4, actions: remoteActions },
+ { baseRevision: 4, modelRevision: 5, actions: tableFormatActions },
+ ]);
+ });
+
+ it('serializes main-thread custom block viewport measurements with a layout start', async () => {
+ const injector = univer.__getInjector();
+ const service = injector.get(DocLayoutExecutorService);
+ const executor = createExecutor();
+ service.register(executor);
+ const unregister = setDocsCustomBlockRenderViewportProvider((unitId, blockId, input) => {
+ if (unitId !== 'traditional-doc' || blockId !== 'embed-1') {
+ return null;
+ }
+ return {
+ width: input.fallbackWidth + 10,
+ height: input.fallbackHeight + 20,
+ contentWidth: 640,
+ contentHeight: 480,
+ };
+ });
+ const documentData = createDocumentData('traditional-doc', DocumentFlavor.TRADITIONAL);
+ documentData.body = {
+ dataStream: '\b\r\n',
+ paragraphs: [{ paragraphId: 'paragraph-1', startIndex: 1 }],
+ customBlocks: [{ startIndex: 0, blockId: 'embed-1' }],
+ };
+ documentData.drawings = {
+ 'embed-1': {
+ unitId: 'traditional-doc',
+ subUnitId: 'traditional-doc',
+ drawingId: 'embed-1',
+ drawingType: 1,
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ angle: 0,
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ size: { width: 100, height: 80 },
+ },
+ },
+ };
+ univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, documentData);
+ await Promise.resolve();
+
+ await service.startLayout(createMountIdentity(), { reason: 'initial' }, 32);
+
+ expect(executor.startLayout).toHaveBeenCalledWith(expect.objectContaining({
+ customBlockViewports: {
+ 'embed-1': {
+ width: 110,
+ height: 100,
+ contentWidth: 640,
+ contentHeight: 480,
+ },
+ },
+ }));
+ unregister();
+ });
+
+ it('skips queued layout starts that a newer edit superseded', async () => {
+ const injector = univer.__getInjector();
+ const service = injector.get(DocLayoutExecutorService);
+ const executor = createExecutor();
+ let resolveFirstStart: (result: IDocLayoutStartResult) => void = () => {};
+ vi.mocked(executor.startLayout)
+ .mockImplementationOnce(() => new Promise((resolve) => {
+ resolveFirstStart = resolve;
+ }))
+ .mockImplementation(async (request) =>
+ createStartResult(request.modelRevision, request.metricsRevision, getRequestIdentity(request)));
+ service.register(executor);
+ univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createDocumentData('traditional-doc', DocumentFlavor.TRADITIONAL)
+ );
+ await Promise.resolve();
+
+ const firstStart = service.startLayout(createMountIdentity(), { reason: 'edit', anchor: 5 }, 32);
+ await vi.waitFor(() => expect(executor.startLayout).toHaveBeenCalledTimes(1));
+ const supersededStart = service.startLayout(createMountIdentity('mount-1', 2), { reason: 'edit', anchor: 6 }, 32);
+ const latestStart = service.startLayout(createMountIdentity('mount-1', 3), { reason: 'edit', anchor: 7 }, 32);
+ resolveFirstStart(createStartResult(0));
+
+ await expect(firstStart).resolves.toEqual(createStartResult(0));
+ await expect(supersededStart).resolves.toEqual({ status: DocLayoutSessionStatus.SUPERSEDED });
+ await expect(latestStart).resolves.toEqual(createStartResult(0, 3, createMountIdentity('mount-1', 3)));
+ expect(executor.startLayout).toHaveBeenCalledTimes(2);
+ expect(executor.startLayout).toHaveBeenLastCalledWith(expect.objectContaining({ anchor: 7 }));
+ });
+
+ it('keeps queued starts for different document mounts independent', async () => {
+ const injector = univer.__getInjector();
+ const service = injector.get(DocLayoutExecutorService);
+ const executor = createExecutor();
+ let resolveFirstStart: (result: IDocLayoutStartResult) => void = () => {};
+ vi.mocked(executor.startLayout)
+ .mockImplementationOnce(() => new Promise((resolve) => {
+ resolveFirstStart = resolve;
+ }))
+ .mockImplementation(async (request) =>
+ createStartResult(request.modelRevision, request.metricsRevision, getRequestIdentity(request)));
+ service.register(executor);
+ univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createDocumentData('traditional-doc', DocumentFlavor.TRADITIONAL)
+ );
+ await Promise.resolve();
+
+ const firstMountStart = service.startLayout(
+ createMountIdentity(),
+ { reason: 'edit', anchor: 5 },
+ 32
+ );
+ await vi.waitFor(() => expect(executor.startLayout).toHaveBeenCalledTimes(1));
+ const secondMountStart = service.startLayout(
+ createMountIdentity('mount-2'),
+ { reason: 'edit', anchor: 6 },
+ 32
+ );
+ resolveFirstStart(createStartResult(0));
+
+ await expect(firstMountStart).resolves.toEqual(createStartResult(0));
+ await expect(secondMountStart).resolves.toEqual(createStartResult(0, 1, createMountIdentity('mount-2')));
+ expect(executor.startLayout).toHaveBeenCalledTimes(2);
+ expect(executor.startLayout).toHaveBeenLastCalledWith(expect.objectContaining({
+ mountId: 'mount-2',
+ anchor: 6,
+ }));
+
+ await service.disposeLayoutMount(createMountIdentity());
+ expect(executor.disposeLayoutMount).toHaveBeenCalledWith({
+ unitId: 'traditional-doc',
+ mountId: 'mount-1',
+ mountEpoch: 1,
+ viewportEpoch: 1,
+ });
+ });
+});
diff --git a/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.ts b/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.ts
index d8f8e36733..6bb0011400 100644
--- a/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.ts
+++ b/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.ts
@@ -127,6 +127,57 @@ describe('DocSelectionManagerService', () => {
sub.unsubscribe();
});
+ it('preserves active editing state when refreshed layout geometry replaces the selection', () => {
+ const service = createService();
+ const refreshes: unknown[] = [];
+ const sub = service.refreshSelection$.subscribe((value) => refreshes.push(value));
+ service.__TEST_ONLY_setCurrentSelection({ unitId: 'doc-1', subUnitId: 'doc-1' });
+ service.__TEST_ONLY_add([{
+ startOffset: 2,
+ endOffset: 2,
+ collapsed: true,
+ isActive: true,
+ }]);
+
+ service.refreshSelection(undefined, true);
+
+ expect(refreshes.at(-1)).toEqual({
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ docRanges: [expect.objectContaining({ startOffset: 2, endOffset: 2 })],
+ isEditing: true,
+ options: undefined,
+ });
+ sub.unsubscribe();
+ });
+
+ it('replaces logical selection state without publishing a render refresh', () => {
+ const service = createService();
+ const refreshes: unknown[] = [];
+ const sub = service.refreshSelection$.subscribe((value) => refreshes.push(value));
+ service.__TEST_ONLY_setCurrentSelection({ unitId: 'doc-1', subUnitId: 'doc-1' });
+
+ service.replaceSelectionInfoWithoutRefresh({
+ textRanges: [{
+ startOffset: 20,
+ endOffset: 20,
+ collapsed: true,
+ isActive: true,
+ }],
+ rectRanges: [],
+ segmentId: '',
+ segmentPage: -1,
+ isEditing: true,
+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ options: { keepVisible: true },
+ }, { unitId: 'doc-1', subUnitId: 'doc-1' });
+
+ expect(service.getActiveTextRange()?.endOffset).toBe(20);
+ expect(service.getSelectionInfo()?.isEditing).toBe(true);
+ expect(refreshes).toEqual([null]);
+ sub.unsubscribe();
+ });
+
it('replaces render selections, publishes them, and sorts text and rect ranges together', async () => {
const service = createService();
const selections: unknown[] = [];
diff --git a/packages/docs/src/services/__tests__/doc-skeleton-manager.service.spec.ts b/packages/docs/src/services/__tests__/doc-skeleton-manager.service.spec.ts
index eaf179172b..850f802375 100644
--- a/packages/docs/src/services/__tests__/doc-skeleton-manager.service.spec.ts
+++ b/packages/docs/src/services/__tests__/doc-skeleton-manager.service.spec.ts
@@ -14,10 +14,17 @@
* limitations under the License.
*/
+import type { IDocLayoutExecutor } from '../doc-layout-executor.service';
import {
+ CommandService,
+ ConfigService,
ContextService,
DesktopLogService,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
DocumentDataModel,
+ DocumentFlavor,
+ ICommandService,
+ IConfigService,
IContextService,
ILogService,
Injector,
@@ -27,11 +34,12 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { DocLayoutExecutorService, DocLayoutExecutorType, DocLayoutSessionStatus } from '../doc-layout-executor.service';
import { DocSkeletonManagerService } from '../doc-skeleton-manager.service';
-function createDocument() {
+function createDocument(options?: { documentFlavor?: DocumentFlavor; id?: string }) {
return new DocumentDataModel({
- id: 'doc-1',
+ id: options?.id ?? 'doc-1',
body: {
dataStream: 'Hello\r\n',
paragraphs: [{ paragraphId: 'p1', startIndex: 5 }],
@@ -43,16 +51,67 @@ function createDocument() {
},
documentStyle: {
pageSize: { width: 594, height: 840 },
+ documentFlavor: options?.documentFlavor ?? DocumentFlavor.TRADITIONAL,
},
});
}
+function createExecutor(): IDocLayoutExecutor {
+ return {
+ type: DocLayoutExecutorType.WORKER,
+ initialize: async () => {},
+ recover: async () => {},
+ createSession: async () => {},
+ startLayout: async () => ({ status: DocLayoutSessionStatus.NOT_FOUND }),
+ stepLayout: async () => {
+ throw new Error('not used');
+ },
+ publishBacklog: async () => {
+ throw new Error('not used');
+ },
+ getLayoutPage: async () => {
+ throw new Error('not used');
+ },
+ cancelLayout: async () => {},
+ getPerformanceMetrics: async () => ({
+ mutationTransferMs: [],
+ patchTransferMs: [],
+ snapshotTransferMs: [],
+ }),
+ resetPerformanceMetrics: async () => {},
+ disposeLayoutMount: async () => {},
+ disposeSession: async () => {},
+ };
+}
+
+function createService(document: DocumentDataModel, registerExecutor = false) {
+ const injector = new Injector();
+ injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([IConfigService, { useClass: ConfigService }]);
+ injector.add([ICommandService, { useClass: CommandService }]);
+ injector.add([ILogService, { useClass: DesktopLogService }]);
+ injector.add([LocaleService]);
+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
+ injector.add([DocLayoutExecutorService]);
+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;
+ univerInstanceService.__addUnit(document);
+ if (registerExecutor) {
+ injector.get(DocLayoutExecutorService).register(createExecutor());
+ }
+
+ return injector.createInstance(DocSkeletonManagerService, {
+ unit: document,
+ unitId: document.getUnitId(),
+ type: UniverInstanceType.UNIVER_DOC,
+ });
+}
+
describe('DocSkeletonManagerService', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
- it('builds and publishes a document skeleton for the render context document', () => {
+ it('builds and publishes a document skeleton for the render context document', async () => {
vi.stubGlobal('document', {
getElementById: () => null,
getElementsByTagName: () => [{ appendChild: vi.fn() }],
@@ -71,20 +130,8 @@ describe('DocSkeletonManagerService', () => {
}),
}),
});
- const injector = new Injector();
- injector.add([IContextService, { useClass: ContextService }]);
- injector.add([ILogService, { useClass: DesktopLogService }]);
- injector.add([LocaleService]);
- injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
const document = createDocument();
- const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;
- univerInstanceService.__addUnit(document);
-
- const service = injector.createInstance(DocSkeletonManagerService, {
- unit: document,
- unitId: 'doc-1',
- type: UniverInstanceType.UNIVER_DOC,
- } as never);
+ const service = createService(document);
expect(service.getViewModel().getDataModel().getUnitId()).toBe('doc-1');
expect(service.getSkeleton()).toBeTruthy();
@@ -95,6 +142,52 @@ describe('DocSkeletonManagerService', () => {
expect(skeleton).toBe(service.getSkeleton());
expect(publishedSkeletons).toEqual([skeleton, skeleton]);
+ await expect(service.getLayoutPerformanceMetrics()).resolves.toEqual({
+ hydrationMs: [],
+ mutationTransferMs: [],
+ patchTransferMs: [],
+ snapshotTransferMs: [],
+ });
subscription.unsubscribe();
});
+
+ it.each([
+ ['internal editor', createDocument({ id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY, documentFlavor: DocumentFlavor.UNSPECIFIED })],
+ ['unspecified document', createDocument({ id: 'unspecified-doc', documentFlavor: DocumentFlavor.UNSPECIFIED })],
+ ])('calculates %s synchronously before publishing', (_label, document) => {
+ const service = createService(document);
+
+ expect(service.getSkeleton().getSkeletonData()).not.toBeNull();
+ expect(service.supportsIncrementalLayout()).toBe(false);
+ });
+
+ it.each([
+ DocumentFlavor.TRADITIONAL,
+ DocumentFlavor.MODERN,
+ ])('keeps an interactive document synchronous without a registered executor: %s', (documentFlavor) => {
+ const service = createService(createDocument({ documentFlavor }));
+
+ expect(service.supportsIncrementalLayout()).toBe(false);
+ expect(service.getSkeleton().getSkeletonData()).not.toBeNull();
+ });
+
+ it.each([
+ DocumentFlavor.TRADITIONAL,
+ DocumentFlavor.MODERN,
+ ])('enables incremental layout for a registered executor and interactive flavor: %s', (documentFlavor) => {
+ const service = createService(createDocument({ documentFlavor }), true);
+
+ expect(service.supportsIncrementalLayout()).toBe(true);
+ expect(service.getSkeleton().getSkeletonData()).toBeUndefined();
+ });
+
+ it('keeps an internal editor synchronous even if its flavor is paginated', () => {
+ const service = createService(createDocument({
+ id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ }));
+
+ expect(service.supportsIncrementalLayout()).toBe(false);
+ expect(service.getSkeleton().getSkeletonData()).not.toBeNull();
+ });
});
diff --git a/packages/docs/src/services/__tests__/document-layout-snapshot.spec.ts b/packages/docs/src/services/__tests__/document-layout-snapshot.spec.ts
new file mode 100644
index 0000000000..07bf0e3244
--- /dev/null
+++ b/packages/docs/src/services/__tests__/document-layout-snapshot.spec.ts
@@ -0,0 +1,74 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentData } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { createDocumentLayoutSnapshot } from '../document-layout-snapshot';
+
+describe('createDocumentLayoutSnapshot', () => {
+ it('excludes exchange-only resources while preserving layout metadata', () => {
+ const snapshot: IDocumentData = {
+ id: 'layout-snapshot',
+ documentStyle: {},
+ resources: [{ name: 'DOC_RESOURCE', data: 'large-resource-payload' }],
+ body: {
+ dataStream: '\b\r\n',
+ paragraphs: [{ startIndex: 1, paragraphId: 'paragraph-1' }],
+ customBlocks: [{
+ startIndex: 0,
+ blockId: 'drawing-1',
+ docxRawXml: '<w:r>large raw XML</w:r>',
+ docxExportTs: { fs: 20 },
+ }],
+ docxRawCustomBlocks: [{
+ startIndex: 0,
+ blockId: 'raw-1',
+ docxRawXml: '<w:r>opaque</w:r>',
+ }],
+ docxRawBlocks: [{ startIndex: 0, xml: '<w:proofErr />' }],
+ docxExportExcludedRanges: [{ start: 0, end: 1 }],
+ payloads: { clipboard: 'large clipboard payload' },
+ },
+ headers: {
+ header: {
+ headerId: 'header',
+ body: {
+ dataStream: '\r\n',
+ docxRawBlocks: [{ startIndex: 0, xml: '<w:header />' }],
+ },
+ },
+ },
+ };
+
+ const layoutSnapshot = createDocumentLayoutSnapshot(snapshot);
+
+ expect(layoutSnapshot.resources).toBeUndefined();
+ expect(layoutSnapshot.body).toMatchObject({
+ dataStream: '\b\r\n',
+ paragraphs: [{ startIndex: 1, paragraphId: 'paragraph-1' }],
+ customBlocks: [{ startIndex: 0, blockId: 'drawing-1' }],
+ });
+ expect(layoutSnapshot.body?.customBlocks?.[0]).not.toHaveProperty('docxRawXml');
+ expect(layoutSnapshot.body?.customBlocks?.[0]).not.toHaveProperty('docxExportTs');
+ expect(layoutSnapshot.body?.docxRawCustomBlocks).toBeUndefined();
+ expect(layoutSnapshot.body?.docxRawBlocks).toBeUndefined();
+ expect(layoutSnapshot.body?.docxExportExcludedRanges).toBeUndefined();
+ expect(layoutSnapshot.body?.payloads).toBeUndefined();
+ expect(layoutSnapshot.headers?.header.body.docxRawBlocks).toBeUndefined();
+ expect(snapshot.resources).toHaveLength(1);
+ expect(snapshot.body?.customBlocks?.[0].docxRawXml).toContain('large raw XML');
+ });
+});
diff --git a/packages/docs/src/services/doc-layout-executor.service.ts b/packages/docs/src/services/doc-layout-executor.service.ts
new file mode 100644
index 0000000000..1f803a2820
--- /dev/null
+++ b/packages/docs/src/services/doc-layout-executor.service.ts
@@ -0,0 +1,776 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel, IDisposable, IDocumentData, ILanguagePack, JSONXActions, LocaleType, Nullable } from '@univerjs/core';
+import type { IDocsCustomBlockRenderViewport, IDocumentLayoutPagePublication, IDocumentLayoutSessionStartOptions, IDocumentLayoutStepResult } from '@univerjs/engine-render';
+import type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';
+import {
+ Disposable,
+
+ DocumentFlavor,
+ ICommandService,
+
+ ILogService,
+ Inject,
+ isInternalEditorID,
+ IUniverInstanceService,
+ JSONX,
+
+ LocaleService,
+
+ requestImmediateMacroTask,
+ toDisposable,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { getDocsCustomBlockRenderViewport } from '@univerjs/engine-render';
+import { BehaviorSubject } from 'rxjs';
+import { RICH_TEXT_EDITING_MUTATION_ID } from '../commands/mutations/core-editing.mutation-id';
+import { createDocumentLayoutSnapshot } from './document-layout-snapshot';
+
+export enum DocLayoutExecutorType {
+ MAIN_THREAD = 'main-thread',
+ WORKER = 'worker',
+}
+
+export enum DocLayoutSessionStatus {
+ ACCEPTED = 'accepted',
+ NOT_FOUND = 'not-found',
+ RESNAPSHOT_REQUIRED = 'resnapshot-required',
+ SUPERSEDED = 'superseded',
+}
+
+export enum DocLayoutExecutorState {
+ UNREGISTERED = 'unregistered',
+ INITIALIZING = 'initializing',
+ ACTIVE = 'active',
+ RECOVERING = 'recovering',
+ FAILED = 'failed',
+}
+
+export interface IDocLayoutExecutorStatus {
+ state: DocLayoutExecutorState;
+ executor: DocLayoutExecutorType | null;
+ diagnostic: string | null;
+ recoveryUnitId: string | null;
+}
+
+export interface IDocLayoutPerformanceMetrics {
+ hydrationMs: number[];
+ mutationTransferMs: number[];
+ patchTransferMs: number[];
+ snapshotTransferMs: number[];
+}
+
+export interface IDocLayoutCreateSessionRequest {
+ unitId: string;
+ sessionEpoch: number;
+ snapshot: IDocumentData;
+ modelRevision: number;
+ locale: LocaleType;
+ localeData?: ILanguagePack;
+ direction: 'ltr' | 'rtl';
+}
+
+export interface IDocLayoutDisposeSessionRequest {
+ unitId: string;
+ sessionEpoch: number;
+}
+
+export interface IDocLayoutMutationProjection {
+ baseRevision: number;
+ modelRevision: number;
+ actions: JSONXActions;
+}
+
+export interface IDocLayoutMountIdentity {
+ unitId: string;
+ mountId: string;
+ mountEpoch: number;
+ viewportEpoch: number;
+}
+
+export interface IDocLayoutStartRequest extends IDocLayoutMountIdentity {
+ metricsRevision: number;
+ baseRevision: number;
+ modelRevision: number;
+ mutations: IDocLayoutMutationProjection[];
+ reason: 'initial' | 'edit';
+ anchor?: number;
+ priorityAnchor?: number;
+ invalidation?: IDocumentLayoutSessionStartOptions['invalidation'];
+ customBlockViewports: Record<string, IDocsCustomBlockRenderViewport>;
+ budgetMs: number;
+}
+
+export type IDocLayoutStartResult =
+ | { status: DocLayoutSessionStatus.ACCEPTED; step: IDocLayoutStepResult }
+ | { status: DocLayoutSessionStatus.NOT_FOUND }
+ | { status: DocLayoutSessionStatus.SUPERSEDED }
+ | { status: DocLayoutSessionStatus.RESNAPSHOT_REQUIRED; modelRevision: number };
+
+export interface IDocLayoutStepRequest extends IDocLayoutMountIdentity {
+ generation: number;
+ budgetMs: number;
+}
+
+export interface IDocLayoutPageRequest extends IDocLayoutMountIdentity {
+ pageIndex: number;
+}
+
+export interface IDocLayoutPageResult extends IDocLayoutMountIdentity {
+ modelRevision: number;
+ metricsRevision: number;
+ page: IDocumentLayoutPagePublication | null;
+}
+
+export interface IDocLayoutCancelRequest extends IDocLayoutMountIdentity {
+ generation?: number;
+}
+
+export type IDocLayoutDisposeMountRequest = IDocLayoutMountIdentity;
+
+export interface IDocLayoutStepResult extends IDocumentLayoutStepResult, IDocLayoutMountIdentity {
+ modelRevision: number;
+ metricsRevision: number;
+}
+
+export interface IDocLayoutExecutor {
+ readonly type: DocLayoutExecutorType;
+ initialize(): Promise<void>;
+ recover(): Promise<void>;
+ /**
+ * Capture the request synchronously before returning. The source document model remains mutable
+ * while the returned promise tracks remote session creation.
+ */
+ createSession(request: IDocLayoutCreateSessionRequest): Promise<void>;
+ startLayout(request: IDocLayoutStartRequest): Promise<IDocLayoutStartResult>;
+ stepLayout(request: IDocLayoutStepRequest): Promise<IDocLayoutStepResult>;
+ publishBacklog(request: Omit<IDocLayoutStepRequest, 'budgetMs'>): Promise<IDocLayoutStepResult>;
+ getLayoutPage(request: IDocLayoutPageRequest): Promise<IDocLayoutPageResult>;
+ cancelLayout(request: IDocLayoutCancelRequest): Promise<void>;
+ getPerformanceMetrics(unitId: string): Promise<Omit<IDocLayoutPerformanceMetrics, 'hydrationMs'>>;
+ resetPerformanceMetrics(unitId: string): Promise<void>;
+ disposeLayoutMount(request: IDocLayoutDisposeMountRequest): Promise<void>;
+ disposeSession(request: IDocLayoutDisposeSessionRequest): Promise<void>;
+}
+
+interface IDocLayoutManagedSession {
+ sessionEpoch: number;
+ modelRevision: number;
+ sourceMutationRevision: number;
+ workerRevision: number;
+ pendingMutations: IDocLayoutMutationProjection[];
+ latestStarts: Map<string, {
+ startId: number;
+ mountEpoch: number;
+ viewportEpoch: number;
+ }>;
+ queue: Promise<void>;
+ needsResnapshot: boolean;
+ disposed: boolean;
+ cancelPendingCreateTask: (() => void) | null;
+}
+
+function isRichTextEditingMutationParams(value: unknown): value is IRichTextEditingMutationParams {
+ return typeof value === 'object' && value != null &&
+ 'unitId' in value && typeof value.unitId === 'string' &&
+ 'actions' in value;
+}
+
+function collectCustomBlockViewports(dataModel: DocumentDataModel): Record<string, IDocsCustomBlockRenderViewport> {
+ const snapshot = dataModel.getSnapshot();
+ const documentStyle = snapshot.documentStyle;
+ const viewports: Record<string, IDocsCustomBlockRenderViewport> = {};
+
+ for (const customBlock of snapshot.body?.customBlocks ?? []) {
+ const drawing = snapshot.drawings?.[customBlock.blockId];
+ if (drawing == null) {
+ continue;
+ }
+
+ const viewport = getDocsCustomBlockRenderViewport(dataModel.getUnitId(), customBlock.blockId, {
+ fallbackHeight: drawing.docTransform.size.height ?? 0,
+ fallbackWidth: drawing.docTransform.size.width ?? 0,
+ pageMarginLeft: documentStyle.marginLeft,
+ pageMarginRight: documentStyle.marginRight,
+ pageWidth: documentStyle.pageSize?.width,
+ });
+ if (viewport != null) {
+ viewports[customBlock.blockId] = viewport;
+ }
+ }
+
+ return viewports;
+}
+
+export interface IDocLayoutStartOptions {
+ reason: 'initial' | 'edit';
+ anchor?: number;
+ priorityAnchor?: number;
+ invalidation?: IDocumentLayoutSessionStartOptions['invalidation'];
+}
+
+export class DocLayoutExecutorService extends Disposable {
+ private static readonly _performanceSampleLimit = 2048;
+ private _executor: Nullable<IDocLayoutExecutor> = null;
+ private _executorReady: Promise<void> | null = null;
+ private _recoveryFailure: { diagnostic: string; unitId: string } | null = null;
+ private _sessionEpoch = 0;
+ private readonly _sessions = new Map<string, IDocLayoutManagedSession>();
+ private readonly _hydrationSamples = new Map<string, number[]>();
+ private readonly _executorStatus$ = new BehaviorSubject<IDocLayoutExecutorStatus>({
+ state: DocLayoutExecutorState.UNREGISTERED,
+ executor: null,
+ diagnostic: null,
+ recoveryUnitId: null,
+ });
+
+ readonly executorStatus$ = this._executorStatus$.asObservable();
+
+ constructor(
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @ILogService private readonly _logService: ILogService
+ ) {
+ super();
+
+ this.disposeWithMe(
+ this._univerInstanceService
+ .getTypeOfUnitAdded$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
+ .subscribe(({ unit }) => this._createSessionIfEligible(unit))
+ );
+ this.disposeWithMe(
+ this._univerInstanceService
+ .getTypeOfUnitDisposed$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
+ .subscribe((unit) => this._disposeSession(unit.getUnitId()))
+ );
+ this.disposeWithMe(this._commandService.onCommandExecuted((command) => {
+ if (command.id !== RICH_TEXT_EDITING_MUTATION_ID) {
+ return;
+ }
+
+ const params = command.params;
+ if (!isRichTextEditingMutationParams(params)) {
+ this._logService.warn('[DocLayoutExecutorService]: ignored malformed document mutation parameters.');
+ return;
+ }
+ this._enqueueCommittedMutation(params);
+ }));
+ this.disposeWithMe(this._localeService.localeChanged$.subscribe(() => {
+ for (const unitId of this._sessions.keys()) {
+ const dataModel = this._getEligibleModel(unitId);
+ if (dataModel != null) {
+ this._replaceSession(dataModel).catch((error: unknown) => {
+ this._logService.error('[DocLayoutExecutorService]: failed to refresh Worker locale.', error);
+ });
+ }
+ }
+ }));
+ }
+
+ register(executor: IDocLayoutExecutor): IDisposable {
+ if (this._executor != null) {
+ throw new Error('A document layout executor is already registered.');
+ }
+
+ this._executor = executor;
+ this._recoveryFailure = null;
+ this._executorStatus$.next({
+ state: DocLayoutExecutorState.INITIALIZING,
+ executor: executor.type,
+ diagnostic: null,
+ recoveryUnitId: null,
+ });
+ const executorReady = executor.initialize();
+ this._executorReady = executorReady;
+ executorReady.then(() => {
+ if (this._executor === executor) {
+ this._executorStatus$.next({
+ state: DocLayoutExecutorState.ACTIVE,
+ executor: executor.type,
+ diagnostic: null,
+ recoveryUnitId: null,
+ });
+ }
+ }).catch((error: unknown) => {
+ if (this._executor !== executor) {
+ return;
+ }
+ this._executor = null;
+ this._executorReady = null;
+ this._disposeManagedSessions();
+ this._sessions.clear();
+ const diagnostic = error instanceof Error ? error.message : String(error);
+ this._executorStatus$.next({
+ state: DocLayoutExecutorState.FAILED,
+ executor: executor.type,
+ diagnostic,
+ recoveryUnitId: null,
+ });
+ this._logService.error('[DocLayoutExecutorService]: document layout executor initialization failed.', error);
+ });
+ for (const unit of this._univerInstanceService.getAllUnitsForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)) {
+ this._createSessionIfEligible(unit);
+ }
+
+ return toDisposable(() => {
+ if (this._executor === executor) {
+ this._executor = null;
+ this._executorReady = null;
+ this._disposeManagedSessions();
+ this._sessions.clear();
+ this._executorStatus$.next({
+ state: DocLayoutExecutorState.UNREGISTERED,
+ executor: null,
+ diagnostic: null,
+ recoveryUnitId: null,
+ });
+ }
+ });
+ }
+
+ getExecutor(): Nullable<IDocLayoutExecutor> {
+ return this._executor;
+ }
+
+ getExecutorStatus(): IDocLayoutExecutorStatus {
+ return this._executorStatus$.value;
+ }
+
+ async getPerformanceMetrics(unitId: string): Promise<IDocLayoutPerformanceMetrics> {
+ const executorMetrics = await this._executor?.getPerformanceMetrics(unitId);
+ return {
+ hydrationMs: [...(this._hydrationSamples.get(unitId) ?? [])],
+ mutationTransferMs: [...(executorMetrics?.mutationTransferMs ?? [])],
+ patchTransferMs: [...(executorMetrics?.patchTransferMs ?? [])],
+ snapshotTransferMs: [...(executorMetrics?.snapshotTransferMs ?? [])],
+ };
+ }
+
+ async resetPerformanceMetrics(unitId: string): Promise<void> {
+ this._hydrationSamples.delete(unitId);
+ await this._executor?.resetPerformanceMetrics(unitId);
+ }
+
+ recordHydrationDuration(unitId: string, durationMs: number): void {
+ this._appendPerformanceSample(this._hydrationSamples, unitId, durationMs);
+ }
+
+ async recoverExecutor(unitId: string, diagnostic: string): Promise<void> {
+ const executor = this._requireExecutor();
+ this._executorStatus$.next({
+ state: DocLayoutExecutorState.RECOVERING,
+ executor: executor.type,
+ diagnostic,
+ recoveryUnitId: unitId,
+ });
+ for (const session of this._sessions.values()) {
+ this._markSessionDisposed(session);
+ }
+ this._sessions.clear();
+ this._hydrationSamples.clear();
+
+ try {
+ const executorReady = executor.recover();
+ this._executorReady = executorReady;
+ await executorReady;
+ } catch (error) {
+ const recoveryDiagnostic = error instanceof Error ? error.message : String(error);
+ this._executor = null;
+ this._executorReady = null;
+ this._recoveryFailure = { diagnostic: recoveryDiagnostic, unitId };
+ this._executorStatus$.next({
+ state: DocLayoutExecutorState.RECOVERING,
+ executor: executor.type,
+ diagnostic: recoveryDiagnostic,
+ recoveryUnitId: unitId,
+ });
+ throw error;
+ }
+ }
+
+ completeRecovery(unitId: string): void {
+ const status = this._executorStatus$.value;
+ if (status.state !== DocLayoutExecutorState.RECOVERING || status.recoveryUnitId !== unitId) {
+ return;
+ }
+ const recoveryFailure = this._recoveryFailure?.unitId === unitId
+ ? this._recoveryFailure
+ : null;
+ this._recoveryFailure = null;
+ this._executorStatus$.next({
+ state: recoveryFailure == null ? DocLayoutExecutorState.ACTIVE : DocLayoutExecutorState.FAILED,
+ executor: status.executor,
+ diagnostic: recoveryFailure?.diagnostic ?? null,
+ recoveryUnitId: null,
+ });
+ }
+
+ async startLayout(
+ identity: IDocLayoutMountIdentity,
+ options: IDocLayoutStartOptions,
+ budgetMs: number
+ ): Promise<IDocLayoutStartResult | null> {
+ const { unitId } = identity;
+ const executor = this._executor;
+ const dataModel = this._getEligibleModel(unitId);
+ if (executor == null || dataModel == null) {
+ return null;
+ }
+
+ let session = this._sessions.get(unitId);
+ if (session != null && session.sourceMutationRevision !== dataModel.getMutationRevision()) {
+ session.needsResnapshot = true;
+ }
+ if (session == null || session.needsResnapshot) {
+ session = await this._replaceSession(dataModel);
+ }
+
+ let result = await this._startSynchronizedLayout(executor, session, identity, options, budgetMs);
+ if (
+ result.status === DocLayoutSessionStatus.NOT_FOUND ||
+ result.status === DocLayoutSessionStatus.RESNAPSHOT_REQUIRED
+ ) {
+ session = await this._replaceSession(dataModel);
+ result = await this._startSynchronizedLayout(executor, session, identity, options, budgetMs);
+ }
+
+ return result;
+ }
+
+ stepLayout(request: IDocLayoutStepRequest): Promise<IDocLayoutStepResult> {
+ const executor = this._requireExecutor();
+ return executor.stepLayout(request);
+ }
+
+ publishBacklog(request: Omit<IDocLayoutStepRequest, 'budgetMs'>): Promise<IDocLayoutStepResult> {
+ const executor = this._requireExecutor();
+ return executor.publishBacklog(request);
+ }
+
+ getLayoutPage(request: IDocLayoutPageRequest): Promise<IDocLayoutPageResult> {
+ const executor = this._requireExecutor();
+ return executor.getLayoutPage(request);
+ }
+
+ cancelLayout(request: IDocLayoutCancelRequest): Promise<void> {
+ const executor = this._executor;
+ return executor == null ? Promise.resolve() : executor.cancelLayout(request);
+ }
+
+ disposeLayoutMount(request: IDocLayoutDisposeMountRequest): Promise<void> {
+ const executor = this._executor;
+ const session = this._sessions.get(request.unitId);
+ const latestStart = session?.latestStarts.get(request.mountId);
+ if (
+ latestStart?.mountEpoch === request.mountEpoch &&
+ latestStart.viewportEpoch === request.viewportEpoch
+ ) {
+ session?.latestStarts.delete(request.mountId);
+ }
+ return executor == null ? Promise.resolve() : executor.disposeLayoutMount(request);
+ }
+
+ override dispose(): void {
+ const executor = this._executor;
+ if (executor != null) {
+ for (const [unitId, session] of this._sessions) {
+ this._markSessionDisposed(session);
+ executor.disposeSession({ unitId, sessionEpoch: session.sessionEpoch }).catch((error: unknown) => {
+ this._logService.error('[DocLayoutExecutorService]: failed to dispose a Worker session.', error);
+ });
+ }
+ }
+ this._sessions.clear();
+ this._executor = null;
+ this._executorReady = null;
+ this._recoveryFailure = null;
+ this._executorStatus$.complete();
+ super.dispose();
+ }
+
+ private _createSessionIfEligible(dataModel: DocumentDataModel): void {
+ if (this._executor == null || !this._isEligible(dataModel) || this._sessions.has(dataModel.getUnitId())) {
+ return;
+ }
+
+ this._replaceSession(dataModel).catch((error: unknown) => {
+ this._logService.error('[DocLayoutExecutorService]: failed to create a Worker session.', error);
+ });
+ }
+
+ private _enqueueCommittedMutation(params: IRichTextEditingMutationParams): void {
+ const executor = this._executor;
+ const dataModel = this._getEligibleModel(params.unitId);
+ if (executor == null || dataModel == null) {
+ return;
+ }
+
+ const session = this._sessions.get(params.unitId);
+ if (session == null) {
+ this._replaceSession(dataModel).catch((error: unknown) => {
+ this._logService.error('[DocLayoutExecutorService]: failed to snapshot a document mutation.', error);
+ });
+ return;
+ }
+
+ if (JSONX.isNoop(params.actions)) {
+ return;
+ }
+ const sourceMutationRevision = dataModel.getMutationRevision();
+ if (sourceMutationRevision !== session.sourceMutationRevision + 1) {
+ session.needsResnapshot = true;
+ return;
+ }
+
+ const baseRevision = session.modelRevision;
+ const modelRevision = baseRevision + 1;
+ session.modelRevision = modelRevision;
+ session.sourceMutationRevision = sourceMutationRevision;
+ session.pendingMutations.push({
+ baseRevision,
+ modelRevision,
+ actions: params.actions,
+ });
+ }
+
+ private async _startSynchronizedLayout(
+ executor: IDocLayoutExecutor,
+ session: IDocLayoutManagedSession,
+ identity: IDocLayoutMountIdentity,
+ options: IDocLayoutStartOptions,
+ budgetMs: number
+ ): Promise<IDocLayoutStartResult> {
+ const { unitId, mountId } = identity;
+ const startId = (session.latestStarts.get(mountId)?.startId ?? 0) + 1;
+ const startIdentity = {
+ startId,
+ mountEpoch: identity.mountEpoch,
+ viewportEpoch: identity.viewportEpoch,
+ };
+ session.latestStarts.set(mountId, startIdentity);
+ const startTask = session.queue.then(async () => {
+ if (session.disposed || this._executor !== executor) {
+ const result: IDocLayoutStartResult = { status: DocLayoutSessionStatus.NOT_FOUND };
+ return result;
+ }
+ const currentModel = this._getEligibleModel(unitId);
+ if (
+ currentModel == null ||
+ currentModel.getMutationRevision() !== session.sourceMutationRevision
+ ) {
+ session.needsResnapshot = true;
+ const result: IDocLayoutStartResult = {
+ status: DocLayoutSessionStatus.RESNAPSHOT_REQUIRED,
+ modelRevision: session.workerRevision,
+ };
+ return result;
+ }
+ if (session.latestStarts.get(mountId) !== startIdentity) {
+ const result: IDocLayoutStartResult = { status: DocLayoutSessionStatus.SUPERSEDED };
+ return result;
+ }
+
+ const mutations = session.pendingMutations.slice();
+ const request: IDocLayoutStartRequest = {
+ ...identity,
+ metricsRevision: startId,
+ baseRevision: session.workerRevision,
+ modelRevision: session.modelRevision,
+ mutations,
+ customBlockViewports: collectCustomBlockViewports(this._getRequiredModel(unitId)),
+ budgetMs,
+ ...options,
+ };
+ const result = await executor.startLayout(request);
+ if (result.status === DocLayoutSessionStatus.ACCEPTED) {
+ session.workerRevision = request.modelRevision;
+ session.pendingMutations.splice(0, mutations.length);
+ } else {
+ session.needsResnapshot = true;
+ }
+ return result;
+ });
+ session.queue = startTask.then(
+ () => undefined,
+ (error: unknown) => {
+ session.needsResnapshot = true;
+ this._logService.error('[DocLayoutExecutorService]: synchronized layout start failed.', error);
+ }
+ );
+ return startTask;
+ }
+
+ private async _replaceSession(dataModel: DocumentDataModel): Promise<IDocLayoutManagedSession> {
+ const executor = this._requireExecutor();
+ const unitId = dataModel.getUnitId();
+ const previous = this._sessions.get(unitId);
+ if (previous != null) {
+ this._markSessionDisposed(previous);
+ }
+
+ const modelRevision = previous?.modelRevision ?? 0;
+ const session: IDocLayoutManagedSession = {
+ sessionEpoch: ++this._sessionEpoch,
+ modelRevision,
+ sourceMutationRevision: dataModel.getMutationRevision(),
+ workerRevision: modelRevision,
+ pendingMutations: [],
+ latestStarts: new Map(),
+ queue: Promise.resolve(),
+ needsResnapshot: false,
+ disposed: false,
+ cancelPendingCreateTask: null,
+ };
+ const createTask = this._createSessionOnNextMacroTask(executor, session, dataModel);
+ session.queue = createTask;
+ this._sessions.set(unitId, session);
+ try {
+ await createTask;
+ } catch (error) {
+ session.needsResnapshot = true;
+ throw error;
+ }
+ return session;
+ }
+
+ private _disposeSession(unitId: string): void {
+ const session = this._sessions.get(unitId);
+ if (session == null) {
+ return;
+ }
+
+ this._markSessionDisposed(session);
+ this._sessions.delete(unitId);
+ this._hydrationSamples.delete(unitId);
+ this._executor?.disposeSession({ unitId, sessionEpoch: session.sessionEpoch }).catch((error: unknown) => {
+ this._logService.error('[DocLayoutExecutorService]: failed to dispose a Worker session.', error);
+ });
+ }
+
+ private _getEligibleModel(unitId: string): Nullable<DocumentDataModel> {
+ const dataModel = this._univerInstanceService.getUnit<DocumentDataModel>(
+ unitId,
+ UniverInstanceType.UNIVER_DOC
+ );
+ return dataModel != null && this._isEligible(dataModel) ? dataModel : null;
+ }
+
+ private _getRequiredModel(unitId: string): DocumentDataModel {
+ const dataModel = this._getEligibleModel(unitId);
+ if (dataModel == null) {
+ throw new Error(`Eligible document model not found for Worker layout: "${unitId}".`);
+ }
+ return dataModel;
+ }
+
+ private _isEligible(dataModel: DocumentDataModel): boolean {
+ if (isInternalEditorID(dataModel.getUnitId())) {
+ return false;
+ }
+
+ const flavor = dataModel.getSnapshot().documentStyle.documentFlavor;
+ return flavor === DocumentFlavor.TRADITIONAL || flavor === DocumentFlavor.MODERN;
+ }
+
+ private _requireExecutor(): IDocLayoutExecutor {
+ if (this._executor == null) {
+ throw new Error('No document layout executor is registered.');
+ }
+ return this._executor;
+ }
+
+ private _appendPerformanceSample(target: Map<string, number[]>, unitId: string, durationMs: number): void {
+ const samples = target.get(unitId) ?? [];
+ samples.push(durationMs);
+ if (samples.length > DocLayoutExecutorService._performanceSampleLimit) {
+ samples.splice(0, samples.length - DocLayoutExecutorService._performanceSampleLimit);
+ }
+ target.set(unitId, samples);
+ }
+
+ private _createSessionOnNextMacroTask(
+ executor: IDocLayoutExecutor,
+ session: IDocLayoutManagedSession,
+ dataModel: DocumentDataModel
+ ): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ const cancelTask = requestImmediateMacroTask(() => {
+ session.cancelPendingCreateTask = null;
+ const unitId = dataModel.getUnitId();
+ if (
+ session.disposed ||
+ this._executor !== executor ||
+ this._sessions.get(unitId) !== session
+ ) {
+ resolve();
+ return;
+ }
+
+ const executorReady = this._executorReady;
+ if (executorReady == null) {
+ resolve();
+ return;
+ }
+ executorReady.then(() => {
+ if (
+ session.disposed ||
+ this._executor !== executor ||
+ this._sessions.get(unitId) !== session ||
+ this._getEligibleModel(unitId) !== dataModel
+ ) {
+ resolve();
+ return;
+ }
+
+ // Mutations committed before the deferred transfer are already present in the
+ // live model snapshot. Fold them into the baseline instead of replaying them.
+ session.sourceMutationRevision = dataModel.getMutationRevision();
+ session.workerRevision = session.modelRevision;
+ session.pendingMutations.length = 0;
+ const request: IDocLayoutCreateSessionRequest = {
+ unitId,
+ sessionEpoch: session.sessionEpoch,
+ snapshot: createDocumentLayoutSnapshot(dataModel.getSnapshot()),
+ modelRevision: session.modelRevision,
+ locale: this._localeService.getCurrentLocale(),
+ localeData: this._localeService.getLocales(),
+ direction: this._localeService.getDirection(),
+ };
+ executor.createSession(request).then(resolve, reject);
+ }, reject);
+ });
+ session.cancelPendingCreateTask = () => {
+ cancelTask();
+ session.cancelPendingCreateTask = null;
+ resolve();
+ };
+ });
+ }
+
+ private _markSessionDisposed(session: IDocLayoutManagedSession): void {
+ session.disposed = true;
+ session.cancelPendingCreateTask?.();
+ session.cancelPendingCreateTask = null;
+ }
+
+ private _disposeManagedSessions(): void {
+ for (const session of this._sessions.values()) {
+ this._markSessionDisposed(session);
+ }
+ }
+}
diff --git a/packages/docs/src/services/doc-selection-manager.service.ts b/packages/docs/src/services/doc-selection-manager.service.ts
index 387311372a..1c31999f6f 100644
--- a/packages/docs/src/services/doc-selection-manager.service.ts
+++ b/packages/docs/src/services/doc-selection-manager.service.ts
@@ -97,12 +97,15 @@ export class DocSelectionManagerService extends RxDisposable {
return this._getTextRanges(params);
}
- refreshSelection(params: Nullable<IDocSelectionManagerSearchParam> = this._currentSelection) {
+ refreshSelection(
+ params: Nullable<IDocSelectionManagerSearchParam> = this._currentSelection,
+ isEditing = false
+ ) {
if (params == null) {
return;
}
- this._refresh(params);
+ this._refresh(params, isEditing);
}
// **Only used in test case** because this does not go through the render layer.
@@ -196,6 +199,25 @@ export class DocSelectionManagerService extends RxDisposable {
});
}
+ /**
+ * Replaces logical selection state without rebuilding render ranges. Atomic
+ * external mutations use this before applying document actions so layout can
+ * follow transformed offsets, then refresh after new geometry is available.
+ */
+ replaceSelectionInfoWithoutRefresh(
+ selectionInfo: IDocSelectionInnerParam,
+ params: Nullable<IDocSelectionManagerSearchParam> = this._currentSelection
+ ): void {
+ if (params == null) {
+ return;
+ }
+
+ this._replaceByParam({
+ ...selectionInfo,
+ ...params,
+ });
+ }
+
// Only use in doc-selection-render.controller.ts
__replaceTextRangesWithNoRefresh(textSelectionInfo: IDocSelectionInnerParam, search: IDocSelectionManagerSearchParam) {
if (this._currentSelection == null) {
@@ -257,7 +279,7 @@ export class DocSelectionManagerService extends RxDisposable {
return this._textSelectionInfo.get(unitId)?.get(subUnitId);
}
- private _refresh(param: IDocSelectionManagerSearchParam): void {
+ private _refresh(param: IDocSelectionManagerSearchParam, isEditing = false): void {
const allTextSelectionInfo = this._getTextRanges(param);
if (allTextSelectionInfo == null) {
@@ -274,7 +296,7 @@ export class DocSelectionManagerService extends RxDisposable {
unitId,
subUnitId,
docRanges,
- isEditing: false,
+ isEditing,
options,
});
}
diff --git a/packages/docs/src/services/doc-skeleton-manager.service.ts b/packages/docs/src/services/doc-skeleton-manager.service.ts
index cc02833fb1..a0947f55ca 100644
--- a/packages/docs/src/services/doc-skeleton-manager.service.ts
+++ b/packages/docs/src/services/doc-skeleton-manager.service.ts
@@ -16,9 +16,10 @@
import type { DocumentDataModel, Nullable } from '@univerjs/core';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
-import { Inject, isInternalEditorID, IUniverInstanceService, LocaleService, RxDisposable, UniverInstanceType } from '@univerjs/core';
+import { DocumentFlavor, Inject, isInternalEditorID, IUniverInstanceService, LocaleService, RxDisposable, UniverInstanceType } from '@univerjs/core';
import { DocumentSkeleton, DocumentViewModel } from '@univerjs/engine-render';
import { BehaviorSubject, takeUntil } from 'rxjs';
+import { DocLayoutExecutorService } from './doc-layout-executor.service';
/**
* This service is for document build and manage doc skeletons. It also manages
@@ -39,9 +40,10 @@ export class DocSkeletonManagerService extends RxDisposable implements IRenderMo
readonly currentViewModel$ = this._currentViewModel$.asObservable();
constructor(
- private readonly _context: IRenderContext<DocumentDataModel>,
+ private readonly _context: Pick<IRenderContext<DocumentDataModel>, 'type' | 'unit' | 'unitId'>,
@Inject(LocaleService) private readonly _localeService: LocaleService,
- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @Inject(DocLayoutExecutorService) private readonly _docLayoutExecutorService: DocLayoutExecutorService
) {
super();
@@ -77,12 +79,28 @@ export class DocSkeletonManagerService extends RxDisposable implements IRenderMo
return this._docViewModel;
}
+ getLayoutPerformanceMetrics(): ReturnType<DocLayoutExecutorService['getPerformanceMetrics']> {
+ return this._docLayoutExecutorService.getPerformanceMetrics(this._context.unitId);
+ }
+
+ supportsIncrementalLayout(): boolean {
+ const documentFlavor = this._context.unit.getSnapshot().documentStyle?.documentFlavor;
+
+ return this._docLayoutExecutorService.getExecutor() != null &&
+ !isInternalEditorID(this._context.unitId) &&
+ (documentFlavor === DocumentFlavor.TRADITIONAL || documentFlavor === DocumentFlavor.MODERN);
+ }
+
recalculate(): DocumentSkeleton {
const skeleton = this._skeleton;
skeleton.calculate();
+ this._publishSkeleton(skeleton);
+ return skeleton;
+ }
+
+ private _publishSkeleton(skeleton: DocumentSkeleton): void {
this._currentSkeletonBefore$.next(skeleton);
this._currentSkeleton$.next(skeleton);
- return skeleton;
}
private _init() {
@@ -111,7 +129,15 @@ export class DocSkeletonManagerService extends RxDisposable implements IRenderMo
this._skeleton = this._buildSkeleton(this._docViewModel);
}
- this.recalculate();
+ if (this.supportsIncrementalLayout()) {
+ // The optional layout executor owns interactive progressive layout. Consumers that
+ // do not register it keep the historical synchronous initialization and editing path.
+ this._publishSkeleton(this._skeleton);
+ } else {
+ // Internal editors, UNSPECIFIED documents, and applications without the optional
+ // executor depend on a complete skeleton immediately for caret/input geometry.
+ this.recalculate();
+ }
// sub: packages/docs/src/services/doc-interceptor/doc-interceptor.service.ts
this._currentViewModel$.next(this._docViewModel);
diff --git a/packages/docs/src/services/document-layout-snapshot.ts b/packages/docs/src/services/document-layout-snapshot.ts
new file mode 100644
index 0000000000..7684e88cf2
--- /dev/null
+++ b/packages/docs/src/services/document-layout-snapshot.ts
@@ -0,0 +1,82 @@
+/**
+ * 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 { ICustomBlock, IDocumentBody, IDocumentData, IFooterData, IHeaderData } from '@univerjs/core';
+
+function projectCustomBlock(block: ICustomBlock): ICustomBlock {
+ const {
+ docxRawXml: _docxRawXml,
+ docxExportTs: _docxExportTs,
+ ...layoutBlock
+ } = block;
+ return layoutBlock;
+}
+
+function projectDocumentBody(body: IDocumentBody): IDocumentBody {
+ const {
+ docxRawCustomBlocks: _docxRawCustomBlocks,
+ docxRawBlocks: _docxRawBlocks,
+ docxExportExcludedRanges: _docxExportExcludedRanges,
+ payloads: _payloads,
+ customBlocks,
+ ...layoutBody
+ } = body;
+ return {
+ ...layoutBody,
+ ...(customBlocks == null ? {} : { customBlocks: customBlocks.map(projectCustomBlock) }),
+ };
+}
+
+function projectHeader(header: IHeaderData): IHeaderData {
+ return {
+ ...header,
+ body: projectDocumentBody(header.body),
+ };
+}
+
+function projectFooter(footer: IFooterData): IFooterData {
+ return {
+ ...footer,
+ body: projectDocumentBody(footer.body),
+ };
+}
+
+/**
+ * Builds the model snapshot owned by the layout Worker. Exchange-only payloads
+ * remain in the authoritative Main model and are deliberately excluded from
+ * 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;
+ return {
+ ...layoutSnapshot,
+ ...(body == null ? {} : { body: projectDocumentBody(body) }),
+ ...(headers == null
+ ? {}
+ : {
+ headers: Object.fromEntries(
+ Object.entries(headers).map(([headerId, header]) => [headerId, projectHeader(header)])
+ ),
+ }),
+ ...(footers == null
+ ? {}
+ : {
+ footers: Object.fromEntries(
+ Object.entries(footers).map(([footerId, footer]) => [footerId, projectFooter(footer)])
+ ),
+ }),
+ };
+}
diff --git a/packages/engine-render/src/__tests__/scene.transformer.spec.ts b/packages/engine-render/src/__tests__/scene.transformer.spec.ts
index c3adfe2c14..ff7abacf2f 100644
--- a/packages/engine-render/src/__tests__/scene.transformer.spec.ts
+++ b/packages/engine-render/src/__tests__/scene.transformer.spec.ts
@@ -78,6 +78,28 @@ describe('Transformer', () => {
engine.dispose();
});
+ it('restores a missing control when an already selected object is activated again', () => {
+ const engine = new Engine('transformer-restore-engine', { elementWidth: 100, elementHeight: 100, dpr: 1 });
+ const scene = new Scene('transformer-restore-scene', engine);
+ const rect = new Rect('transformer-restore-rect', { width: 10, height: 10 });
+ scene.addObject(rect);
+ const transformer = new Transformer(scene);
+ const createControl = vi.fn();
+ const subscription = transformer.createControl$.subscribe(createControl);
+
+ transformer.setSelectedControl(rect);
+ transformer.clearControls();
+ transformer.activeAnObject(rect);
+
+ expect(transformer.getSelectedObjectMap().get(rect.oKey)).toBe(rect);
+ expect(createControl).toHaveBeenCalledTimes(2);
+
+ subscription.unsubscribe();
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ });
+
it('keeps read-only objects selectable without starting a move gesture', () => {
const engine = new Engine('transformer-readonly-engine', { elementWidth: 100, elementHeight: 100, dpr: 1 });
const scene = new Scene('transformer-readonly-scene', engine);
diff --git a/packages/engine-render/src/__tests__/worker-layout.spec.ts b/packages/engine-render/src/__tests__/worker-layout.spec.ts
new file mode 100644
index 0000000000..01d8c913a1
--- /dev/null
+++ b/packages/engine-render/src/__tests__/worker-layout.spec.ts
@@ -0,0 +1,1694 @@
+/**
+ * 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 '../basics/i-document-skeleton-cached';
+import { cpuUsage } from 'node:process';
+import {
+ ColumnLayoutType,
+ ColumnResponsiveType,
+ createDocumentModelWithStyle,
+ DataStreamTreeTokenType,
+ DocumentDataModel,
+ DocumentFlavor,
+ DrawingTypeEnum,
+ JSONX,
+ LocaleService,
+ ObjectRelativeFromH,
+ ObjectRelativeFromV,
+ PositionedObjectLayoutType,
+ PresetListType,
+ TableAlignmentType,
+ TableRowHeightRule,
+ TableSizeType,
+ TableTextWrapType,
+ TextX,
+ TextXActionType,
+ VerticalAlignmentType,
+} from '@univerjs/core';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { DocumentSkeleton } from '../components/docs/layout/doc-skeleton';
+import { DocumentViewModel } from '../components/docs/view-model/document-view-model';
+import { DocumentLayoutSession } from '../worker-layout';
+
+type LayoutPublication = ReturnType<DocumentLayoutSession['step']>['publication'];
+
+function normalizeSkeleton(value: unknown): unknown {
+ if (value instanceof Map) {
+ return [...value].map(([key, item]) => [key, normalizeSkeleton(item)]);
+ }
+ if (Array.isArray(value)) {
+ return value.map(normalizeSkeleton);
+ }
+ if (value != null && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value)
+ // drawingAnchor.elements contains active-layout line references.
+ // Publications preserve the anchor's persistent paragraph/top
+ // semantics and deliberately rebuild those scratch references.
+ .filter(([key]) => key !== 'parent' && key !== 'elements')
+ .map(([key, item]) => [key, normalizeSkeleton(item)])
+ );
+ }
+ return value;
+}
+
+function percentile(samples: number[], ratio: number): number {
+ const sorted = [...samples].sort((a, b) => a - b);
+ return sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * ratio) - 1)] ?? 0;
+}
+
+function expectBoundedPatchTransfer(samples: number[]): void {
+ expect(samples.length).toBeGreaterThan(0);
+ expect(percentile(samples, 0.95)).toBeLessThan(50);
+ expect(Math.max(...samples)).toBeLessThan(100);
+}
+
+function summarizePages(skeleton: ReturnType<DocumentSkeleton['getSkeletonData']>) {
+ return skeleton?.pages.map((page) => ({
+ st: page.st,
+ ed: page.ed,
+ headerId: page.headerId,
+ footerId: page.footerId,
+ drawingIds: [...page.skeDrawings.keys()],
+ tableIds: [...page.skeTables.keys()],
+ columnGroupIds: [...page.skeColumnGroups.keys()],
+ }));
+}
+
+function summarizeDrawingAnchors(skeleton: ReturnType<DocumentSkeleton['getSkeletonData']>) {
+ return [...(skeleton?.drawingAnchor ?? [])].map(([segmentId, anchors]) => ({
+ segmentId,
+ anchors: [...anchors].map(([paragraphIndex, anchor]) => ({
+ paragraphIndex,
+ top: anchor.top,
+ })),
+ }));
+}
+
+function collectNestedElementIds(skeleton: ReturnType<DocumentSkeleton['getSkeletonData']>) {
+ const drawingIds = new Set<string>();
+ const tableIds = new Set<string>();
+ const columnGroupIds = new Set<string>();
+ const visit = (page: IDocumentSkeletonPage): void => {
+ page.skeDrawings.forEach((_drawing, drawingId) => drawingIds.add(drawingId));
+ page.skeTables.forEach((table, tableId) => {
+ tableIds.add(tableId);
+ table.rows.forEach((row) => row.cells.forEach(visit));
+ });
+ page.skeColumnGroups.forEach((columnGroup, columnGroupId) => {
+ columnGroupIds.add(columnGroupId);
+ columnGroup.columns.forEach((column) => visit(column.page));
+ });
+ };
+ skeleton?.pages.forEach(visit);
+ skeleton?.skeHeaders.forEach((pages) => pages.forEach(visit));
+ skeleton?.skeFooters.forEach((pages) => pages.forEach(visit));
+ return { drawingIds, tableIds, columnGroupIds };
+}
+
+describe('worker document layout session', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('publishes structured-cloneable pages without a DOM', () => {
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText(content: string) {
+ return {
+ width: content.length * 7,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 2,
+ };
+ },
+ };
+ }
+ });
+
+ const dataModel = createDocumentModelWithStyle(
+ `${'Worker layout content '.repeat(40)}\rSecond paragraph.\r`,
+ {}
+ );
+ const firstParagraph = dataModel.getBody()?.paragraphs?.[0];
+ if (firstParagraph == null) {
+ throw new Error('Expected the test document first paragraph.');
+ }
+ firstParagraph.bullet = {
+ listId: 'worker-layout-list',
+ listType: PresetListType.ORDER_LIST,
+ nestingLevel: 0,
+ };
+ dataModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.TRADITIONAL });
+ dataModel.updateDocumentDataPageSize(240, 180);
+ const localeService = new LocaleService();
+ const session = new DocumentLayoutSession(dataModel, localeService);
+ const targetModel = new DocumentDataModel(structuredClone(dataModel.getSnapshot()));
+ const targetSkeleton = DocumentSkeleton.create(new DocumentViewModel(targetModel), new LocaleService());
+ targetSkeleton.calculate();
+ const initialTargetPages = [...(targetSkeleton.getSkeletonData()?.pages ?? [])];
+ const synchronousModel = new DocumentDataModel(structuredClone(dataModel.getSnapshot()));
+ const synchronousSkeleton = DocumentSkeleton.create(new DocumentViewModel(synchronousModel), new LocaleService());
+ synchronousSkeleton.calculate();
+ const initialGeneration = session.start({ reason: 'initial' });
+ let initialResult = session.step(initialGeneration, 0);
+ for (let step = 0; step < 1_000 && !initialResult.progress.complete; step++) {
+ initialResult = session.step(initialGeneration, 0);
+ }
+ expect(initialResult.progress.complete).toBe(true);
+
+ const body = dataModel.getBody();
+ if (body == null) {
+ throw new Error('Expected the test document body.');
+ }
+ targetSkeleton.beginExternalLayout({ reason: 'edit' });
+ const generation = session.start({
+ reason: 'edit',
+ anchor: Math.floor(body.dataStream.length / 3),
+ });
+ const publications: LayoutPublication[] = [];
+ const transferDurations: number[] = [];
+ let sawPlaceholderTail = false;
+
+ let result = session.step(generation, 0);
+ publications.push(result.publication);
+ if (result.publication != null) {
+ const transferStart = cpuUsage();
+ const transferredPublication = structuredClone(result.publication);
+ targetSkeleton.applyLayoutPublication(transferredPublication, result.progress);
+ const transferCpu = cpuUsage(transferStart);
+ transferDurations.push((transferCpu.user + transferCpu.system) / 1_000);
+ if (result.progress.didPublishAnchor && !result.progress.complete) {
+ const partialSkeleton = targetSkeleton.getSkeletonData();
+ if (partialSkeleton == null) {
+ throw new Error('Expected a published skeleton.');
+ }
+ const tail = partialSkeleton.pages.slice(result.progress.publishedPageCount);
+ sawPlaceholderTail = tail.length > 0 && tail.every((page) => page.isLayoutPlaceholder);
+ }
+ }
+ for (let step = 0; step < 1_000 && !result.progress.complete; step++) {
+ result = session.step(generation, 0);
+ publications.push(result.publication);
+ if (result.publication != null) {
+ const transferStart = cpuUsage();
+ const transferredPublication = structuredClone(result.publication);
+ targetSkeleton.applyLayoutPublication(transferredPublication, result.progress);
+ const transferCpu = cpuUsage(transferStart);
+ transferDurations.push((transferCpu.user + transferCpu.system) / 1_000);
+ if (result.progress.didPublishAnchor && !result.progress.complete) {
+ const partialSkeleton = targetSkeleton.getSkeletonData();
+ if (partialSkeleton == null) {
+ throw new Error('Expected a published skeleton.');
+ }
+ const tail = partialSkeleton.pages.slice(result.progress.publishedPageCount);
+ sawPlaceholderTail = tail.length > 0 && tail.every((page) => page.isLayoutPlaceholder);
+ }
+ }
+ }
+
+ expect(result.progress).toMatchObject({ complete: true, cancelled: false });
+ expect(sawPlaceholderTail).toBe(true);
+ // Placeholder publication must not mutate the complete layout pages that
+ // the next Main typing generation reuses when the caret crosses a page.
+ expect(initialTargetPages.slice(1).some((page) =>
+ page.sections.length === 0 &&
+ page.skeDrawings.size === 0 &&
+ page.skeTables.size === 0 &&
+ page.skeColumnGroups.size === 0
+ )).toBe(false);
+ const pagePublications = publications.flatMap((publication) =>
+ publication?.kind === 'page' ? publication.pages : []
+ );
+ expect(pagePublications.length).toBeGreaterThan(1);
+ expect(publications.every((publication) =>
+ publication == null || publication.kind !== 'page' || publication.pages.length <= 1
+ )).toBe(true);
+ const geometryPublications = publications.filter((publication) => publication != null);
+ expect(geometryPublications[0]?.resources.reset).toBe(true);
+ expect(geometryPublications.at(-1)?.resources.reset).toBe(true);
+ expect(geometryPublications.slice(1, -1).every((publication) => !publication.resources.reset)).toBe(true);
+ expect(() => structuredClone(publications)).not.toThrow();
+ expect(
+ DocumentLayoutSession.hydratePage(pagePublications[0], dataModel.getSnapshot()).sections.length
+ ).toBeGreaterThan(0);
+ expectBoundedPatchTransfer(transferDurations);
+ expect(synchronousSkeleton.getSkeletonData()?.skeListLevel?.size).toBeGreaterThan(0);
+ expect(synchronousSkeleton.getSkeletonData()?.drawingAnchor?.size).toBeGreaterThan(0);
+ expect(normalizeSkeleton(targetSkeleton.getSkeletonData())).toEqual(
+ normalizeSkeleton(synchronousSkeleton.getSkeletonData())
+ );
+
+ session.dispose();
+ targetSkeleton.dispose();
+ synchronousSkeleton.dispose();
+ dataModel.dispose();
+ targetModel.dispose();
+ synchronousModel.dispose();
+ localeService.dispose();
+ });
+
+ it('keeps only the requested page window materialized on Main and fetches distant pages from Worker', () => {
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText(content: string) {
+ return {
+ width: content.length * 7,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 2,
+ };
+ },
+ };
+ }
+ });
+
+ const content = Array.from(
+ { length: 160 },
+ (_, index) => `Materialized page window paragraph ${index} has enough text to wrap across lines.\r`
+ ).join('');
+ const workerModel = createDocumentModelWithStyle(content, {});
+ workerModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.TRADITIONAL });
+ workerModel.updateDocumentDataPageSize(240, 180);
+ const session = new DocumentLayoutSession(workerModel, new LocaleService());
+ const mainModel = new DocumentDataModel(structuredClone(workerModel.getSnapshot()));
+ const mainSkeleton = DocumentSkeleton.create(
+ new DocumentViewModel(mainModel),
+ new LocaleService()
+ );
+ mainSkeleton.beginExternalLayout({ reason: 'initial' });
+
+ const initialWindow = { startPageIndex: 0, endPageIndex: 4 };
+ const generation = session.start({ reason: 'initial' });
+ let result = session.step(generation, 0);
+ for (let step = 0; step < 4_000; step++) {
+ if (result.publication != null) {
+ mainSkeleton.applyLayoutPublication(
+ structuredClone(result.publication),
+ result.progress,
+ initialWindow
+ );
+ expect(mainSkeleton.getSkeletonData()?.pages.filter((page) =>
+ !page.isLayoutPlaceholder && !page.isMaterializationPlaceholder
+ ).length).toBeLessThanOrEqual(5);
+ }
+ if (result.progress.complete) {
+ break;
+ }
+ result = session.step(generation, 0);
+ }
+
+ const pages = mainSkeleton.getSkeletonData()?.pages;
+ expect(result.progress.complete).toBe(true);
+ expect(pages?.length).toBeGreaterThan(12);
+ expect(pages?.slice(0, 5).every((page) =>
+ !page.isLayoutPlaceholder && !page.isMaterializationPlaceholder
+ )).toBe(true);
+ expect(pages?.slice(5).every((page) => page.isMaterializationPlaceholder)).toBe(true);
+
+ const distantPageIndex = 10;
+ const distantWindow = { startPageIndex: 8, endPageIndex: 12 };
+ for (
+ let pageIndex = distantWindow.startPageIndex;
+ pageIndex <= distantWindow.endPageIndex;
+ pageIndex++
+ ) {
+ const pagePublication = session.getPage(pageIndex);
+ if (pagePublication == null) {
+ throw new Error(`Expected Worker to retain canonical page ${pageIndex}.`);
+ }
+ expect(mainSkeleton.applyLayoutPagePublication(
+ structuredClone(pagePublication),
+ distantWindow
+ )).toBe(true);
+ }
+
+ const materializedPages = mainSkeleton.getSkeletonData()?.pages.filter((page) =>
+ !page.isLayoutPlaceholder && !page.isMaterializationPlaceholder
+ ) ?? [];
+ expect(materializedPages).toHaveLength(5);
+ expect(mainSkeleton.getSkeletonData()?.pages[0].isMaterializationPlaceholder).toBe(true);
+ const distantPublication = session.getPage(distantPageIndex);
+ if (distantPublication == null) {
+ throw new Error('Expected Worker to retain the canonical distant page.');
+ }
+ expect(normalizeSkeleton(mainSkeleton.getSkeletonData()?.pages[distantPageIndex])).toEqual(
+ normalizeSkeleton(DocumentLayoutSession.hydratePage(distantPublication, workerModel.getSnapshot()))
+ );
+
+ const editAnchor = mainSkeleton.getSkeletonData()?.pages[distantPageIndex].st;
+ if (editAnchor == null || editAnchor < 0) {
+ throw new Error('Expected the distant Main page to expose a logical edit anchor.');
+ }
+ const textX = new TextX();
+ textX.push({ t: TextXActionType.RETAIN, len: editAnchor });
+ textX.push({ t: TextXActionType.INSERT, len: 1, body: { dataStream: 'X' } });
+ mainModel.apply(JSONX.getInstance().editOp(textX.serialize(), ['body']));
+ mainSkeleton.getViewModel().reset(mainModel);
+ const mainGeneration = mainSkeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor: editAnchor,
+ priorityAnchor: editAnchor + 1,
+ invalidation: {
+ oldStart: editAnchor,
+ oldEnd: editAnchor,
+ newEnd: editAnchor + 1,
+ },
+ });
+ let mainProgress = mainSkeleton.stepIncrementalLayout(mainGeneration, 0, 1);
+ for (let step = 0; step < 20 && !mainProgress.didPublishAnchor; step++) {
+ mainProgress = mainSkeleton.stepIncrementalLayout(mainGeneration, 0, 1);
+ }
+ expect(mainProgress.didPublishAnchor).toBe(true);
+ expect(mainSkeleton.findNodePositionByCharIndex(editAnchor + 1)).not.toBeNull();
+
+ session.dispose();
+ mainSkeleton.dispose();
+ workerModel.dispose();
+ mainModel.dispose();
+ });
+
+ it('converges a stable edit tail and keeps its completion transfer page-bounded', () => {
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText(content: string) {
+ return {
+ width: content.length * 7,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 2,
+ };
+ },
+ };
+ }
+ });
+
+ const content = Array.from(
+ { length: 240 },
+ (_, index) => `Stable Worker paragraph ${index} leaves room for a local insertion.\r`
+ ).join('');
+ const initialModel = createDocumentModelWithStyle(content, {});
+ initialModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.TRADITIONAL });
+ initialModel.updateDocumentDataPageSize(240, 260);
+ const session = new DocumentLayoutSession(initialModel, new LocaleService());
+ const initialGeneration = session.start({ reason: 'initial' });
+ let initialResult = session.step(initialGeneration, 0);
+ for (let step = 0; step < 2_000 && !initialResult.progress.complete; step++) {
+ initialResult = session.step(initialGeneration, 0);
+ }
+ expect(initialResult.progress.complete).toBe(true);
+
+ const initialSkeleton = DocumentSkeleton.create(
+ new DocumentViewModel(new DocumentDataModel(structuredClone(initialModel.getSnapshot()))),
+ new LocaleService()
+ );
+ initialSkeleton.calculate();
+ const pages = initialSkeleton.getSkeletonData()?.pages ?? [];
+ expect(pages.length).toBeGreaterThan(20);
+ const anchorPageIndex = 8;
+ const anchor = pages[anchorPageIndex].st + 5;
+ const nextSnapshot = structuredClone(initialModel.getSnapshot());
+ const previousDataStream = nextSnapshot.body!.dataStream;
+ nextSnapshot.body!.dataStream = `${previousDataStream.slice(0, anchor)}x${previousDataStream.slice(anchor)}`;
+ for (const paragraph of nextSnapshot.body!.paragraphs ?? []) {
+ if (paragraph.startIndex >= anchor) {
+ paragraph.startIndex++;
+ }
+ }
+ for (const sectionBreak of nextSnapshot.body!.sectionBreaks ?? []) {
+ if (sectionBreak.startIndex >= anchor) {
+ sectionBreak.startIndex++;
+ }
+ }
+ const nextModel = new DocumentDataModel(nextSnapshot);
+ session.resetDataModel(nextModel);
+ const generation = session.start({
+ reason: 'edit',
+ anchor,
+ priorityAnchor: anchor + 1,
+ invalidation: {
+ oldStart: anchor,
+ oldEnd: anchor,
+ newEnd: anchor + 1,
+ },
+ });
+
+ let result = session.step(generation, 0);
+ for (let step = 0; step < 100 && result.publication == null; step++) {
+ result = session.step(generation, 0);
+ }
+ expect(result.publication).not.toBeNull();
+ expect(result.progress).toMatchObject({
+ complete: false,
+ didPublishAnchor: true,
+ });
+
+ const pagePublications: LayoutPublication[] = [result.publication];
+ let layoutStepCount = 0;
+ for (let step = 0; step < 2_000 && !result.progress.complete; step++) {
+ result = session.publishBacklog(generation);
+ if (!result.progress.didPublish) {
+ result = session.step(generation, 0);
+ layoutStepCount++;
+ }
+ pagePublications.push(result.publication);
+ }
+ expect(result.progress).toMatchObject({ complete: true, cancelled: false });
+ expect(layoutStepCount).toBeLessThan(200);
+ expect(pagePublications.every((publication) =>
+ publication?.kind !== 'page' || publication.pages.length <= 1
+ )).toBe(true);
+
+ session.dispose();
+ initialSkeleton.dispose();
+ nextModel.dispose();
+ initialModel.dispose();
+ });
+
+ it('preserves logical offsets across sequential page publications with explicit page breaks', () => {
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText(content: string) {
+ return {
+ width: content.length * 7,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 2,
+ };
+ },
+ };
+ }
+ });
+
+ const pageBreak = DataStreamTreeTokenType.PAGE_BREAK;
+ const phrase = 'The target sentence ends here.';
+ const content = [
+ `First explicit page${pageBreak}`,
+ `Second explicit page${pageBreak}`,
+ `Third explicit page${pageBreak}`,
+ `Fourth explicit page${pageBreak}`,
+ `${phrase}\r`,
+ ].join('');
+ const dataModel = createDocumentModelWithStyle(content, {});
+ dataModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.TRADITIONAL });
+ dataModel.updateDocumentDataPageSize(240, 180);
+ const localeService = new LocaleService();
+ const session = new DocumentLayoutSession(dataModel, localeService);
+ const targetModel = new DocumentDataModel(structuredClone(dataModel.getSnapshot()));
+ const targetSkeleton = DocumentSkeleton.create(new DocumentViewModel(targetModel), new LocaleService());
+ const synchronousModel = new DocumentDataModel(structuredClone(dataModel.getSnapshot()));
+ const synchronousSkeleton = DocumentSkeleton.create(new DocumentViewModel(synchronousModel), new LocaleService());
+ synchronousSkeleton.calculate();
+ targetSkeleton.beginExternalLayout({ reason: 'initial' });
+
+ const generation = session.start({ reason: 'initial' });
+ let result = session.step(generation, 0);
+ for (let step = 0; step < 1_000; step++) {
+ if (result.publication != null) {
+ targetSkeleton.applyLayoutPublication(structuredClone(result.publication), result.progress);
+ }
+ if (result.progress.complete) {
+ break;
+ }
+ result = session.step(generation, 0);
+ }
+
+ expect(result.progress).toMatchObject({ complete: true, cancelled: false });
+ expect(normalizeSkeleton(targetSkeleton.getSkeletonData())).toEqual(
+ normalizeSkeleton(synchronousSkeleton.getSkeletonData())
+ );
+ const expectedOffset = content.indexOf(phrase) + phrase.length;
+ const targetPosition = targetSkeleton.findNodePositionByCharIndex(expectedOffset, true);
+ if (targetPosition == null) {
+ throw new Error('Expected the published Worker skeleton to resolve the target offset');
+ }
+ expect(targetSkeleton.findCharIndexByPosition(targetPosition)).toBe(expectedOffset);
+
+ session.dispose();
+ targetSkeleton.dispose();
+ synchronousSkeleton.dispose();
+ dataModel.dispose();
+ targetModel.dispose();
+ synchronousModel.dispose();
+ localeService.dispose();
+ });
+
+ it('publishes every bridge page from the dirty boundary through a transformed collaboration anchor', () => {
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText(content: string) {
+ return {
+ width: content.length * 7,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 2,
+ };
+ },
+ };
+ }
+ });
+
+ const content = Array.from(
+ { length: 120 },
+ (_, index) => `Collaboration paragraph ${index} spans compact pages.\r`
+ ).join('');
+ const dataModel = createDocumentModelWithStyle(content, {});
+ dataModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.TRADITIONAL });
+ dataModel.updateDocumentDataPageSize(240, 180);
+ const localeService = new LocaleService();
+ const session = new DocumentLayoutSession(dataModel, localeService);
+ const referenceModel = new DocumentDataModel(structuredClone(dataModel.getSnapshot()));
+ const referenceSkeleton = DocumentSkeleton.create(
+ new DocumentViewModel(referenceModel),
+ new LocaleService()
+ );
+ referenceSkeleton.calculate();
+ const localPage = referenceSkeleton.getSkeletonData()?.pages[5];
+ const localOffset = localPage?.sections[0]?.columns[0]?.lines[0]?.st;
+ if (localOffset == null) {
+ throw new Error('Expected a local collaboration anchor on the sixth page.');
+ }
+
+ const initialGeneration = session.start({ reason: 'initial' });
+ let initialResult = session.step(initialGeneration, 0);
+ for (let step = 0; step < 2_000 && !initialResult.progress.complete; step++) {
+ initialResult = session.step(initialGeneration, 0);
+ }
+ expect(initialResult.progress.complete).toBe(true);
+
+ const remoteText = 'REMOTE COLLABORATOR '.repeat(300);
+ const textX = new TextX();
+ textX.push({
+ t: TextXActionType.INSERT,
+ len: remoteText.length,
+ body: { dataStream: remoteText },
+ });
+ dataModel.apply(JSONX.getInstance().editOp(textX.serialize(), ['body']));
+ session.resetDataModel(dataModel);
+
+ const generation = session.start({
+ reason: 'edit',
+ anchor: 0,
+ priorityAnchor: localOffset + remoteText.length,
+ invalidation: {
+ oldStart: 0,
+ oldEnd: 0,
+ newEnd: remoteText.length,
+ },
+ });
+ let result = session.step(generation, 0);
+ for (let step = 0; step < 2_000 && !result.progress.didPublishAnchor; step++) {
+ result = session.step(generation, 0);
+ }
+
+ expect(result.progress.didPublishAnchor).toBe(true);
+ expect(result.progress.publishedPageCount).toBeGreaterThan(2);
+ expect(result.publication?.kind).toBe('page');
+ if (result.publication?.kind !== 'page') {
+ throw new Error('Expected a paginated collaboration publication.');
+ }
+ expect(result.publication.pages.map((page) => page.pageIndex)).toEqual(
+ Array.from({ length: result.progress.publishedPageCount }, (_, pageIndex) => pageIndex)
+ );
+
+ session.dispose();
+ referenceSkeleton.dispose();
+ referenceModel.dispose();
+ dataModel.dispose();
+ localeService.dispose();
+ });
+
+ it('keeps a divergent Main interaction boundary stable while publishing the Worker tail progressively', () => {
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText(content: string) {
+ return {
+ width: content.length * 7,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 2,
+ };
+ },
+ };
+ }
+ });
+
+ const dataModel = createDocumentModelWithStyle(`${'Protected page content '.repeat(240)}\r`, {});
+ dataModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.TRADITIONAL });
+ dataModel.updateDocumentDataPageSize(240, 180);
+ const localeService = new LocaleService();
+ const session = new DocumentLayoutSession(dataModel, localeService);
+ const targetModel = new DocumentDataModel(structuredClone(dataModel.getSnapshot()));
+ const targetSkeleton = DocumentSkeleton.create(new DocumentViewModel(targetModel), new LocaleService());
+ targetSkeleton.calculate();
+ const initialTargetSkeletonData = targetSkeleton.getSkeletonData();
+
+ const initialGeneration = session.start({ reason: 'initial' });
+ let initialResult = session.step(initialGeneration, 0);
+ for (let step = 0; step < 2_000 && !initialResult.progress.complete; step++) {
+ initialResult = session.step(initialGeneration, 0);
+ }
+ expect(initialResult.progress.complete).toBe(true);
+
+ const anchor = Math.floor((dataModel.getBody()?.dataStream.length ?? 0) / 3);
+ const textX = new TextX();
+ textX.push({ t: TextXActionType.RETAIN, len: anchor });
+ textX.push({ t: TextXActionType.INSERT, len: 1, body: { dataStream: 'X' } });
+ const actions = JSONX.getInstance().editOp(textX.serialize(), ['body']);
+ dataModel.apply(actions);
+ targetModel.apply(actions);
+ session.resetDataModel(dataModel);
+ targetSkeleton.getViewModel().reset(targetModel);
+
+ const mainGeneration = targetSkeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor,
+ invalidation: { oldStart: anchor, oldEnd: anchor, newEnd: anchor + 1 },
+ });
+ let mainProgress = targetSkeleton.stepIncrementalLayout(mainGeneration, 8);
+ for (let step = 0; step < 2_000 && !mainProgress.didPublishAnchor; step++) {
+ mainProgress = targetSkeleton.stepIncrementalLayout(mainGeneration, 8);
+ }
+ expect(mainProgress.didPublishAnchor).toBe(true);
+ const protectedPageIndex = targetSkeleton.findNodePositionByCharIndex(anchor)?.page ?? -1;
+ const protectedPage = targetSkeleton.getSkeletonData()?.pages[protectedPageIndex];
+ expect(protectedPageIndex).toBeGreaterThanOrEqual(0);
+ expect(protectedPage).toBeDefined();
+
+ targetSkeleton.beginExternalLayout({
+ reason: 'edit',
+ protectedRange: {
+ mode: 'paginated',
+ startPageIndex: protectedPageIndex,
+ endPageIndex: protectedPageIndex,
+ },
+ });
+ const workerGeneration = session.start({
+ reason: 'edit',
+ anchor,
+ invalidation: { oldStart: anchor, oldEnd: anchor, newEnd: anchor + 1 },
+ });
+ let workerResult = session.step(workerGeneration, 0);
+ let changedProtectedPublication = false;
+ let acceptedPresentationDifference = false;
+ let stagedProtectedPublication = false;
+ let publishedUnprotectedTail = false;
+ let didReplaceProtectedPages = false;
+ for (let step = 0; step < 2_000; step++) {
+ if (workerResult.publication != null) {
+ if (workerResult.publication.kind === 'page' && !changedProtectedPublication) {
+ const protectedPublication = workerResult.publication.pages.find(
+ (page) => page.pageIndex === protectedPageIndex
+ );
+ if (protectedPublication != null) {
+ const presentationOnlyPublication = structuredClone(workerResult.publication);
+ const presentationOnlyProtectedPage = presentationOnlyPublication.pages.find(
+ (page) => page.pageIndex === protectedPageIndex
+ );
+ if (presentationOnlyProtectedPage == null) {
+ throw new Error('Expected a protected page publication.');
+ }
+ presentationOnlyProtectedPage.page.width += 1;
+ expect(() => targetSkeleton.applyLayoutPublication(
+ presentationOnlyPublication,
+ workerResult.progress
+ )).not.toThrow();
+ expect(targetSkeleton.getSkeletonData()?.pages[protectedPageIndex]).toBe(protectedPage);
+ acceptedPresentationDifference = true;
+ protectedPublication.page.pageWidth += 1;
+ changedProtectedPublication = true;
+ }
+ }
+ const applyResult = targetSkeleton.applyLayoutPublication(
+ workerResult.publication,
+ workerResult.progress
+ );
+ didReplaceProtectedPages ||= applyResult.didReplaceProtectedPages;
+ if (changedProtectedPublication && !workerResult.progress.complete) {
+ stagedProtectedPublication = true;
+ expect(applyResult.didReplaceProtectedPages).toBe(false);
+ }
+ if (!workerResult.progress.complete) {
+ expect(targetSkeleton.getSkeletonData()?.pages[protectedPageIndex]).toBe(protectedPage);
+ const publishedTailPage = workerResult.publication.kind === 'page'
+ ? workerResult.publication.pages.find((page) => page.pageIndex > protectedPageIndex)
+ : undefined;
+ if (changedProtectedPublication && publishedTailPage != null) {
+ expect(
+ targetSkeleton.getSkeletonData()?.pages[publishedTailPage.pageIndex]?.isLayoutPlaceholder
+ ).not.toBe(true);
+ publishedUnprotectedTail = true;
+ }
+ }
+ }
+ if (workerResult.progress.complete) {
+ break;
+ }
+ workerResult = session.step(workerGeneration, 0);
+ }
+
+ expect(changedProtectedPublication).toBe(true);
+ expect(acceptedPresentationDifference).toBe(true);
+ expect(stagedProtectedPublication).toBe(true);
+ expect(publishedUnprotectedTail).toBe(true);
+ expect(workerResult.progress.complete).toBe(true);
+ expect(didReplaceProtectedPages).toBe(true);
+ expect(targetSkeleton.getSkeletonData()?.pages[protectedPageIndex]).not.toBe(protectedPage);
+ expect(targetSkeleton.getSkeletonData()?.pages[protectedPageIndex]?.pageWidth).toBe(
+ (protectedPage?.pageWidth ?? 0) + 1
+ );
+ expect(targetSkeleton.getSkeletonData()?.pages[protectedPageIndex]?.isLayoutPlaceholder).not.toBe(true);
+ expect(initialTargetSkeletonData?.pages).not.toHaveLength(0);
+ expect(protectedPage?.sections).not.toHaveLength(0);
+
+ session.dispose();
+ targetSkeleton.dispose();
+ dataModel.dispose();
+ targetModel.dispose();
+ localeService.dispose();
+ });
+
+ it('publishes inline drawings with the page that owns their flow geometry', () => {
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText(content: string) {
+ return {
+ width: content.length * 7,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 2,
+ };
+ },
+ };
+ }
+ });
+
+ const drawingId = 'inline-picture';
+ const content = [
+ `Before${DataStreamTreeTokenType.CUSTOM_BLOCK}after${DataStreamTreeTokenType.PARAGRAPH}`,
+ ...Array.from(
+ { length: 20 },
+ (_, index) => `Paragraph ${index} fills the following pages.${DataStreamTreeTokenType.PARAGRAPH}`
+ ),
+ ].join('');
+ const sourceModel = createDocumentModelWithStyle(content, {});
+ const snapshot = sourceModel.getSnapshot();
+ if (snapshot.body == null) {
+ throw new Error('Expected the drawing test document body.');
+ }
+ snapshot.body.customBlocks = [{
+ startIndex: content.indexOf(DataStreamTreeTokenType.CUSTOM_BLOCK),
+ blockId: drawingId,
+ }];
+ snapshot.drawings = {
+ [drawingId]: {
+ drawingId,
+ drawingType: DrawingTypeEnum.DRAWING_BLOCK,
+ unitId: snapshot.id,
+ subUnitId: snapshot.id,
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ angle: 0,
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ size: { width: 100, height: 50 },
+ },
+ },
+ };
+ const dataModel = new DocumentDataModel(snapshot);
+ dataModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.TRADITIONAL });
+ dataModel.updateDocumentDataPageSize(240, 180);
+ const localeService = new LocaleService();
+ const session = new DocumentLayoutSession(dataModel, localeService);
+ const generation = session.start({ reason: 'initial' });
+ const publishedDrawingIds = new Set<string>();
+ let result = session.step(generation, 0);
+ for (let step = 0; step < 1_000; step++) {
+ if (result.publication?.kind === 'page') {
+ for (const pagePublication of result.publication.pages) {
+ for (const [publishedDrawingId] of pagePublication.page.skeDrawings) {
+ publishedDrawingIds.add(publishedDrawingId);
+ }
+ }
+ }
+ if (result.progress.complete) {
+ break;
+ }
+ result = session.step(generation, 0);
+ }
+
+ expect(result.progress).toMatchObject({ complete: true, cancelled: false });
+ expect(result.progress.pageCount).toBeGreaterThan(1);
+ expect(publishedDrawingIds).toEqual(new Set([drawingId]));
+
+ session.dispose();
+ dataModel.dispose();
+ sourceModel.dispose();
+ localeService.dispose();
+ });
+
+ it('keeps modern explicit-page drawing geometry stable across block publications', () => {
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText(content: string) {
+ return {
+ width: content.length * 7,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 2,
+ };
+ },
+ };
+ }
+ });
+
+ const T = DataStreamTreeTokenType;
+ const firstDrawingId = 'modern-first-page-drawing';
+ const secondDrawingId = 'modern-second-page-drawing';
+ const content = [
+ `First ${T.CUSTOM_BLOCK} page${T.PARAGRAPH}${T.PAGE_BREAK}`,
+ `Second ${T.CUSTOM_BLOCK} page${T.PARAGRAPH}${T.PAGE_BREAK}`,
+ ...Array.from({ length: 20 }, (_, index) => `Trailing paragraph ${index}${T.PARAGRAPH}`),
+ ].join('');
+ const sourceModel = createDocumentModelWithStyle(content, {});
+ const snapshot = sourceModel.getSnapshot();
+ if (snapshot.body == null) {
+ throw new Error('Expected the modern drawing test document body.');
+ }
+ const firstDrawingStart = content.indexOf(T.CUSTOM_BLOCK);
+ const secondDrawingStart = content.indexOf(T.CUSTOM_BLOCK, firstDrawingStart + 1);
+ snapshot.body.customBlocks = [
+ { startIndex: firstDrawingStart, blockId: firstDrawingId },
+ { startIndex: secondDrawingStart, blockId: secondDrawingId },
+ ];
+ snapshot.drawings = Object.fromEntries([firstDrawingId, secondDrawingId].map((drawingId) => [drawingId, {
+ drawingId,
+ drawingType: DrawingTypeEnum.DRAWING_BLOCK,
+ unitId: snapshot.id,
+ subUnitId: snapshot.id,
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ docTransform: {
+ angle: 0,
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ size: { width: 40, height: 20 },
+ },
+ }]));
+ const dataModel = new DocumentDataModel(snapshot);
+ dataModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });
+ const session = new DocumentLayoutSession(dataModel, new LocaleService());
+ const targetModel = new DocumentDataModel(structuredClone(dataModel.getSnapshot()));
+ const targetSkeleton = DocumentSkeleton.create(new DocumentViewModel(targetModel), new LocaleService());
+ const synchronousModel = new DocumentDataModel(structuredClone(dataModel.getSnapshot()));
+ const synchronousSkeleton = DocumentSkeleton.create(new DocumentViewModel(synchronousModel), new LocaleService());
+ synchronousSkeleton.calculate();
+ const generation = session.start({ reason: 'initial' });
+ const secondDrawingTops: number[] = [];
+ let result = session.step(generation, 0);
+ for (let step = 0; step < 100; step++) {
+ if (result.publication?.kind === 'block') {
+ targetSkeleton.applyLayoutPublication(structuredClone(result.publication), result.progress);
+ const drawing = result.publication.block.skeDrawings.find(([drawingId]) => drawingId === secondDrawingId)?.[1];
+ if (drawing != null && !result.progress.complete) {
+ secondDrawingTops.push(drawing.aTop);
+ }
+ }
+ if (result.progress.complete) {
+ break;
+ }
+ result = session.step(generation, 0);
+ }
+
+ expect(result.progress).toMatchObject({ complete: true, mode: 'continuous', pageCount: 1 });
+ expect(secondDrawingTops.length).toBeGreaterThan(1);
+ expect(new Set(secondDrawingTops).size).toBe(1);
+ expect(normalizeSkeleton(targetSkeleton.getSkeletonData())).toEqual(
+ normalizeSkeleton(synchronousSkeleton.getSkeletonData())
+ );
+
+ synchronousSkeleton.dispose();
+ synchronousModel.dispose();
+ targetSkeleton.dispose();
+ targetModel.dispose();
+ session.dispose();
+ dataModel.dispose();
+ sourceModel.dispose();
+ });
+
+ it('preserves tables, column groups, drawings, lists, headers and footers across Worker transport', () => {
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText(content: string) {
+ return {
+ width: content.length * 7,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 2,
+ };
+ },
+ };
+ }
+ });
+
+ const T = DataStreamTreeTokenType;
+ const documentId = 'worker-rich-elements';
+ const bodyDrawingId = 'worker-rich-elements-body-drawing';
+ const tableDrawingId = 'worker-rich-elements-table-drawing';
+ const columnDrawingId = 'worker-rich-elements-column-drawing';
+ const headerDrawingId = 'worker-rich-elements-header-drawing';
+ const footerDrawingId = 'worker-rich-elements-footer-drawing';
+ const tableId = 'worker-rich-elements-table';
+ const columnTableId = 'worker-rich-elements-column-table';
+ const columnGroupId = 'worker-rich-elements-columns';
+ const intro = `List paragraph${T.PARAGRAPH}`;
+ const drawingParagraph = `Before ${T.CUSTOM_BLOCK} after${T.PARAGRAPH}`;
+ const tableCellText = `Table ${T.CUSTOM_BLOCK} cell content crosses the Worker transport.`;
+ const tableStream = [
+ T.TABLE_START,
+ T.TABLE_ROW_START,
+ T.TABLE_CELL_START,
+ tableCellText,
+ T.PARAGRAPH,
+ T.SECTION_BREAK,
+ T.TABLE_CELL_END,
+ T.TABLE_ROW_END,
+ T.TABLE_END,
+ ].join('');
+ const columnTableStream = [
+ T.TABLE_START,
+ T.TABLE_ROW_START,
+ T.TABLE_CELL_START,
+ `Nested column table${T.PARAGRAPH}`,
+ T.SECTION_BREAK,
+ T.TABLE_CELL_END,
+ T.TABLE_ROW_END,
+ T.TABLE_END,
+ ].join('');
+ const columnGroupStream = [
+ T.COLUMN_GROUP_START,
+ T.COLUMN_START,
+ `Left ${T.CUSTOM_BLOCK} column${T.PARAGRAPH}`,
+ columnTableStream,
+ T.PARAGRAPH,
+ T.COLUMN_END,
+ T.COLUMN_START,
+ `Right column${T.PARAGRAPH}`,
+ T.COLUMN_END,
+ T.COLUMN_GROUP_END,
+ ].join('');
+ const trailing = Array.from(
+ { length: 24 },
+ (_, index) => `Trailing paragraph ${index} fills another physical page.${T.PARAGRAPH}`
+ ).join('');
+ const dataStream = `${intro}${drawingParagraph}${tableStream}${T.PARAGRAPH}${columnGroupStream}${T.PARAGRAPH}${trailing}${T.SECTION_BREAK}`;
+ const tableStart = dataStream.indexOf(T.TABLE_START);
+ const columnTableStart = dataStream.indexOf(T.TABLE_START, tableStart + 1);
+ const columnGroupStart = dataStream.indexOf(T.COLUMN_GROUP_START);
+ const bodyDrawingStart = dataStream.indexOf(T.CUSTOM_BLOCK);
+ const tableDrawingStart = dataStream.indexOf(T.CUSTOM_BLOCK, bodyDrawingStart + 1);
+ const columnDrawingStart = dataStream.indexOf(T.CUSTOM_BLOCK, tableDrawingStart + 1);
+ const paragraphs = [...dataStream.matchAll(new RegExp(T.PARAGRAPH, 'g'))].map((match, index) => ({
+ startIndex: match.index,
+ paragraphId: `worker-rich-elements-paragraph-${index}`,
+ ...(index === 0
+ ? {
+ bullet: {
+ listId: 'worker-rich-elements-list',
+ listType: PresetListType.ORDER_LIST,
+ nestingLevel: 0,
+ },
+ }
+ : {}),
+ }));
+ const snapshot = {
+ id: documentId,
+ body: {
+ dataStream,
+ paragraphs,
+ sectionBreaks: [
+ {
+ sectionId: 'worker-rich-elements-cell-section',
+ startIndex: tableStart + tableStream.indexOf(T.SECTION_BREAK),
+ },
+ {
+ sectionId: 'worker-rich-elements-column-cell-section',
+ startIndex: columnTableStart + columnTableStream.indexOf(T.SECTION_BREAK),
+ },
+ {
+ sectionId: 'worker-rich-elements-body-section',
+ startIndex: dataStream.length - 1,
+ defaultHeaderId: 'worker-rich-elements-header',
+ defaultFooterId: 'worker-rich-elements-footer',
+ },
+ ],
+ customBlocks: [
+ { startIndex: bodyDrawingStart, blockId: bodyDrawingId },
+ { startIndex: tableDrawingStart, blockId: tableDrawingId },
+ { startIndex: columnDrawingStart, blockId: columnDrawingId },
+ ],
+ tables: [
+ { startIndex: tableStart, endIndex: tableStart + tableStream.length, tableId },
+ {
+ startIndex: columnTableStart,
+ endIndex: columnTableStart + columnTableStream.length,
+ tableId: columnTableId,
+ },
+ ],
+ columnGroups: [{
+ startIndex: columnGroupStart,
+ endIndex: columnGroupStart + columnGroupStream.length - 1,
+ columnGroupId,
+ gap: { v: 12 },
+ layout: ColumnLayoutType.FIXED,
+ responsive: ColumnResponsiveType.SHRINK,
+ columns: [
+ { columnId: 'worker-rich-elements-left', widthRatio: 1, minWidth: { v: 40 } },
+ { columnId: 'worker-rich-elements-right', widthRatio: 1, minWidth: { v: 40 } },
+ ],
+ }],
+ },
+ tableSource: {
+ [tableId]: {
+ tableId,
+ description: 'large-table-source-payload'.repeat(1_000),
+ align: TableAlignmentType.CENTER,
+ 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: 220 } },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 220 } } }],
+ tableRows: [{
+ trHeight: { hRule: TableRowHeightRule.AUTO, val: { v: 0 } },
+ tableCells: [{ vAlign: VerticalAlignmentType.TOP }],
+ }],
+ },
+ [columnTableId]: {
+ tableId: columnTableId,
+ 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: 90 } },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 90 } } }],
+ tableRows: [{
+ trHeight: { hRule: TableRowHeightRule.AUTO, val: { v: 0 } },
+ tableCells: [{ vAlign: VerticalAlignmentType.TOP }],
+ }],
+ },
+ },
+ drawings: {
+ [bodyDrawingId]: {
+ drawingId: bodyDrawingId,
+ description: 'large-drawing-source-payload'.repeat(1_000),
+ drawingType: DrawingTypeEnum.DRAWING_BLOCK,
+ unitId: documentId,
+ subUnitId: documentId,
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ angle: 0,
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ size: { width: 80, height: 40 },
+ },
+ },
+ [tableDrawingId]: {
+ drawingId: tableDrawingId,
+ drawingType: DrawingTypeEnum.DRAWING_BLOCK,
+ unitId: documentId,
+ subUnitId: documentId,
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ angle: 0,
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ size: { width: 30, height: 20 },
+ },
+ },
+ [columnDrawingId]: {
+ drawingId: columnDrawingId,
+ drawingType: DrawingTypeEnum.DRAWING_BLOCK,
+ unitId: documentId,
+ subUnitId: documentId,
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ angle: 0,
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ size: { width: 25, height: 18 },
+ },
+ },
+ [headerDrawingId]: {
+ drawingId: headerDrawingId,
+ drawingType: DrawingTypeEnum.DRAWING_BLOCK,
+ unitId: documentId,
+ subUnitId: documentId,
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ angle: 0,
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ size: { width: 20, height: 12 },
+ },
+ },
+ [footerDrawingId]: {
+ drawingId: footerDrawingId,
+ drawingType: DrawingTypeEnum.DRAWING_BLOCK,
+ unitId: documentId,
+ subUnitId: documentId,
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ angle: 0,
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ size: { width: 20, height: 12 },
+ },
+ },
+ },
+ drawingsOrder: [
+ bodyDrawingId,
+ tableDrawingId,
+ columnDrawingId,
+ headerDrawingId,
+ footerDrawingId,
+ ],
+ headers: {
+ 'worker-rich-elements-header': {
+ headerId: 'worker-rich-elements-header',
+ body: {
+ dataStream: `Header ${T.CUSTOM_BLOCK} content${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 16, paragraphId: 'worker-rich-elements-header-paragraph' }],
+ sectionBreaks: [{ startIndex: 17, sectionId: 'worker-rich-elements-header-section' }],
+ customBlocks: [{ startIndex: 7, blockId: headerDrawingId }],
+ },
+ },
+ },
+ footers: {
+ 'worker-rich-elements-footer': {
+ footerId: 'worker-rich-elements-footer',
+ body: {
+ dataStream: `Footer ${T.CUSTOM_BLOCK} content${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [{ startIndex: 16, paragraphId: 'worker-rich-elements-footer-paragraph' }],
+ sectionBreaks: [{ startIndex: 17, sectionId: 'worker-rich-elements-footer-section' }],
+ customBlocks: [{ startIndex: 7, blockId: footerDrawingId }],
+ },
+ },
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 280, height: 220 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ marginHeader: 10,
+ marginFooter: 10,
+ },
+ };
+ const sourceModel = new DocumentDataModel(structuredClone(snapshot));
+ const targetModel = new DocumentDataModel(structuredClone(snapshot));
+ const incrementalModel = new DocumentDataModel(structuredClone(snapshot));
+ const synchronousModel = new DocumentDataModel(structuredClone(snapshot));
+ const localeService = new LocaleService();
+ const session = new DocumentLayoutSession(sourceModel, localeService);
+ const targetSkeleton = DocumentSkeleton.create(new DocumentViewModel(targetModel), new LocaleService());
+ const incrementalSkeleton = DocumentSkeleton.create(
+ new DocumentViewModel(incrementalModel),
+ new LocaleService()
+ );
+ const synchronousSkeleton = DocumentSkeleton.create(
+ new DocumentViewModel(synchronousModel),
+ new LocaleService()
+ );
+ expect(incrementalSkeleton.getViewModel().getTableByStartIndex(tableStart)?.tableSource.tableId).toBe(tableId);
+ expect(incrementalSkeleton.getViewModel().getColumnGroupByStartIndex(columnGroupStart)?.columnGroup.columnGroupId)
+ .toBe(columnGroupId);
+ synchronousSkeleton.calculate();
+ const incrementalGeneration = incrementalSkeleton.startIncrementalLayout({ reason: 'initial' });
+ let incrementalProgress = incrementalSkeleton.stepIncrementalLayout(incrementalGeneration, 0);
+ for (let step = 0; step < 2_000 && !incrementalProgress.complete; step++) {
+ incrementalProgress = incrementalSkeleton.stepIncrementalLayout(incrementalGeneration, 0);
+ }
+ expect(incrementalProgress.complete).toBe(true);
+ targetSkeleton.beginExternalLayout({ reason: 'initial' });
+
+ const generation = session.start({ reason: 'initial' });
+ const publicationPayloads: string[] = [];
+ let result = session.step(generation, 0);
+ for (let step = 0; step < 2_000; step++) {
+ if (result.publication != null) {
+ publicationPayloads.push(JSON.stringify(result.publication));
+ targetSkeleton.applyLayoutPublication(structuredClone(result.publication), result.progress);
+ }
+ if (result.progress.complete) {
+ break;
+ }
+ result = session.step(generation, 0);
+ }
+
+ expect(result.progress).toMatchObject({ complete: true, cancelled: false });
+ expect(result.progress.pageCount).toBeGreaterThan(1);
+ expect(publicationPayloads.join('')).toContain(bodyDrawingId);
+ expect(publicationPayloads.join('')).toContain(tableId);
+ expect(publicationPayloads.join('')).not.toContain('"drawingOrigin"');
+ expect(publicationPayloads.join('')).not.toContain('"tableSource"');
+ expect(publicationPayloads.join('')).not.toContain('"rowSource"');
+ expect(publicationPayloads.join('')).not.toContain('large-drawing-source-payload');
+ expect(publicationPayloads.join('')).not.toContain('large-table-source-payload');
+ expect(() => structuredClone(targetSkeleton.getSkeletonData())).not.toThrow();
+ expect(summarizePages(targetSkeleton.getSkeletonData())).toEqual(
+ summarizePages(incrementalSkeleton.getSkeletonData())
+ );
+ expect(normalizeSkeleton(targetSkeleton.getSkeletonData()?.pages)).toEqual(
+ normalizeSkeleton(incrementalSkeleton.getSkeletonData()?.pages)
+ );
+ expect(normalizeSkeleton(targetSkeleton.getSkeletonData()?.skeHeaders)).toEqual(
+ normalizeSkeleton(incrementalSkeleton.getSkeletonData()?.skeHeaders)
+ );
+ expect(normalizeSkeleton(targetSkeleton.getSkeletonData()?.skeFooters)).toEqual(
+ normalizeSkeleton(incrementalSkeleton.getSkeletonData()?.skeFooters)
+ );
+ expect(normalizeSkeleton(targetSkeleton.getSkeletonData()?.skeListLevel)).toEqual(
+ normalizeSkeleton(incrementalSkeleton.getSkeletonData()?.skeListLevel)
+ );
+ expect(summarizeDrawingAnchors(targetSkeleton.getSkeletonData())).toEqual(
+ summarizeDrawingAnchors(incrementalSkeleton.getSkeletonData())
+ );
+ const targetElements = collectNestedElementIds(targetSkeleton.getSkeletonData());
+ expect(targetElements.drawingIds).toContain(bodyDrawingId);
+ expect(targetElements.tableIds).toContain(tableId);
+ const targetPages = targetSkeleton.getSkeletonData()?.pages ?? [];
+ const hydratedBodyDrawing = targetPages.flatMap((page) => [...page.skeDrawings.values()])
+ .find((drawing) => drawing.drawingId === bodyDrawingId);
+ const hydratedBodyTable = targetPages.flatMap((page) => [...page.skeTables.values()])
+ .find((table) => table.tableSource.tableId === tableId);
+ expect(hydratedBodyDrawing?.drawingOrigin).toBe(targetModel.getSnapshot().drawings?.[bodyDrawingId]);
+ expect(hydratedBodyTable?.tableSource).toBe(targetModel.getSnapshot().tableSource?.[tableId]);
+ expect([...targetSkeleton.getSkeletonData()?.drawingAnchor?.values() ?? []]
+ .flatMap((anchors) => [...anchors.values()])
+ .every((anchor) => anchor.elements.length === 0)).toBe(true);
+ expect(normalizeSkeleton(incrementalSkeleton.getSkeletonData()?.pages)).toEqual(
+ normalizeSkeleton(synchronousSkeleton.getSkeletonData()?.pages)
+ );
+ expect(normalizeSkeleton(incrementalSkeleton.getSkeletonData()?.skeHeaders)).toEqual(
+ normalizeSkeleton(synchronousSkeleton.getSkeletonData()?.skeHeaders)
+ );
+ expect(normalizeSkeleton(incrementalSkeleton.getSkeletonData()?.skeFooters)).toEqual(
+ normalizeSkeleton(synchronousSkeleton.getSkeletonData()?.skeFooters)
+ );
+ expect(normalizeSkeleton(incrementalSkeleton.getSkeletonData()?.skeListLevel)).toEqual(
+ normalizeSkeleton(synchronousSkeleton.getSkeletonData()?.skeListLevel)
+ );
+ expect(summarizeDrawingAnchors(incrementalSkeleton.getSkeletonData())).toEqual(
+ summarizeDrawingAnchors(synchronousSkeleton.getSkeletonData())
+ );
+
+ const targetData = targetSkeleton.getSkeletonData();
+ const nestedElementIds = collectNestedElementIds(targetData);
+ expect(targetData?.skeHeaders.size).toBeGreaterThan(0);
+ expect(targetData?.skeFooters.size).toBeGreaterThan(0);
+ expect(targetData?.skeListLevel?.size).toBeGreaterThan(0);
+ expect(nestedElementIds.drawingIds).toEqual(new Set([
+ bodyDrawingId,
+ tableDrawingId,
+ columnDrawingId,
+ headerDrawingId,
+ footerDrawingId,
+ ]));
+ expect(nestedElementIds.tableIds.has(tableId)).toBe(true);
+ expect(nestedElementIds.tableIds.has(columnTableId)).toBe(true);
+ expect(nestedElementIds.columnGroupIds.has(columnGroupId)).toBe(true);
+ const headerPages = [...targetData?.skeHeaders.get('worker-rich-elements-header')?.values() ?? []];
+ const footerPages = [...targetData?.skeFooters.get('worker-rich-elements-footer')?.values() ?? []];
+ expect(headerPages.some((page) => page.skeDrawings.has(headerDrawingId))).toBe(true);
+ expect(footerPages.some((page) => page.skeDrawings.has(footerDrawingId))).toBe(true);
+
+ session.dispose();
+ targetSkeleton.dispose();
+ incrementalSkeleton.dispose();
+ synchronousSkeleton.dispose();
+ sourceModel.dispose();
+ targetModel.dispose();
+ incrementalModel.dispose();
+ synchronousModel.dispose();
+ localeService.dispose();
+ });
+
+ it('publishes modern documents as bounded continuous block patches', () => {
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText(content: string) {
+ return {
+ width: content.length * 7,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 2,
+ };
+ },
+ };
+ }
+ });
+
+ const content = Array.from(
+ { length: 24 },
+ (_, index) => `Modern paragraph ${index} is laid out independently.\r`
+ ).join('');
+ const dataModel = createDocumentModelWithStyle(content, {});
+ dataModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });
+ dataModel.updateDocumentDataPageSize(320, Number.POSITIVE_INFINITY);
+ const localeService = new LocaleService();
+ const session = new DocumentLayoutSession(dataModel, localeService);
+ const targetModel = new DocumentDataModel(structuredClone(dataModel.getSnapshot()));
+ const targetSkeleton = DocumentSkeleton.create(new DocumentViewModel(targetModel), new LocaleService());
+ const synchronousModel = new DocumentDataModel(structuredClone(dataModel.getSnapshot()));
+ let synchronousSkeleton = DocumentSkeleton.create(new DocumentViewModel(synchronousModel), new LocaleService());
+ synchronousSkeleton.calculate();
+ targetSkeleton.beginExternalLayout({ reason: 'initial' });
+
+ const generation = session.start({ reason: 'initial' });
+ const blockLineCounts: number[] = [];
+ const publications: LayoutPublication[] = [];
+ const transferDurations: number[] = [];
+ let result = session.step(generation, 0);
+ for (let step = 0; step < 1_000; step++) {
+ if (result.publication != null) {
+ publications.push(result.publication);
+ expect(result.publication.kind).toBe('block');
+ if (result.publication.kind === 'block') {
+ blockLineCounts.push(result.publication.block.flow.lines.length);
+ }
+ const transferStart = cpuUsage();
+ const transferredPublication = structuredClone(result.publication);
+ targetSkeleton.applyLayoutPublication(transferredPublication, result.progress);
+ const transferCpu = cpuUsage(transferStart);
+ transferDurations.push((transferCpu.user + transferCpu.system) / 1_000);
+ }
+ if (result.progress.complete) {
+ break;
+ }
+ result = session.step(generation, 0);
+ }
+
+ const finalLineCount = synchronousSkeleton.getSkeletonData()?.pages[0].sections.flatMap(
+ (section) => section.columns
+ ).flatMap((column) => column.lines).length ?? 0;
+ expect(result.progress).toMatchObject({ mode: 'continuous', complete: true, pageCount: 1 });
+ expect(publications.length).toBeGreaterThan(10);
+ expect(Math.max(...blockLineCounts.slice(1))).toBeLessThan(finalLineCount);
+ expect(() => structuredClone(publications)).not.toThrow();
+ expectBoundedPatchTransfer(transferDurations);
+ expect(normalizeSkeleton(targetSkeleton.getSkeletonData())).toEqual(
+ normalizeSkeleton(synchronousSkeleton.getSkeletonData())
+ );
+
+ const anchor = content.indexOf('Modern paragraph 12') + 'Modern paragraph '.length;
+ const insertedText = 'EDIT-';
+ const textX = new TextX();
+ textX.push({ t: TextXActionType.RETAIN, len: anchor });
+ textX.push({
+ t: TextXActionType.INSERT,
+ len: insertedText.length,
+ body: { dataStream: insertedText },
+ });
+ const actions = JSONX.getInstance().editOp(textX.serialize(), ['body']);
+ dataModel.apply(actions);
+ targetModel.apply(actions);
+ synchronousModel.apply(actions);
+ session.resetDataModel(dataModel);
+ targetSkeleton.getViewModel().reset(targetModel);
+ synchronousSkeleton.dispose();
+ synchronousSkeleton = DocumentSkeleton.create(new DocumentViewModel(synchronousModel), new LocaleService());
+ synchronousSkeleton.calculate();
+
+ const mainEditGeneration = targetSkeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor,
+ priorityAnchor: anchor + insertedText.length,
+ invalidation: {
+ oldStart: anchor,
+ oldEnd: anchor,
+ newEnd: anchor + insertedText.length,
+ },
+ });
+ // A zero budget still completes one atomic block, but cannot consume the
+ // whole small fixture in a fast process before exposing its continuation.
+ let mainEditProgress = targetSkeleton.stepIncrementalLayout(mainEditGeneration, 0);
+ for (let step = 0; step < 1_000 && !mainEditProgress.didPublishAnchor; step++) {
+ mainEditProgress = targetSkeleton.stepIncrementalLayout(mainEditGeneration, 0);
+ }
+ expect(mainEditProgress.didPublishAnchor).toBe(true);
+ expect(mainEditProgress.stableLaidOutThrough).toBeLessThan(mainEditProgress.laidOutThrough);
+ const protectedContinuousPage = targetSkeleton.getSkeletonData()?.pages[0];
+ expect(protectedContinuousPage).toBeDefined();
+
+ const probeProtectedEndOffset = anchor + insertedText.length;
+ targetSkeleton.beginExternalLayout({
+ reason: 'edit',
+ protectedRange: {
+ mode: 'continuous',
+ startOffset: anchor,
+ endOffset: probeProtectedEndOffset,
+ },
+ });
+ const probeGeneration = session.start({
+ reason: 'edit',
+ anchor,
+ invalidation: {
+ oldStart: anchor,
+ oldEnd: anchor,
+ newEnd: anchor + insertedText.length,
+ },
+ });
+ let probeResult = session.step(probeGeneration, 0);
+ let deferredVerticalBoundaryMismatch = false;
+ for (let step = 0; step < 1_000 && !probeResult.progress.complete; step++) {
+ const publication = probeResult.publication;
+ if (publication?.kind === 'block') {
+ const transferredPublication = structuredClone(publication);
+ const firstUnprotectedLineIndex = transferredPublication.block.flow.lines.findIndex(
+ (line) => line.st > probeProtectedEndOffset
+ );
+ const workerBoundaryLine = transferredPublication.block.flow.lines[firstUnprotectedLineIndex - 1];
+ if (workerBoundaryLine != null) {
+ workerBoundaryLine.top += 1;
+ expect(() => targetSkeleton.applyLayoutPublication(
+ transferredPublication,
+ probeResult.progress
+ )).not.toThrow();
+ deferredVerticalBoundaryMismatch = true;
+ break;
+ }
+ }
+ probeResult = session.step(probeGeneration, 0);
+ }
+ expect(deferredVerticalBoundaryMismatch).toBe(true);
+ expect(targetSkeleton.getSkeletonData()?.pages[0]).toBe(protectedContinuousPage);
+ targetSkeleton.cancelExternalLayout();
+
+ targetSkeleton.beginExternalLayout({
+ reason: 'edit',
+ protectedRange: {
+ mode: 'continuous',
+ startOffset: anchor,
+ endOffset: mainEditProgress.stableLaidOutThrough,
+ },
+ });
+
+ const editGeneration = session.start({
+ reason: 'edit',
+ anchor,
+ invalidation: {
+ oldStart: anchor,
+ oldEnd: anchor,
+ newEnd: anchor + insertedText.length,
+ },
+ });
+ let editResult = session.step(editGeneration, 0);
+ let firstEditBlockLineIndex: number | null = null;
+ const editTransferDurations: number[] = [];
+ for (let step = 0; step < 1_000; step++) {
+ if (editResult.publication != null) {
+ if (editResult.publication.kind === 'block' && firstEditBlockLineIndex == null) {
+ firstEditBlockLineIndex = editResult.publication.block.flow.lineIndex;
+ }
+ const transferStart = cpuUsage();
+ const transferredPublication = structuredClone(editResult.publication);
+ targetSkeleton.applyLayoutPublication(transferredPublication, editResult.progress);
+ const transferCpu = cpuUsage(transferStart);
+ editTransferDurations.push((transferCpu.user + transferCpu.system) / 1_000);
+ if (!editResult.progress.complete) {
+ expect(targetSkeleton.getSkeletonData()?.pages[0]).toBe(protectedContinuousPage);
+ }
+ }
+ if (editResult.progress.complete) {
+ break;
+ }
+ editResult = session.step(editGeneration, 0);
+ }
+
+ expect(firstEditBlockLineIndex).not.toBeNull();
+ expect(firstEditBlockLineIndex).toBeGreaterThan(0);
+ expect(targetSkeleton.getSkeletonData()?.pages[0]).toBe(protectedContinuousPage);
+ expectBoundedPatchTransfer(editTransferDurations);
+ expect(normalizeSkeleton(targetSkeleton.getSkeletonData())).toEqual(
+ normalizeSkeleton(synchronousSkeleton.getSkeletonData())
+ );
+
+ const remotePrefix = 'REMOTE PREFIX '.repeat(120);
+ const remoteTextX = new TextX();
+ remoteTextX.push({
+ t: TextXActionType.INSERT,
+ len: remotePrefix.length,
+ body: { dataStream: remotePrefix },
+ });
+ const remoteActions = JSONX.getInstance().editOp(remoteTextX.serialize(), ['body']);
+ dataModel.apply(remoteActions);
+ targetModel.apply(remoteActions);
+ synchronousModel.apply(remoteActions);
+ session.resetDataModel(dataModel);
+ targetSkeleton.getViewModel().reset(targetModel);
+ synchronousSkeleton.dispose();
+ synchronousSkeleton = DocumentSkeleton.create(new DocumentViewModel(synchronousModel), new LocaleService());
+ synchronousSkeleton.calculate();
+
+ const transformedCaret = (dataModel.getBody()?.dataStream.length ?? 0) - 2;
+ const remoteMainGeneration = targetSkeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor: 0,
+ priorityAnchor: transformedCaret,
+ invalidation: {
+ oldStart: 0,
+ oldEnd: 0,
+ newEnd: remotePrefix.length,
+ },
+ });
+ let remoteMainProgress = targetSkeleton.stepIncrementalLayout(remoteMainGeneration, 0);
+ for (let step = 0; step < 1_000 && !remoteMainProgress.didPublishAnchor; step++) {
+ remoteMainProgress = targetSkeleton.stepIncrementalLayout(remoteMainGeneration, 0);
+ }
+ expect(remoteMainProgress.didPublishAnchor).toBe(true);
+ const remotelyProtectedPage = targetSkeleton.getSkeletonData()?.pages[0];
+ expect(remotelyProtectedPage).toBeDefined();
+
+ targetSkeleton.beginExternalLayout({
+ reason: 'edit',
+ protectedRange: {
+ mode: 'continuous',
+ startOffset: transformedCaret,
+ endOffset: dataModel.getBody()?.dataStream.length ?? transformedCaret,
+ },
+ });
+ const remoteGeneration = session.start({
+ reason: 'edit',
+ anchor: 0,
+ invalidation: {
+ oldStart: 0,
+ oldEnd: 0,
+ newEnd: remotePrefix.length,
+ },
+ });
+ let remoteResult = session.step(remoteGeneration, 0);
+ let didReplaceProtectedContinuousLayout = false;
+ for (let step = 0; step < 1_000; step++) {
+ if (remoteResult.publication != null) {
+ const applyResult = targetSkeleton.applyLayoutPublication(
+ structuredClone(remoteResult.publication),
+ remoteResult.progress
+ );
+ didReplaceProtectedContinuousLayout ||= applyResult.didReplaceProtectedPages;
+ if (!remoteResult.progress.complete) {
+ expect(targetSkeleton.getSkeletonData()?.pages[0]).toBe(remotelyProtectedPage);
+ }
+ }
+ if (remoteResult.progress.complete) {
+ break;
+ }
+ remoteResult = session.step(remoteGeneration, 0);
+ }
+
+ expect(remoteResult.progress.complete).toBe(true);
+ expect(didReplaceProtectedContinuousLayout).toBe(true);
+ expect(targetSkeleton.getSkeletonData()?.pages[0]).toBe(remotelyProtectedPage);
+ expect(normalizeSkeleton(targetSkeleton.getSkeletonData())).toEqual(
+ normalizeSkeleton(synchronousSkeleton.getSkeletonData())
+ );
+
+ session.dispose();
+ targetSkeleton.dispose();
+ synchronousSkeleton.dispose();
+ dataModel.dispose();
+ targetModel.dispose();
+ synchronousModel.dispose();
+ localeService.dispose();
+ });
+});
diff --git a/packages/engine-render/src/basics/__tests__/tools.spec.ts b/packages/engine-render/src/basics/__tests__/tools.spec.ts
index 0df357a6ac..08a980d310 100644
--- a/packages/engine-render/src/basics/__tests__/tools.spec.ts
+++ b/packages/engine-render/src/basics/__tests__/tools.spec.ts
@@ -323,9 +323,11 @@ describe('tools extra', () => {
it('Emoji test', () => {
expect(startWithEmoji('🐱‍🏍One Team, One Dream!!! 🐱‍🏍')).toBe(true);
+ expect(startWithEmoji('ordinary text')).toBe(false);
expect(startWithEmoji('1abc')).toBe(false);
expect(startWithEmoji('#tag')).toBe(false);
expect(startWithEmoji('1️⃣')).toBe(true);
+ expect(startWithEmoji('*️⃣')).toBe(true);
expect(startWithEmoji('31️⃣2')).toBe(false);
expect(startWithEmoji('👨‍👩‍👧‍👦abc')).toBe(true);
expect(startWithEmoji('1👨‍👩‍👧‍👦abc')).toBe(false);
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 ab430c026c..b9ef30c0dd 100644
--- a/packages/engine-render/src/basics/i-document-skeleton-cached.ts
+++ b/packages/engine-render/src/basics/i-document-skeleton-cached.ts
@@ -79,6 +79,13 @@ export enum DocumentSkeletonPageType {
};
export interface IDocumentSkeletonPage {
+ /**
+ * Preserves page geometry while incremental pagination rebuilds a later page.
+ * Layout placeholders intentionally contain no editable flow nodes.
+ */
+ isLayoutPlaceholder?: boolean;
+ /** Canonical page geometry is available in the layout executor but not materialized on Main. */
+ isMaterializationPlaceholder?: boolean;
/** Stable id of the document section that owns this body page. */
sectionId?: string;
sections: IDocumentSkeletonSection[];
@@ -119,7 +126,7 @@ export interface IDocumentSkeletonPage {
segmentId: string; // header/footer id if header/footer, empty string if body page
type: DocumentSkeletonPageType; // page type: header, footer, body, or cell
renderConfig?: IDocumentRenderConfig;
- parent?: IDocumentSkeletonCached | IDocumentSkeletonRow;
+ parent?: IDocumentSkeletonCached | IDocumentSkeletonRow | IDocumentSkeletonColumnGroupColumn;
}
export interface IDocumentSkeletonHeaderFooter extends IDocumentSkeletonPage {}
diff --git a/packages/engine-render/src/basics/range.ts b/packages/engine-render/src/basics/range.ts
index ec55dc61b0..a871c1dcde 100644
--- a/packages/engine-render/src/basics/range.ts
+++ b/packages/engine-render/src/basics/range.ts
@@ -49,7 +49,9 @@ export interface IRectRangeWithStyle extends ITextRangeWithStyle {
}
// Only use in add/replaceDocRanges methods.
-export type ISuccinctDocRangeParam = Pick<ITextRangeWithStyle, 'startOffset' | 'endOffset' | 'segmentId' | 'segmentPage' | 'style' | 'rangeType'>;
+export type ISuccinctDocRangeParam =
+ Pick<ITextRangeWithStyle, 'startOffset' | 'endOffset' | 'segmentId' | 'segmentPage' | 'style' | 'rangeType'> &
+ Partial<Pick<ITextRangeWithStyle, 'collapsed' | 'direction' | 'isActive' | 'startNodePosition' | 'endNodePosition'>>;
export interface IDocSelectionInnerParam {
textRanges: ITextRangeWithStyle[];
diff --git a/packages/engine-render/src/basics/tools.ts b/packages/engine-render/src/basics/tools.ts
index 32f9eda3c1..bb537b9508 100644
--- a/packages/engine-render/src/basics/tools.ts
+++ b/packages/engine-render/src/basics/tools.ts
@@ -407,6 +407,12 @@ export function isEmojiGrapheme(grapheme: string): boolean {
}
export function startWithEmoji(text: string): boolean {
+ const firstCodeUnit = text.charCodeAt(0);
+ const canStartKeycapEmoji = firstCodeUnit === 0x23 || firstCodeUnit === 0x2A || (firstCodeUnit >= 0x30 && firstCodeUnit <= 0x39);
+ if (firstCodeUnit <= 0x7F && !canStartKeycapEmoji) {
+ return false;
+ }
+
const first = getFirstGrapheme(text);
return first ? isEmojiGrapheme(first) : false;
}
diff --git a/packages/engine-render/src/components/docs/__tests__/doc-background.spec.ts b/packages/engine-render/src/components/docs/__tests__/doc-background.spec.ts
index c63459c02e..e027adbd83 100644
--- a/packages/engine-render/src/components/docs/__tests__/doc-background.spec.ts
+++ b/packages/engine-render/src/components/docs/__tests__/doc-background.spec.ts
@@ -46,9 +46,10 @@ function createPage(overrides: Partial<IDocumentSkeletonPage> = {}) {
} as IDocumentSkeletonPage;
}
-function createSkeleton(pages: IDocumentSkeletonPage[], documentFlavor = DocumentFlavor.TRADITIONAL) {
+function createSkeleton(pages: IDocumentSkeletonPage[], documentFlavor = DocumentFlavor.TRADITIONAL, progress?: object) {
return {
getSkeletonData: () => ({ pages }),
+ getLayoutProgress: () => progress,
getViewModel: () => ({
getDataModel: () => ({
getSnapshot: () => ({
@@ -177,4 +178,76 @@ describe('DocBackground', () => {
background.dispose();
});
+
+ it('draws viewport-visible placeholder pages beyond the completed tail', () => {
+ const background = DocBackground.create(
+ 'incremental-background',
+ createSkeleton([createPage()], DocumentFlavor.TRADITIONAL, {
+ complete: false,
+ pageCount: 1,
+ estimatedPageCount: 3,
+ }),
+ {
+ pageLayoutType: PageLayoutType.VERTICAL,
+ pageMarginLeft: 24,
+ pageMarginTop: 18,
+ }
+ );
+ background.resize(240, 432);
+ const gradient = { addColorStop: vi.fn() };
+ const ctx = {
+ ...createCtx(),
+ beginPath: vi.fn(),
+ createLinearGradient: vi.fn(() => gradient),
+ fill: vi.fn(),
+ roundRect: vi.fn(),
+ set fillStyle(_value: unknown) {},
+ } as any;
+ const rectDraw = vi.spyOn(Rect, 'drawWith').mockImplementation(() => {});
+ vi.spyOn(Path, 'drawWith').mockImplementation(() => {});
+
+ background.draw(ctx, {
+ viewBound: { left: 0, top: 270, right: 240, bottom: 400 },
+ cacheBound: { left: 0, top: 270, right: 240, bottom: 400 },
+ } as any);
+
+ expect(rectDraw).toHaveBeenCalledTimes(2);
+ expect(rectDraw.mock.calls[1][1]).toMatchObject({ width: 200, height: 120 });
+ expect(ctx.fill).toHaveBeenCalled();
+ background.dispose();
+ });
+
+ it('does not draw layout skeleton lines inside the current published traditional page', () => {
+ const background = DocBackground.create(
+ 'incremental-current-page-background',
+ createSkeleton([createPage()], DocumentFlavor.TRADITIONAL, {
+ complete: false,
+ pageCount: 1,
+ estimatedPageCount: 1,
+ publishedPageCount: 1,
+ }),
+ {
+ pageLayoutType: PageLayoutType.VERTICAL,
+ pageMarginLeft: 24,
+ pageMarginTop: 18,
+ }
+ );
+ background.resize(240, 160);
+ const gradient = { addColorStop: vi.fn() };
+ const ctx = Object.assign(createCtx(), {
+ beginPath: vi.fn(),
+ createLinearGradient: vi.fn(() => gradient),
+ fill: vi.fn(),
+ roundRect: vi.fn(),
+ fillStyle: '',
+ });
+ vi.spyOn(Rect, 'drawWith').mockImplementation(() => {});
+ vi.spyOn(Path, 'drawWith').mockImplementation(() => {});
+
+ background.draw(ctx);
+
+ expect(ctx.createLinearGradient).not.toHaveBeenCalled();
+ expect(ctx.fill).not.toHaveBeenCalled();
+ background.dispose();
+ });
});
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 ad95401ac6..26103408c7 100644
--- a/packages/engine-render/src/components/docs/__tests__/document.spec.ts
+++ b/packages/engine-render/src/components/docs/__tests__/document.spec.ts
@@ -2119,4 +2119,63 @@ describe('documents render', () => {
documents.dispose();
});
+
+ it('visits only viewport-adjacent lines when imported modern geometry keeps a finite page height', () => {
+ const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');
+ bodyPage.pageHeight = 120;
+ bodyPage.height = 100_020;
+ bodyPage.skeTables.clear();
+ bodyPage.renderConfig.centerAngle = 0;
+ bodyPage.renderConfig.vertexAngle = 0;
+
+ const column = bodyPage.sections[0].columns[0];
+ const lines = Array.from({ length: 5_000 }, (_, index) => createLine(LineType.PARAGRAPH, index * 20));
+ for (const line of lines) {
+ line.parent = column;
+ }
+ let numericLineReads = 0;
+ column.lines = new Proxy(lines, {
+ get(target, property, receiver) {
+ if (typeof property === 'string' && /^\d+$/.test(property)) {
+ numericLineReads++;
+ }
+ return Reflect.get(target, property, receiver);
+ },
+ });
+
+ const skeletonData = {
+ pages: [bodyPage],
+ skeHeaders: new Map(),
+ skeFooters: new Map(),
+ };
+ bodyPage.parent = skeletonData;
+
+ const documents = new Documents('docs-modern-viewport', {
+ getSkeletonData: () => skeletonData,
+ getViewModel: () => ({
+ getDataModel: () => ({ documentStyle: { documentFlavor: DocumentFlavor.MODERN } }),
+ }),
+ } as any, {
+ pageLayoutType: PageLayoutType.VERTICAL,
+ pageMarginLeft: 0,
+ pageMarginTop: 0,
+ });
+ const spanDraw = vi.fn();
+ vi.spyOn(documents as any, 'getExtensionsByOrder').mockReturnValue([{
+ uKey: 'DocsSpanExtension',
+ type: DOCS_EXTENSION_TYPE.SPAN,
+ extensionOffset: {},
+ clearCache: vi.fn(),
+ draw: spanDraw,
+ }] as any);
+
+ documents.draw(canvas.getContext(), {
+ viewBound: { left: 0, top: 50_000, right: 900, bottom: 50_100 },
+ cacheBound: { left: 0, top: 50_000, right: 900, bottom: 50_100 },
+ } as any);
+
+ expect(spanDraw).toHaveBeenCalled();
+ expect(numericLineReads).toBeLessThan(160);
+ documents.dispose();
+ });
});
diff --git a/packages/engine-render/src/components/docs/doc-background.ts b/packages/engine-render/src/components/docs/doc-background.ts
index 1ca8132c9c..b4d97fc475 100644
--- a/packages/engine-render/src/components/docs/doc-background.ts
+++ b/packages/engine-render/src/components/docs/doc-background.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { IDocumentSkeletonPage } from '../../basics/i-document-skeleton-cached';
import type { IViewportInfo } from '../../basics/vector2';
import type { UniverRenderingContext } from '../../context';
import type { IPathProps } from '../../shape';
@@ -29,6 +30,10 @@ const PAGE_FILL_COLOR = 'gray.0';
const UNSPECIFIED_PAGE_FILL_COLOR = 'gray.50';
const DOCS_WORKSPACE_FILL_COLOR = 'gray.100';
const MARGIN_STROKE_COLOR = 'gray.300';
+const SKELETON_BASE_COLOR = 'rgba(148, 163, 184, 0.18)';
+const SKELETON_HIGHLIGHT_COLOR = 'rgba(255, 255, 255, 0.5)';
+const SKELETON_LINE_HEIGHT = 12;
+const SKELETON_LINE_GAP = 14;
export class DocBackground extends DocComponent {
private _drawLiquid: Liquid;
@@ -86,6 +91,7 @@ export class DocBackground extends DocComponent {
this._drawWorkspaceBackground(ctx, workspaceFill, bounds);
if (documentFlavor === DocumentFlavor.MODERN) {
+ this._drawContinuousLayoutSkeleton(ctx, bounds);
return;
}
@@ -175,6 +181,19 @@ export class DocBackground extends DocComponent {
Path.drawWith(ctx, marginIdentification);
ctx.restore();
+ if (page.isLayoutPlaceholder || page.isMaterializationPlaceholder) {
+ const contentWidth = Math.max(80, pageWidth - marginLeft - marginRight);
+ const contentHeight = Math.max(160, pageHeight - originMarginTop - originMarginBottom - 48);
+ this._drawSkeletonLines(
+ ctx,
+ pageLeft + marginLeft,
+ pageTop + originMarginTop + 24,
+ contentWidth,
+ contentHeight,
+ bounds
+ );
+ }
+
const { x, y } = this._drawLiquid.translatePage(
page,
this.pageLayoutType,
@@ -185,6 +204,8 @@ export class DocBackground extends DocComponent {
pageLeft += x;
pageTop += y;
}
+
+ this._drawPaginatedPlaceholderPages(ctx, pages[pages.length - 1], pageLeft, pageTop, bounds);
}
private _drawWorkspaceBackground(ctx: UniverRenderingContext, fill: string, bounds?: IViewportInfo) {
@@ -209,6 +230,125 @@ export class DocBackground extends DocComponent {
ctx.restore();
}
+ private _drawPaginatedPlaceholderPages(
+ ctx: UniverRenderingContext,
+ templatePage: IDocumentSkeletonPage,
+ initialPageLeft: number,
+ initialPageTop: number,
+ bounds?: IViewportInfo
+ ): void {
+ const progress = this.getSkeleton()?.getLayoutProgress?.();
+ const publishedPageCount = this.getSkeleton()?.getSkeletonData()?.pages.length ?? progress?.pageCount ?? 0;
+ if (progress == null || progress.complete || progress.estimatedPageCount <= publishedPageCount) {
+ return;
+ }
+
+ const visibleBound = bounds?.cacheBound ?? bounds?.viewBound;
+ let pageLeft = initialPageLeft;
+ let pageTop = initialPageTop;
+
+ for (let pageIndex = publishedPageCount; pageIndex < progress.estimatedPageCount; pageIndex++) {
+ const isVisible = visibleBound == null || !(
+ pageLeft + templatePage.pageWidth < visibleBound.left ||
+ pageLeft > visibleBound.right ||
+ pageTop + templatePage.pageHeight < visibleBound.top ||
+ pageTop > visibleBound.bottom
+ );
+
+ if (isVisible) {
+ ctx.save();
+ ctx.translate(pageLeft - 0.5, pageTop - 0.5);
+ Rect.drawWith(ctx, {
+ width: templatePage.pageWidth,
+ height: templatePage.pageHeight,
+ strokeWidth: 1,
+ stroke: this._pageStrokeColor ?? PAGE_STROKE_COLOR,
+ fill: this._pageFillColor ?? PAGE_FILL_COLOR,
+ zIndex: 3,
+ });
+ ctx.restore();
+
+ const contentLeft = pageLeft + templatePage.marginLeft;
+ const contentTop = pageTop + templatePage.marginTop + 24;
+ const contentWidth = Math.max(
+ 80,
+ templatePage.pageWidth - templatePage.marginLeft - templatePage.marginRight
+ );
+ const contentHeight = Math.max(
+ 160,
+ templatePage.pageHeight - templatePage.marginTop - templatePage.marginBottom - 48
+ );
+ this._drawSkeletonLines(ctx, contentLeft, contentTop, contentWidth, contentHeight, bounds);
+ }
+
+ const offset = this._drawLiquid.translatePage(
+ templatePage,
+ this.pageLayoutType,
+ this.pageMarginLeft,
+ this.pageMarginTop
+ );
+ pageLeft += offset.x;
+ pageTop += offset.y;
+ }
+ }
+
+ private _drawContinuousLayoutSkeleton(ctx: UniverRenderingContext, bounds?: IViewportInfo): void {
+ const skeleton = this.getSkeleton();
+ const progress = skeleton?.getLayoutProgress?.();
+ const page = skeleton?.getSkeletonData()?.pages[0];
+ if (progress == null || progress.complete || page == null) {
+ return;
+ }
+
+ const visibleBound = bounds?.cacheBound ?? bounds?.viewBound;
+ const startX = page.marginLeft;
+ const startY = Math.max(page.marginTop, page.height + 20);
+ const width = Math.max(80, page.pageWidth - page.marginLeft - page.marginRight);
+ const visibleBottom = visibleBound?.bottom ?? startY + 320;
+ this._drawSkeletonLines(ctx, startX, startY, width, Math.max(160, visibleBottom - startY), bounds);
+ }
+
+ private _drawSkeletonLines(
+ ctx: UniverRenderingContext,
+ left: number,
+ top: number,
+ width: number,
+ height: number,
+ bounds?: IViewportInfo
+ ): void {
+ if (height <= SKELETON_LINE_HEIGHT) {
+ return;
+ }
+
+ const visibleBound = bounds?.cacheBound ?? bounds?.viewBound;
+ const animationPhase = (Date.now() % 1200) / 1200;
+ const highlightWidth = Math.max(80, width * 0.35);
+ const highlightLeft = left - highlightWidth + (width + highlightWidth * 2) * animationPhase;
+ const gradient = ctx.createLinearGradient(highlightLeft, 0, highlightLeft + highlightWidth, 0);
+ gradient.addColorStop(0, SKELETON_BASE_COLOR);
+ gradient.addColorStop(0.5, SKELETON_HIGHLIGHT_COLOR);
+ gradient.addColorStop(1, SKELETON_BASE_COLOR);
+
+ ctx.save();
+ ctx.fillStyle = gradient;
+ const lineStep = SKELETON_LINE_HEIGHT + SKELETON_LINE_GAP;
+ const lineCount = Math.min(12, Math.ceil(height / lineStep));
+ for (let index = 0; index < lineCount; index++) {
+ const y = top + index * lineStep;
+ if (visibleBound != null && (y + SKELETON_LINE_HEIGHT < visibleBound.top || y > visibleBound.bottom)) {
+ continue;
+ }
+ const lineWidth = index % 4 === 3 ? width * 0.62 : width * (0.82 + (index % 3) * 0.07);
+ ctx.beginPath();
+ ctx.roundRect(left, y, lineWidth, SKELETON_LINE_HEIGHT, SKELETON_LINE_HEIGHT / 2);
+ ctx.fill();
+ }
+ ctx.restore();
+
+ // Keep only the lightweight background layer animating while layout is incomplete.
+ this.makeDirty(true);
+ }
+
private _drawPageBackgroundImage(ctx: UniverRenderingContext, source: string | undefined, width: number, height: number) {
if (!source || width <= 0 || height <= 0) {
return;
diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.ts
index 18d6e82ded..ab56373a89 100644
--- a/packages/engine-render/src/components/docs/document.ts
+++ b/packages/engine-render/src/components/docs/document.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { DocumentFlavor, ICustomRange, IDocumentRenderConfig, IScale, ITableCell, ITableCellBorder, Nullable } from '@univerjs/core';
+import type { ICustomRange, IDocumentRenderConfig, IScale, ITableCell, ITableCellBorder, Nullable } from '@univerjs/core';
import type {
IDocumentSkeletonColumnGroup,
IDocumentSkeletonColumnGroupColumn,
@@ -33,7 +33,7 @@ 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 { CellValueType, ColumnSeparatorType, DashStyleType, HorizontalAlign, VerticalAlign, WrapStrategy } from '@univerjs/core';
+import { CellValueType, ColumnSeparatorType, DashStyleType, DocumentFlavor, HorizontalAlign, VerticalAlign, WrapStrategy } from '@univerjs/core';
import { Subject } from 'rxjs';
import { BORDER_TYPE as BORDER_LTRB, drawLineByBorderType } from '../../basics';
import { calculateRectRotate, getRotateOffsetAndFarthestHypotenuse } from '../../basics/draw';
@@ -59,6 +59,46 @@ const DEFAULT_BORDER_COLOR: ITableCellBorder = {
};
const TABLE_VIEWPORT_BORDER_CLIP_PADDING = 2;
const TABLE_OVERFLOW_INTERACTION_PADDING = 24;
+const CONTINUOUS_LAYOUT_LINE_OVERSCAN = 240;
+
+function getLineTop(line: IDocumentSkeletonLine): number {
+ return line.top + (line.marginTop ?? 0) + (line.paddingTop ?? 0);
+}
+
+function getVisibleContinuousLineRange(
+ lines: IDocumentSkeletonLine[],
+ viewportTop: number,
+ viewportBottom: number,
+ flowTop: number
+): { start: number; end: number } {
+ const visibleTop = viewportTop - CONTINUOUS_LAYOUT_LINE_OVERSCAN - flowTop;
+ const visibleBottom = viewportBottom + CONTINUOUS_LAYOUT_LINE_OVERSCAN - flowTop;
+ let low = 0;
+ let high = lines.length;
+
+ while (low < high) {
+ const middle = (low + high) >>> 1;
+ const line = lines[middle];
+ const lineBottom = getLineTop(line) + (line.lineHeight ?? 0);
+ if (lineBottom < visibleTop) {
+ low = middle + 1;
+ } else {
+ high = middle;
+ }
+ }
+ const start = low;
+ high = lines.length;
+ while (low < high) {
+ const middle = (low + high) >>> 1;
+ if (getLineTop(lines[middle]) <= visibleBottom) {
+ low = middle + 1;
+ } else {
+ high = middle;
+ }
+ }
+
+ return { start, end: low };
+}
export function resolveHeaderFooterFieldGlyph(
glyph: IDocumentSkeletonGlyph,
@@ -239,6 +279,7 @@ export class Documents extends DocComponent {
this._drawLiquid.reset();
const { pages, skeHeaders, skeFooters } = skeletonData;
+ const isContinuousLayout = this.getSkeleton()?.getViewModel?.().getDataModel().documentStyle.documentFlavor === DocumentFlavor.MODERN;
const parentScale = this.getParentScale();
// const scale = getScale(parentScale);
const extensions = this.getExtensionsByOrder();
@@ -304,7 +345,7 @@ export class Documents extends DocComponent {
const vertexAngle = degToRad(vertexAngleDeg);
const finalAngle = vertexAngle - centerAngle;
- if (this.isSkipByDiffBounds(page, pageTop, pageLeft, bounds)) {
+ if (!isContinuousLayout && this.isSkipByDiffBounds(page, pageTop, pageLeft, bounds)) {
const { x, y } = this._drawLiquid.translatePage(
page,
this.pageLayoutType,
@@ -390,6 +431,14 @@ export class Documents extends DocComponent {
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;
@@ -453,10 +502,27 @@ export class Documents extends DocComponent {
alignOffset.x = pagePaddingLeft;
}
- for (let i = 0; i < linesCount; i++) {
+ 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);
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 be9cbd9d87..aa7763c097 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
@@ -22,6 +22,7 @@ import {
DataStreamTreeTokenType,
DocumentDataModel,
DocumentFlavor,
+ DrawingTypeEnum,
GridType,
LocaleService,
ObjectRelativeFromH,
@@ -30,17 +31,115 @@ import {
PositionedObjectLayoutType,
SectionType,
SpacingRule,
+ TableAlignmentType,
+ TableRowHeightRule,
TableSizeType,
+ TableTextWrapType,
Univer,
+ VerticalAlignmentType,
WrapTextType,
} from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
-import { DocumentSkeletonPageType, GlyphType, PageLayoutType } from '../../../../basics/i-document-skeleton-cached';
+import {
+ DocumentSkeletonPageType,
+ GlyphType,
+ PageLayoutType,
+} from '../../../../basics/i-document-skeleton-cached';
import { Vector2 } from '../../../../basics/vector2';
+import { setDocsCustomBlockRenderViewportProvider } from '../../custom-block-render-viewport';
import { DocumentViewModel } from '../../view-model/document-view-model';
import { DocumentSkeleton } from '../doc-skeleton';
import { FontCache } from '../shaping-engine/font-cache';
+function normalizeSkeleton(value: unknown): unknown {
+ if (typeof value === 'number' && Object.is(value, -0)) {
+ return 0;
+ }
+ if (value instanceof Map) {
+ return [...value.entries()]
+ .sort(([left], [right]) => String(left).localeCompare(String(right)))
+ .map(([key, entryValue]) => [key, normalizeSkeleton(entryValue)]);
+ }
+ if (Array.isArray(value)) {
+ return value.map(normalizeSkeleton);
+ }
+ if (value != null && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value)
+ .filter(([key]) => key !== 'parent')
+ .map(([key, entryValue]) => [key, normalizeSkeleton(entryValue)])
+ );
+ }
+ return value;
+}
+
+function completeIncrementalLayout(skeleton: DocumentSkeleton, anchor?: number) {
+ const generation = skeleton.startIncrementalLayout({
+ reason: anchor == null ? 'initial' : 'edit',
+ anchor,
+ });
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let step = 0; step < 20_000 && !progress.complete; step++) {
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+
+ expect(progress).toMatchObject({ complete: true, cancelled: false });
+ return progress;
+}
+
+function createSkeletonDrawing(drawingId: string, unitId: string) {
+ return {
+ drawingId,
+ aLeft: 0,
+ aTop: 0,
+ width: 100,
+ height: 50,
+ angle: 0,
+ initialState: true,
+ drawingOrigin: {
+ drawingId,
+ drawingType: DrawingTypeEnum.DRAWING_BLOCK,
+ unitId,
+ subUnitId: unitId,
+ docTransform: {
+ angle: 0,
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PARAGRAPH, posOffset: 0 },
+ size: { width: 100, height: 50 },
+ },
+ layoutType: PositionedObjectLayoutType.INLINE,
+ },
+ columnLeft: 0,
+ isPageBreak: false,
+ lineTop: 0,
+ lineHeight: 50,
+ blockAnchorTop: 0,
+ customBlockRenderViewport: { contentHeight: 50, viewportHeight: 10, viewScale: 1 },
+ };
+}
+
+function expectIncrementalSkeletonToEqualSynchronous(
+ snapshot: ConstructorParameters<typeof DocumentDataModel>[0],
+ localeService: LocaleService,
+ anchor?: number
+) {
+ const synchronous = DocumentSkeleton.create(
+ new DocumentViewModel(new DocumentDataModel(structuredClone(snapshot))),
+ localeService
+ );
+ const incremental = DocumentSkeleton.create(
+ new DocumentViewModel(new DocumentDataModel(structuredClone(snapshot))),
+ localeService
+ );
+
+ synchronous.calculate();
+ completeIncrementalLayout(incremental, anchor);
+ expect(normalizeSkeleton(incremental.getSkeletonData())).toEqual(normalizeSkeleton(synchronous.getSkeletonData()));
+
+ incremental.dispose();
+ synchronous.dispose();
+}
+
function createPage(type: DocumentSkeletonPageType, st: number, tableId = '') {
const listGlyph = { st, ed: st, count: 1, width: 3, left: 0, xOffset: 0, content: '•', glyphType: GlyphType.LIST } as any;
const glyphA = { st: st + 1, ed: st + 1, count: 1, width: 4, left: 3, xOffset: 0, content: 'A', glyphType: GlyphType.WORD } as any;
@@ -111,6 +210,44 @@ function createPage(type: DocumentSkeletonPageType, st: number, tableId = '') {
}
describe('doc skeleton', () => {
+ it('publishes one presentation batch while preserving incompatible flow metrics', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const documentModel = createDocumentModelWithStyle('Presentation refresh\r', {});
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+ skeleton.calculate();
+
+ const drawings = skeleton.getSkeletonData()?.pages[0].skeDrawings;
+ expect(drawings).toBeDefined();
+ drawings?.set('stable', createSkeletonDrawing('stable', documentModel.getUnitId()));
+ drawings?.set('flow-change', createSkeletonDrawing('flow-change', documentModel.getUnitId()));
+
+ const unregister = setDocsCustomBlockRenderViewportProvider((_unitId, drawingId) => ({
+ width: drawingId === 'flow-change' ? 101 : 100,
+ height: 50,
+ contentHeight: 60,
+ viewScale: 0.5,
+ viewportHeight: 99,
+ }));
+ const result = skeleton.refreshCustomBlockPresentationViewports();
+
+ expect(result).toEqual({ didRefresh: true, requiresLayout: true });
+ expect(drawings?.get('stable')?.customBlockRenderViewport).toMatchObject({
+ contentHeight: 60,
+ viewScale: 0.5,
+ viewportHeight: 99,
+ });
+ expect(drawings?.get('flow-change')?.customBlockRenderViewport).toMatchObject({
+ contentHeight: 50,
+ viewScale: 0.5,
+ viewportHeight: 99,
+ });
+
+ unregister();
+ skeleton.dispose();
+ univer.dispose();
+ });
+
it('uses empty paragraph glyphs as mouse hit-test targets', () => {
const body = createPage(DocumentSkeletonPageType.BODY, 0);
const emptyParagraphGlyph = {
@@ -913,6 +1050,17 @@ describe('doc skeleton', () => {
expect(createSkeletonSpy.mock.calls.length).toBeGreaterThan(1);
expect(skeleton.getSkeletonData()?.pages.map(({ pageNumber }) => pageNumber)).toEqual([1, 2]);
+ const incremental = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+ const generation = incremental.startIncrementalLayout({ reason: 'initial' });
+ let progress = incremental.stepIncrementalLayout(generation, 0);
+ for (let step = 0; step < 1_000 && !progress.complete; step++) {
+ progress = incremental.stepIncrementalLayout(generation, 0);
+ }
+
+ expect(progress.complete).toBe(true);
+ expect(normalizeSkeleton(incremental.getSkeletonData())).toEqual(normalizeSkeleton(skeleton.getSkeletonData()));
+
+ incremental.dispose();
skeleton.dispose();
univer.dispose();
});
@@ -929,7 +1077,9 @@ describe('doc skeleton', () => {
const viewModel = new DocumentViewModel(documentModel);
const skeleton = DocumentSkeleton.create(viewModel, localeService);
+ expect(skeleton.hasCompleteLayout()).toBe(false);
skeleton.calculate();
+ expect(skeleton.hasCompleteLayout()).toBe(true);
const skeletonData = skeleton.getSkeletonData();
expect(skeletonData?.pages.length).toBeGreaterThan(0);
@@ -959,6 +1109,1032 @@ describe('doc skeleton', () => {
univer.dispose();
});
+ it.each([
+ ['traditional', DocumentFlavor.TRADITIONAL],
+ ['modern', DocumentFlavor.MODERN],
+ ])('incremental %s layout converges to the synchronous skeleton', (_, documentFlavor) => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const content = Array.from(
+ { length: 18 },
+ (_, index) => `Paragraph ${index} contains enough words to wrap and exercise resumable document layout.\r`
+ ).join('');
+ const sourceModel = createDocumentModelWithStyle(content, {});
+ sourceModel.updateDocumentStyle({ documentFlavor });
+ const snapshot = structuredClone(sourceModel.getSnapshot());
+ const syncSkeleton = DocumentSkeleton.create(
+ new DocumentViewModel(new DocumentDataModel(structuredClone(snapshot))),
+ localeService
+ );
+ const incrementalSkeleton = DocumentSkeleton.create(
+ new DocumentViewModel(new DocumentDataModel(structuredClone(snapshot))),
+ localeService
+ );
+
+ syncSkeleton.calculate();
+ const generation = incrementalSkeleton.startIncrementalLayout({ anchor: Math.floor(content.length / 3) });
+ const progressSnapshots: ReturnType<DocumentSkeleton['stepIncrementalLayout']>[] = [];
+ for (let index = 0; index < 100; index++) {
+ const progress = incrementalSkeleton.stepIncrementalLayout(generation, 0);
+ progressSnapshots.push(progress);
+ if (progress.complete) {
+ break;
+ }
+ }
+
+ expect(progressSnapshots.some((progress) => !progress.complete)).toBe(true);
+ expect(progressSnapshots.at(-1)?.complete).toBe(true);
+ expect(progressSnapshots.at(-1)?.mode).toBe(documentFlavor === DocumentFlavor.MODERN ? 'continuous' : 'paginated');
+ expect(normalizeSkeleton(incrementalSkeleton.getSkeletonData())).toEqual(normalizeSkeleton(syncSkeleton.getSkeletonData()));
+
+ syncSkeleton.dispose();
+ incrementalSkeleton.dispose();
+ univer.dispose();
+ });
+
+ it('keeps a paginated body table structurally identical after incremental layout', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const T = DataStreamTreeTokenType;
+ const cellText = 'A long table cell keeps flowing across physical pages. '.repeat(80);
+ const tableStream = [
+ T.TABLE_START,
+ T.TABLE_ROW_START,
+ T.TABLE_CELL_START,
+ cellText,
+ T.PARAGRAPH,
+ T.SECTION_BREAK,
+ T.TABLE_CELL_END,
+ T.TABLE_ROW_END,
+ T.TABLE_END,
+ ].join('');
+ const trailingText = `Paragraph after the table.${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const dataStream = `${tableStream}${trailingText}`;
+ const cellParagraphIndex = 3 + cellText.length;
+ const snapshot = {
+ id: 'incremental-table-equivalence',
+ body: {
+ dataStream,
+ paragraphs: [
+ { startIndex: cellParagraphIndex, paragraphId: 'cell-paragraph' },
+ { startIndex: dataStream.length - 2, paragraphId: 'trailing-paragraph' },
+ ],
+ sectionBreaks: [
+ { sectionId: 'cell-section', startIndex: cellParagraphIndex + 1 },
+ { sectionId: 'body-section', startIndex: dataStream.length - 1 },
+ ],
+ tables: [{ startIndex: 0, endIndex: tableStream.length, tableId: 'body-table' }],
+ },
+ tableSource: {
+ 'body-table': {
+ tableId: 'body-table',
+ align: TableAlignmentType.CENTER,
+ 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: 220 } },
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 220 } } }],
+ tableRows: [{
+ repeatHeaderRow: BooleanNumber.FALSE,
+ trHeight: {
+ hRule: TableRowHeightRule.AUTO,
+ val: { v: 0 },
+ },
+ tableCells: [{ vAlign: VerticalAlignmentType.TOP }],
+ }],
+ },
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 280, height: 220 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ };
+
+ expectIncrementalSkeletonToEqualSynchronous(snapshot, localeService, Math.floor(cellText.length / 2));
+
+ univer.dispose();
+ });
+
+ it('publishes a traditional first-open layout one stable page at a time', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const content = Array.from(
+ { length: 100 },
+ (_, index) => `Opening paragraph ${index} wraps onto compact physical pages.\r`
+ ).join('');
+ const documentModel = createDocumentModelWithStyle(content, {});
+ documentModel.updateDocumentDataPageSize(160, 180);
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+
+ const generation = skeleton.startIncrementalLayout({ reason: 'initial' });
+ const publications: number[] = [];
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let index = 0; index < 500 && !progress.complete; index++) {
+ if (progress.didPublish) {
+ publications.push(progress.publishedPageCount);
+ }
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+ if (progress.didPublish) {
+ publications.push(progress.publishedPageCount);
+ }
+
+ expect(progress.complete).toBe(true);
+ expect(publications.length).toBeGreaterThan(2);
+ expect(publications[0]).toBe(1);
+ expect(publications.every((count, index) => index === 0 || count - publications[index - 1] === 1)).toBe(true);
+
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it('publishes computed page backlog without advancing layout work', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const content = Array.from(
+ { length: 100 },
+ (_, index) => `Backlog paragraph ${index} wraps onto compact physical pages.\r`
+ ).join('');
+ const documentModel = createDocumentModelWithStyle(content, {});
+ documentModel.updateDocumentDataPageSize(160, 180);
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+
+ const generation = skeleton.startIncrementalLayout({ reason: 'initial' });
+ const first = skeleton.stepIncrementalLayout(generation, 10_000);
+ const backlog = skeleton.publishIncrementalLayoutBacklog(generation);
+
+ expect(first.didPublish).toBe(true);
+ expect(first.publishedPageCount).toBe(1);
+ expect(first.processedBlockCount).toBe(first.totalBlockCount);
+ expect(backlog.didPublish).toBe(true);
+ expect(backlog.publishedPageCount).toBe(2);
+ expect(backlog.processedBlockCount).toBe(first.processedBlockCount);
+
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it('does not report a page backlog for continuous layout', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const content = Array.from(
+ { length: 100 },
+ (_, index) => `Continuous paragraph ${index} remains in one document flow.\r`
+ ).join('');
+ const documentModel = createDocumentModelWithStyle(content, {});
+ documentModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+
+ const generation = skeleton.startIncrementalLayout({ reason: 'initial' });
+ const first = skeleton.stepIncrementalLayout(generation, 0);
+ const backlog = skeleton.publishIncrementalLayoutBacklog(generation);
+
+ expect(first.didPublish).toBe(true);
+ expect(backlog.didPublish).toBe(false);
+ expect(backlog.processedBlockCount).toBe(first.processedBlockCount);
+ expect(backlog.publicationRevision).toBe(first.publicationRevision);
+
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it('merges legacy section identities into one continuous modern page', () => {
+ const first = `First modern section${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`;
+ const second = `Second modern section${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`;
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const documentModel = new DocumentDataModel({
+ id: 'modern-legacy-sections',
+ body: {
+ dataStream: `${first}${second}`,
+ paragraphs: [
+ { startIndex: first.length - 2, paragraphId: 'first-paragraph' },
+ { startIndex: first.length + second.length - 2, paragraphId: 'second-paragraph' },
+ ],
+ sectionBreaks: [
+ { sectionId: 'legacy-first-section', startIndex: first.length - 1 },
+ { sectionId: 'legacy-second-section', startIndex: first.length + second.length - 1 },
+ ],
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.MODERN,
+ pageSize: { width: 320, height: 400 },
+ },
+ });
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+
+ const generation = skeleton.startIncrementalLayout({ reason: 'initial' });
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let step = 0; step < 20 && !progress.complete; step++) {
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+
+ expect(progress).toMatchObject({ complete: true, mode: 'continuous', pageCount: 1 });
+ expect(skeleton.getSkeletonData()?.pages).toHaveLength(1);
+
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it('drains pages sequentially when the final block creates a multi-page tail', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const pageBreak = DataStreamTreeTokenType.PAGE_BREAK;
+ const tail = Array.from({ length: 20 }, (_, index) => `Tail page ${index}${pageBreak}`).join('');
+ const documentModel = createDocumentModelWithStyle(
+ `${tail}\r`,
+ {}
+ );
+ documentModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.TRADITIONAL });
+ documentModel.updateDocumentDataPageSize(160, 180);
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+
+ const generation = skeleton.startIncrementalLayout({ reason: 'initial' });
+ const publications: number[] = [];
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let index = 0; index < 2_000 && !progress.complete; index++) {
+ if (progress.didPublish) {
+ publications.push(progress.publishedPageCount);
+ }
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+ if (progress.didPublish) {
+ publications.push(progress.publishedPageCount);
+ }
+
+ expect(progress.complete).toBe(true);
+ expect(publications.length).toBeGreaterThan(10);
+ expect(publications.every((count, index) => index === 0 || count - publications[index - 1] === 1)).toBe(true);
+ expect(publications.at(-1)).toBe(skeleton.getSkeletonData()?.pages.length);
+
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it('publishes the edited page first and then advances the affected tail one page at a time', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const content = Array.from(
+ { length: 140 },
+ (_, index) => `Editing paragraph ${index} wraps onto compact physical pages.\r`
+ ).join('');
+ const documentModel = createDocumentModelWithStyle(content, {});
+ documentModel.updateDocumentDataPageSize(160, 180);
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+ skeleton.calculate();
+ const previousPages = skeleton.getSkeletonData()!.pages;
+ expect(previousPages.length).toBeGreaterThan(7);
+ const editedPageIndex = 6;
+
+ const generation = skeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor: previousPages[editedPageIndex].st,
+ });
+ const publications: number[] = [];
+ const anchorPublications: boolean[] = [];
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let index = 0; index < 500 && !progress.complete; index++) {
+ if (progress.didPublish) {
+ publications.push(progress.publishedPageCount);
+ anchorPublications.push(progress.didPublishAnchor);
+ }
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+ if (progress.didPublish) {
+ publications.push(progress.publishedPageCount);
+ anchorPublications.push(progress.didPublishAnchor);
+ }
+
+ expect(progress.complete).toBe(true);
+ expect(publications[0]).toBe(editedPageIndex + 1);
+ expect(publications.every((count, index) => index === 0 || count - publications[index - 1] === 1)).toBe(true);
+ expect(anchorPublications[0]).toBe(true);
+ expect(anchorPublications.slice(1).every((didPublishAnchor) => !didPublishAnchor)).toBe(true);
+
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it('reuses the unaffected tail when an insertion keeps the edited page boundary stable', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const content = Array.from(
+ { length: 140 },
+ (_, index) => `Stable paragraph ${index} leaves room for a local insertion.\r`
+ ).join('');
+ const oldModel = createDocumentModelWithStyle(content, {});
+ oldModel.updateDocumentDataPageSize(240, 260);
+ const viewModel = new DocumentViewModel(oldModel);
+ const skeleton = DocumentSkeleton.create(viewModel, localeService);
+ skeleton.calculate();
+ const previousPages = skeleton.getSkeletonData()!.pages;
+ expect(previousPages.length).toBeGreaterThan(7);
+ const editedPageIndex = 6;
+ const anchor = previousPages[editedPageIndex].st + 5;
+ const oldDataStream = oldModel.getBody()!.dataStream;
+ const nextContent = `${oldDataStream.slice(0, anchor)}x${oldDataStream.slice(anchor)}`;
+ const nextSnapshot = structuredClone(oldModel.getSnapshot());
+ nextSnapshot.body!.dataStream = nextContent;
+ for (const paragraph of nextSnapshot.body!.paragraphs ?? []) {
+ if (paragraph.startIndex >= anchor) {
+ paragraph.startIndex++;
+ }
+ }
+ for (const sectionBreak of nextSnapshot.body!.sectionBreaks ?? []) {
+ if (sectionBreak.startIndex >= anchor) {
+ sectionBreak.startIndex++;
+ }
+ }
+ const nextModel = new DocumentDataModel(nextSnapshot);
+ viewModel.reset(nextModel);
+ const expected = DocumentSkeleton.create(new DocumentViewModel(nextModel), localeService);
+ expected.calculate();
+ const expectedPageCount = expected.getSkeletonData()!.pages.length;
+
+ const generation = skeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor,
+ invalidation: {
+ oldStart: anchor,
+ oldEnd: anchor,
+ newEnd: anchor + 1,
+ },
+ });
+ const publications: ReturnType<DocumentSkeleton['stepIncrementalLayout']>[] = [];
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let index = 0; index < 500 && !progress.complete; index++) {
+ if (progress.didPublish) {
+ publications.push(progress);
+ }
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+ if (progress.didPublish) {
+ publications.push(progress);
+ }
+
+ expect(progress.complete).toBe(true);
+ expect(publications).toHaveLength(1);
+ expect(publications[0]).toMatchObject({
+ didPublishAnchor: true,
+ publishedPageCount: expectedPageCount,
+ });
+ expect(normalizeSkeleton(skeleton.getSkeletonData()?.pages)).toEqual(
+ normalizeSkeleton(expected.getSkeletonData()?.pages)
+ );
+
+ expected.dispose();
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it('rebuilds the active interaction page without synchronously traversing an earlier remote edit', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const content = Array.from(
+ { length: 180 },
+ (_, index) => `Collaborative paragraph ${index} wraps onto compact physical pages.\r`
+ ).join('');
+ const oldModel = createDocumentModelWithStyle(content, {});
+ oldModel.updateDocumentDataPageSize(180, 200);
+ const viewModel = new DocumentViewModel(oldModel);
+ const skeleton = DocumentSkeleton.create(viewModel, localeService);
+ skeleton.calculate();
+ const previousPages = skeleton.getSkeletonData()!.pages;
+ expect(previousPages.length).toBeGreaterThan(10);
+
+ const dirtyPageIndex = 1;
+ const activePageIndex = 8;
+ const dirtyOffset = previousPages[dirtyPageIndex].st + 2;
+ const previousActiveOffset = previousPages[activePageIndex].st + 5;
+ const nextSnapshot = structuredClone(oldModel.getSnapshot());
+ const previousDataStream = nextSnapshot.body!.dataStream;
+ nextSnapshot.body!.dataStream = `${previousDataStream.slice(0, dirtyOffset)}B${previousDataStream.slice(dirtyOffset)}`;
+ for (const paragraph of nextSnapshot.body!.paragraphs ?? []) {
+ if (paragraph.startIndex >= dirtyOffset) {
+ paragraph.startIndex++;
+ }
+ }
+ const nextModel = new DocumentDataModel(nextSnapshot);
+ viewModel.reset(nextModel);
+
+ const priorityAnchor = previousActiveOffset + 1;
+ const generation = skeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor: priorityAnchor,
+ priorityAnchor,
+ invalidation: {
+ oldStart: dirtyOffset,
+ oldEnd: dirtyOffset,
+ newEnd: dirtyOffset + 1,
+ },
+ preserveInteractionWindow: true,
+ });
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let step = 0; step < 500 && !progress.anchorReady; step++) {
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+
+ expect(progress.anchorReady).toBe(true);
+ expect(progress.publishedPageCount).toBeGreaterThanOrEqual(activePageIndex + 1);
+ expect(skeleton.getSkeletonData()?.pages[dirtyPageIndex]).toMatchObject({
+ isLayoutPlaceholder: true,
+ });
+ expect(skeleton.findNodePositionByCharIndex(priorityAnchor)?.page).toBeGreaterThanOrEqual(activePageIndex - 1);
+
+ skeleton.dispose();
+ nextModel.dispose();
+ univer.dispose();
+ });
+
+ it('preserves logical offsets after explicit page breaks in a foreground interaction publication', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const pageBreak = DataStreamTreeTokenType.PAGE_BREAK;
+ const content = [
+ `First explicit page${pageBreak}`,
+ `Second explicit page${pageBreak}`,
+ `Third explicit page${pageBreak}`,
+ `Fourth explicit page${pageBreak}`,
+ 'The target paragraph ends here.\r',
+ ].join('');
+ const initialModel = createDocumentModelWithStyle(content, {});
+ initialModel.updateDocumentDataPageSize(240, 260);
+ const viewModel = new DocumentViewModel(initialModel);
+ const skeleton = DocumentSkeleton.create(viewModel, localeService);
+ skeleton.calculate();
+
+ const initialBody = initialModel.getBody();
+ if (initialBody == null) {
+ throw new Error('Expected an initial document body');
+ }
+ const initialStream = initialBody.dataStream;
+ const insertionOffset = initialStream.indexOf('ends here') + 'ends here'.length;
+ const nextSnapshot = structuredClone(initialModel.getSnapshot());
+ if (nextSnapshot.body == null) {
+ throw new Error('Expected a cloned document body');
+ }
+ nextSnapshot.body.dataStream = `${initialStream.slice(0, insertionOffset)}Y${initialStream.slice(insertionOffset)}`;
+ for (const paragraph of nextSnapshot.body.paragraphs ?? []) {
+ if (paragraph.startIndex >= insertionOffset) {
+ paragraph.startIndex++;
+ }
+ }
+ const nextModel = new DocumentDataModel(nextSnapshot);
+ viewModel.reset(nextModel);
+
+ const priorityAnchor = insertionOffset + 1;
+ const generation = skeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor: insertionOffset,
+ priorityAnchor,
+ invalidation: {
+ oldStart: insertionOffset,
+ oldEnd: insertionOffset,
+ newEnd: priorityAnchor,
+ },
+ preserveInteractionWindow: true,
+ });
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let step = 0; step < 500 && !progress.anchorReady; step++) {
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+
+ expect(progress.anchorReady).toBe(true);
+ const position = skeleton.findNodePositionByCharIndex(priorityAnchor, true);
+ if (position == null) {
+ throw new Error('Expected a caret position for the foreground anchor');
+ }
+ expect(skeleton.findCharIndexByPosition(position)).toBe(priorityAnchor);
+ const skeletonData = skeleton.getSkeletonData();
+ if (skeletonData == null) {
+ throw new Error('Expected foreground skeleton data');
+ }
+ const targetGlyph = skeletonData.pages
+ .flatMap((page) => page.sections)
+ .flatMap((section) => section.columns)
+ .flatMap((column) => column.lines)
+ .flatMap((line) => line.divides)
+ .flatMap((divide) => divide.glyphGroup)
+ .find((glyph) => (glyph.raw ?? glyph.content) === 'Y');
+ if (targetGlyph == null) {
+ throw new Error('Expected the inserted glyph in the foreground skeleton');
+ }
+ const targetPosition = skeleton.findPositionByGlyph(targetGlyph, -1);
+ if (targetPosition == null) {
+ throw new Error('Expected a caret position for the inserted glyph');
+ }
+ expect(skeleton.findCharIndexByPosition({ ...targetPosition, isBack: false })).toBe(priorityAnchor);
+
+ skeleton.dispose();
+ nextModel.dispose();
+ univer.dispose();
+ });
+
+ it('preserves explicit page-break offsets when foreground layout restarts at the document start', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const pageBreak = DataStreamTreeTokenType.PAGE_BREAK;
+ const phrase = 'The target paragraph ends here.';
+ const content = [
+ `First explicit page${pageBreak}`,
+ `Second explicit page${pageBreak}`,
+ `Third explicit page${pageBreak}`,
+ `Fourth explicit page${pageBreak}`,
+ `${phrase}\r`,
+ ].join('');
+ const dataModel = createDocumentModelWithStyle(content, {});
+ dataModel.updateDocumentDataPageSize(240, 260);
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(dataModel), localeService);
+ skeleton.calculate();
+
+ const generation = skeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor: 0,
+ priorityAnchor: 0,
+ });
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let step = 0; step < 500 && progress.publishedPageCount < 5; step++) {
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+
+ const expectedOffset = content.indexOf(phrase) + phrase.length;
+ const skeletonData = skeleton.getSkeletonData();
+ if (skeletonData == null) {
+ throw new Error('Expected foreground skeleton data');
+ }
+ const targetLine = skeletonData.pages
+ .flatMap((page) => page.sections)
+ .flatMap((section) => section.columns)
+ .flatMap((column) => column.lines)
+ .find((line) => line.divides
+ .flatMap((divide) => divide.glyphGroup)
+ .map((glyph) => glyph.raw ?? glyph.content)
+ .join('')
+ .includes(phrase));
+ if (targetLine == null) {
+ throw new Error('Expected the target paragraph in the foreground skeleton');
+ }
+ const targetText = targetLine.divides
+ .flatMap((divide) => divide.glyphGroup)
+ .map((glyph) => glyph.raw ?? glyph.content)
+ .join('');
+ expect(targetLine.st + targetText.indexOf(phrase) + phrase.length).toBe(expectedOffset);
+
+ skeleton.dispose();
+ dataModel.dispose();
+ univer.dispose();
+ });
+
+ it('keeps cancelled typing generations anchored to the first dirty physical page', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const content = Array.from(
+ { length: 140 },
+ (_, index) => `Typing paragraph ${index} wraps onto compact physical pages.\r`
+ ).join('');
+ const initialModel = createDocumentModelWithStyle(content, {});
+ initialModel.updateDocumentDataPageSize(160, 180);
+ const viewModel = new DocumentViewModel(initialModel);
+ const skeleton = DocumentSkeleton.create(viewModel, localeService);
+ skeleton.calculate();
+
+ const initialPages = skeleton.getSkeletonData()!.pages;
+ expect(initialPages.length).toBeGreaterThan(7);
+ const editedPageIndex = 6;
+ const firstDirtyOffset = initialPages[editedPageIndex].ed - 8;
+ skeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor: firstDirtyOffset,
+ invalidation: {
+ oldStart: firstDirtyOffset,
+ oldEnd: firstDirtyOffset,
+ newEnd: firstDirtyOffset + 1,
+ },
+ });
+
+ // Continuous typing can advance the logical caret past the stale page end
+ // before the previous generation completes. The replacement page must still
+ // be the physical page containing the first uncommitted edit.
+ const latestOffset = initialPages[editedPageIndex].ed + 8;
+ const latestGeneration = skeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor: latestOffset,
+ invalidation: {
+ oldStart: latestOffset,
+ oldEnd: latestOffset,
+ newEnd: latestOffset + 1,
+ },
+ });
+ let progress = skeleton.stepIncrementalLayout(latestGeneration, 0);
+ for (let step = 0; step < 500 && !progress.anchorReady; step++) {
+ progress = skeleton.stepIncrementalLayout(latestGeneration, 0);
+ }
+ expect(progress.anchorReady).toBe(true);
+ expect(progress.laidOutThrough).toBeGreaterThanOrEqual(latestOffset + 1);
+
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it('reuses a safe single-column prefix for an anchored modern layout', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const paragraphs = Array.from(
+ { length: 120 },
+ (_, index) => `Modern paragraph ${index} keeps the continuous prefix stable.\r`
+ );
+ const content = paragraphs.join('');
+ const documentModel = createDocumentModelWithStyle(content, {});
+ documentModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });
+ const snapshot = structuredClone(documentModel.getSnapshot());
+ const skeleton = DocumentSkeleton.create(
+ new DocumentViewModel(new DocumentDataModel(structuredClone(snapshot))),
+ localeService
+ );
+ const expected = DocumentSkeleton.create(
+ new DocumentViewModel(new DocumentDataModel(structuredClone(snapshot))),
+ localeService
+ );
+ skeleton.calculate();
+ expected.calculate();
+
+ const anchor = paragraphs.slice(0, 100).join('').length + 5;
+ const generation = skeleton.startIncrementalLayout({ anchor });
+ const firstProgress = skeleton.stepIncrementalLayout(generation, 0);
+
+ expect(firstProgress.anchorReady).toBe(true);
+ expect(firstProgress.processedBlockCount).toBeGreaterThan(100);
+ let finalProgress = firstProgress;
+ for (let index = 0; index < 30 && !finalProgress.complete; index++) {
+ finalProgress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+ expect(finalProgress.complete).toBe(true);
+ const actualNormalized = normalizeSkeleton(skeleton.getSkeletonData());
+ const expectedNormalized = normalizeSkeleton(expected.getSkeletonData());
+ expect(actualNormalized).toEqual(expectedNormalized);
+
+ skeleton.dispose();
+ expected.dispose();
+ univer.dispose();
+ });
+
+ it('falls back to full incremental layout for a complex modern page', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const paragraphs = Array.from(
+ { length: 20 },
+ (_, index) => `Modern fallback paragraph ${index}.\r`
+ );
+ const documentModel = createDocumentModelWithStyle(paragraphs.join(''), {});
+ documentModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+ skeleton.calculate();
+ skeleton.getSkeletonData()?.pages[0].skeDrawings.set(
+ 'complex-drawing',
+ createSkeletonDrawing('complex-drawing', documentModel.getUnitId())
+ );
+
+ const anchor = paragraphs.slice(0, 15).join('').length + 2;
+ const generation = skeleton.startIncrementalLayout({ anchor });
+ const firstProgress = skeleton.stepIncrementalLayout(generation, 0);
+
+ expect(firstProgress.anchorReady).toBe(false);
+ expect(firstProgress.processedBlockCount).toBe(1);
+
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it('reuses the stable page prefix when an edit anchors a later traditional page', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const content = Array.from(
+ { length: 120 },
+ (_, index) => `Paragraph ${index} has enough text to wrap across several lines on a compact page.\r`
+ ).join('');
+ const documentModel = createDocumentModelWithStyle(content, {});
+ documentModel.updateDocumentDataPageSize(160, 180);
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+
+ skeleton.calculate();
+ const initialSkeleton = normalizeSkeleton(skeleton.getSkeletonData());
+ const initialPages = skeleton.getSkeletonData()?.pages ?? [];
+ expect(initialPages.length).toBeGreaterThan(8);
+
+ const anchorPageIndex = 6;
+ const anchor = initialPages[anchorPageIndex].st;
+ const generation = skeleton.startIncrementalLayout({ anchor });
+ const firstProgress = skeleton.stepIncrementalLayout(generation, 0);
+
+ expect(firstProgress.anchorReady).toBe(false);
+ let foregroundProgress = firstProgress;
+ for (let index = 0; index < 200 && !foregroundProgress.anchorReady; index++) {
+ foregroundProgress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+ expect(foregroundProgress.anchorReady).toBe(true);
+ expect(foregroundProgress.pageCount).toBeGreaterThanOrEqual(anchorPageIndex + 1);
+ expect(foregroundProgress.estimatedPageCount).toBe(initialPages.length);
+ expect(foregroundProgress.processedBlockCount).toBeGreaterThan(1);
+ expect(skeleton.getSkeletonData()?.pages.every((page) => page.ed >= page.st)).toBe(true);
+ expect(skeleton.getSkeletonData()?.pages).toHaveLength(initialPages.length);
+ expect(skeleton.findNodePositionByCharIndex(anchor, false)?.page).toBe(anchorPageIndex);
+ expect(skeleton.getSkeletonData()?.pages[anchorPageIndex]).toMatchObject({
+ st: initialPages[anchorPageIndex].st,
+ ed: initialPages[anchorPageIndex].ed,
+ height: initialPages[anchorPageIndex].height,
+ });
+ const publishedAnchorPage = skeleton.getSkeletonData()?.pages[anchorPageIndex];
+ const publishedGlyph = publishedAnchorPage?.sections[0]?.columns[0]?.lines[0]?.divides[0]?.glyphGroup[0];
+ if (publishedGlyph == null) {
+ throw new Error('Expected the foreground publication to contain an addressable glyph.');
+ }
+ const publishedPosition = skeleton.findPositionByGlyph(publishedGlyph, -1);
+ if (publishedPosition == null) {
+ throw new Error('Expected the foreground glyph to resolve to a node position.');
+ }
+ expect(publishedPosition.page).toBe(anchorPageIndex);
+ expect(publishedPosition.path).toEqual(['pages', anchorPageIndex]);
+ expect(skeleton.findCharIndexByPosition({ ...publishedPosition, isBack: true })).toBeTypeOf('number');
+ expect(skeleton.getSkeletonData()?.pages[anchorPageIndex + 1]).toMatchObject({
+ isLayoutPlaceholder: true,
+ sections: [],
+ st: -1,
+ ed: -1,
+ pageWidth: initialPages[anchorPageIndex + 1].pageWidth,
+ pageHeight: initialPages[anchorPageIndex + 1].pageHeight,
+ });
+
+ let finalProgress = foregroundProgress;
+ for (let index = 0; index < 200 && !finalProgress.complete; index++) {
+ finalProgress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+
+ expect(finalProgress).toMatchObject({ complete: true, cancelled: false });
+ expect(normalizeSkeleton(skeleton.getSkeletonData())).toEqual(initialSkeleton);
+
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it('reuses a geometrically stable page tail after a Worker interaction edit', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const content = Array.from(
+ { length: 300 },
+ (_, index) => `Short paragraph ${index}.\r`
+ ).join('');
+ const documentModel = createDocumentModelWithStyle(content, {});
+ documentModel.updateDocumentDataPageSize(600, 600);
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+
+ skeleton.calculate();
+ const initialPages = skeleton.getSkeletonData()?.pages ?? [];
+ expect(initialPages.length).toBeGreaterThan(3);
+ const anchorPageIndex = 2;
+ const anchorPage = initialPages[anchorPageIndex];
+ const anchorLines = anchorPage.sections[0].columns[0].lines;
+ expect(anchorLines.length).toBeGreaterThan(2);
+ const anchor = anchorLines[Math.floor(anchorLines.length / 2)].st + 1;
+ const nextSnapshot = structuredClone(documentModel.getSnapshot());
+ const previousDataStream = nextSnapshot.body!.dataStream;
+ nextSnapshot.body!.dataStream = `${previousDataStream.slice(0, anchor)}x${previousDataStream.slice(anchor)}`;
+ for (const paragraph of nextSnapshot.body!.paragraphs ?? []) {
+ if (paragraph.startIndex >= anchor) {
+ paragraph.startIndex++;
+ }
+ }
+ for (const sectionBreak of nextSnapshot.body!.sectionBreaks ?? []) {
+ if (sectionBreak.startIndex >= anchor) {
+ sectionBreak.startIndex++;
+ }
+ }
+ const nextModel = new DocumentDataModel(nextSnapshot);
+ const viewModel = skeleton.getViewModel();
+ viewModel.reset(nextModel);
+ const generation = skeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor,
+ priorityAnchor: anchor + 1,
+ invalidation: {
+ oldStart: anchor,
+ oldEnd: anchor,
+ newEnd: anchor + 1,
+ },
+ reuseUnaffectedTail: false,
+ });
+ let foregroundProgress = skeleton.stepIncrementalLayout(generation, 0);
+ let foregroundSteps = 1;
+ for (; foregroundSteps < 100 && !foregroundProgress.anchorReady; foregroundSteps++) {
+ foregroundProgress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+
+ expect(foregroundProgress.anchorReady).toBe(true);
+ expect(foregroundSteps).toBeLessThan(anchorLines.length);
+ expect(skeleton.findNodePositionByCharIndex(anchor + 1, false)?.page).toBe(anchorPageIndex);
+
+ skeleton.cancelIncrementalLayout(generation);
+ const secondInsertionOffset = anchor + 1;
+ const secondSnapshot = structuredClone(nextModel.getSnapshot());
+ const onceEditedDataStream = secondSnapshot.body!.dataStream;
+ secondSnapshot.body!.dataStream = `${onceEditedDataStream.slice(0, secondInsertionOffset)}y${onceEditedDataStream.slice(secondInsertionOffset)}`;
+ for (const paragraph of secondSnapshot.body!.paragraphs ?? []) {
+ if (paragraph.startIndex >= secondInsertionOffset) {
+ paragraph.startIndex++;
+ }
+ }
+ for (const sectionBreak of secondSnapshot.body!.sectionBreaks ?? []) {
+ if (sectionBreak.startIndex >= secondInsertionOffset) {
+ sectionBreak.startIndex++;
+ }
+ }
+ const secondModel = new DocumentDataModel(secondSnapshot);
+ viewModel.reset(secondModel);
+ const secondExpected = DocumentSkeleton.create(new DocumentViewModel(secondModel), localeService);
+ secondExpected.calculate();
+ const secondExpectedSkeleton = normalizeSkeleton(secondExpected.getSkeletonData());
+ const secondGeneration = skeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor: secondInsertionOffset,
+ priorityAnchor: secondInsertionOffset + 1,
+ invalidation: {
+ oldStart: secondInsertionOffset,
+ oldEnd: secondInsertionOffset,
+ newEnd: secondInsertionOffset + 1,
+ },
+ reuseUnaffectedTail: false,
+ });
+ let finalProgress = skeleton.stepIncrementalLayout(secondGeneration, 0);
+ let secondForegroundSteps = 1;
+ for (; secondForegroundSteps < 100 && !finalProgress.anchorReady; secondForegroundSteps++) {
+ finalProgress = skeleton.stepIncrementalLayout(secondGeneration, 0);
+ }
+ expect(secondForegroundSteps).toBeLessThan(anchorLines.length);
+ for (let index = 0; index < 300 && !finalProgress.complete; index++) {
+ finalProgress = skeleton.stepIncrementalLayout(secondGeneration, 0);
+ }
+
+ expect(finalProgress).toMatchObject({ complete: true, cancelled: false });
+ expect(normalizeSkeleton(skeleton.getSkeletonData())).toEqual(secondExpectedSkeleton);
+
+ secondExpected.dispose();
+ secondModel.dispose();
+ nextModel.dispose();
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it('rebuilds an edit batch without scalar invalidation instead of reusing a stale page tail', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const content = Array.from(
+ { length: 180 },
+ (_, index) => `Batch paragraph ${index} keeps enough text on each physical page.\r`
+ ).join('');
+ const documentModel = createDocumentModelWithStyle(content, {});
+ documentModel.updateDocumentDataPageSize(240, 260);
+ const batchViewModel = new DocumentViewModel(documentModel);
+ const preciseViewModel = new DocumentViewModel(documentModel);
+ const batchSkeleton = DocumentSkeleton.create(batchViewModel, localeService);
+ const preciseSkeleton = DocumentSkeleton.create(preciseViewModel, localeService);
+
+ batchSkeleton.calculate();
+ preciseSkeleton.calculate();
+ const initialPages = batchSkeleton.getSkeletonData()?.pages ?? [];
+ expect(initialPages.length).toBeGreaterThan(3);
+ const anchorPage = initialPages[2];
+ const anchorLine = anchorPage.sections[0]?.columns[0]?.lines[1];
+ if (anchorLine == null) {
+ throw new Error('Expected an editable line on the third physical page');
+ }
+ const anchor = anchorLine.st + 2;
+ const insertion = '\rBATCH-LINE';
+ const nextSnapshot = structuredClone(documentModel.getSnapshot());
+ const previousDataStream = nextSnapshot.body!.dataStream;
+ nextSnapshot.body!.dataStream = `${previousDataStream.slice(0, anchor)}${insertion}${previousDataStream.slice(anchor)}`;
+ for (const paragraph of nextSnapshot.body!.paragraphs ?? []) {
+ if (paragraph.startIndex >= anchor) {
+ paragraph.startIndex += insertion.length;
+ }
+ }
+ for (const sectionBreak of nextSnapshot.body!.sectionBreaks ?? []) {
+ if (sectionBreak.startIndex >= anchor) {
+ sectionBreak.startIndex += insertion.length;
+ }
+ }
+
+ const nextModel = new DocumentDataModel(nextSnapshot);
+ batchViewModel.reset(nextModel);
+ preciseViewModel.reset(nextModel);
+ const expected = DocumentSkeleton.create(new DocumentViewModel(nextModel), localeService);
+ expected.calculate();
+ const batchGeneration = batchSkeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor,
+ priorityAnchor: anchor + insertion.length,
+ reuseUnaffectedTail: false,
+ });
+ let batchProgress = batchSkeleton.stepIncrementalLayout(batchGeneration, 0);
+ for (let step = 0; step < 2_000 && !batchProgress.complete; step++) {
+ batchProgress = batchSkeleton.stepIncrementalLayout(batchGeneration, 0);
+ }
+ const preciseGeneration = preciseSkeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor,
+ priorityAnchor: anchor + insertion.length,
+ invalidation: {
+ newEnd: anchor + insertion.length,
+ oldEnd: anchor,
+ oldStart: anchor,
+ },
+ reuseUnaffectedTail: false,
+ });
+ let preciseProgress = preciseSkeleton.stepIncrementalLayout(preciseGeneration, 0);
+ for (let step = 0; step < 2_000 && !preciseProgress.complete; step++) {
+ preciseProgress = preciseSkeleton.stepIncrementalLayout(preciseGeneration, 0);
+ }
+
+ const expectedSkeleton = normalizeSkeleton(expected.getSkeletonData());
+ expect(batchProgress).toMatchObject({ complete: true, cancelled: false });
+ expect(preciseProgress).toMatchObject({ complete: true, cancelled: false });
+ expect(normalizeSkeleton(batchSkeleton.getSkeletonData())).toEqual(expectedSkeleton);
+ expect(normalizeSkeleton(preciseSkeleton.getSkeletonData())).toEqual(expectedSkeleton);
+
+ expected.dispose();
+ nextModel.dispose();
+ preciseSkeleton.dispose();
+ batchSkeleton.dispose();
+ univer.dispose();
+ });
+
+ it('reuses a plain-paragraph checkpoint when only aggregate page ranges overlap the anchor', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const content = Array.from(
+ { length: 120 },
+ (_, index) => `Paragraph ${index} has enough text to wrap across several lines on a compact page.\r`
+ ).join('');
+ const documentModel = createDocumentModelWithStyle(content, {});
+ documentModel.updateDocumentDataPageSize(160, 180);
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+
+ skeleton.calculate();
+ const initialPages = skeleton.getSkeletonData()?.pages ?? [];
+ const anchorPageIndex = 6;
+ const anchorPage = initialPages[anchorPageIndex];
+ const anchor = anchorPage.sections[0].columns[0].lines[0].st;
+ const previousFirstPage = initialPages[0];
+ initialPages[0].ed = anchorPage.ed;
+ anchorPage.st = initialPages[0].st;
+ anchorPage.ed = content.length - 1;
+
+ const generation = skeleton.startIncrementalLayout({ anchor });
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let index = 0; index < 200 && !progress.anchorReady; index++) {
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+ const rebuiltPages = skeleton.getSkeletonData()?.pages ?? [];
+
+ expect(progress.anchorReady).toBe(true);
+ expect(progress.laidOutThrough).toBeLessThan(content.length - 1);
+ expect(rebuiltPages[0]).toBe(previousFirstPage);
+
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it('cancels an obsolete incremental generation before it can commit', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const documentModel = createDocumentModelWithStyle('First paragraph.\rSecond paragraph.\rThird paragraph.\r', {});
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+ const cancelledProgress: number[] = [];
+ const subscription = skeleton.layoutProgress$.subscribe((progress) => {
+ if (progress.cancelled) {
+ cancelledProgress.push(progress.generation);
+ }
+ });
+
+ const obsoleteGeneration = skeleton.startIncrementalLayout({ anchor: 40 });
+ skeleton.stepIncrementalLayout(obsoleteGeneration, 0);
+ const currentGeneration = skeleton.startIncrementalLayout({ anchor: 2 });
+
+ expect(skeleton.stepIncrementalLayout(obsoleteGeneration, 0).cancelled).toBe(true);
+ expect(cancelledProgress).toContain(obsoleteGeneration);
+ expect(skeleton.stepIncrementalLayout(currentGeneration, 0).cancelled).toBe(false);
+
+ subscription.unsubscribe();
+ skeleton.dispose();
+ univer.dispose();
+ });
+
it('creates an initial page when the first laid out section is continuous', () => {
const univer = new Univer();
const localeService = univer.__getInjector().get(LocaleService);
@@ -2592,6 +3768,10 @@ describe('doc skeleton', () => {
expect(() => skeleton.calculate()).not.toThrow();
expect(skeleton.getSkeletonData()?.pages.length).toBeGreaterThan(0);
+ expect(skeleton.getSkeletonData()?.skeHeaders.size).toBeGreaterThan(0);
+ expect(skeleton.getSkeletonData()?.skeFooters.size).toBeGreaterThan(0);
+
+ expectIncrementalSkeletonToEqualSynchronous(documentModel.getSnapshot(), localeService);
skeleton.dispose();
univer.dispose();
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
new file mode 100644
index 0000000000..49f512ff7d
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/__tests__/document-layout-page-patch.spec.ts
@@ -0,0 +1,82 @@
+/**
+ * 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 { createDocumentModelWithStyle, DocumentFlavor, LocaleService, Univer } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { DocumentViewModel } from '../../view-model/document-view-model';
+import { DocumentSkeleton } from '../doc-skeleton';
+import { hydrateDocumentSkeletonPage, serializeDocumentSkeletonPage } from '../document-layout-page-patch';
+
+function normalizeSkeleton(value: unknown): unknown {
+ if (value instanceof Map) {
+ return [...value].map(([key, item]) => [key, normalizeSkeleton(item)]);
+ }
+
+ if (Array.isArray(value)) {
+ return value.map(normalizeSkeleton);
+ }
+
+ if (value != null && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value)
+ .filter(([key]) => key !== 'parent')
+ .map(([key, item]) => [key, normalizeSkeleton(item)])
+ );
+ }
+
+ return value;
+}
+
+describe('document layout page patch', () => {
+ it('survives structured clone and restores render parent links', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const documentModel = createDocumentModelWithStyle(
+ 'Worker-safe page publication.\rSecond line.\r',
+ {}
+ );
+ documentModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.TRADITIONAL });
+ documentModel.updateDocumentDataPageSize(240, 320);
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);
+ skeleton.calculate();
+
+ const page = skeleton.getSkeletonData()?.pages[0];
+ if (page == null) {
+ throw new Error('Expected the document to produce a page.');
+ }
+ page.isNaturalPageOverflow = true;
+
+ const patch = structuredClone(serializeDocumentSkeletonPage(page));
+ const hydrated = hydrateDocumentSkeletonPage(patch);
+ const firstSection = hydrated.sections[0];
+ const firstColumn = firstSection?.columns[0];
+ const firstLine = firstColumn?.lines[0];
+ const firstDivide = firstLine?.divides[0];
+ const firstGlyph = firstDivide?.glyphGroup[0];
+
+ expect(JSON.stringify(patch)).not.toContain('"parent"');
+ expect(normalizeSkeleton(hydrated)).toEqual(normalizeSkeleton(page));
+ expect(hydrated.isNaturalPageOverflow).toBe(true);
+ expect(firstSection?.parent).toBe(hydrated);
+ expect(firstColumn?.parent).toBe(firstSection);
+ expect(firstLine?.parent).toBe(firstColumn);
+ expect(firstDivide?.parent).toBe(firstLine);
+ expect(firstGlyph?.parent).toBe(firstDivide);
+
+ skeleton.dispose();
+ univer.dispose();
+ });
+});
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 8ffa2fad72..675d97ae5e 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
@@ -345,6 +345,20 @@ describe('docs layout tools extra', () => {
expect(columns.length).toBe(1);
});
+ it('anchors a complete paragraph to its model paragraph index when hidden flow tokens create a gap', () => {
+ const { page, line1, divide1, divide2 } = createPageSkeleton();
+ line1.paragraphStart = true;
+ line1.paragraphIndex = 10;
+ const paragraphMark = divide2.glyphGroup[divide2.glyphGroup.length - 1];
+ paragraphMark.raw = DataStreamTreeTokenType.PARAGRAPH;
+ paragraphMark.streamType = DataStreamTreeTokenType.PARAGRAPH;
+
+ updateBlockIndex([page], -1);
+
+ expect(divide1.st).toBe(8);
+ expect(line1.ed).toBe(10);
+ });
+
it('uses content width for unspecified editor documents when updating block indexes', () => {
const { page, column } = createPageSkeleton();
@@ -973,6 +987,45 @@ describe('docs layout tools extra', () => {
}]);
});
+ it('uses the accumulated height of preceding pages for table coordinates', () => {
+ const createPageWithTable = (pageHeight: number, tableId: string) => {
+ const { page } = createPageSkeleton();
+ page.marginBottom = 20;
+ page.marginLeft = 30;
+ page.marginRight = 30;
+ page.marginTop = 20;
+ page.pageHeight = pageHeight;
+ page.pageWidth = 300;
+ page.sections = [];
+ page.skeTables = new Map([[tableId, {
+ tableId,
+ height: 30,
+ left: 10,
+ rows: [],
+ top: 15,
+ width: 100,
+ }]]);
+ return page;
+ };
+
+ const tables = documentSkeletonTableIterator([
+ createPageWithTable(400, 'short-page-table'),
+ createPageWithTable(700, 'tall-page-table'),
+ ], {
+ docsTop: 8,
+ pageMarginTop: 12,
+ });
+
+ expect(tables.map(({ pageIndex, tableId, tableRect }) => ({
+ pageIndex,
+ tableId,
+ top: tableRect.top,
+ }))).toEqual([
+ { pageIndex: 0, tableId: 'short-page-table', top: 43 },
+ { pageIndex: 1, tableId: 'tall-page-table', top: 455 },
+ ]);
+ });
+
it('resolves column child page offsets from skeleton parents', () => {
const columnPage = {};
const column = {
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 f4f54667a5..209ad3e164 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
@@ -17,6 +17,7 @@
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,
@@ -29,6 +30,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { BreakType, DocumentSkeletonPageType } from '../../../../../basics/i-document-skeleton-cached';
import { getDocumentCompatibilityPolicy } from '../../../document-compatibility';
import {
+ cachePrecomputedSlicedTableSkeletons,
+ cachePrecomputedTableSkeleton,
createTableSkeleton,
createTableSkeletons,
getNullTableSkeleton,
@@ -36,6 +39,10 @@ import {
getTableLeft,
getTableSliceId,
rollbackListCache,
+ startTableSkeletonBuild,
+ startTableSkeletonsBuild,
+ stepTableSkeletonBuild,
+ stepTableSkeletonsBuild,
} from '../table';
const createSkeletonCellPagesMock = vi.fn();
@@ -44,6 +51,17 @@ const createNullCellPageMock = vi.fn();
vi.mock('../../model/page', () => ({
createSkeletonCellPages: (...args: unknown[]) => createSkeletonCellPagesMock(...args),
createNullCellPage: (...args: unknown[]) => createNullCellPageMock(...args),
+ startSkeletonCellPagesBuild: (...args: unknown[]) => ({
+ args,
+ complete: false,
+ requiresSyncFallback: false,
+ pages: [],
+ }),
+ stepSkeletonCellPagesBuild: (state: { args: unknown[]; complete: boolean; pages: unknown[] }) => {
+ state.pages = createSkeletonCellPagesMock(...state.args);
+ state.complete = true;
+ return true;
+ },
}));
function createMockTable(overrides: Partial<ITable> = {}): ITable {
@@ -329,6 +347,122 @@ describe('docs table layout', () => {
expect(skeleton?.rows[0].cells[1].marginTop).toBeGreaterThanOrEqual(1);
});
+ 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);
+
+ expect(state).not.toBeNull();
+ expect(stepTableSkeletonBuild(state!)).toBe(false);
+ expect(state).toMatchObject({ rowIndex: 0, currentColumnIndex: 1, complete: false });
+ expect(state?.tableSkeleton.rows).toHaveLength(1);
+
+ expect(stepTableSkeletonBuild(state!)).toBe(false);
+ expect(state).toMatchObject({ rowIndex: 1, currentColumnIndex: 0, complete: false });
+
+ while (!stepTableSkeletonBuild(state!)) {
+ // Continue until all source cells are complete.
+ }
+ expect(state).toMatchObject({ rowIndex: 2, complete: true });
+ expect(state?.tableSkeleton.rows).toHaveLength(2);
+ });
+
+ it('reuses incrementally precomputed rows when a table is split', () => {
+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig } = createContextAndTable();
+ const state = startTableSkeletonBuild(ctx, curPage, viewModel, tableNode, sectionBreakConfig)!;
+ while (!stepTableSkeletonBuild(state)) {
+ // Build all source rows through the resumable path before pagination consumes them.
+ }
+ cachePrecomputedTableSkeleton(ctx, tableNode.startIndex, state.tableSkeleton);
+ const callsBeforePagination = createSkeletonCellPagesMock.mock.calls.length;
+
+ const result = createTableSkeletons(ctx, curPage, viewModel, tableNode, sectionBreakConfig, 90);
+
+ expect(result.skeTables.flatMap((table) => table.rows).filter((row) => !row.isRepeatRow)).toHaveLength(2);
+ expect(createSkeletonCellPagesMock.mock.calls.length).toBe(callsBeforePagination);
+ });
+
+ it('builds exact paginated cell pages incrementally before the synchronous consumer needs them', () => {
+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig } = createContextAndTable();
+ const state = startTableSkeletonsBuild(
+ ctx,
+ curPage,
+ viewModel,
+ tableNode,
+ sectionBreakConfig,
+ 90
+ )!;
+
+ expect(stepTableSkeletonsBuild(state)).toBe(false);
+ expect(state).toMatchObject({ rowIndex: 0, columnIndex: 1, complete: false });
+ while (!stepTableSkeletonsBuild(state)) {
+ // Continue through each cell paragraph until exact pagination is ready.
+ }
+ expect(state.result).not.toBeNull();
+
+ cachePrecomputedSlicedTableSkeletons(ctx, tableNode.startIndex, 90, state.result!);
+ const callsBeforeConsume = createSkeletonCellPagesMock.mock.calls.length;
+ const result = createTableSkeletons(ctx, curPage, viewModel, tableNode, sectionBreakConfig, 90);
+
+ expect(result).toBe(state.result);
+ expect(createSkeletonCellPagesMock.mock.calls.length).toBe(callsBeforeConsume);
+ });
+
+ it('defers split-table work only after the normal layout path provides its exact context', () => {
+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig } = createContextAndTable();
+ type DeferredRequest = Parameters<NonNullable<ILayoutContext['deferSlicedTableLayout']>>[0];
+ let request: DeferredRequest | undefined;
+ ctx.deferSlicedTableLayout = (value: DeferredRequest) => {
+ request = value;
+ return true;
+ };
+
+ const provisional = createTableSkeletons(
+ ctx,
+ curPage,
+ viewModel,
+ tableNode,
+ sectionBreakConfig,
+ 90
+ );
+
+ expect(provisional).toEqual({ skeTables: [], fromCurrentPage: false });
+ expect(request).toMatchObject({
+ curPage,
+ viewModel,
+ tableNode,
+ sectionBreakConfig,
+ availableHeight: 90,
+ });
+
+ ctx.deferSlicedTableLayout = undefined;
+ const state = startTableSkeletonsBuild(
+ ctx,
+ request!.curPage,
+ request!.viewModel,
+ request!.tableNode,
+ request!.sectionBreakConfig,
+ request!.availableHeight
+ )!;
+ while (!stepTableSkeletonsBuild(state)) {
+ // Resume the exact deferred request one cell paragraph at a time.
+ }
+ cachePrecomputedSlicedTableSkeletons(
+ ctx,
+ tableNode.startIndex,
+ request!.availableHeight,
+ state.result!
+ );
+
+ expect(createTableSkeletons(
+ ctx,
+ curPage,
+ viewModel,
+ tableNode,
+ sectionBreakConfig,
+ 90
+ )).toBe(state.result);
+ });
+
it('uses every nested cell page when estimating a table inside a cell', () => {
const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();
curPage.type = DocumentSkeletonPageType.CELL;
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 b927470a53..fff6d54cf1 100644
--- a/packages/engine-render/src/components/docs/layout/block/section.ts
+++ b/packages/engine-render/src/components/docs/layout/block/section.ts
@@ -26,18 +26,24 @@ import { dealWithBlockError } from './block-error';
import { appendColumnGroupBlockLine, createColumnGroupSkeleton } from './column';
import { dealWidthParagraph } from './paragraph/paragraph-layout';
+export interface IDealWithSectionOptions {
+ startParagraphIndex?: number;
+ maxParagraphs?: number;
+}
+
export function dealWithSection(
ctx: ILayoutContext,
viewModel: DocumentViewModel,
sectionNode: DataStreamTreeNode,
curPage: IDocumentSkeletonPage,
sectionBreakConfig: ISectionBreakConfig,
- layoutAnchor: Nullable<number>
+ layoutAnchor: Nullable<number>,
+ options?: IDealWithSectionOptions
) {
const allCurrentSkeletonPages: IDocumentSkeletonPage[] = [];
const renderedBlockIdMap = new Map<string, boolean>();
- let paragraphStartIndex = 0;
+ let paragraphStartIndex = options?.startParagraphIndex ?? 0;
if (layoutAnchor != null) {
const { startIndex, endIndex } = sectionNode;
@@ -52,7 +58,12 @@ export function dealWithSection(
}
}
- for (let i = paragraphStartIndex; i < sectionNode.children.length; i++) {
+ const paragraphEndIndex = Math.min(
+ sectionNode.children.length,
+ paragraphStartIndex + (options?.maxParagraphs ?? Number.POSITIVE_INFINITY)
+ );
+
+ for (let i = paragraphStartIndex; i < paragraphEndIndex; i++) {
const paragraphNode = sectionNode.children[i];
// const { paragraph, table, tableOfContents, blockType, customBlock, blockId } = block;
// if (preRenderedBlockIdMap?.get(blockId)) {
@@ -124,6 +135,8 @@ export function dealWithSection(
return {
pages: allCurrentSkeletonPages,
renderedBlockIdMap,
+ nextParagraphIndex: paragraphEndIndex,
+ complete: paragraphEndIndex >= sectionNode.children.length,
};
}
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 d1b24f8dc6..0658d8948c 100644
--- a/packages/engine-render/src/components/docs/layout/block/table.ts
+++ b/packages/engine-render/src/components/docs/layout/block/table.ts
@@ -24,57 +24,176 @@ import type {
} from '../../../../basics';
import type { DataStreamTreeNode } from '../../view-model/data-stream-tree-node';
import type { DocumentViewModel } from '../../view-model/document-view-model';
+import type { ICellSkeletonBuildState } from '../model/page';
import type { ILayoutContext } from '../tools';
import { BooleanNumber, TableAlignmentType, TableRowHeightRule, VerticalAlignmentType } from '@univerjs/core';
import { DocumentSkeletonPageType } from '../../../../basics';
import { getDocumentCompatibilityPolicy } from '../../document-compatibility';
-import { createNullCellPage, createSkeletonCellPages } from '../model/page';
+import {
+ createNullCellPage,
+ createSkeletonCellPages,
+
+ startSkeletonCellPagesBuild,
+ stepSkeletonCellPagesBuild,
+} from '../model/page';
+
+const precomputedTableSkeletons = new WeakMap<ILayoutContext, Map<number, IDocumentSkeletonTable>>();
+const precomputedSlicedTableSkeletons = new WeakMap<
+ ILayoutContext,
+ Map<number, { availableHeight: number; result: ISlicedTableSkeletonParams }>
+>();
+
+export interface ITableSkeletonBuildState {
+ ctx: ILayoutContext;
+ curPage: IDocumentSkeletonPage;
+ viewModel: DocumentViewModel;
+ tableNode: DataStreamTreeNode;
+ sectionBreakConfig: ISectionBreakConfig;
+ table: ITable;
+ tableSkeleton: IDocumentSkeletonTable;
+ rowIndex: number;
+ rowTop: number;
+ tableWidth: number;
+ complete: boolean;
+ currentRowNode: Nullable<DataStreamTreeNode>;
+ currentRowSkeleton: Nullable<IDocumentSkeletonRow>;
+ currentColumnIndex: number;
+ currentRowLeft: number;
+ currentRowHeight: number;
+ currentCellBuild: Nullable<ICellSkeletonBuildState>;
+}
-export function createTableSkeleton(
+export function startTableSkeletonBuild(
ctx: ILayoutContext,
curPage: IDocumentSkeletonPage,
viewModel: DocumentViewModel,
tableNode: DataStreamTreeNode,
sectionBreakConfig: ISectionBreakConfig
-): Nullable<IDocumentSkeletonTable> {
- const { startIndex, endIndex, children: rowNodes } = tableNode;
- const table = viewModel.getTableByStartIndex(startIndex)?.tableSource;
+): Nullable<ITableSkeletonBuildState> {
+ const table = viewModel.getTableByStartIndex(tableNode.startIndex)?.tableSource;
if (table == null) {
- console.warn(`Table not found when creating table skeleton at index ${startIndex}`);
+ console.warn(`Table not found when creating table skeleton at index ${tableNode.startIndex}`);
return null;
}
- const tableSkeleton = getNullTableSkeleton(startIndex, endIndex, table);
- let rowTop = 0;
- let tableWidth = 0;
+ return {
+ ctx,
+ curPage,
+ viewModel,
+ tableNode,
+ sectionBreakConfig,
+ table,
+ tableSkeleton: getNullTableSkeleton(tableNode.startIndex, tableNode.endIndex, table),
+ rowIndex: 0,
+ rowTop: 0,
+ tableWidth: 0,
+ complete: false,
+ currentRowNode: null,
+ currentRowSkeleton: null,
+ currentColumnIndex: 0,
+ currentRowLeft: 0,
+ currentRowHeight: 0,
+ currentCellBuild: null,
+ };
+}
- for (const rowNode of rowNodes) {
- const { children: cellNodes, startIndex, endIndex } = rowNode;
- const row = rowNodes.indexOf(rowNode);
- const rowSource = table.tableRows[row];
- const { trHeight } = rowSource;
- const rowSkeleton = _getNullTableRowSkeleton(startIndex, endIndex, row, rowSource, false, tableSkeleton);
- const { hRule, val } = trHeight;
+export function stepTableSkeletonBuild(state: ITableSkeletonBuildState): boolean {
+ if (state.complete) {
+ return true;
+ }
- tableSkeleton.rows.push(rowSkeleton);
- let left = 0;
- let rowHeight = 0;
+ if (state.currentRowNode == null || state.currentRowSkeleton == null) {
+ const rowNode = state.tableNode.children[state.rowIndex];
+ if (rowNode != null) {
+ _startUnslicedTableRow(state, rowNode);
+ }
+ }
- for (const cellNode of cellNodes) {
- const col = cellNodes.indexOf(cellNode);
- const cellConfig = rowSource.tableCells[col];
+ if (state.currentRowNode != null && state.currentRowSkeleton != null) {
+ if (!_stepUnslicedTableRow(state)) {
+ return false;
+ }
+ }
- if (isCoveredTableCell(cellConfig)) {
- const cellPageSkeleton = createMergedCoveredCellPage(ctx, sectionBreakConfig, table, row, col, rowSkeleton);
- cellPageSkeleton.left = left;
- if (shouldAdvanceTableCellLeft(table, row, col)) {
- left += cellPageSkeleton.pageWidth;
- }
- rowSkeleton.cells.push(cellPageSkeleton);
- continue;
- }
+ if (state.rowIndex >= state.tableNode.children.length) {
+ _finishTableSkeletonBuild(state);
+ }
+
+ return state.complete;
+}
+
+export function cachePrecomputedTableSkeleton(
+ ctx: ILayoutContext,
+ tableStartIndex: number,
+ tableSkeleton: IDocumentSkeletonTable
+): void {
+ let cache = precomputedTableSkeletons.get(ctx);
+ if (cache == null) {
+ cache = new Map();
+ precomputedTableSkeletons.set(ctx, cache);
+ }
+ cache.set(tableStartIndex, tableSkeleton);
+}
+
+export function createTableSkeleton(
+ ctx: ILayoutContext,
+ curPage: IDocumentSkeletonPage,
+ viewModel: DocumentViewModel,
+ tableNode: DataStreamTreeNode,
+ sectionBreakConfig: ISectionBreakConfig
+): Nullable<IDocumentSkeletonTable> {
+ const cached = precomputedTableSkeletons.get(ctx)?.get(tableNode.startIndex);
+ if (cached != null) {
+ return cached;
+ }
- const cellPageSkeletons = createSkeletonCellPages(
+ const state = startTableSkeletonBuild(ctx, curPage, viewModel, tableNode, sectionBreakConfig);
+ if (state == null) {
+ return null;
+ }
+ while (!stepTableSkeletonBuild(state)) {
+ // Compatibility path remains synchronous. Incremental callers step the same state row by row.
+ }
+
+ return state.tableSkeleton;
+}
+
+function _startUnslicedTableRow(state: ITableSkeletonBuildState, rowNode: DataStreamTreeNode): void {
+ const { table, tableSkeleton } = state;
+ const { startIndex, endIndex } = rowNode;
+ const row = state.rowIndex;
+ const rowSource = table.tableRows[row];
+ const rowSkeleton = _getNullTableRowSkeleton(startIndex, endIndex, row, rowSource, false, tableSkeleton);
+ tableSkeleton.rows.push(rowSkeleton);
+ state.currentRowNode = rowNode;
+ state.currentRowSkeleton = rowSkeleton;
+ state.currentColumnIndex = 0;
+ state.currentRowLeft = 0;
+ state.currentRowHeight = 0;
+}
+
+function _stepUnslicedTableRow(state: ITableSkeletonBuildState): boolean {
+ const { ctx, sectionBreakConfig, table, viewModel } = state;
+ const rowNode = state.currentRowNode!;
+ const rowSkeleton = state.currentRowSkeleton!;
+ const row = state.rowIndex;
+ const col = state.currentColumnIndex;
+ const cellNode = rowNode.children[col];
+ const cellConfig = table.tableRows[row].tableCells[col];
+
+ if (cellNode != null) {
+ if (isCoveredTableCell(cellConfig)) {
+ const cellPageSkeleton = createMergedCoveredCellPage(
+ ctx,
+ sectionBreakConfig,
+ table,
+ row,
+ col,
+ rowSkeleton
+ );
+ _appendUnslicedCell(state, [cellPageSkeleton]);
+ } else {
+ state.currentCellBuild ??= startSkeletonCellPagesBuild(
ctx,
viewModel,
cellNode,
@@ -83,81 +202,96 @@ export function createTableSkeleton(
row,
col
);
- if (cellPageSkeletons.slice(1).some((page) => page.isExplicitPageBreak === true)) {
- tableSkeleton.hasPageBreak = true;
+ if (!stepSkeletonCellPagesBuild(state.currentCellBuild)) {
+ return false;
}
- const cellPageSkeleton = cellPageSkeletons[0];
-
- const pageHeight = getCellPagesLayoutHeight(
- cellPageSkeletons,
- curPage.type === DocumentSkeletonPageType.CELL
- );
- cellPageSkeleton.left = left;
- left += cellPageSkeleton.pageWidth;
- cellPageSkeleton.parent = rowSkeleton;
- rowSkeleton.cells.push(cellPageSkeleton);
- rowHeight = Math.max(rowHeight, pageHeight);
- }
-
- if (hRule === TableRowHeightRule.AT_LEAST) {
- rowHeight = Math.max(rowHeight, val.v);
- } else if (hRule === TableRowHeightRule.EXACT) {
- rowHeight = val.v;
- }
-
- // Set row height to cell page height.
- for (const cellPageSkeleton of rowSkeleton.cells) {
- cellPageSkeleton.pageHeight = rowHeight;
+ const cellPageSkeletons = state.currentCellBuild.requiresSyncFallback
+ ? createSkeletonCellPages(
+ ctx,
+ viewModel,
+ cellNode,
+ sectionBreakConfig,
+ table,
+ row,
+ col
+ )
+ : state.currentCellBuild.pages;
+ state.currentCellBuild = null;
+ _appendUnslicedCell(state, cellPageSkeletons);
}
+ state.currentColumnIndex++;
+ }
- // Handle vertical alignment in cell.
- const rowConfig = table.tableRows[row];
- for (let i = 0; i < rowConfig.tableCells.length; i++) {
- const cellConfig = rowConfig.tableCells[i];
- const cellPageSkeleton = rowSkeleton.cells[i];
- const { vAlign = VerticalAlignmentType.CONTENT_ALIGNMENT_UNSPECIFIED } = cellConfig;
- const { pageHeight, height, originMarginTop, originMarginBottom } = cellPageSkeleton;
-
- let marginTop = originMarginTop;
-
- 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;
- }
+ if (state.currentColumnIndex < rowNode.children.length) {
+ return false;
+ }
- marginTop = Math.max(originMarginTop, marginTop);
+ _finishUnslicedTableRow(state);
+ return true;
+}
- cellPageSkeleton.marginTop = marginTop;
- }
+function _appendUnslicedCell(state: ITableSkeletonBuildState, cellPageSkeletons: IDocumentSkeletonPage[]): void {
+ const rowSkeleton = state.currentRowSkeleton!;
+ const row = state.rowIndex;
+ const col = state.currentColumnIndex;
+ const cellPageSkeleton = cellPageSkeletons[0];
+ if (cellPageSkeletons.slice(1).some((page) => page.isExplicitPageBreak === true)) {
+ state.tableSkeleton.hasPageBreak = true;
+ }
+ const pageHeight = getCellPagesLayoutHeight(
+ cellPageSkeletons,
+ state.curPage.type === DocumentSkeletonPageType.CELL
+ );
+ cellPageSkeleton.left = state.currentRowLeft;
+ if (shouldAdvanceTableCellLeft(state.table, row, col)) {
+ state.currentRowLeft += cellPageSkeleton.pageWidth;
+ }
+ cellPageSkeleton.parent = rowSkeleton;
+ rowSkeleton.cells.push(cellPageSkeleton);
+ state.currentRowHeight = Math.max(state.currentRowHeight, pageHeight);
+}
- rowSkeleton.height = rowHeight;
- rowSkeleton.top = rowTop;
- rowTop += rowHeight;
+function _finishUnslicedTableRow(state: ITableSkeletonBuildState): void {
+ const rowSkeleton = state.currentRowSkeleton!;
+ const rowSource = state.table.tableRows[state.rowIndex];
+ const { hRule, val } = rowSource.trHeight;
+ let rowHeight = state.currentRowHeight;
- tableWidth = Math.max(tableWidth, left);
+ if (hRule === TableRowHeightRule.AT_LEAST) {
+ rowHeight = Math.max(rowHeight, val.v);
+ } else if (hRule === TableRowHeightRule.EXACT) {
+ rowHeight = val.v;
+ }
+ for (const cellPageSkeleton of rowSkeleton.cells) {
+ cellPageSkeleton.pageHeight = rowHeight;
}
+ _verticalAlignInCell(rowSkeleton, rowSource);
+
+ rowSkeleton.height = rowHeight;
+ rowSkeleton.top = state.rowTop;
+ state.rowTop += rowHeight;
+ state.tableWidth = Math.max(state.tableWidth, state.currentRowLeft);
+ state.rowIndex++;
+ state.currentRowNode = null;
+ state.currentRowSkeleton = null;
+ state.currentColumnIndex = 0;
+ state.currentCellBuild = null;
+}
- tableSkeleton.width = tableWidth;
- tableSkeleton.height = rowTop;
+function _finishTableSkeletonBuild(state: ITableSkeletonBuildState): void {
+ const { curPage, table, tableSkeleton } = state;
+ tableSkeleton.width = state.tableWidth;
+ tableSkeleton.height = state.rowTop;
applyMergedCellSpanHeights(tableSkeleton);
const { pageWidth, marginLeft = 0, marginRight = 0 } = curPage;
-
- tableSkeleton.left = getTableLeft(pageWidth - marginLeft - marginRight, tableWidth, table.align, table.indent);
-
- return tableSkeleton;
+ tableSkeleton.left = getTableLeft(
+ pageWidth - marginLeft - marginRight,
+ state.tableWidth,
+ table.align,
+ table.indent
+ );
+ state.complete = true;
}
function getCellPagesLayoutHeight(pages: IDocumentSkeletonPage[], includeContinuations: boolean): number {
@@ -191,6 +325,24 @@ export interface ISlicedTableSkeletonParams {
fromCurrentPage: boolean;
}
+export interface ISlicedTableSkeletonBuildState {
+ ctx: ILayoutContext;
+ curPage: IDocumentSkeletonPage;
+ viewModel: DocumentViewModel;
+ tableNode: DataStreamTreeNode;
+ sectionBreakConfig: ISectionBreakConfig;
+ availableHeight: number;
+ table: ITable;
+ skeTables: IDocumentSkeletonTable[];
+ createCache: ICreateTableCache;
+ rowIndex: number;
+ columnIndex: number;
+ preparedCellPages: Map<number, IDocumentSkeletonPage[]>;
+ pendingCellBuild: Nullable<ICellSkeletonBuildState>;
+ complete: boolean;
+ result: Nullable<ISlicedTableSkeletonParams>;
+}
+
interface ICreateTableCache {
rowTop: number;
tableWidth: number;
@@ -199,6 +351,158 @@ interface ICreateTableCache {
repeatRowsHeight: number;
}
+export function startTableSkeletonsBuild(
+ ctx: ILayoutContext,
+ curPage: IDocumentSkeletonPage,
+ viewModel: DocumentViewModel,
+ tableNode: DataStreamTreeNode,
+ sectionBreakConfig: ISectionBreakConfig,
+ availableHeight: number
+): Nullable<ISlicedTableSkeletonBuildState> {
+ const { startIndex, endIndex, children: rowNodes } = tableNode;
+ const table = viewModel.getTableByStartIndex(startIndex)?.tableSource;
+ if (table == null) {
+ return null;
+ }
+
+ const skeTables = [getNullTableSkeleton(startIndex, endIndex, table)];
+ return {
+ ctx,
+ curPage,
+ viewModel,
+ tableNode,
+ sectionBreakConfig,
+ availableHeight,
+ table,
+ skeTables,
+ createCache: {
+ rowTop: 0,
+ tableWidth: precomputedTableSkeletons.get(ctx)?.get(startIndex)?.width ?? 0,
+ remainHeight: availableHeight,
+ repeatRows: getLeadingRepeatHeaderRows(table, rowNodes),
+ repeatRowsHeight: 0,
+ },
+ rowIndex: 0,
+ columnIndex: 0,
+ preparedCellPages: new Map(),
+ pendingCellBuild: null,
+ complete: false,
+ result: null,
+ };
+}
+
+export function stepTableSkeletonsBuild(state: ISlicedTableSkeletonBuildState): boolean {
+ if (state.complete) {
+ return true;
+ }
+
+ const rowNode = state.tableNode.children[state.rowIndex];
+ if (rowNode == null) {
+ _finishTableSkeletonsBuild(state);
+ return true;
+ }
+
+ const cellNode = rowNode.children[state.columnIndex];
+ const rowSource = state.table.tableRows[state.rowIndex];
+ const cellConfig = rowSource.tableCells[state.columnIndex];
+ if (cellNode != null && !isCoveredTableCell(cellConfig)) {
+ const pageContentHeight = getAvailableHeight(state.curPage, state.createCache, false);
+ const availableHeight = getAvailableHeight(state.curPage, state.createCache, true);
+ const canRowSplit =
+ rowSource.cantSplit !== BooleanNumber.TRUE &&
+ rowSource.trHeight.hRule === TableRowHeightRule.AUTO;
+ const needOpenNewTable = state.createCache.remainHeight <= 72;
+ const firstCellPageHeight = canRowSplit && !needOpenNewTable
+ ? state.createCache.remainHeight
+ : availableHeight;
+ state.pendingCellBuild ??= startSkeletonCellPagesBuild(
+ state.ctx,
+ state.viewModel,
+ cellNode,
+ state.sectionBreakConfig,
+ state.table,
+ state.rowIndex,
+ state.columnIndex,
+ firstCellPageHeight,
+ pageContentHeight
+ );
+ if (!stepSkeletonCellPagesBuild(state.pendingCellBuild)) {
+ return false;
+ }
+ const pages = state.pendingCellBuild.requiresSyncFallback
+ ? createSkeletonCellPages(
+ state.ctx,
+ state.viewModel,
+ cellNode,
+ state.sectionBreakConfig,
+ state.table,
+ state.rowIndex,
+ state.columnIndex,
+ firstCellPageHeight,
+ pageContentHeight
+ )
+ : state.pendingCellBuild.pages;
+ state.pendingCellBuild = null;
+ state.preparedCellPages.set(state.columnIndex, pages);
+ }
+
+ state.columnIndex++;
+ if (state.columnIndex < rowNode.children.length) {
+ return false;
+ }
+
+ dealWithTableRow(
+ state.ctx,
+ state.curPage,
+ state.skeTables,
+ state.viewModel,
+ state.sectionBreakConfig,
+ rowNode,
+ state.rowIndex,
+ state.table,
+ state.createCache,
+ false,
+ undefined,
+ state.preparedCellPages
+ );
+ state.rowIndex++;
+ state.columnIndex = 0;
+ state.preparedCellPages = new Map();
+ state.pendingCellBuild = null;
+
+ if (state.rowIndex >= state.tableNode.children.length) {
+ _finishTableSkeletonsBuild(state);
+ }
+ return state.complete;
+}
+
+export function cachePrecomputedSlicedTableSkeletons(
+ ctx: ILayoutContext,
+ tableStartIndex: number,
+ availableHeight: number,
+ result: ISlicedTableSkeletonParams
+): void {
+ let cache = precomputedSlicedTableSkeletons.get(ctx);
+ if (cache == null) {
+ cache = new Map();
+ precomputedSlicedTableSkeletons.set(ctx, cache);
+ }
+ cache.set(tableStartIndex, { availableHeight, result });
+}
+
+function _finishTableSkeletonsBuild(state: ISlicedTableSkeletonBuildState): void {
+ updateTableSkeletonsPosition(state.createCache, state.curPage, state.skeTables, state.table);
+ const policy =
+ state.sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy();
+ state.result = {
+ skeTables: state.skeTables,
+ fromCurrentPage:
+ state.skeTables[0].height <=
+ state.availableHeight + policy.table.currentPageOverflowTolerance,
+ };
+ state.complete = true;
+}
+
// Create skeletons of a table, which may be divided into different pages according to the available height of the page.
export function createTableSkeletons(
ctx: ILayoutContext,
@@ -210,6 +514,31 @@ export function createTableSkeletons(
): ISlicedTableSkeletonParams {
const skeTables: IDocumentSkeletonTable[] = [];
const { startIndex, endIndex, children: rowNodes } = tableNode;
+ const precomputedSliced = precomputedSlicedTableSkeletons.get(ctx)?.get(startIndex);
+ if (
+ precomputedSliced != null &&
+ Math.abs(precomputedSliced.availableHeight - availableHeight) < 0.01
+ ) {
+ precomputedSlicedTableSkeletons.get(ctx)?.delete(startIndex);
+ precomputedTableSkeletons.get(ctx)?.delete(startIndex);
+ return precomputedSliced.result;
+ }
+
+ if (
+ ctx.deferSlicedTableLayout?.({
+ curPage,
+ viewModel,
+ tableNode,
+ sectionBreakConfig,
+ availableHeight,
+ }) === true
+ ) {
+ // The current paragraph attempt is transactional and will be discarded.
+ // Returning an empty split lets the existing layout stack unwind without
+ // publishing provisional geometry; the incremental coordinator restores
+ // the paragraph checkpoint after the deferred calculation completes.
+ return { skeTables: [], fromCurrentPage: false };
+ }
const table = viewModel.getTableByStartIndex(startIndex)?.tableSource;
if (table == null) {
@@ -221,11 +550,13 @@ export function createTableSkeletons(
}
const repeatRows = getLeadingRepeatHeaderRows(table, rowNodes);
+ const precomputedTable = precomputedTableSkeletons.get(ctx)?.get(startIndex);
+ precomputedTableSkeletons.get(ctx)?.delete(startIndex);
const curTableSkeleton = getNullTableSkeleton(startIndex, endIndex, table);
const createCache: ICreateTableCache = {
rowTop: 0,
- tableWidth: 0,
+ tableWidth: precomputedTable?.width ?? 0,
remainHeight: availableHeight,
repeatRows,
repeatRowsHeight: 0,
@@ -245,7 +576,9 @@ export function createTableSkeletons(
rowNode,
row,
table,
- createCache
+ createCache,
+ false,
+ precomputedTable?.rows[row]
);
}
@@ -316,7 +649,9 @@ function dealWithTableRow(
row: number,
table: ITable,
cache: ICreateTableCache,
- isRepeatRow = false
+ isRepeatRow = false,
+ precomputedRow?: IDocumentSkeletonRow,
+ preparedCellPages?: Map<number, IDocumentSkeletonPage[]>
) {
const pageContentHeight = getAvailableHeight(curPage, cache, false);
const availableHeight = getAvailableHeight(curPage, cache, true);
@@ -324,16 +659,21 @@ function dealWithTableRow(
const { children: cellNodes, startIndex, endIndex } = rowNode;
const rowSource = table.tableRows[row];
const { trHeight, cantSplit } = rowSource;
- const rowSkeletons: IDocumentSkeletonRow[] = [];
const { hRule, val } = trHeight;
const canRowSplit = cantSplit !== BooleanNumber.TRUE && trHeight.hRule !== TableRowHeightRule.EXACT;
const needOpenNewTable = cache.remainHeight <= 0;
+ const precomputedRowFits =
+ !isRepeatRow &&
+ precomputedRow != null &&
+ precomputedRow.height <= pageContentHeight &&
+ (needOpenNewTable || !canRowSplit || precomputedRow.height <= cache.remainHeight);
+ const rowSkeletons: IDocumentSkeletonRow[] = precomputedRowFits ? [precomputedRow] : [];
let curTableSkeleton = getCurTableSkeleton(skeTables);
- const rowHeights = [0];
+ const rowHeights = precomputedRowFits ? [precomputedRow.height] : [0];
const forcedPageBreakRows = new WeakSet<IDocumentSkeletonRow>();
- for (const cellNode of cellNodes) {
+ for (const cellNode of precomputedRowFits ? [] : cellNodes) {
const col = cellNodes.indexOf(cellNode);
const cellConfig = rowSource.tableCells[col];
if (isCoveredTableCell(cellConfig)) {
@@ -352,17 +692,18 @@ function dealWithTableRow(
continue;
}
- const cellPageSkeletons = createSkeletonCellPages(
- ctx,
- viewModel,
- cellNode,
- sectionBreakConfig,
- table,
- row,
- col,
- canRowSplit && !needOpenNewTable ? cache.remainHeight : availableHeight,
- pageContentHeight
- );
+ const cellPageSkeletons = preparedCellPages?.get(col) ??
+ createSkeletonCellPages(
+ ctx,
+ viewModel,
+ cellNode,
+ sectionBreakConfig,
+ table,
+ row,
+ col,
+ canRowSplit && !needOpenNewTable ? cache.remainHeight : availableHeight,
+ pageContentHeight
+ );
while (rowSkeletons.length < cellPageSkeletons.length) {
rowSkeletons.push(createNullRowSkeletonWithCells(
ctx,
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 a469c918f4..8e6f4ea6e9 100644
--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
@@ -15,33 +15,37 @@
*/
import type { ColumnSeparatorType, ISectionColumnProperties, LocaleService, Nullable } from '@univerjs/core';
-import type {
- IDocumentSkeletonCached,
- IDocumentSkeletonColumn,
- IDocumentSkeletonGlyph,
- IDocumentSkeletonLine,
- IDocumentSkeletonPage,
- ISkeletonResourceReference,
-} from '../../../basics/i-document-skeleton-cached';
-import type { IDocsConfig, INodeInfo, INodePosition, INodeSearch } from '../../../basics/interfaces';
+import type { IDocumentSkeletonCached, IDocumentSkeletonColumn, IDocumentSkeletonColumnGroup, IDocumentSkeletonColumnGroupColumn, IDocumentSkeletonDivide, IDocumentSkeletonDrawing, IDocumentSkeletonDrawingAnchor, IDocumentSkeletonGlyph, IDocumentSkeletonLine, IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonSection, IDocumentSkeletonTable, ISkeletonResourceReference } from '../../../basics/i-document-skeleton-cached';
+import type { IDocsConfig, INodeInfo, INodePosition, INodeSearch, ISectionBreakConfig } from '../../../basics/interfaces';
import type { 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';
+import type { ISlicedTableSkeletonBuildState, ITableSkeletonBuildState } from './block/table';
+import type { IDocumentSkeletonPagePatch } from './document-layout-page-patch';
+import type { IDocumentLayoutBlockGeometryPublication, IDocumentLayoutDrawingAnchorPublication, IDocumentLayoutGeometryPublication, IDocumentLayoutPagePublication, IDocumentLayoutResourcePublication } from './document-layout-publication';
+import type { DocumentLayoutMode, DocumentLayoutReason, IDocumentLayoutApplyResult, IDocumentLayoutInvalidation, IDocumentLayoutPageRange, IDocumentLayoutProgress, IDocumentLayoutProtectedPageRange, IDocumentLayoutProtectedRange } from './document-layout-types';
import type { IDocumentPaginationMetrics, ILayoutContext } from './tools';
-import { BooleanNumber, DataStreamTreeTokenType, PRESET_LIST_TYPE, SectionType, Skeleton } from '@univerjs/core';
+import { BooleanNumber, DataStreamTreeNodeType, DataStreamTreeTokenType, DocumentFlavor, PRESET_LIST_TYPE, SectionType, Skeleton } from '@univerjs/core';
import { Subject } from 'rxjs';
-import {
- BreakType,
- DocumentSkeletonPageType,
- GlyphType,
- LineType,
- PageLayoutType,
-} from '../../../basics/i-document-skeleton-cached';
+import { BreakType, DocumentSkeletonPageType, GlyphType, LineType, PageLayoutType } from '../../../basics/i-document-skeleton-cached';
+import { getDocsCustomBlockRenderViewport } from '../custom-block-render-viewport';
import { getDocumentCompatibilityPolicy } from '../document-compatibility';
import { Liquid } from '../liquid';
import { getDocsTableRenderViewport, hasDocsTableHorizontalViewport } from '../table-render-viewport';
import { DocumentEditArea } from '../view-model/document-view-model';
import { dealWithSection } from './block/section';
-import { getTableIdAndSliceIndex } from './block/table';
+import {
+ cachePrecomputedSlicedTableSkeletons,
+ cachePrecomputedTableSkeleton,
+ getTableIdAndSliceIndex,
+
+ startTableSkeletonBuild,
+ startTableSkeletonsBuild,
+ stepTableSkeletonBuild,
+ stepTableSkeletonsBuild,
+} from './block/table';
+import { applyDocumentSkeletonContinuousBlock, hydrateDocumentSkeletonPage, hydrateDocumentSkeletonPageMaterializationPlaceholder, serializeDocumentSkeletonPage } from './document-layout-page-patch';
import { Hyphen } from './hyphenation/hyphen';
import { LanguageDetector } from './hyphenation/language-detector';
import { createSkeletonPage } from './model/page';
@@ -51,6 +55,7 @@ import {
getLastPage,
getNullSkeleton,
getPageFromPath,
+
prepareSectionBreakConfig,
resetContext,
setPageParent,
@@ -75,6 +80,10 @@ function hasCompatiblePageGeometry(page: IDocumentSkeletonPage, config: ReturnTy
page.marginRight === marginRight;
}
+function isSameLayoutMetric(left: number, right: number): boolean {
+ return Math.abs(left - right) < 0.01;
+}
+
function hasCompatiblePhysicalPage(page: IDocumentSkeletonPage, config: ReturnType<typeof prepareSectionBreakConfig>): boolean {
const { pageSize, pageOrient } = config;
return page.pageWidth === pageSize?.width &&
@@ -246,6 +255,370 @@ export enum DocumentSkeletonState {
INVALID = 'invalid',
}
+export interface IDocumentCustomBlockPresentationRefreshResult {
+ didRefresh: boolean;
+ requiresLayout: boolean;
+}
+
+interface IIncrementalLayoutState {
+ generation: number;
+ reason: DocumentLayoutReason;
+ mode: DocumentLayoutMode;
+ ctx: ILayoutContext;
+ sectionIndex: number;
+ paragraphIndex: number;
+ sectionInitialized: boolean;
+ sectionBreakConfig: Nullable<ISectionBreakConfig>;
+ layoutAnchor: Nullable<number>;
+ priorityAnchor: Nullable<number>;
+ priorityPageIndex: number;
+ priorityPageEnd: Nullable<number>;
+ interactionPageTail: Nullable<IInteractionPageTail>;
+ interactionPageComplete: boolean;
+ interactionWindowComplete: boolean;
+ interactionWindowResume: Nullable<IInteractionWindowResume>;
+ invalidation: Nullable<IDocumentLayoutInvalidation>;
+ laidOutThrough: number;
+ stableLaidOutThrough: number;
+ complete: boolean;
+ cancelled: boolean;
+ processedBlockCount: number;
+ totalBlockCount: number;
+ startedAt: number;
+ maxBlockDuration: number;
+ pendingTableBuild: Nullable<ITableSkeletonBuildState>;
+ pendingSlicedTableBuild: Nullable<ISlicedTableSkeletonBuildState>;
+ pendingParagraphCheckpoint: Nullable<IIncrementalParagraphCheckpoint>;
+ stablePageCount: number;
+ finalizedPageCount: number;
+ anchorPublished: boolean;
+ lastPublishedPageCount: number;
+ lastPublishedBlockCount: number;
+ publicationRevision: number;
+ reuseUnaffectedTail: boolean;
+ reusedTail: boolean;
+ tailConvergencePageCount: number;
+ dirtyRetryCount: number;
+}
+
+interface IInteractionPageTail {
+ previousSkeleton: IDocumentSkeletonCached;
+ previousPage: IDocumentSkeletonPage;
+ anchorEnd: number;
+ previousAnchorEnd: number;
+ pageEnd: number;
+ nextBlockIndex: number;
+ nextSectionIndex: number;
+ nextParagraphIndex: number;
+ resumeBlockIndex: number;
+ resumeSectionIndex: number;
+ resumeParagraphIndex: number;
+ terminal: boolean;
+}
+
+interface IInteractionWindowResume {
+ anchorEnd: number;
+ pageEnd: number;
+ processedBlockCount: number;
+ sectionIndex: number;
+ paragraphIndex: number;
+}
+
+interface IIncrementalParagraphCheckpoint {
+ pageIndex: number;
+ page: IDocumentSkeletonPage;
+ skeHeaders: IDocumentSkeletonCached['skeHeaders'];
+ skeFooters: IDocumentSkeletonCached['skeFooters'];
+ skeListLevel: NonNullable<ISkeletonResourceReference['skeListLevel']>;
+ drawingAnchor: NonNullable<ISkeletonResourceReference['drawingAnchor']>;
+ layoutStartPointer: ILayoutContext['layoutStartPointer'];
+ isDirty: boolean;
+ floatObjectsCache: ILayoutContext['floatObjectsCache'];
+ paragraphConfigCache: ILayoutContext['paragraphConfigCache'];
+ sectionBreakConfigCache: ILayoutContext['sectionBreakConfigCache'];
+ paragraphsOpenNewPage: ILayoutContext['paragraphsOpenNewPage'];
+ paginationMetrics: ILayoutContext['paginationMetrics'];
+}
+
+interface ITopLevelBlockEntry {
+ block: DataStreamTreeNode;
+ sectionIndex: number;
+ paragraphIndex: number;
+}
+
+function getLayoutNow(): number {
+ return typeof performance === 'undefined' ? Date.now() : performance.now();
+}
+
+function mapCurrentOffsetToPrevious(
+ offset: number,
+ invalidation: IDocumentLayoutInvalidation | undefined
+): number {
+ if (invalidation == null || offset < invalidation.oldStart) {
+ return offset;
+ }
+ if (offset < invalidation.newEnd) {
+ return invalidation.oldStart;
+ }
+ return offset - (invalidation.newEnd - invalidation.oldEnd);
+}
+
+function mapPreviousOffsetToCurrent(
+ offset: number,
+ invalidation: IDocumentLayoutInvalidation | undefined
+): number {
+ if (invalidation == null || offset < invalidation.oldStart) {
+ return offset;
+ }
+ if (offset < invalidation.oldEnd) {
+ return invalidation.newEnd;
+ }
+ return offset + (invalidation.newEnd - invalidation.oldEnd);
+}
+
+function clonePageFlowForPublish(source: IDocumentSkeletonPage): IDocumentSkeletonPage {
+ const page: IDocumentSkeletonPage = {
+ ...source,
+ sections: [],
+ // Continuous-page merging translates drawing coordinates. Keep partial
+ // publications isolated from the active layout graph so publishing the
+ // same page fragment again cannot accumulate that translation.
+ skeDrawings: new Map([...source.skeDrawings].map(([drawingId, drawing]) => [
+ drawingId,
+ { ...drawing },
+ ])),
+ skeTables: new Map([...source.skeTables].map(([tableId, table]) => [
+ tableId,
+ { ...table },
+ ])),
+ skeColumnGroups: new Map([...source.skeColumnGroups].map(([groupId, group]) => [
+ groupId,
+ { ...group },
+ ])),
+ parent: undefined,
+ };
+
+ const cloneFlowNodes = (sourcePage: IDocumentSkeletonPage, targetPage: IDocumentSkeletonPage) => {
+ targetPage.sections = sourcePage.sections.map((sourceSection) => {
+ const section: IDocumentSkeletonSection = {
+ ...sourceSection,
+ columns: [],
+ parent: targetPage,
+ };
+ section.columns = sourceSection.columns.map((sourceColumn) => {
+ const column: IDocumentSkeletonColumn = {
+ ...sourceColumn,
+ lines: [],
+ parent: section,
+ };
+ column.lines = sourceColumn.lines.map((sourceLine) => {
+ const line: IDocumentSkeletonLine = {
+ ...sourceLine,
+ divides: [],
+ parent: column,
+ };
+ if (sourceLine.bullet != null) {
+ line.bullet = { ...sourceLine.bullet };
+ }
+ line.divides = sourceLine.divides.map((sourceDivide): IDocumentSkeletonDivide => {
+ const divide: IDocumentSkeletonDivide = {
+ ...sourceDivide,
+ glyphGroup: [],
+ parent: line,
+ };
+ // Published flow nodes own a separate parent graph. Clone glyph containers
+ // so selection hit testing resolves positions against the published page.
+ divide.glyphGroup = sourceDivide.glyphGroup.map((glyph) => ({
+ ...glyph,
+ parent: divide,
+ }));
+ return divide;
+ });
+ return line;
+ });
+ return column;
+ });
+ return section;
+ });
+ };
+
+ cloneFlowNodes(source, page);
+
+ const cloneEmbeddedStructures = (sourcePage: IDocumentSkeletonPage, targetPage: IDocumentSkeletonPage) => {
+ targetPage.skeTables = new Map([...sourcePage.skeTables].map(([tableId, sourceTable]) => {
+ const table: IDocumentSkeletonTable = {
+ ...sourceTable,
+ rows: [],
+ parent: targetPage,
+ };
+ table.rows = sourceTable.rows.map((sourceRow) => {
+ const row: IDocumentSkeletonRow = {
+ ...sourceRow,
+ cells: [],
+ parent: table,
+ };
+ row.cells = sourceRow.cells.map((sourceCell) => {
+ const cell = {
+ ...sourceCell,
+ sections: [],
+ parent: row,
+ };
+ cloneFlowNodes(sourceCell, cell);
+ cloneEmbeddedStructures(sourceCell, cell);
+ return cell;
+ });
+ return row;
+ });
+ return [tableId, table];
+ }));
+ targetPage.skeColumnGroups = new Map([...sourcePage.skeColumnGroups].map(([groupId, sourceGroup]) => {
+ const group: IDocumentSkeletonColumnGroup = {
+ ...sourceGroup,
+ columns: [],
+ parent: targetPage,
+ };
+ group.columns = sourceGroup.columns.map((sourceColumn) => {
+ const columnPage: IDocumentSkeletonPage = {
+ ...sourceColumn.page,
+ sections: [],
+ };
+ const column: IDocumentSkeletonColumnGroupColumn = {
+ ...sourceColumn,
+ parent: group,
+ page: columnPage,
+ };
+ columnPage.parent = column;
+ cloneFlowNodes(sourceColumn.page, column.page);
+ cloneEmbeddedStructures(sourceColumn.page, column.page);
+ return column;
+ });
+ return [groupId, group];
+ }));
+ };
+
+ cloneEmbeddedStructures(source, page);
+
+ return page;
+}
+
+function copyPageBoundaryMetadata(
+ target: IDocumentSkeletonPage,
+ source: IDocumentSkeletonPage
+): void {
+ target.breakType = source.breakType;
+ if (source.isExplicitPageBreak == null) {
+ delete target.isExplicitPageBreak;
+ } else {
+ target.isExplicitPageBreak = source.isExplicitPageBreak;
+ }
+ if (source.isNaturalPageOverflow == null) {
+ delete target.isNaturalPageOverflow;
+ } else {
+ target.isNaturalPageOverflow = source.isNaturalPageOverflow;
+ }
+}
+
+function shiftPageCharacterOffsets(page: IDocumentSkeletonPage, delta: number): void {
+ const shiftRange = (value: { st: number; ed: number }) => {
+ value.st += delta;
+ value.ed += delta;
+ };
+ const shiftFlow = (flowPage: IDocumentSkeletonPage) => {
+ shiftRange(flowPage);
+ for (const section of flowPage.sections) {
+ shiftRange(section);
+ for (const column of section.columns) {
+ shiftRange(column);
+ for (const line of column.lines) {
+ shiftRange(line);
+ line.paragraphIndex += delta;
+ if (line.bullet != null) {
+ line.bullet.startIndexItem += delta;
+ }
+ for (const divide of line.divides) {
+ shiftRange(divide);
+ }
+ }
+ }
+ }
+ };
+ const shiftEmbeddedStructures = (flowPage: IDocumentSkeletonPage) => {
+ for (const table of flowPage.skeTables.values()) {
+ shiftRange(table);
+ for (const row of table.rows) {
+ shiftRange(row);
+ for (const cell of row.cells) {
+ // Empty cells use the zero range as a sentinel. Populated cells
+ // retain body-absolute ranges and therefore follow the edit delta.
+ if (cell.st !== 0 || cell.ed !== 0) {
+ shiftFlow(cell);
+ shiftEmbeddedStructures(cell);
+ }
+ }
+ }
+ }
+ for (const group of flowPage.skeColumnGroups.values()) {
+ shiftRange(group);
+ for (const column of group.columns) {
+ shiftRange(column);
+ if (column.page.st !== 0 || column.page.ed !== 0) {
+ shiftFlow(column.page);
+ shiftEmbeddedStructures(column.page);
+ }
+ }
+ }
+ };
+
+ shiftFlow(page);
+ shiftEmbeddedStructures(page);
+}
+
+function clonePageLayoutPlaceholderForPublish(source: IDocumentSkeletonPage): IDocumentSkeletonPage {
+ return {
+ ...source,
+ isLayoutPlaceholder: true,
+ sections: [],
+ st: -1,
+ ed: -1,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ skeColumnGroups: new Map(),
+ parent: undefined,
+ };
+}
+
+function clonePageMaterializationPlaceholderForPublish(source: IDocumentSkeletonPage): IDocumentSkeletonPage {
+ const placeholder = clonePageLayoutPlaceholderForPublish(source);
+ delete placeholder.isLayoutPlaceholder;
+ placeholder.isMaterializationPlaceholder = true;
+ placeholder.st = source.st;
+ placeholder.ed = source.ed;
+ return placeholder;
+}
+
+function hasSamePageExitGeometry(
+ previous: IDocumentSkeletonPage,
+ current: IDocumentSkeletonPage
+): boolean {
+ const scalarKeys = [
+ 'sectionId',
+ 'pageWidth',
+ 'pageHeight',
+ 'pageOrient',
+ 'marginLeft',
+ 'marginRight',
+ 'marginTop',
+ 'marginBottom',
+ 'pageNumber',
+ 'pageNumberStart',
+ ] as const;
+ if (scalarKeys.some((key) => previous[key] !== current[key])) {
+ return false;
+ }
+
+ return true;
+}
+
function removeDupPages(ctx: ILayoutContext) {
const hash = new Set();
@@ -257,12 +630,12 @@ function removeDupPages(ctx: ILayoutContext) {
});
}
-function mergeContinuousDuplicatePages(pages: IDocumentSkeletonPage[]) {
+function mergeContinuousDuplicatePages(pages: IDocumentSkeletonPage[], mergeAll = false) {
for (let index = 1; index < pages.length;) {
const previousPage = pages[index - 1];
const page = pages[index];
- if (previousPage.pageNumber !== page.pageNumber || previousPage.sectionId !== page.sectionId) {
+ if (!mergeAll && (previousPage.pageNumber !== page.pageNumber || previousPage.sectionId !== page.sectionId)) {
index++;
continue;
}
@@ -286,6 +659,12 @@ function mergeContinuousDuplicatePages(pages: IDocumentSkeletonPage[]) {
previousPage.skeTables.set(tableId, table);
});
+ page.skeColumnGroups?.forEach((columnGroup, columnGroupId) => {
+ columnGroup.top += topOffset;
+ columnGroup.parent = previousPage;
+ previousPage.skeColumnGroups.set(columnGroupId, columnGroup);
+ });
+
previousPage.height += page.height;
previousPage.width = Math.max(previousPage.width, page.width);
previousPage.ed = Math.max(previousPage.ed, page.ed);
@@ -394,6 +773,103 @@ function isHitTestAddressableGlyph(glyph: IDocumentSkeletonGlyph): boolean {
(glyph.streamType === DataStreamTreeTokenType.PARAGRAPH && glyph.count > 0);
}
+function getFirstBodyFlowCharIndex(page: IDocumentSkeletonPage): number {
+ for (const section of page.sections) {
+ for (const column of section.columns) {
+ for (const line of column.lines) {
+ for (const divide of line.divides) {
+ let charIndex = divide.st;
+ for (const glyph of divide.glyphGroup) {
+ if (isHitTestAddressableGlyph(glyph)) {
+ return charIndex;
+ }
+ charIndex += glyph.count;
+ }
+ }
+ }
+ }
+ }
+
+ // A pure table-continuation page has no top-level body glyph. Its aggregate
+ // start remains the correct signal that the spanning table must be rebuilt.
+ return page.st;
+}
+
+function getLastBodyFlowCharIndex(page: IDocumentSkeletonPage): number {
+ for (const section of [...page.sections].reverse()) {
+ for (const column of [...section.columns].reverse()) {
+ for (const line of [...column.lines].reverse()) {
+ for (const divide of [...line.divides].reverse()) {
+ let charIndex = divide.st;
+ let lastAddressableIndex: number | null = null;
+ for (const glyph of divide.glyphGroup) {
+ if (isHitTestAddressableGlyph(glyph)) {
+ lastAddressableIndex = charIndex + Math.max(1, glyph.count) - 1;
+ }
+ charIndex += glyph.count;
+ }
+ if (lastAddressableIndex != null) {
+ return lastAddressableIndex;
+ }
+ }
+ }
+ }
+ }
+
+ return page.ed;
+}
+
+function serializePaginatedContinuationCheckpoint(page: IDocumentSkeletonPagePatch): string {
+ return JSON.stringify({
+ st: page.st,
+ ed: page.ed,
+ sectionId: page.sectionId,
+ headerId: page.headerId,
+ footerId: page.footerId,
+ pageWidth: page.pageWidth,
+ pageHeight: page.pageHeight,
+ pageOrient: page.pageOrient,
+ marginLeft: page.marginLeft,
+ marginRight: page.marginRight,
+ marginTop: page.marginTop,
+ marginBottom: page.marginBottom,
+ pageNumber: page.pageNumber,
+ pageNumberStart: page.pageNumberStart,
+ breakType: page.breakType,
+ segmentId: page.segmentId,
+ type: page.type,
+ // Main owns the complete protected-page geometry. Internal line wraps do
+ // not participate in the merge checkpoint because Worker pages after the
+ // protected range are complete, self-contained page publications. The
+ // checkpoint only needs to prove that the next page starts at the same
+ // logical offset and with the same paginated section configuration.
+ tables: page.skeTables.map(([tableId, table]) => ({
+ tableId,
+ st: table.st,
+ ed: table.ed,
+ rows: table.rows.map((row) => ({
+ index: row.index,
+ st: row.st,
+ ed: row.ed,
+ isRepeatRow: row.isRepeatRow,
+ cells: row.cells.map((cell) => ({ st: cell.st, ed: cell.ed })),
+ })),
+ })),
+ columnGroups: page.skeColumnGroups.map(([columnGroupId, group]) => ({
+ columnGroupId,
+ st: group.st,
+ ed: group.ed,
+ columns: group.columns.map((column) => ({
+ columnId: column.columnId,
+ st: column.st,
+ ed: column.ed,
+ pageSt: column.page.st,
+ pageEd: column.page.ed,
+ })),
+ })),
+ });
+}
+
function resolveMostSpecificPageByCharIndex(page: IDocumentSkeletonPage, charIndex: number): IDocumentSkeletonPage {
for (const table of page.skeTables?.values() ?? []) {
for (const row of table.rows) {
@@ -424,6 +900,42 @@ function resolveMostSpecificPageByCharIndex(page: IDocumentSkeletonPage, charInd
return page;
}
+function hasRenderedNodeAtCharIndex(page: IDocumentSkeletonPage, charIndex: number): boolean {
+ const specificPage = resolveMostSpecificPageByCharIndex(page, charIndex);
+
+ for (const section of specificPage.sections) {
+ for (const column of section.columns) {
+ for (const line of column.lines) {
+ for (const divide of line.divides) {
+ if (charIndex >= divide.st && charIndex <= divide.ed) {
+ return true;
+ }
+ }
+ }
+ }
+ }
+
+ return false;
+}
+
+function hydrateDrawingAnchors(
+ publication: IDocumentLayoutDrawingAnchorPublication
+): Map<string, Map<number, IDocumentSkeletonDrawingAnchor>> {
+ return new Map(publication.map(([segmentId, anchors]) => [
+ segmentId,
+ new Map(anchors.map(([paragraphIndex, anchor]) => [
+ paragraphIndex,
+ {
+ ...anchor,
+ // Line objects are active-layout scratch references. They are rebuilt
+ // by createAndUpdateBlockAnchor when the next layout starts and must
+ // not force a full-document scan on the presentation thread.
+ elements: [],
+ },
+ ])),
+ ]));
+}
+
function getSegmentPageFromRelativePath(
skeletonData: IDocumentSkeletonCached,
segmentPageIndex: number,
@@ -462,6 +974,9 @@ export class DocumentSkeleton extends Skeleton {
private _dirty$ = new Subject<boolean>();
readonly dirty$ = this._dirty$.asObservable();
+ private _layoutProgress$ = new Subject<IDocumentLayoutProgress>();
+ readonly layoutProgress$ = this._layoutProgress$.asObservable();
+
private _skeletonData: Nullable<IDocumentSkeletonCached>;
private _findLiquid: Liquid = new Liquid();
@@ -477,21 +992,67 @@ export class DocumentSkeleton extends Skeleton {
private _paginationMetrics: Nullable<IDocumentPaginationMetrics> = null;
+ private _lastCompleteSkeletonData: Nullable<IDocumentSkeletonCached> = null;
+
+ private _pendingInvalidationAnchor: Nullable<number> = null;
+
+ private _layoutGeneration = 0;
+
+ private _activeLayout: Nullable<IIncrementalLayoutState> = null;
+
+ private _externalLayoutProgress: Nullable<IDocumentLayoutProgress> = null;
+
+ private _externalProtectedPages: Nullable<{
+ range: IDocumentLayoutProtectedPageRange;
+ pages: Map<number, {
+ page: IDocumentSkeletonPage;
+ checkpoint: string;
+ }>;
+ divergenceStartPageIndex: number | null;
+ pendingPages: Map<number, IDocumentSkeletonPage>;
+ publishedPageIndexes: Set<number>;
+ }> = null;
+
+ private _externalProtectedContinuousLayout: Nullable<{
+ range: Extract<IDocumentLayoutProtectedRange, { mode: 'continuous' }>;
+ pendingPublications: IDocumentLayoutBlockGeometryPublication[];
+ }> = null;
+
+ private _topLevelBlockSections: DataStreamTreeNode[] | null = null;
+
+ private _topLevelBlocks: ITopLevelBlockEntry[] = [];
+
+ private readonly _isolateIncrementalPublications: boolean;
+
constructor(
private _docViewModel: DocumentViewModel,
- localeService: LocaleService
+ localeService: LocaleService,
+ options: { isolateIncrementalPublications?: boolean } = {}
) {
super(localeService);
+ this._isolateIncrementalPublications = options.isolateIncrementalPublications !== false;
}
- static create(docViewModel: DocumentViewModel, localeService: LocaleService) {
- return new DocumentSkeleton(docViewModel, localeService);
+ static create(
+ docViewModel: DocumentViewModel,
+ localeService: LocaleService,
+ options?: { isolateIncrementalPublications?: boolean }
+ ) {
+ return new DocumentSkeleton(docViewModel, localeService, options);
}
override dispose(): void {
+ this.cancelIncrementalLayout();
super.dispose();
+ this._layoutProgress$.complete();
this._skeletonData = null;
- this._findLiquid = null as unknown as Liquid;
+ this._lastCompleteSkeletonData = null;
+ this._pendingInvalidationAnchor = null;
+ this._externalLayoutProgress = null;
+ this._externalProtectedPages = null;
+ this._externalProtectedContinuousLayout = null;
+ this._topLevelBlockSections = null;
+ this._topLevelBlocks = [];
this._docViewModel.dispose();
this._initialWidth = 0;
}
@@ -509,17 +1070,1530 @@ export class DocumentSkeleton extends Skeleton {
return;
}
+ this.cancelIncrementalLayout();
+ this._externalLayoutProgress = null;
+ this._externalProtectedPages = null;
+ this._externalProtectedContinuousLayout = null;
const ctx = this._prepareLayoutContext();
-
- // const start = +new Date();
this._skeletonData = this._createSkeleton(ctx, bounds);
+ this._lastCompleteSkeletonData = this._skeletonData;
+ this._pendingInvalidationAnchor = null;
this._paginationMetrics = ctx.paginationMetrics ?? null;
- // console.log('skeleton calculate cost', +new Date() - start);
this._dirty$.next(true);
}
- getSkeletonData() {
- return this._skeletonData;
+ startIncrementalLayout(options?: {
+ reason?: DocumentLayoutReason;
+ anchor?: number;
+ priorityAnchor?: number;
+ invalidation?: IDocumentLayoutInvalidation;
+ bounds?: IViewportInfo;
+ reuseUnaffectedTail?: boolean;
+ preserveInteractionWindow?: boolean;
+ }): number {
+ this.cancelIncrementalLayout();
+ this._externalLayoutProgress = null;
+ this._externalProtectedPages = null;
+ this._externalProtectedContinuousLayout = null;
+
+ const generation = ++this._layoutGeneration;
+ const reason = options?.reason ?? (options?.anchor == null ? 'initial' : 'edit');
+ const dataModel = this.getViewModel().getDataModel();
+ const sections = this.getViewModel().getChildren();
+ const topLevelBlocks = this._getTopLevelBlocks(sections);
+ const mode: DocumentLayoutMode = dataModel.documentStyle.documentFlavor === DocumentFlavor.MODERN
+ ? 'continuous'
+ : 'paginated';
+ const priorityAnchor = options?.priorityAnchor ?? options?.anchor;
+ const hasPublishedCheckpoint = this._skeletonData != null || this._lastCompleteSkeletonData != null;
+ const previousSkeleton = this._lastCompleteSkeletonData ?? this._skeletonData;
+ const invalidation = options?.invalidation;
+ const layoutAnchor = options?.anchor;
+ const invalidationAnchor = layoutAnchor == null
+ ? this._pendingInvalidationAnchor ?? undefined
+ : Math.min(layoutAnchor, this._pendingInvalidationAnchor ?? layoutAnchor);
+ // A cancelled typing generation leaves the last complete skeleton in the
+ // coordinate space that existed before the first uncommitted edit. Map the
+ // replacement physical page from that stable dirty anchor, not from the
+ // latest logical caret, which may already have crossed the stale page end.
+ const mutationDelta = invalidation == null ? 0 : invalidation.newEnd - invalidation.oldEnd;
+ let priorityPageAnchor = priorityAnchor;
+ if (priorityPageAnchor != null && invalidation != null) {
+ if (priorityPageAnchor >= invalidation.newEnd) {
+ priorityPageAnchor -= mutationDelta;
+ } else if (priorityPageAnchor >= invalidation.oldStart) {
+ priorityPageAnchor = invalidation.oldStart;
+ }
+ }
+ priorityPageAnchor ??= invalidationAnchor;
+ const priorityPageIndex = priorityPageAnchor == null || previousSkeleton == null
+ ? -1
+ : this._findBodyPageIndex(previousSkeleton.pages, priorityPageAnchor);
+ const previousPriorityPage = priorityPageIndex < 0
+ ? null
+ : previousSkeleton?.pages[priorityPageIndex] ?? null;
+ const previousPriorityPageEnd = previousPriorityPage == null
+ ? null
+ : getLastBodyFlowCharIndex(previousPriorityPage);
+ const priorityPageEnd = previousPriorityPageEnd == null
+ ? null
+ : previousPriorityPageEnd + (
+ invalidation != null && invalidation.oldStart <= previousPriorityPageEnd
+ ? mutationDelta
+ : 0
+ );
+ const incrementalStart = this._prepareIncrementalLayoutStart(
+ invalidationAnchor,
+ mode,
+ invalidation,
+ options?.preserveInteractionWindow === true,
+ options?.reuseUnaffectedTail === false
+ );
+ // The first-open anchor only prioritizes the initial viewport; it does not
+ // represent mutated content. Carry invalidation across generations only
+ // after a publishable checkpoint already exists.
+ this._pendingInvalidationAnchor = hasPublishedCheckpoint ? invalidationAnchor ?? null : null;
+
+ this._activeLayout = {
+ generation,
+ reason,
+ mode,
+ ctx: incrementalStart.ctx,
+ sectionIndex: incrementalStart.sectionIndex,
+ paragraphIndex: incrementalStart.paragraphIndex,
+ sectionInitialized: false,
+ sectionBreakConfig: null,
+ layoutAnchor: incrementalStart.layoutAnchor,
+ priorityAnchor: priorityAnchor ?? null,
+ priorityPageIndex,
+ priorityPageEnd,
+ interactionPageTail: incrementalStart.interactionPageTail,
+ interactionPageComplete: false,
+ interactionWindowComplete: false,
+ interactionWindowResume: null,
+ invalidation: invalidation ?? null,
+ laidOutThrough: incrementalStart.laidOutThrough,
+ stableLaidOutThrough: -1,
+ complete: false,
+ cancelled: false,
+ processedBlockCount: incrementalStart.processedBlockCount,
+ totalBlockCount: topLevelBlocks.length,
+ startedAt: getLayoutNow(),
+ maxBlockDuration: 0,
+ pendingTableBuild: null,
+ pendingSlicedTableBuild: null,
+ pendingParagraphCheckpoint: null,
+ stablePageCount: Math.max(0, incrementalStart.ctx.skeleton.pages.length - 1),
+ finalizedPageCount: Math.max(0, incrementalStart.ctx.skeleton.pages.length - 1),
+ anchorPublished: false,
+ lastPublishedPageCount: incrementalStart.ctx.skeleton.pages.length > 0
+ ? Math.max(0, incrementalStart.ctx.skeleton.pages.length - 1)
+ : 0,
+ lastPublishedBlockCount: incrementalStart.processedBlockCount,
+ publicationRevision: 0,
+ reuseUnaffectedTail: options?.reuseUnaffectedTail !== false,
+ reusedTail: false,
+ tailConvergencePageCount: incrementalStart.ctx.skeleton.pages.length,
+ dirtyRetryCount: 0,
+ };
+
+ return generation;
+ }
+
+ private _prepareIncrementalLayoutStart(
+ anchor: number | undefined,
+ mode: DocumentLayoutMode,
+ invalidation?: IDocumentLayoutInvalidation,
+ preserveInteractionWindow = false,
+ reuseInteractionPagePrefix = false
+ ): {
+ ctx: ILayoutContext;
+ sectionIndex: number;
+ paragraphIndex: number;
+ layoutAnchor: Nullable<number>;
+ laidOutThrough: number;
+ processedBlockCount: number;
+ interactionPageTail: Nullable<IInteractionPageTail>;
+ } {
+ const ctx = this._prepareLayoutContext();
+ // Canonical suffix recovery starts from the last complete skeleton. Main's
+ // protected interaction page may instead advance from the preceding edit's
+ // published page so each typing generation maps only one mutation delta.
+ const previousSkeleton = this._lastCompleteSkeletonData ?? this._skeletonData;
+ const interactionSkeleton = reuseInteractionPagePrefix
+ ? this._skeletonData ?? previousSkeleton
+ : previousSkeleton;
+ const sections = this.getViewModel().getChildren();
+ const continuousPrefix = mode === 'continuous'
+ ? this._prepareContinuousPrefix(ctx, previousSkeleton, sections, anchor)
+ : null;
+ if (continuousPrefix != null) {
+ return continuousPrefix;
+ }
+
+ if (anchor == null || previousSkeleton == null || previousSkeleton.pages.length < 2) {
+ return {
+ ctx,
+ sectionIndex: 0,
+ paragraphIndex: 0,
+ layoutAnchor: null,
+ laidOutThrough: -1,
+ processedBlockCount: 0,
+ interactionPageTail: null,
+ };
+ }
+
+ const blocks = this._getTopLevelBlocks(sections);
+ const getBlockFlowStart = (block: (typeof blocks)[number]['block']) =>
+ block.children.length === 1 && block.children[0].nodeType === DataStreamTreeNodeType.TABLE
+ ? block.children[0].startIndex
+ : block.startIndex;
+ const blockContainsOffset = (block: (typeof blocks)[number]['block'], offset: number) =>
+ (offset >= block.startIndex && offset <= block.endIndex) ||
+ block.children.some((child) => offset >= child.startIndex && offset <= child.endIndex);
+ const anchorBlockIndex = blocks.findIndex(({ block }) => blockContainsOffset(block, anchor));
+ if (anchorBlockIndex < 0) {
+ return {
+ ctx,
+ sectionIndex: 0,
+ paragraphIndex: 0,
+ layoutAnchor: null,
+ laidOutThrough: -1,
+ processedBlockCount: 0,
+ interactionPageTail: null,
+ };
+ }
+
+ const previousAnchor = mapCurrentOffsetToPrevious(anchor, invalidation);
+ const anchorPageIndex = this._findBodyPageIndex(previousSkeleton.pages, previousAnchor);
+ const hasEarlierOverlappingRange = anchorPageIndex > 0 && previousSkeleton.pages
+ .slice(0, anchorPageIndex)
+ .some((page) => previousAnchor >= page.st && previousAnchor <= page.ed);
+ const anchorBlockOwnsTable = blocks[anchorBlockIndex].block.children.some(
+ (child) => child.nodeType === DataStreamTreeNodeType.TABLE &&
+ anchor >= child.startIndex &&
+ anchor <= child.endIndex
+ );
+ const canResumePlainParagraph = blocks[anchorBlockIndex].block.nodeType === DataStreamTreeNodeType.PARAGRAPH &&
+ blocks[anchorBlockIndex].block.children.length === 0;
+ if (reuseInteractionPagePrefix && canResumePlainParagraph) {
+ const interactionPreviousAnchor = mapCurrentOffsetToPrevious(anchor, invalidation);
+ const interactionPageIndex = interactionSkeleton == null
+ ? -1
+ : this._findBodyPageIndex(interactionSkeleton.pages, interactionPreviousAnchor);
+ const paginatedPrefix = this._preparePaginatedParagraphPrefix(
+ ctx,
+ interactionSkeleton ?? previousSkeleton,
+ blocks[anchorBlockIndex],
+ anchorBlockIndex,
+ interactionPageIndex,
+ invalidation
+ );
+ if (paginatedPrefix != null) {
+ return paginatedPrefix;
+ }
+ }
+ if (hasEarlierOverlappingRange && !anchorBlockOwnsTable && !canResumePlainParagraph) {
+ return {
+ ctx,
+ sectionIndex: 0,
+ paragraphIndex: 0,
+ layoutAnchor: anchor,
+ laidOutThrough: -1,
+ processedBlockCount: 0,
+ interactionPageTail: null,
+ };
+ }
+
+ let startBlockIndex = anchorBlockIndex;
+ let startPageIndex = this._findBodyPageIndex(
+ previousSkeleton.pages,
+ mapCurrentOffsetToPrevious(getBlockFlowStart(blocks[startBlockIndex].block), invalidation)
+ );
+ if (startPageIndex <= 0) {
+ return {
+ ctx,
+ sectionIndex: 0,
+ paragraphIndex: 0,
+ layoutAnchor: null,
+ laidOutThrough: -1,
+ processedBlockCount: 0,
+ interactionPageTail: null,
+ };
+ }
+
+ // A block may span pages, and a page may start with the tail of an earlier block.
+ // Walk back to the first top-level block contributing to the rebuild page so the
+ // retained prefix and recomputed suffix meet only at a stable block boundary.
+ while (startPageIndex > 0) {
+ const pageStart = getFirstBodyFlowCharIndex(previousSkeleton.pages[startPageIndex]);
+ const currentPageStart = mapPreviousOffsetToCurrent(pageStart, invalidation);
+ const firstPageBlockIndex = blocks.findIndex(({ block }) => blockContainsOffset(block, currentPageStart));
+ if (firstPageBlockIndex < 0 || firstPageBlockIndex >= startBlockIndex) {
+ break;
+ }
+
+ startBlockIndex = firstPageBlockIndex;
+ const earlierPageIndex = this._findBodyPageIndex(
+ previousSkeleton.pages,
+ mapCurrentOffsetToPrevious(getBlockFlowStart(blocks[startBlockIndex].block), invalidation)
+ );
+ if (earlierPageIndex < 0 || earlierPageIndex >= startPageIndex) {
+ break;
+ }
+ startPageIndex = earlierPageIndex;
+ }
+
+ // The first top-level glyph on a table-continuation page may belong to a
+ // cell paragraph rather than to the outer table block. A checkpoint made
+ // there cannot restore the table iterator state and produces one-page row
+ // fragments when the suffix is laid out. Rewind to the outermost table
+ // that crosses the proposed checkpoint page so the rebuilt suffix starts
+ // from a real document block boundary.
+ const checkpointStart = getBlockFlowStart(blocks[startBlockIndex].block);
+ const crossingTables = (ctx.dataModel.getBody()?.tables ?? [])
+ .filter((table) => table.startIndex < checkpointStart && table.endIndex >= checkpointStart);
+ crossingTables.sort((left, right) => left.startIndex - right.startIndex);
+ const crossingTable = crossingTables[0];
+ if (crossingTable != null) {
+ // A paragraph that owns a table starts at the table's structural end
+ // token. Resuming that paragraph after retaining the table lays the
+ // table owner twice and creates a one-character, full-height page.
+ // Table iterator checkpoints are not serializable yet, so rebuild
+ // cooperatively from the start while the previous skeleton stays on
+ // screen. This path converges exactly with synchronous pagination.
+ return {
+ ctx,
+ sectionIndex: 0,
+ paragraphIndex: 0,
+ layoutAnchor: anchor,
+ laidOutThrough: -1,
+ processedBlockCount: 0,
+ interactionPageTail: null,
+ };
+ }
+
+ const start = blocks[startBlockIndex];
+ const previousPage = previousSkeleton.pages[startPageIndex];
+ const sectionBreakConfig = prepareSectionBreakConfig(ctx, start.sectionIndex);
+
+ this._copySkeletonResources(
+ previousSkeleton,
+ ctx.skeletonResourceReference,
+ checkpointStart
+ );
+ // A single contiguous body edit can project the retained interaction island.
+ // Disjoint body edits deliberately take the canonical recovery path because
+ // one scalar invalidation cannot map every retained offset without ambiguity.
+ const retainedPages = previousSkeleton.pages.slice(0, startPageIndex).map((page) => {
+ if (!preserveInteractionWindow || invalidation == null || page.ed < invalidation.oldStart) {
+ return page;
+ }
+ if (page.st < invalidation.oldEnd) {
+ return clonePageLayoutPlaceholderForPublish(page);
+ }
+ const retainedPage = clonePageFlowForPublish(page);
+ shiftPageCharacterOffsets(retainedPage, invalidation.newEnd - invalidation.oldEnd);
+ return retainedPage;
+ });
+ ctx.skeleton.pages.push(...retainedPages);
+ const rebuiltPage = createSkeletonPage(
+ ctx,
+ sectionBreakConfig,
+ ctx.skeletonResourceReference,
+ previousPage.pageNumber
+ );
+ copyPageBoundaryMetadata(rebuiltPage, previousPage);
+ ctx.skeleton.pages.push(rebuiltPage);
+
+ return {
+ ctx,
+ sectionIndex: start.sectionIndex,
+ paragraphIndex: start.paragraphIndex,
+ layoutAnchor: start.block.endIndex,
+ laidOutThrough: checkpointStart - 1,
+ processedBlockCount: startBlockIndex,
+ interactionPageTail: null,
+ };
+ }
+
+ private _preparePaginatedParagraphPrefix(
+ ctx: ILayoutContext,
+ previousSkeleton: IDocumentSkeletonCached,
+ anchorEntry: ITopLevelBlockEntry,
+ anchorBlockIndex: number,
+ anchorPageIndex: number,
+ invalidation?: IDocumentLayoutInvalidation
+ ): Nullable<{
+ ctx: ILayoutContext;
+ sectionIndex: number;
+ paragraphIndex: number;
+ layoutAnchor: Nullable<number>;
+ laidOutThrough: number;
+ processedBlockCount: number;
+ interactionPageTail: Nullable<IInteractionPageTail>;
+ }> {
+ const previousPage = previousSkeleton.pages[anchorPageIndex];
+ const previousSection = previousPage?.sections[0];
+ const previousColumn = previousSection?.columns[0];
+ if (
+ previousPage == null ||
+ previousPage.sections.length !== 1 ||
+ previousSection?.columns.length !== 1 ||
+ previousColumn == null ||
+ previousPage.skeDrawings.size > 0 ||
+ previousPage.skeTables.size > 0 ||
+ previousPage.skeColumnGroups.size > 0
+ ) {
+ return null;
+ }
+
+ const previousAnchorStart = mapCurrentOffsetToPrevious(anchorEntry.block.startIndex, invalidation);
+ const previousAnchorEnd = mapCurrentOffsetToPrevious(anchorEntry.block.endIndex, invalidation);
+ const mappedPreviousAnchorEnd = mapPreviousOffsetToCurrent(previousAnchorEnd, invalidation);
+ const previousParagraphEnd = previousColumn.lines.find(
+ (line) => line.paragraphIndex >= previousAnchorStart
+ )?.paragraphIndex;
+ if (invalidation != null && invalidation.oldStart < previousAnchorStart) {
+ return null;
+ }
+ const retainedLines = previousColumn.lines
+ .filter((line) => line.ed < previousAnchorStart)
+ .map((line) => ({ ...line }));
+ if (retainedLines.length === 0) {
+ return null;
+ }
+
+ const lastRetainedLine = retainedLines[retainedLines.length - 1];
+ lastRetainedLine.lineHeight = Math.max(0, lastRetainedLine.lineHeight - lastRetainedLine.marginBottom);
+ lastRetainedLine.marginBottom = 0;
+ const retainedEnd = lastRetainedLine.ed;
+ // The finalized source page stores aggregate metrics for every line that
+ // used to follow this prefix. Reusing those metrics after filtering the
+ // lines makes the next paragraph start from the old page bottom; Enter can
+ // then move a paragraph to the following page until background layout
+ // replaces it. Rebuild all mutable flow metrics from the retained lines.
+ const retainedHeight = retainedLines.reduce(
+ (height, line) => Math.max(height, line.top + line.lineHeight),
+ 0
+ );
+ const retainedColumn: IDocumentSkeletonColumn = {
+ ...previousColumn,
+ lines: retainedLines,
+ ed: retainedEnd,
+ height: retainedHeight,
+ width: previousPage.pageWidth - previousPage.marginLeft - previousPage.marginRight,
+ isFull: false,
+ parent: undefined,
+ };
+ for (const line of retainedLines) {
+ line.parent = retainedColumn;
+ }
+ const retainedSection: IDocumentSkeletonSection = {
+ ...previousSection,
+ columns: [retainedColumn],
+ ed: retainedEnd,
+ height: previousPage.pageHeight - previousPage.marginTop - previousPage.marginBottom,
+ parent: undefined,
+ };
+ retainedColumn.parent = retainedSection;
+ const retainedPage: IDocumentSkeletonPage = {
+ ...previousPage,
+ sections: [retainedSection],
+ ed: retainedEnd,
+ height: retainedHeight,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ skeColumnGroups: new Map(),
+ parent: undefined,
+ };
+ retainedSection.parent = retainedPage;
+
+ this._copySkeletonResources(
+ previousSkeleton,
+ ctx.skeletonResourceReference,
+ anchorEntry.block.startIndex
+ );
+ ctx.skeleton.pages.push(...previousSkeleton.pages.slice(0, anchorPageIndex), retainedPage);
+
+ const previousPageEnd = getLastBodyFlowCharIndex(previousPage);
+ const pageEnd = mapPreviousOffsetToCurrent(previousPageEnd, invalidation);
+ const blocks = this._getTopLevelBlocks(this.getViewModel().getChildren());
+ const nextBlockIndex = blocks.findIndex(({ block }, index) =>
+ index > anchorBlockIndex && block.startIndex > pageEnd
+ );
+ const pageTailEnd = nextBlockIndex < 0 ? blocks.length : nextBlockIndex;
+ const pageTailBlocks = blocks.slice(anchorBlockIndex, pageTailEnd);
+ const terminal = pageTailBlocks.some(({ block }) => block.endIndex > pageEnd);
+ // Reusing the old page tail is valid only when the edited paragraph still
+ // maps to the same paragraph boundary. Enter and paragraph-boundary deletes
+ // change that boundary; old wrapped lines then contain text owned by a new
+ // block and cannot be spliced behind the recomputed paragraph.
+ const canReusePageTail = invalidation != null &&
+ previousParagraphEnd === previousAnchorEnd &&
+ anchorEntry.block.endIndex === mappedPreviousAnchorEnd &&
+ anchorEntry.block.endIndex <= pageEnd &&
+ pageTailBlocks.length > 0 &&
+ pageTailBlocks.every(({ block }) =>
+ block.nodeType === DataStreamTreeNodeType.PARAGRAPH &&
+ block.children.length === 0
+ ) &&
+ previousColumn.lines
+ .filter((line) => line.paragraphIndex > previousAnchorEnd)
+ .every((line) => line.bullet == null);
+ const nextBlock = nextBlockIndex < 0 ? null : blocks[nextBlockIndex];
+ const resumeBlockIndex = anchorBlockIndex + 1;
+ const resumeBlock = blocks[resumeBlockIndex];
+
+ return {
+ ctx,
+ sectionIndex: anchorEntry.sectionIndex,
+ paragraphIndex: anchorEntry.paragraphIndex,
+ layoutAnchor: anchorEntry.block.endIndex,
+ laidOutThrough: anchorEntry.block.startIndex - 1,
+ processedBlockCount: anchorBlockIndex,
+ interactionPageTail: canReusePageTail
+ ? {
+ previousSkeleton,
+ previousPage,
+ anchorEnd: anchorEntry.block.endIndex,
+ previousAnchorEnd,
+ pageEnd,
+ nextBlockIndex: pageTailEnd,
+ nextSectionIndex: nextBlock?.sectionIndex ?? this.getViewModel().getChildren().length,
+ nextParagraphIndex: nextBlock?.paragraphIndex ?? 0,
+ resumeBlockIndex,
+ resumeSectionIndex: resumeBlock?.sectionIndex ?? this.getViewModel().getChildren().length,
+ resumeParagraphIndex: resumeBlock?.paragraphIndex ?? 0,
+ terminal,
+ }
+ : null,
+ };
+ }
+
+ private _prepareContinuousPrefix(
+ ctx: ILayoutContext,
+ previousSkeleton: Nullable<IDocumentSkeletonCached>,
+ sections: ReturnType<DocumentViewModel['getChildren']>,
+ anchor?: number
+ ): Nullable<{
+ ctx: ILayoutContext;
+ sectionIndex: number;
+ paragraphIndex: number;
+ layoutAnchor: Nullable<number>;
+ laidOutThrough: number;
+ processedBlockCount: number;
+ interactionPageTail: Nullable<IInteractionPageTail>;
+ }> {
+ if (anchor == null || previousSkeleton?.pages.length !== 1 || sections.length !== 1) {
+ return null;
+ }
+
+ const previousPage = previousSkeleton.pages[0];
+ const previousSection = previousPage.sections[0];
+ const previousColumn = previousSection?.columns[0];
+ if (
+ previousPage.sections.length !== 1 ||
+ previousSection?.columns.length !== 1 ||
+ previousColumn == null ||
+ previousPage.skeDrawings.size > 0 ||
+ previousPage.skeTables.size > 0 ||
+ previousPage.skeColumnGroups.size > 0
+ ) {
+ return null;
+ }
+
+ const blocks = sections[0].children;
+ const anchorBlockIndex = blocks.findIndex((block) => anchor >= block.startIndex && anchor <= block.endIndex);
+ const anchorBlock = blocks[anchorBlockIndex];
+ if (
+ anchorBlockIndex <= 0 ||
+ anchorBlock?.nodeType !== DataStreamTreeNodeType.PARAGRAPH
+ ) {
+ return null;
+ }
+
+ const retainedLines = previousColumn.lines
+ .filter((line) => line.ed < anchorBlock.startIndex)
+ .map((line) => ({ ...line }));
+ if (retainedLines.length === 0) {
+ return null;
+ }
+
+ const lastRetainedLine = retainedLines[retainedLines.length - 1];
+ // The following paragraph applied its collapsed top/bottom spacing to this
+ // line during the previous layout. Undo that one boundary contribution so
+ // laying the anchor paragraph applies it exactly once again.
+ lastRetainedLine.lineHeight = Math.max(0, lastRetainedLine.lineHeight - lastRetainedLine.marginBottom);
+ lastRetainedLine.marginBottom = 0;
+ const retainedEnd = retainedLines[retainedLines.length - 1].ed;
+ const retainedHeight = retainedLines.reduce(
+ (height, line) => Math.max(height, line.top + line.lineHeight),
+ 0
+ );
+ const retainedColumn: IDocumentSkeletonColumn = {
+ ...previousColumn,
+ lines: retainedLines,
+ ed: retainedEnd,
+ height: retainedHeight,
+ width: previousPage.pageWidth - previousPage.marginLeft - previousPage.marginRight,
+ isFull: false,
+ parent: undefined,
+ };
+ for (const line of retainedLines) {
+ line.parent = retainedColumn;
+ }
+ const retainedSection: IDocumentSkeletonSection = {
+ ...previousSection,
+ columns: [retainedColumn],
+ ed: retainedEnd,
+ height: previousPage.pageHeight - previousPage.marginTop - previousPage.marginBottom,
+ parent: undefined,
+ };
+ retainedColumn.parent = retainedSection;
+ const retainedPage: IDocumentSkeletonPage = {
+ ...previousPage,
+ sections: [retainedSection],
+ ed: retainedEnd,
+ height: retainedHeight,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ skeColumnGroups: new Map(),
+ parent: undefined,
+ };
+ retainedSection.parent = retainedPage;
+
+ this._copySkeletonResources(
+ previousSkeleton,
+ ctx.skeletonResourceReference,
+ anchorBlock.startIndex
+ );
+ ctx.skeleton.pages.push(retainedPage);
+
+ return {
+ ctx,
+ sectionIndex: 0,
+ paragraphIndex: anchorBlockIndex,
+ layoutAnchor: anchorBlock.endIndex,
+ laidOutThrough: anchorBlock.startIndex - 1,
+ processedBlockCount: anchorBlockIndex,
+ interactionPageTail: null,
+ };
+ }
+
+ private _findBodyPageIndex(pages: IDocumentSkeletonPage[], charIndex: number): number {
+ for (let pageIndex = 0; pageIndex < pages.length; pageIndex++) {
+ if (hasRenderedNodeAtCharIndex(pages[pageIndex], charIndex)) {
+ return pageIndex;
+ }
+ }
+
+ // Structural tokens do not always have a glyph. Fall back to the aggregate
+ // page range for those nodes, but prefer the concrete rendered node above:
+ // ranges overlap when a table spans pages and would otherwise select its
+ // first page for content that is actually rendered later.
+ return pages.findIndex((page) => charIndex >= page.st && charIndex <= page.ed);
+ }
+
+ private _getTopLevelBlocks(sections: DataStreamTreeNode[]): ITopLevelBlockEntry[] {
+ if (this._topLevelBlockSections === sections) {
+ return this._topLevelBlocks;
+ }
+
+ const blocks: ITopLevelBlockEntry[] = [];
+ for (let sectionIndex = 0; sectionIndex < sections.length; sectionIndex++) {
+ const section = sections[sectionIndex];
+ for (let paragraphIndex = 0; paragraphIndex < section.children.length; paragraphIndex++) {
+ blocks.push({
+ block: section.children[paragraphIndex],
+ sectionIndex,
+ paragraphIndex,
+ });
+ }
+ }
+ this._topLevelBlockSections = sections;
+ this._topLevelBlocks = blocks;
+ return blocks;
+ }
+
+ private _copySkeletonResources(
+ source: IDocumentSkeletonCached,
+ target: ISkeletonResourceReference,
+ endIndexExclusive: number
+ ): void {
+ for (const [key, value] of source.skeHeaders) {
+ target.skeHeaders.set(key, value);
+ }
+ for (const [key, value] of source.skeFooters) {
+ target.skeFooters.set(key, value);
+ }
+ for (const [key, value] of source.skeListLevel ?? []) {
+ target.skeListLevel?.set(
+ key,
+ value.map((level) => level.filter(({ paragraph }) => paragraph.startIndex < endIndexExclusive))
+ );
+ }
+ for (const [key, value] of source.drawingAnchor ?? []) {
+ target.drawingAnchor?.set(key, new Map(
+ [...value]
+ .filter(([paragraphIndex]) => paragraphIndex < endIndexExclusive)
+ .map(([paragraphIndex, anchor]) => [
+ paragraphIndex,
+ { ...anchor, elements: [...anchor.elements] },
+ ])
+ ));
+ }
+ }
+
+ cancelIncrementalLayout(generation?: number): void {
+ const state = this._activeLayout;
+ if (state == null || (generation != null && state.generation !== generation)) {
+ return;
+ }
+
+ state.cancelled = true;
+ this._activeLayout = null;
+ this._layoutProgress$.next(this._getLayoutProgress(state));
+ }
+
+ stepIncrementalLayout(
+ generation: number,
+ budgetMs = 8,
+ maxWorkUnits = Number.POSITIVE_INFINITY
+ ): IDocumentLayoutProgress {
+ return this._stepIncrementalLayout(generation, budgetMs, true, maxWorkUnits);
+ }
+
+ /**
+ * Publishes at most one page that a previous layout slice has already
+ * completed. It never advances shaping or pagination work.
+ */
+ publishIncrementalLayoutBacklog(generation: number): IDocumentLayoutProgress {
+ const state = this._activeLayout;
+ if (state?.generation === generation && state.mode === 'continuous') {
+ const progress = this._getLayoutProgress(state);
+ this._layoutProgress$.next(progress);
+ return progress;
+ }
+ return this._stepIncrementalLayout(generation, 0, false, Number.POSITIVE_INFINITY);
+ }
+
+ private _stepIncrementalLayout(
+ generation: number,
+ budgetMs: number,
+ advanceLayout: boolean,
+ maxWorkUnits: number
+ ): IDocumentLayoutProgress {
+ const state = this._activeLayout;
+ if (state == null || state.generation !== generation || state.cancelled) {
+ return {
+ generation,
+ publicationRevision: 0,
+ didPublish: false,
+ didPublishAnchor: false,
+ publishedPageCount: 0,
+ reason: 'edit',
+ mode: state?.mode ?? 'paginated',
+ complete: false,
+ cancelled: true,
+ anchorReady: false,
+ laidOutThrough: -1,
+ stableLaidOutThrough: -1,
+ pageCount: 0,
+ processedBlockCount: 0,
+ totalBlockCount: 0,
+ estimatedPageCount: 0,
+ estimatedHeight: 0,
+ elapsedTime: 0,
+ maxBlockDuration: 0,
+ interactionWindowComplete: false,
+ };
+ }
+
+ const sliceStartedAt = getLayoutNow();
+ const normalizedMaxWorkUnits = Number.isFinite(maxWorkUnits)
+ ? Math.max(1, Math.floor(maxWorkUnits))
+ : Number.POSITIVE_INFINITY;
+ let blocksProcessed = 0;
+
+ if (advanceLayout) {
+ while (!state.complete && !state.cancelled) {
+ const blockStartedAt = getLayoutNow();
+ this._advanceIncrementalLayout(state);
+ const blockDuration = getLayoutNow() - blockStartedAt;
+ state.maxBlockDuration = Math.max(state.maxBlockDuration, blockDuration);
+ blocksProcessed++;
+
+ if (
+ !state.complete &&
+ state.ctx.skeleton.pages.length > state.tailConvergencePageCount
+ ) {
+ state.tailConvergencePageCount = state.ctx.skeleton.pages.length;
+ if (this._tryConvergeUnaffectedTail(state)) {
+ break;
+ }
+ }
+
+ if (
+ blocksProcessed >= normalizedMaxWorkUnits ||
+ (blocksProcessed > 0 && getLayoutNow() - sliceStartedAt >= budgetMs)
+ ) {
+ break;
+ }
+ }
+ }
+
+ if (
+ advanceLayout &&
+ !state.complete &&
+ !state.cancelled &&
+ state.ctx.skeleton.pages.length > state.tailConvergencePageCount
+ ) {
+ state.tailConvergencePageCount = state.ctx.skeleton.pages.length;
+ this._tryConvergeUnaffectedTail(state);
+ }
+
+ const anchorReady = this._isPriorityAnchorReady(state);
+ const pageCount = state.ctx.skeleton.pages.length;
+ const shouldPublishPriority = state.priorityAnchor != null && anchorReady && !state.anchorPublished;
+ const currentPriorityPageIndex = this._findPublishablePriorityPageIndex(state);
+ // A local edit can move the caret onto an adjacent physical page. Publishing
+ // only through its page in the previous complete skeleton leaves the new
+ // caret page private to the layout session and makes selection recreation
+ // fail even though the anchor itself is already stable.
+ const priorityPublishedPageCount = Math.max(
+ state.priorityPageIndex + 1,
+ currentPriorityPageIndex + 1
+ );
+ const stableComputedPageCount = state.complete
+ ? pageCount
+ : Math.max(
+ Math.max(0, pageCount - 1),
+ state.interactionPageComplete ? state.priorityPageIndex + 1 : 0
+ );
+ const hasStablePageToPublish = stableComputedPageCount > state.lastPublishedPageCount;
+ const hasStableBlockToPublish = state.mode === 'continuous' &&
+ state.processedBlockCount > state.lastPublishedBlockCount;
+ const suppressPreAnchorPublication =
+ state.reason === 'edit' &&
+ state.priorityAnchor != null &&
+ !state.anchorPublished;
+ const canPublish = shouldPublishPriority || hasStablePageToPublish || hasStableBlockToPublish || state.complete;
+ const publishedPageCount = state.mode === 'continuous'
+ ? pageCount
+ : state.complete
+ ? state.reusedTail
+ ? pageCount
+ : shouldPublishPriority
+ ? Math.max(state.lastPublishedPageCount, priorityPublishedPageCount)
+ : Math.min(pageCount, state.lastPublishedPageCount + 1)
+ : shouldPublishPriority
+ ? Math.max(state.lastPublishedPageCount, priorityPublishedPageCount)
+ : Math.min(stableComputedPageCount, state.lastPublishedPageCount + 1);
+ let didPublish = false;
+ let didPublishAnchor = false;
+ if (
+ !state.cancelled &&
+ canPublish &&
+ (!suppressPreAnchorPublication || shouldPublishPriority || state.complete)
+ ) {
+ if (state.mode === 'paginated') {
+ this._finalizePaginatedPagesForPublication(state, publishedPageCount);
+ }
+ const isFinalPublication = state.complete && publishedPageCount >= pageCount;
+ if (isFinalPublication) {
+ this._lastCompleteSkeletonData = state.ctx.skeleton;
+ this._pendingInvalidationAnchor = null;
+ }
+ this._skeletonData = isFinalPublication
+ ? state.ctx.skeleton
+ : !this._isolateIncrementalPublications && state.mode === 'paginated'
+ ? this._createSharedPublishablePartialSkeleton(state, publishedPageCount)
+ : this._createPublishablePartialSkeleton(state, publishedPageCount);
+ this._paginationMetrics = state.ctx.paginationMetrics ?? null;
+ this._dirty$.next(true);
+ didPublish = true;
+ didPublishAnchor = shouldPublishPriority;
+ state.publicationRevision++;
+ state.anchorPublished ||= shouldPublishPriority;
+ state.lastPublishedPageCount = state.mode === 'continuous'
+ ? Math.min(1, publishedPageCount)
+ : publishedPageCount;
+ state.lastPublishedBlockCount = state.processedBlockCount;
+ }
+
+ const progress = this._getLayoutProgress(state, didPublish, didPublishAnchor);
+ this._layoutProgress$.next(progress);
+
+ if (progress.complete || state.cancelled) {
+ this._activeLayout = null;
+ }
+
+ return progress;
+ }
+
+ private _createPublishablePartialSkeleton(
+ state: IIncrementalLayoutState,
+ publishedPageCount: number
+ ): IDocumentSkeletonCached {
+ const source = state.ctx.skeleton;
+ const previous = this._lastCompleteSkeletonData;
+ const preservesPreviousPagination =
+ state.mode === 'paginated' &&
+ state.priorityAnchor != null &&
+ state.priorityPageIndex >= 0 &&
+ previous != null;
+ const stablePages = source.pages.slice(0, state.stablePageCount);
+ const activePages = source.pages
+ .slice(state.stablePageCount, Math.max(state.stablePageCount, publishedPageCount))
+ .map(clonePageFlowForPublish);
+ const startIndex = stablePages.at(-1)?.ed ?? -1;
+
+ updateBlockIndex(
+ activePages,
+ startIndex,
+ state.ctx.docsConfig.documentCompatibilityPolicy
+ );
+ // Continuous sections are represented as same-number page fragments while
+ // layout is in progress. Final layout merges them before publication; do
+ // the same on cloned foreground pages so the temporary page list has the
+ // same physical-page identity as the previous complete skeleton.
+ mergeContinuousDuplicatePages(activePages, state.mode === 'continuous');
+
+ const flowPages = [...stablePages, ...activePages];
+ const currentPriorityPageIndex = state.priorityAnchor == null
+ ? -1
+ : this._findBodyPageIndex(flowPages, state.priorityAnchor);
+ let publishedFlowPages = flowPages;
+ if (
+ preservesPreviousPagination &&
+ currentPriorityPageIndex >= 0 &&
+ publishedPageCount <= state.priorityPageIndex + 1
+ ) {
+ // A spanning table can temporarily paginate into extra fragments while
+ // foreground layout is advancing toward the edit anchor. Publishing
+ // those fragments changes the physical page beneath the viewport even
+ // though every fragment is before the edited page. Keep the previously
+ // completed bridge pages and atomically replace only the physical page
+ // that contains the anchor. Background layout can then reconcile the
+ // complete tail without making the caret page jump in the meantime.
+ const retainedBridgePages = previous.pages
+ .slice(state.stablePageCount, state.priorityPageIndex)
+ .map(clonePageFlowForPublish);
+ const priorityPage = clonePageFlowForPublish(flowPages[currentPriorityPageIndex]);
+ const previousPriorityPage = previous.pages[state.priorityPageIndex];
+ const priorityPageStartIndex = retainedBridgePages.at(-1)?.ed ?? stablePages.at(-1)?.ed ?? -1;
+
+ updateBlockIndex(
+ [priorityPage],
+ priorityPageStartIndex,
+ state.ctx.docsConfig.documentCompatibilityPolicy
+ );
+ if (previousPriorityPage != null) {
+ priorityPage.pageNumber = previousPriorityPage.pageNumber;
+ }
+ publishedFlowPages = [...stablePages, ...retainedBridgePages, priorityPage];
+ }
+ const placeholderPages = preservesPreviousPagination
+ ? previous.pages
+ .slice(Math.max(state.priorityPageIndex + 1, publishedPageCount))
+ .map(clonePageLayoutPlaceholderForPublish)
+ : [];
+ const published: IDocumentSkeletonCached = {
+ ...source,
+ pages: [...publishedFlowPages, ...placeholderPages],
+ };
+ const publishedActivePages = publishedFlowPages.slice(stablePages.length);
+ setPageParent([...publishedActivePages, ...placeholderPages], published);
+
+ return published;
+ }
+
+ private _createSharedPublishablePartialSkeleton(
+ state: IIncrementalLayoutState,
+ publishedPageCount: number
+ ): IDocumentSkeletonCached {
+ const source = state.ctx.skeleton;
+ const previous = this._lastCompleteSkeletonData;
+ let publishedPages = source.pages.slice(0, publishedPageCount);
+ if (
+ state.priorityAnchor == null ||
+ state.priorityPageIndex < 0 ||
+ previous == null
+ ) {
+ return { ...source, pages: publishedPages };
+ }
+ const currentPriorityPageIndex = this._findBodyPageIndex(
+ source.pages,
+ state.priorityAnchor
+ );
+ if (
+ currentPriorityPageIndex >= 0 &&
+ publishedPageCount <= state.priorityPageIndex + 1
+ ) {
+ const priorityPage = source.pages[currentPriorityPageIndex];
+ const previousPriorityPage = previous.pages[state.priorityPageIndex];
+ publishedPages = [
+ ...source.pages.slice(0, state.stablePageCount),
+ ...previous.pages.slice(state.stablePageCount, state.priorityPageIndex),
+ previousPriorityPage == null
+ ? priorityPage
+ : { ...priorityPage, pageNumber: previousPriorityPage.pageNumber },
+ ];
+ }
+ publishedPages.push(...previous.pages
+ .slice(Math.max(state.priorityPageIndex + 1, publishedPageCount))
+ .map(clonePageLayoutPlaceholderForPublish));
+ return {
+ ...source,
+ pages: publishedPages,
+ };
+ }
+
+ private _findPublishablePriorityPageIndex(state: IIncrementalLayoutState): number {
+ const anchor = state.priorityAnchor;
+ if (anchor == null) {
+ return -1;
+ }
+
+ const directPageIndex = this._findBodyPageIndex(state.ctx.skeleton.pages, anchor);
+ if (directPageIndex >= 0 || state.mode !== 'paginated') {
+ return directPageIndex;
+ }
+
+ // Continuation pages keep block-relative indexes until publication. Resolve
+ // the post-edit caret against finalized clones so an edit that moves it to
+ // an adjacent page publishes that page, without exposing unrelated tail
+ // pages or mutating the active layout session prematurely.
+ const stablePages = state.ctx.skeleton.pages.slice(0, state.stablePageCount);
+ const activePages = state.ctx.skeleton.pages
+ .slice(state.stablePageCount)
+ .map(clonePageFlowForPublish);
+ updateBlockIndex(
+ activePages,
+ stablePages.at(-1)?.ed ?? -1,
+ state.ctx.docsConfig.documentCompatibilityPolicy
+ );
+ return this._findBodyPageIndex([...stablePages, ...activePages], anchor);
+ }
+
+ private _finalizePaginatedPagesForPublication(
+ state: IIncrementalLayoutState,
+ publishedPageCount: number
+ ): void {
+ const { ctx } = state;
+ const endPageIndex = state.reusedTail
+ ? Math.min(publishedPageCount, state.priorityPageIndex + 1)
+ : publishedPageCount;
+ const pages = ctx.skeleton.pages.slice(state.finalizedPageCount, endPageIndex);
+ if (pages.length > 0) {
+ const startIndex = ctx.skeleton.pages[state.finalizedPageCount - 1]?.ed ?? -1;
+ updateBlockIndex(pages, startIndex, ctx.docsConfig.documentCompatibilityPolicy);
+ updateInlineDrawingCoordsAndBorder(ctx, pages);
+ }
+ state.finalizedPageCount = state.reusedTail
+ ? publishedPageCount
+ : Math.max(state.finalizedPageCount, endPageIndex);
+ }
+
+ getLayoutProgress(): Nullable<IDocumentLayoutProgress> {
+ return this._activeLayout == null
+ ? this._externalLayoutProgress
+ : this._getLayoutProgress(this._activeLayout);
+ }
+
+ /**
+ * Opens a presentation barrier before an external executor starts layout.
+ * The Main interaction snapshot remains authoritative inside its protected
+ * page or block range while the external executor publishes a newer tail.
+ */
+ beginExternalLayout(options: {
+ reason: DocumentLayoutReason;
+ protectedRange?: IDocumentLayoutProtectedRange;
+ }): void {
+ this.cancelIncrementalLayout();
+ const pages = this._skeletonData?.pages ?? [];
+ const protectedRange = options.protectedRange;
+ const protectedPageRange: IDocumentLayoutProtectedPageRange | undefined = protectedRange?.mode === 'paginated'
+ ? protectedRange
+ : undefined;
+ if (protectedPageRange == null) {
+ this._externalProtectedPages = null;
+ } else {
+ const protectedPages = new Map<number, {
+ page: IDocumentSkeletonPage;
+ checkpoint: string;
+ }>();
+ for (
+ let pageIndex = protectedPageRange.startPageIndex;
+ pageIndex <= protectedPageRange.endPageIndex;
+ pageIndex++
+ ) {
+ const page = pages[pageIndex];
+ if (page == null || page.isLayoutPlaceholder || page.isMaterializationPlaceholder) {
+ continue;
+ }
+ protectedPages.set(pageIndex, {
+ page,
+ checkpoint: serializePaginatedContinuationCheckpoint(serializeDocumentSkeletonPage(page)),
+ });
+ }
+ this._externalProtectedPages = {
+ range: protectedPageRange,
+ pages: protectedPages,
+ divergenceStartPageIndex: null,
+ pendingPages: new Map(),
+ publishedPageIndexes: new Set(),
+ };
+ }
+ this._externalProtectedContinuousLayout = protectedRange?.mode === 'continuous'
+ ? {
+ range: protectedRange,
+ pendingPublications: [],
+ }
+ : null;
+ const dataModel = this.getViewModel().getDataModel();
+ const mode: DocumentLayoutMode = dataModel.documentStyle.documentFlavor === DocumentFlavor.MODERN
+ ? 'continuous'
+ : 'paginated';
+ const totalBlockCount = this._getTopLevelBlocks(this.getViewModel().getChildren()).length;
+ const firstPage = pages[0];
+ this._externalLayoutProgress = {
+ generation: ++this._layoutGeneration,
+ publicationRevision: 0,
+ didPublish: false,
+ didPublishAnchor: false,
+ publishedPageCount: pages.length,
+ reason: options.reason,
+ mode,
+ complete: false,
+ cancelled: false,
+ anchorReady: false,
+ laidOutThrough: -1,
+ stableLaidOutThrough: -1,
+ pageCount: pages.length,
+ processedBlockCount: 0,
+ totalBlockCount,
+ estimatedPageCount: pages.length,
+ estimatedHeight: mode === 'continuous'
+ ? firstPage?.height ?? 0
+ : pages.length * ((firstPage?.pageHeight ?? firstPage?.height ?? 0) + 14),
+ elapsedTime: 0,
+ maxBlockDuration: 0,
+ interactionWindowComplete: false,
+ };
+ this._layoutProgress$.next(this._externalLayoutProgress);
+ }
+
+ cancelExternalLayout(): void {
+ this._externalLayoutProgress = null;
+ this._externalProtectedPages = null;
+ this._externalProtectedContinuousLayout = null;
+ }
+
+ /**
+ * Whether this skeleton owns a fully finalized layout that can be used as
+ * stable geometry while a later incremental generation is still running.
+ */
+ hasCompleteLayout(): boolean {
+ return this._lastCompleteSkeletonData != null;
+ }
+
+ getSkeletonData() {
+ return this._skeletonData;
+ }
+
+ /**
+ * Refreshes Custom Block viewport-only metrics without rebuilding document flow.
+ * Pure presentation metrics are published as one batch. Flow metrics are only
+ * replaced for compatible drawings; incompatible drawings retain their stable
+ * flow geometry while callers schedule a normal layout generation.
+ */
+ refreshCustomBlockPresentationViewports(): IDocumentCustomBlockPresentationRefreshResult {
+ const skeletonData = this._skeletonData;
+ if (skeletonData == null) {
+ return { didRefresh: false, requiresLayout: false };
+ }
+
+ const unitId = this._docViewModel.getDataModel().getUnitId();
+ const updates: Array<{
+ drawing: IDocumentSkeletonDrawing;
+ flowCompatible: boolean;
+ viewport: IDocsCustomBlockRenderViewport;
+ }> = [];
+ let requiresLayout = false;
+
+ for (const page of skeletonData.pages) {
+ if (page.isLayoutPlaceholder || page.isMaterializationPlaceholder) {
+ continue;
+ }
+
+ for (const drawing of page.skeDrawings.values()) {
+ if (drawing.customBlockRenderViewport == null) {
+ continue;
+ }
+
+ const fallbackWidth = drawing.drawingOrigin.docTransform.size.width ?? drawing.width;
+ const fallbackHeight = drawing.drawingOrigin.docTransform.size.height ?? drawing.height;
+ const viewport = getDocsCustomBlockRenderViewport(unitId, drawing.drawingId, {
+ blockLeft: drawing.aLeft,
+ fallbackHeight,
+ fallbackWidth,
+ pageMarginLeft: page.marginLeft,
+ pageMarginRight: page.marginRight,
+ pageWidth: page.pageWidth,
+ });
+ if (viewport == null) {
+ continue;
+ }
+ const flowCompatible = isSameLayoutMetric(viewport.width, drawing.width) &&
+ isSameLayoutMetric(viewport.height, drawing.height);
+ requiresLayout ||= !flowCompatible;
+ updates.push({ drawing, flowCompatible, viewport });
+ }
+ }
+
+ for (const { drawing, flowCompatible, viewport } of updates) {
+ const currentViewport = drawing.customBlockRenderViewport;
+ drawing.customBlockRenderViewport = {
+ bleedLeft: viewport.bleedLeft,
+ bleedWidth: viewport.bleedWidth,
+ contentHeight: flowCompatible ? viewport.contentHeight : currentViewport?.contentHeight,
+ contentWidth: flowCompatible ? viewport.contentWidth : currentViewport?.contentWidth,
+ height: flowCompatible ? viewport.height : currentViewport?.height,
+ pageContentWidth: flowCompatible ? viewport.pageContentWidth : currentViewport?.pageContentWidth,
+ viewScale: viewport.viewScale,
+ viewportHeight: viewport.viewportHeight,
+ };
+ }
+ if (updates.length > 0) {
+ this._dirty$.next(true);
+ }
+
+ return { didRefresh: updates.length > 0, requiresLayout };
+ }
+
+ applyLayoutPublication(
+ publication: IDocumentLayoutGeometryPublication,
+ progress: IDocumentLayoutProgress,
+ materializedPageRange?: IDocumentLayoutPageRange
+ ): IDocumentLayoutApplyResult {
+ const skeletonData: IDocumentSkeletonCached = this._skeletonData ?? {
+ pages: [],
+ left: publication.left,
+ top: publication.top,
+ st: publication.st,
+ ...(publication.ed == null ? {} : { ed: publication.ed }),
+ skeHeaders: new Map(),
+ skeFooters: new Map(),
+ };
+ const protectedContinuousLayout = publication.kind === 'block'
+ ? this._externalProtectedContinuousLayout
+ : null;
+ if (publication.kind === 'block' && protectedContinuousLayout != null) {
+ protectedContinuousLayout.pendingPublications.push(publication);
+ }
+ const commitsProtectedContinuousLayout = progress.complete && protectedContinuousLayout != null;
+ const publicationToApply = publication.kind === 'block' && protectedContinuousLayout != null && !commitsProtectedContinuousLayout
+ ? this._resolveProtectedContinuousPublication(skeletonData, publication, protectedContinuousLayout.range.endOffset)
+ : publication;
+
+ if (publicationToApply == null) {
+ if (progress.complete) {
+ setPageParent(skeletonData.pages, skeletonData);
+ this._lastCompleteSkeletonData = skeletonData;
+ this._pendingInvalidationAnchor = null;
+ this._externalProtectedContinuousLayout = null;
+ }
+ this._externalLayoutProgress = progress.complete ? null : progress;
+ this._layoutProgress$.next(progress);
+ return { didReplaceProtectedPages: false };
+ }
+
+ skeletonData.left = publicationToApply.left;
+ skeletonData.top = publicationToApply.top;
+ skeletonData.st = publicationToApply.st;
+ if (publicationToApply.ed == null) {
+ delete skeletonData.ed;
+ } else {
+ skeletonData.ed = publicationToApply.ed;
+ }
+ if (publicationToApply.kind === 'block') {
+ const publications = commitsProtectedContinuousLayout
+ ? protectedContinuousLayout.pendingPublications
+ : [publicationToApply];
+ for (const pendingPublication of publications) {
+ this._applyExternalLayoutResources(skeletonData, pendingPublication.resources);
+ applyDocumentSkeletonContinuousBlock(
+ skeletonData,
+ pendingPublication.block,
+ this._docViewModel.getSnapshot()
+ );
+ }
+ } else {
+ this._applyExternalLayoutResources(skeletonData, publicationToApply.resources);
+ for (const pagePublication of publicationToApply.pages) {
+ const protectedPages = this._externalProtectedPages;
+ const protectedPage = protectedPages?.pages.get(pagePublication.pageIndex);
+ protectedPages?.publishedPageIndexes.add(pagePublication.pageIndex);
+ // Reuse the Main page object only when the complete page geometry is
+ // continuation-compatible. A divergent page inside the interaction
+ // window stays behind the presentation barrier, while canonical pages
+ // beyond that window remain independent and can publish progressively.
+ // Completion replaces only the protected divergent pages atomically.
+ if (protectedPage != null && protectedPages != null) {
+ skeletonData.pages[pagePublication.pageIndex] = protectedPage.page;
+ if (
+ protectedPage.checkpoint !==
+ serializePaginatedContinuationCheckpoint(pagePublication.page)
+ ) {
+ const hydratedPage = hydrateDocumentSkeletonPage(
+ pagePublication.page,
+ skeletonData,
+ this._docViewModel.getSnapshot()
+ );
+ protectedPages.divergenceStartPageIndex = Math.min(
+ protectedPages.divergenceStartPageIndex ?? pagePublication.pageIndex,
+ pagePublication.pageIndex
+ );
+ protectedPages.pendingPages.set(pagePublication.pageIndex, hydratedPage);
+ }
+ } else if (
+ materializedPageRange == null ||
+ (
+ pagePublication.pageIndex >= materializedPageRange.startPageIndex &&
+ pagePublication.pageIndex <= materializedPageRange.endPageIndex
+ )
+ ) {
+ skeletonData.pages[pagePublication.pageIndex] = hydrateDocumentSkeletonPage(
+ pagePublication.page,
+ skeletonData,
+ this._docViewModel.getSnapshot()
+ );
+ } else {
+ skeletonData.pages[pagePublication.pageIndex] = hydrateDocumentSkeletonPageMaterializationPlaceholder(
+ pagePublication.page,
+ skeletonData
+ );
+ }
+ }
+ if (materializedPageRange != null) {
+ this._compactMaterializedPages(skeletonData, materializedPageRange);
+ }
+ }
+ if (publicationToApply.kind === 'page' && progress.didPublishAnchor && !progress.complete) {
+ const placeholderPages: IDocumentSkeletonPage[] = [];
+ for (let pageIndex = progress.publishedPageCount; pageIndex < skeletonData.pages.length; pageIndex++) {
+ const currentPage = skeletonData.pages[pageIndex];
+ if (currentPage == null || currentPage.isLayoutPlaceholder) {
+ continue;
+ }
+ const protectedRange = this._externalProtectedPages?.range;
+ if (
+ protectedRange != null &&
+ pageIndex >= protectedRange.startPageIndex &&
+ pageIndex <= protectedRange.endPageIndex
+ ) {
+ continue;
+ }
+
+ const placeholderPage = clonePageLayoutPlaceholderForPublish(currentPage);
+ skeletonData.pages[pageIndex] = placeholderPage;
+ placeholderPages.push(placeholderPage);
+ }
+ setPageParent(placeholderPages, skeletonData);
+ }
+ const protectedPages = this._externalProtectedPages;
+ const didReplaceProtectedPages = progress.complete && (
+ protectedPages?.divergenceStartPageIndex != null ||
+ (commitsProtectedContinuousLayout && protectedContinuousLayout.pendingPublications.length > 0)
+ );
+ if (progress.complete) {
+ if (protectedPages?.divergenceStartPageIndex != null) {
+ for (
+ let pageIndex = protectedPages.divergenceStartPageIndex;
+ pageIndex < progress.pageCount;
+ pageIndex++
+ ) {
+ const pendingPage = protectedPages.pendingPages.get(pageIndex);
+ if (pendingPage == null) {
+ if (!protectedPages.publishedPageIndexes.has(pageIndex)) {
+ throw new Error(
+ `Paginated layout Worker completed without publishing page ${pageIndex} after a divergent Main boundary.`
+ );
+ }
+ continue;
+ }
+ skeletonData.pages[pageIndex] = pendingPage;
+ }
+ }
+ skeletonData.pages.length = progress.pageCount;
+ if (publicationToApply.resources.skeListLevel != null) {
+ skeletonData.skeListLevel = new Map(
+ publicationToApply.resources.skeListLevel.map(([listId, levels]) => [
+ listId,
+ levels.map((level) => level.map(({ bullet, paragraph }) => ({ bullet, paragraph }))),
+ ])
+ );
+ }
+ if (publicationToApply.resources.drawingAnchor != null) {
+ skeletonData.drawingAnchor = hydrateDrawingAnchors(
+ publicationToApply.resources.drawingAnchor
+ );
+ }
+ setPageParent(skeletonData.pages, skeletonData);
+ this._lastCompleteSkeletonData = skeletonData;
+ this._pendingInvalidationAnchor = null;
+ this._externalProtectedPages = null;
+ this._externalProtectedContinuousLayout = null;
+ }
+
+ this._skeletonData = skeletonData;
+ this._externalLayoutProgress = progress.complete ? null : progress;
+ this._dirty$.next(true);
+ this._layoutProgress$.next(progress);
+ return { didReplaceProtectedPages };
+ }
+
+ applyLayoutPagePublication(
+ publication: IDocumentLayoutPagePublication,
+ materializedPageRange: IDocumentLayoutPageRange
+ ): boolean {
+ const skeletonData = this._skeletonData;
+ if (skeletonData == null || publication.pageIndex >= skeletonData.pages.length) {
+ return false;
+ }
+
+ skeletonData.pages[publication.pageIndex] = hydrateDocumentSkeletonPage(
+ publication.page,
+ skeletonData,
+ this._docViewModel.getSnapshot()
+ );
+ this._compactMaterializedPages(skeletonData, materializedPageRange);
+ this._dirty$.next(true);
+ return true;
+ }
+
+ private _compactMaterializedPages(
+ skeletonData: IDocumentSkeletonCached,
+ materializedPageRange: IDocumentLayoutPageRange
+ ): void {
+ const placeholders: IDocumentSkeletonPage[] = [];
+ for (let pageIndex = 0; pageIndex < skeletonData.pages.length; pageIndex++) {
+ if (
+ pageIndex >= materializedPageRange.startPageIndex &&
+ pageIndex <= materializedPageRange.endPageIndex
+ ) {
+ continue;
+ }
+ const page = skeletonData.pages[pageIndex];
+ if (page.isLayoutPlaceholder || page.isMaterializationPlaceholder) {
+ continue;
+ }
+ const placeholder = clonePageMaterializationPlaceholderForPublish(page);
+ skeletonData.pages[pageIndex] = placeholder;
+ placeholders.push(placeholder);
+ }
+ setPageParent(placeholders, skeletonData);
+ }
+
+ private _applyExternalLayoutResources(
+ skeletonData: IDocumentSkeletonCached,
+ resources: IDocumentLayoutResourcePublication
+ ): void {
+ if (resources.reset) {
+ skeletonData.skeHeaders.clear();
+ skeletonData.skeFooters.clear();
+ }
+ for (const [segmentId, pagesByWidth] of resources.skeHeaders) {
+ let hydratedPagesByWidth = skeletonData.skeHeaders.get(segmentId);
+ if (hydratedPagesByWidth == null) {
+ hydratedPagesByWidth = new Map();
+ skeletonData.skeHeaders.set(segmentId, hydratedPagesByWidth);
+ }
+ for (const [width, page] of pagesByWidth) {
+ hydratedPagesByWidth.set(
+ width,
+ hydrateDocumentSkeletonPage(page, undefined, this._docViewModel.getSnapshot())
+ );
+ }
+ }
+ for (const [segmentId, pagesByWidth] of resources.skeFooters) {
+ let hydratedPagesByWidth = skeletonData.skeFooters.get(segmentId);
+ if (hydratedPagesByWidth == null) {
+ hydratedPagesByWidth = new Map();
+ skeletonData.skeFooters.set(segmentId, hydratedPagesByWidth);
+ }
+ for (const [width, page] of pagesByWidth) {
+ hydratedPagesByWidth.set(
+ width,
+ hydrateDocumentSkeletonPage(page, undefined, this._docViewModel.getSnapshot())
+ );
+ }
+ }
+ }
+
+ private _resolveProtectedContinuousPublication(
+ skeletonData: IDocumentSkeletonCached,
+ publication: IDocumentLayoutBlockGeometryPublication,
+ protectedEndOffset: number
+ ): IDocumentLayoutBlockGeometryPublication | null {
+ const { flow } = publication.block;
+ const firstUnprotectedLineOffset = flow.lines.findIndex((line) => line.st > protectedEndOffset);
+ if (firstUnprotectedLineOffset < 0) {
+ return null;
+ }
+
+ const existingColumn = skeletonData.pages[publication.block.pageIndex]
+ ?.sections[flow.sectionIndex]
+ ?.columns[flow.columnIndex];
+ if (existingColumn == null) {
+ throw new Error('Continuous layout cannot merge a Worker tail without the Main interaction boundary.');
+ }
+
+ const firstUnprotectedLine = flow.lines[firstUnprotectedLineOffset];
+ const matchingTailLineIndex = existingColumn.lines.findIndex(
+ (line) => line.st >= firstUnprotectedLine.st
+ );
+ const targetLineIndex = matchingTailLineIndex < 0
+ ? existingColumn.lines.length
+ : matchingTailLineIndex;
+
+ if (firstUnprotectedLineOffset > 0) {
+ const mainBoundaryLine = existingColumn.lines[targetLineIndex - 1];
+ const workerBoundaryLine = flow.lines[firstUnprotectedLineOffset - 1];
+ if (
+ mainBoundaryLine == null ||
+ mainBoundaryLine.st !== workerBoundaryLine.st ||
+ mainBoundaryLine.ed !== workerBoundaryLine.ed ||
+ mainBoundaryLine.lineHeight !== workerBoundaryLine.lineHeight ||
+ mainBoundaryLine.width !== workerBoundaryLine.width
+ ) {
+ throw new Error(`Continuous layout Main and Worker boundaries do not share the same continuation checkpoint: Main ${mainBoundaryLine?.st}:${mainBoundaryLine?.ed}@${mainBoundaryLine?.top}/${mainBoundaryLine?.lineHeight}/${mainBoundaryLine?.width}, Worker ${workerBoundaryLine.st}:${workerBoundaryLine.ed}@${workerBoundaryLine.top}/${workerBoundaryLine.lineHeight}/${workerBoundaryLine.width}.`);
+ }
+ if (mainBoundaryLine.top !== workerBoundaryLine.top) {
+ // A Custom Block can finish measuring after Main publishes the
+ // interaction window but before Worker captures its viewport.
+ // The continuation identity still matches, while every absolute
+ // coordinate after it belongs to a different vertical geometry.
+ // Keep Main visible and commit the canonical Worker result only
+ // after completion instead of translating a partial collection of
+ // lines, tables, drawings, and column groups independently.
+ return null;
+ }
+ }
+
+ return {
+ ...publication,
+ block: {
+ ...publication.block,
+ flow: {
+ ...flow,
+ lineIndex: targetLineIndex,
+ lines: flow.lines.slice(firstUnprotectedLineOffset),
+ },
+ },
+ };
}
/**
@@ -718,6 +2792,10 @@ export class DocumentSkeleton extends Skeleton {
};
}
+ findBodyPageIndexByCharIndex(charIndex: number): number {
+ return this._findBodyPageIndex(this._skeletonData?.pages ?? [], charIndex);
+ }
+
findNodeByCharIndex(charIndex: number, segmentId = '', segmentPageIndex = -1): Nullable<IDocumentSkeletonGlyph> {
const nodes = this._findNodeByIndex(charIndex, segmentId, segmentPageIndex);
@@ -737,7 +2815,7 @@ export class DocumentSkeleton extends Skeleton {
const { pages, skeFooters, skeHeaders } = skeletonData;
- const { divide, line, column, section, segmentPage, pageType, path, isBack } = position;
+ const { divide, line, column, section, segmentPage, pageType, path } = position;
let { glyph } = position;
@@ -1245,7 +3323,7 @@ export class DocumentSkeleton extends Skeleton {
}
let exactMatch = null;
- if (skeTables.size > 0) {
+ if (pointInPage && skeTables.size > 0) {
const unitId = this._docViewModel.getDataModel().getUnitId?.() ?? '';
for (const table of skeTables.values()) {
const { top: tableTop, left: tableLeft, rows } = table;
@@ -1442,6 +3520,904 @@ export class DocumentSkeleton extends Skeleton {
this._findLiquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
}
+ private _getLayoutProgress(
+ state: IIncrementalLayoutState,
+ didPublish = false,
+ didPublishAnchor = false
+ ): IDocumentLayoutProgress {
+ const pages = state.ctx.skeleton.pages;
+ const pageCount = pages.length;
+ const publicationComplete = state.complete && state.lastPublishedPageCount >= pageCount;
+ const totalBlockCount = state.totalBlockCount;
+ const processedBlockCount = state.processedBlockCount;
+ const defaultEstimatedPageCount = Math.ceil(totalBlockCount / 20);
+ const observedEstimatedPageCount = pageCount > 1 && processedBlockCount > 0
+ ? Math.ceil(((pageCount - 1) * totalBlockCount) / processedBlockCount)
+ : 0;
+ const previousCompletePageCount = state.priorityAnchor == null
+ ? 0
+ : this._lastCompleteSkeletonData?.pages.length ?? 0;
+ const estimatedPageCount = state.mode === 'paginated' && !publicationComplete
+ ? previousCompletePageCount > 0
+ ? Math.max(pageCount, previousCompletePageCount)
+ : Math.max(
+ pageCount,
+ Math.min(
+ Math.max(defaultEstimatedPageCount, observedEstimatedPageCount),
+ Math.max(defaultEstimatedPageCount * 4, pageCount)
+ )
+ )
+ : pageCount;
+ const firstPage = pages[0];
+ const estimatedHeight = state.mode === 'continuous'
+ ? publicationComplete
+ ? (firstPage?.height ?? 0)
+ : Math.max(
+ firstPage?.height ?? 0,
+ totalBlockCount * 32,
+ processedBlockCount > 0
+ ? ((firstPage?.height ?? 0) * totalBlockCount) / processedBlockCount
+ : 0
+ )
+ : estimatedPageCount * ((firstPage?.pageHeight ?? firstPage?.height ?? 0) + 14);
+
+ return {
+ generation: state.generation,
+ publicationRevision: state.publicationRevision,
+ didPublish,
+ didPublishAnchor,
+ publishedPageCount: state.lastPublishedPageCount,
+ reason: state.reason,
+ mode: state.mode,
+ complete: publicationComplete,
+ cancelled: state.cancelled,
+ anchorReady: this._isPriorityAnchorReady(state),
+ laidOutThrough: state.laidOutThrough,
+ stableLaidOutThrough: state.complete ? state.laidOutThrough : state.stableLaidOutThrough,
+ pageCount,
+ processedBlockCount,
+ totalBlockCount,
+ estimatedPageCount,
+ estimatedHeight,
+ elapsedTime: getLayoutNow() - state.startedAt,
+ maxBlockDuration: state.maxBlockDuration,
+ interactionWindowComplete: state.interactionWindowComplete,
+ };
+ }
+
+ private _tryConvergeUnaffectedTail(state: IIncrementalLayoutState): boolean {
+ const invalidation = state.invalidation;
+ const previous = this._lastCompleteSkeletonData;
+ if (
+ !state.reuseUnaffectedTail ||
+ state.mode !== 'paginated' ||
+ state.reason !== 'edit' ||
+ invalidation == null ||
+ previous == null ||
+ state.priorityAnchor == null ||
+ state.priorityPageIndex < 0 ||
+ !this._isPriorityAnchorReady(state)
+ ) {
+ return false;
+ }
+
+ // Active pages carry block-local ranges until the normal publication
+ // finalizer assigns body-absolute indexes. Finalize only the completed
+ // prefix before comparing continuation checkpoints; the open last page
+ // remains untouched and every page is finalized at most once.
+ this._finalizePaginatedPagesForPublication(
+ state,
+ Math.max(0, state.ctx.skeleton.pages.length - 1)
+ );
+
+ const foreground = state.anchorPublished
+ ? null
+ : this._createPublishablePartialSkeleton(state, state.priorityPageIndex + 1);
+ const currentPageIndex = foreground == null
+ ? state.ctx.skeleton.pages.length - 2
+ : state.priorityPageIndex;
+ const currentPage = foreground?.pages[currentPageIndex] ?? state.ctx.skeleton.pages[currentPageIndex];
+ if (currentPageIndex < state.priorityPageIndex || currentPage == null) {
+ return false;
+ }
+ const currentPageEnd = currentPage.ed;
+ const previousPageEnd = mapCurrentOffsetToPrevious(currentPageEnd, invalidation);
+ const previousPageIndex = foreground == null
+ ? previous.pages.findIndex((page, pageIndex) =>
+ pageIndex >= state.priorityPageIndex &&
+ page.ed === previousPageEnd
+ )
+ : state.priorityPageIndex;
+ const previousPage = previous.pages[previousPageIndex];
+ if (
+ previousPage == null ||
+ invalidation.oldEnd > previousPage.ed ||
+ previousPage.skeDrawings.size > 0 ||
+ previousPage.skeTables.size > 0 ||
+ previousPage.skeColumnGroups.size > 0 ||
+ currentPage.skeDrawings.size > 0 ||
+ currentPage.skeTables.size > 0 ||
+ currentPage.skeColumnGroups.size > 0 ||
+ !hasSamePageExitGeometry(previousPage, currentPage)
+ ) {
+ return false;
+ }
+
+ const mutationDelta = invalidation.newEnd - invalidation.oldEnd;
+ if (
+ invalidation.newEnd > currentPageEnd ||
+ currentPageEnd !== previousPage.ed + mutationDelta
+ ) {
+ return false;
+ }
+
+ const prefix = (foreground?.pages ?? state.ctx.skeleton.pages).slice(0, currentPageIndex + 1);
+ const tail = previous.pages
+ .slice(previousPageIndex + 1)
+ .map((page) => {
+ shiftPageCharacterOffsets(page, mutationDelta);
+ return page;
+ });
+
+ state.ctx.skeleton.pages = [...prefix, ...tail];
+ for (const [segmentId, pagesByWidth] of previous.skeHeaders) {
+ state.ctx.skeleton.skeHeaders.set(segmentId, pagesByWidth);
+ }
+ for (const [segmentId, pagesByWidth] of previous.skeFooters) {
+ state.ctx.skeleton.skeFooters.set(segmentId, pagesByWidth);
+ }
+ state.reusedTail = true;
+ this._finishIncrementalLayout(state);
+ return true;
+ }
+
+ private _isPriorityAnchorReady(state: IIncrementalLayoutState): boolean {
+ const anchor = state.priorityAnchor;
+ if (anchor == null || state.complete) {
+ return true;
+ }
+
+ if (state.interactionPageComplete) {
+ return true;
+ }
+
+ if (state.mode === 'continuous') {
+ return state.laidOutThrough >= anchor;
+ }
+
+ // A paginated page is not publishable merely because the edited paragraph
+ // has been shaped. Page-level vertical alignment and pagination depend on
+ // every block that still fits on that physical page. Wait until layout has
+ // crossed the previous complete page boundary and stabilized the caret's
+ // block so the published page can resolve the post-edit selection instead
+ // of exposing only the paragraph immediately before it.
+ if (state.priorityPageEnd != null) {
+ const requiredOffset = Math.max(
+ anchor,
+ state.priorityPageEnd,
+ state.invalidation?.newEnd ?? anchor
+ );
+ return state.stableLaidOutThrough >= requiredOffset &&
+ state.ctx.skeleton.pages.length > Math.max(
+ state.stablePageCount + 1,
+ state.priorityPageIndex + 1
+ );
+ }
+
+ // 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;
+ }
+
+ private _tryReuseInteractionPageTail(
+ state: IIncrementalLayoutState,
+ paragraphNode: DataStreamTreeNode
+ ): boolean {
+ const candidate = state.interactionPageTail;
+ if (candidate == null || paragraphNode.endIndex !== candidate.anchorEnd) {
+ return false;
+ }
+
+ state.interactionPageTail = null;
+ const currentPage = state.ctx.skeleton.pages[state.priorityPageIndex];
+ const currentSection = currentPage?.sections[0];
+ const currentColumn = currentSection?.columns[0];
+ if (
+ currentPage == null ||
+ currentPage.sections.length !== 1 ||
+ currentSection?.columns.length !== 1 ||
+ currentColumn == null ||
+ currentPage.skeDrawings.size > 0 ||
+ currentPage.skeTables.size > 0 ||
+ currentPage.skeColumnGroups.size > 0
+ ) {
+ return false;
+ }
+
+ const shiftedPreviousPage = clonePageFlowForPublish(candidate.previousPage);
+ shiftPageCharacterOffsets(
+ shiftedPreviousPage,
+ candidate.pageEnd - getLastBodyFlowCharIndex(candidate.previousPage)
+ );
+ const previousSection = shiftedPreviousPage.sections[0];
+ const previousColumn = previousSection?.columns[0];
+ if (shiftedPreviousPage.sections.length !== 1 || previousSection?.columns.length !== 1 || previousColumn == null) {
+ return false;
+ }
+
+ const currentAnchorLines = currentColumn.lines.filter((line) => line.paragraphIndex === candidate.anchorEnd);
+ const previousAnchorLines = previousColumn.lines.filter((line) => line.paragraphIndex === candidate.anchorEnd);
+ const originalPreviousColumn = candidate.previousPage.sections[0]?.columns[0];
+ const originalPreviousAnchorLines = originalPreviousColumn?.lines.filter(
+ (line) => line.paragraphIndex === candidate.previousAnchorEnd
+ ) ?? [];
+ if (currentAnchorLines.length === 0 || currentAnchorLines.length !== previousAnchorLines.length) {
+ return false;
+ }
+
+ const hasSameLineGeometry = currentAnchorLines.every((line, index) => {
+ const previousLine = previousAnchorLines[index];
+ return isSameLayoutMetric(line.top, previousLine.top) &&
+ isSameLayoutMetric(line.contentHeight, previousLine.contentHeight) &&
+ isSameLayoutMetric(line.paddingTop, previousLine.paddingTop) &&
+ isSameLayoutMetric(line.paddingBottom, previousLine.paddingBottom) &&
+ isSameLayoutMetric(line.marginTop, previousLine.marginTop) &&
+ isSameLayoutMetric(
+ line.lineHeight - line.marginBottom,
+ previousLine.lineHeight - previousLine.marginBottom
+ );
+ });
+ if (!hasSameLineGeometry) {
+ return false;
+ }
+
+ for (let index = 0; index < currentAnchorLines.length; index++) {
+ currentAnchorLines[index].asc = previousAnchorLines[index].asc;
+ currentAnchorLines[index].dsc = previousAnchorLines[index].dsc;
+ if (originalPreviousAnchorLines[index]?.bullet == null) {
+ delete currentAnchorLines[index].bullet;
+ }
+ }
+
+ const currentLastAnchorLine = currentAnchorLines[currentAnchorLines.length - 1];
+ const previousLastAnchorLine = previousAnchorLines[previousAnchorLines.length - 1];
+ currentLastAnchorLine.lineHeight = previousLastAnchorLine.lineHeight;
+ currentLastAnchorLine.marginBottom = previousLastAnchorLine.marginBottom;
+ currentLastAnchorLine.spaceBelowApply = previousLastAnchorLine.spaceBelowApply;
+
+ const suffixLines = previousColumn.lines.filter((line) => line.paragraphIndex > candidate.anchorEnd);
+ for (const line of suffixLines) {
+ line.parent = currentColumn;
+ currentColumn.lines.push(line);
+ }
+ const previousSkeleton = candidate.previousSkeleton;
+ const previousPageEnd = getLastBodyFlowCharIndex(candidate.previousPage);
+ for (const [segmentId, anchors] of previousSkeleton.drawingAnchor ?? []) {
+ let targetAnchors = state.ctx.skeletonResourceReference.drawingAnchor?.get(segmentId);
+ if (targetAnchors == null) {
+ targetAnchors = new Map();
+ state.ctx.skeletonResourceReference.drawingAnchor?.set(segmentId, targetAnchors);
+ }
+ for (const [paragraphIndex, anchor] of anchors) {
+ if (paragraphIndex <= candidate.previousAnchorEnd || paragraphIndex > previousPageEnd) {
+ continue;
+ }
+ const currentParagraphIndex = mapPreviousOffsetToCurrent(
+ paragraphIndex,
+ state.invalidation ?? undefined
+ );
+ targetAnchors.set(
+ currentParagraphIndex,
+ {
+ ...anchor,
+ paragraphIndex: currentParagraphIndex,
+ elements: suffixLines.filter((line) => line.paragraphIndex === currentParagraphIndex),
+ }
+ );
+ }
+ }
+ currentColumn.ed = previousColumn.ed;
+ currentColumn.height = previousColumn.height;
+ currentColumn.isFull = previousColumn.isFull;
+ currentSection.ed = previousSection.ed;
+ currentSection.height = previousSection.height;
+ currentPage.ed = shiftedPreviousPage.ed;
+ currentPage.height = shiftedPreviousPage.height;
+ copyPageBoundaryMetadata(currentPage, shiftedPreviousPage);
+
+ state.interactionPageComplete = true;
+ state.interactionWindowComplete = candidate.terminal;
+ state.laidOutThrough = Math.max(state.laidOutThrough, candidate.pageEnd);
+ state.stableLaidOutThrough = Math.max(state.stableLaidOutThrough, candidate.pageEnd);
+ state.processedBlockCount = candidate.terminal ? candidate.resumeBlockIndex : candidate.nextBlockIndex;
+ state.layoutAnchor = null;
+
+ const sections = state.ctx.viewModel.getChildren();
+ if (candidate.terminal) {
+ state.sectionIndex = candidate.resumeSectionIndex;
+ state.paragraphIndex = candidate.resumeParagraphIndex;
+ state.interactionWindowResume = {
+ anchorEnd: candidate.anchorEnd,
+ pageEnd: candidate.pageEnd,
+ processedBlockCount: candidate.resumeBlockIndex,
+ sectionIndex: candidate.resumeSectionIndex,
+ paragraphIndex: candidate.resumeParagraphIndex,
+ };
+ return true;
+ }
+ if (candidate.nextSectionIndex >= sections.length) {
+ this._finishIncrementalLayout(state);
+ return true;
+ }
+
+ const sectionChanged = state.sectionIndex !== candidate.nextSectionIndex;
+ state.sectionIndex = candidate.nextSectionIndex;
+ state.paragraphIndex = candidate.nextParagraphIndex;
+ if (sectionChanged) {
+ state.sectionInitialized = false;
+ state.sectionBreakConfig = null;
+ } else if (state.sectionBreakConfig != null) {
+ const nextPage = createSkeletonPage(
+ state.ctx,
+ state.sectionBreakConfig,
+ state.ctx.skeletonResourceReference,
+ candidate.previousPage.pageNumber + 1
+ );
+ const previousNextPage = candidate.previousSkeleton.pages[state.priorityPageIndex + 1];
+ if (previousNextPage != null) {
+ copyPageBoundaryMetadata(nextPage, previousNextPage);
+ }
+ state.ctx.skeleton.pages.push(nextPage);
+ }
+ return true;
+ }
+
+ private _advanceIncrementalLayout(state: IIncrementalLayoutState): void {
+ const { ctx } = state;
+
+ if (state.interactionWindowResume != null) {
+ this._resumeAfterSealedInteractionPage(state);
+ }
+
+ if (state.pendingSlicedTableBuild != null) {
+ if (!stepTableSkeletonsBuild(state.pendingSlicedTableBuild)) {
+ return;
+ }
+
+ const pending = state.pendingSlicedTableBuild;
+ if (pending.result != null) {
+ cachePrecomputedSlicedTableSkeletons(
+ ctx,
+ pending.tableNode.startIndex,
+ pending.availableHeight,
+ pending.result
+ );
+ }
+ if (state.pendingParagraphCheckpoint != null) {
+ this._restoreIncrementalParagraphCheckpoint(ctx, state.pendingParagraphCheckpoint);
+ }
+ state.pendingSlicedTableBuild = null;
+ state.pendingParagraphCheckpoint = null;
+ return;
+ }
+
+ const sections = ctx.viewModel.getChildren();
+
+ if (state.sectionIndex >= sections.length) {
+ this._finishIncrementalLayout(state);
+ return;
+ }
+
+ const sectionNode = sections[state.sectionIndex];
+ if (!state.sectionInitialized) {
+ this._initializeIncrementalSection(state, sectionNode);
+ }
+
+ const sectionBreakConfig = state.sectionBreakConfig;
+ const curSkeletonPage = getLastPage(ctx.skeleton.pages);
+ if (sectionBreakConfig == null || curSkeletonPage == null) {
+ throw new Error('Incremental document layout failed to initialize a section page.');
+ }
+
+ const paragraphNode = sectionNode.children[state.paragraphIndex];
+ const tableNode = paragraphNode?.children.length === 1 &&
+ paragraphNode.children[0].nodeType === DataStreamTreeNodeType.TABLE
+ ? paragraphNode.children[0]
+ : null;
+ if (tableNode != null) {
+ state.pendingTableBuild ??= startTableSkeletonBuild(
+ ctx,
+ curSkeletonPage,
+ ctx.viewModel,
+ tableNode,
+ sectionBreakConfig
+ );
+ if (state.pendingTableBuild != null && !stepTableSkeletonBuild(state.pendingTableBuild)) {
+ return;
+ }
+ if (state.pendingTableBuild != null) {
+ const tableSkeleton = state.pendingTableBuild.tableSkeleton;
+ cachePrecomputedTableSkeleton(
+ ctx,
+ tableNode.startIndex,
+ tableSkeleton
+ );
+ }
+ }
+
+ const checkpoint = tableNode == null || state.mode !== 'paginated'
+ ? null
+ : this._captureIncrementalParagraphCheckpoint(ctx, curSkeletonPage);
+ if (checkpoint != null) {
+ ctx.deferSlicedTableLayout = (request) => {
+ const pending = startTableSkeletonsBuild(
+ ctx,
+ request.curPage,
+ request.viewModel,
+ request.tableNode,
+ request.sectionBreakConfig,
+ request.availableHeight
+ );
+ if (pending == null) {
+ return false;
+ }
+
+ state.pendingSlicedTableBuild = pending;
+ state.pendingParagraphCheckpoint = checkpoint;
+ return true;
+ };
+ }
+
+ let result: ReturnType<typeof dealWithSection>;
+ try {
+ result = dealWithSection(
+ ctx,
+ ctx.viewModel,
+ sectionNode,
+ curSkeletonPage,
+ sectionBreakConfig,
+ state.layoutAnchor,
+ {
+ startParagraphIndex: state.paragraphIndex,
+ maxParagraphs: 1,
+ }
+ );
+ } finally {
+ ctx.deferSlicedTableLayout = undefined;
+ }
+
+ if (state.pendingSlicedTableBuild != null) {
+ // The provisional paragraph result is discarded. The deferred table
+ // calculation continues from the exact split point on later slices.
+ return;
+ }
+
+ state.pendingTableBuild = null;
+
+ const lastPage = getLastPage(ctx.skeleton.pages);
+ if (result.pages[0] === lastPage) {
+ result.pages.shift();
+ }
+ ctx.skeleton.pages.push(...result.pages);
+
+ state.paragraphIndex = result.nextParagraphIndex;
+ // The anchor only selects the first block of a resumed section. Keeping it
+ // would reset dealWithSection to that same block on every later slice.
+ state.layoutAnchor = null;
+ const previouslyLaidOutThrough = state.laidOutThrough;
+ state.laidOutThrough = Math.max(state.laidOutThrough, paragraphNode?.endIndex ?? -1);
+ if (paragraphNode != null) {
+ // Laying out the current block finalizes the previous block's collapsed
+ // spacing. The current block remains an unstable continuation boundary
+ // until its successor has been laid out.
+ state.stableLaidOutThrough = Math.max(state.stableLaidOutThrough, previouslyLaidOutThrough);
+ state.processedBlockCount++;
+ }
+
+ if (ctx.isDirty) {
+ this._restartDirtyIncrementalLayout(state);
+ return;
+ }
+
+ if (paragraphNode != null && this._tryReuseInteractionPageTail(state, paragraphNode)) {
+ return;
+ }
+
+ if (result.complete) {
+ const nextColumnProperties = state.sectionIndex + 1 < sections.length
+ ? prepareSectionBreakConfig(ctx, state.sectionIndex + 1).columnProperties ?? []
+ : [];
+ if (
+ sectionBreakConfig.sectionTypeNext === SectionType.CONTINUOUS &&
+ (sectionBreakConfig.columnProperties?.length ?? 0) > 0 &&
+ !hasSameColumnGeometry(sectionBreakConfig.columnProperties!, nextColumnProperties)
+ ) {
+ const completedPage = getLastPage(ctx.skeleton.pages);
+ if (completedPage != null) {
+ balanceFinalContinuousColumnSection(completedPage);
+ }
+ }
+ state.sectionIndex++;
+ state.paragraphIndex = 0;
+ state.sectionInitialized = false;
+ state.sectionBreakConfig = null;
+ state.layoutAnchor = null;
+ state.pendingTableBuild = null;
+ state.pendingSlicedTableBuild = null;
+ state.pendingParagraphCheckpoint = null;
+ }
+
+ if (state.sectionIndex >= sections.length) {
+ this._finishIncrementalLayout(state);
+ }
+ }
+
+ private _resumeAfterSealedInteractionPage(state: IIncrementalLayoutState): void {
+ const resume = state.interactionWindowResume;
+ if (resume == null) {
+ return;
+ }
+ state.interactionWindowResume = null;
+ state.interactionWindowComplete = false;
+ state.interactionPageComplete = false;
+
+ const page = state.ctx.skeleton.pages[state.priorityPageIndex];
+ const section = page?.sections[0];
+ const column = section?.columns[0];
+ if (page == null || section == null || column == null) {
+ return;
+ }
+ const firstSuffixLine = column.lines.findIndex((line) => line.paragraphIndex > resume.anchorEnd);
+ if (firstSuffixLine >= 0) {
+ column.lines.splice(firstSuffixLine);
+ }
+ const anchorLine = column.lines.at(-1);
+ if (anchorLine != null) {
+ anchorLine.lineHeight = Math.max(0, anchorLine.lineHeight - anchorLine.marginBottom);
+ anchorLine.marginBottom = 0;
+ }
+ column.ed = resume.anchorEnd;
+ column.isFull = false;
+ section.ed = resume.anchorEnd;
+ page.ed = resume.anchorEnd;
+ for (const anchors of state.ctx.skeletonResourceReference.drawingAnchor?.values() ?? []) {
+ for (const paragraphIndex of anchors.keys()) {
+ if (paragraphIndex > resume.anchorEnd && paragraphIndex <= resume.pageEnd) {
+ anchors.delete(paragraphIndex);
+ }
+ }
+ }
+ state.sectionIndex = resume.sectionIndex;
+ state.paragraphIndex = resume.paragraphIndex;
+ state.processedBlockCount = resume.processedBlockCount;
+ state.laidOutThrough = resume.anchorEnd;
+ state.stableLaidOutThrough = Math.min(state.stableLaidOutThrough, resume.anchorEnd);
+ }
+
+ private _captureIncrementalParagraphCheckpoint(
+ ctx: ILayoutContext,
+ currentPage: IDocumentSkeletonPage
+ ): IIncrementalParagraphCheckpoint {
+ const pageIndex = ctx.skeleton.pages.indexOf(currentPage);
+ if (pageIndex < 0) {
+ throw new Error('Cannot checkpoint a page outside the active document skeleton.');
+ }
+
+ return {
+ pageIndex,
+ page: clonePageFlowForPublish(currentPage),
+ skeHeaders: new Map(
+ [...ctx.skeleton.skeHeaders].map(([key, pages]) => [key, new Map(pages)])
+ ),
+ skeFooters: new Map(
+ [...ctx.skeleton.skeFooters].map(([key, pages]) => [key, new Map(pages)])
+ ),
+ skeListLevel: new Map(
+ [...ctx.skeletonResourceReference.skeListLevel!].map(([key, levels]) => [
+ key,
+ levels.map((level) => [...level]),
+ ])
+ ),
+ drawingAnchor: new Map(
+ [...ctx.skeletonResourceReference.drawingAnchor!].map(([key, anchors]) => [
+ key,
+ new Map([...anchors].map(([index, anchor]) => [
+ index,
+ { ...anchor, elements: [...anchor.elements] },
+ ])),
+ ])
+ ),
+ layoutStartPointer: { ...ctx.layoutStartPointer },
+ isDirty: ctx.isDirty,
+ floatObjectsCache: new Map(
+ [...ctx.floatObjectsCache].map(([key, value]) => [key, { ...value }])
+ ),
+ paragraphConfigCache: new Map(
+ [...ctx.paragraphConfigCache].map(([key, configs]) => [
+ key,
+ new Map([...configs].map(([index, config]) => [index, { ...config }])),
+ ])
+ ),
+ sectionBreakConfigCache: new Map(ctx.sectionBreakConfigCache),
+ paragraphsOpenNewPage: new Set(ctx.paragraphsOpenNewPage),
+ paginationMetrics: ctx.paginationMetrics == null ? undefined : { ...ctx.paginationMetrics },
+ };
+ }
+
+ private _restoreIncrementalParagraphCheckpoint(
+ ctx: ILayoutContext,
+ checkpoint: IIncrementalParagraphCheckpoint
+ ): void {
+ const replaceMap = <K, V>(target: Map<K, V>, source: Map<K, V>) => {
+ target.clear();
+ for (const [key, value] of source) {
+ target.set(key, value);
+ }
+ };
+
+ ctx.skeleton.pages.splice(
+ checkpoint.pageIndex,
+ ctx.skeleton.pages.length - checkpoint.pageIndex,
+ checkpoint.page
+ );
+ checkpoint.page.parent = ctx.skeleton;
+ replaceMap(ctx.skeleton.skeHeaders, checkpoint.skeHeaders);
+ replaceMap(ctx.skeleton.skeFooters, checkpoint.skeFooters);
+ replaceMap(ctx.skeletonResourceReference.skeListLevel!, checkpoint.skeListLevel);
+ replaceMap(ctx.skeletonResourceReference.drawingAnchor!, checkpoint.drawingAnchor);
+
+ for (const key of Object.keys(ctx.layoutStartPointer)) {
+ delete ctx.layoutStartPointer[key];
+ }
+ Object.assign(ctx.layoutStartPointer, checkpoint.layoutStartPointer);
+ ctx.isDirty = checkpoint.isDirty;
+ replaceMap(ctx.floatObjectsCache, checkpoint.floatObjectsCache);
+ replaceMap(ctx.paragraphConfigCache, checkpoint.paragraphConfigCache);
+ replaceMap(ctx.sectionBreakConfigCache, checkpoint.sectionBreakConfigCache);
+ ctx.paragraphsOpenNewPage.clear();
+ for (const paragraphIndex of checkpoint.paragraphsOpenNewPage) {
+ ctx.paragraphsOpenNewPage.add(paragraphIndex);
+ }
+ ctx.paginationMetrics = checkpoint.paginationMetrics == null
+ ? undefined
+ : { ...checkpoint.paginationMetrics };
+ }
+
+ private _initializeIncrementalSection(
+ state: IIncrementalLayoutState,
+ sectionNode: ReturnType<DocumentViewModel['getChildren']>[number]
+ ): void {
+ const { ctx } = state;
+ const { skeleton, skeletonResourceReference, viewModel } = ctx;
+ const allSkeletonPages = skeleton.pages;
+ const sectionBreakConfig = prepareSectionBreakConfig(ctx, state.sectionIndex);
+ const {
+ sectionType,
+ columnProperties,
+ columnSeparatorType,
+ pageNumberStart = 1,
+ evenAndOddHeaders,
+ } = sectionBreakConfig;
+ const explicitPageNumberStart = viewModel.getSectionBreak(sectionNode.endIndex)?.pageNumberStart;
+ const layoutAnchor = state.layoutAnchor;
+ // Modern documents have one logical flow. Imported legacy section
+ // metadata must append to that flow instead of creating physical page
+ // fragments. Keep the anchored first section on its established restore
+ // path; after the anchor is consumed, subsequent sections are continuous.
+ const effectiveSectionType = state.mode === 'continuous' && layoutAnchor == null
+ ? SectionType.CONTINUOUS
+ : getEffectiveSectionType(sectionType);
+
+ let curSkeletonPage = getLastPage(allSkeletonPages);
+ let reuseNextColumn = false;
+
+ ctx.sectionBreakConfigCache.set(sectionNode.endIndex, sectionBreakConfig);
+
+ if (
+ effectiveSectionType === SectionType.NEXT_COLUMN &&
+ layoutAnchor == null &&
+ curSkeletonPage != null &&
+ hasCompatiblePageGeometry(curSkeletonPage, sectionBreakConfig)
+ ) {
+ updateBlockIndex(allSkeletonPages, -1, ctx.docsConfig.documentCompatibilityPolicy);
+ reuseNextColumn = this._addNewSectionByNextColumn(
+ curSkeletonPage,
+ columnProperties!,
+ columnSeparatorType!
+ );
+ }
+
+ const hasCompatibleContinuousPage =
+ effectiveSectionType === SectionType.CONTINUOUS &&
+ curSkeletonPage != null &&
+ hasCompatiblePhysicalPage(curSkeletonPage, sectionBreakConfig);
+ if (hasCompatibleContinuousPage) {
+ updateBlockIndex(allSkeletonPages, -1, ctx.docsConfig.documentCompatibilityPolicy);
+ }
+
+ if (
+ hasCompatibleContinuousPage &&
+ curSkeletonPage != null &&
+ (layoutAnchor != null || hasAvailableContinuousSectionSpace(curSkeletonPage))
+ ) {
+ if (layoutAnchor != null) {
+ this._restoreContinuousSection(curSkeletonPage, columnProperties!, columnSeparatorType!);
+ } else {
+ this._addNewSectionByContinuous(curSkeletonPage, columnProperties!, columnSeparatorType!);
+ }
+ } else if (!reuseNextColumn && (layoutAnchor == null || curSkeletonPage == null)) {
+ const reuseExplicitPageBreak =
+ effectiveSectionType === SectionType.NEXT_PAGE &&
+ curSkeletonPage?.breakType === BreakType.PAGE &&
+ hasOnlyExplicitPageBoundaryMarkers(curSkeletonPage);
+ const previousSkeletonPage = allSkeletonPages.at(-2);
+ const reuseOverflowedSectionBoundary =
+ effectiveSectionType === SectionType.NEXT_PAGE &&
+ curSkeletonPage?.breakType === BreakType.SECTION &&
+ previousSkeletonPage?.sectionId === curSkeletonPage.sectionId &&
+ hasOnlyExplicitPageBoundaryMarkers(curSkeletonPage);
+ const reuseBoundaryPage = reuseExplicitPageBreak || reuseOverflowedSectionBoundary;
+ let nextPageNumber = reuseBoundaryPage
+ ? explicitPageNumberStart ?? curSkeletonPage.pageNumber
+ : curSkeletonPage == null
+ ? pageNumberStart
+ : explicitPageNumberStart ?? curSkeletonPage.pageNumber + 1;
+ if (reuseBoundaryPage) {
+ allSkeletonPages.pop();
+ }
+ if (
+ curSkeletonPage != null &&
+ effectiveSectionType === SectionType.NEXT_PAGE &&
+ explicitPageNumberStart != null &&
+ evenAndOddHeaders === BooleanNumber.TRUE &&
+ (allSkeletonPages.length + 1) % 2 !== explicitPageNumberStart % 2
+ ) {
+ allSkeletonPages.push(createSkeletonPage(
+ ctx,
+ sectionBreakConfig,
+ skeletonResourceReference,
+ curSkeletonPage.pageNumber + 1
+ ));
+ }
+ if (
+ curSkeletonPage != null &&
+ (effectiveSectionType === SectionType.EVEN_PAGE || effectiveSectionType === SectionType.ODD_PAGE) &&
+ !isTargetPageParity(nextPageNumber, effectiveSectionType)
+ ) {
+ const fillerPage = createSkeletonPage(
+ ctx,
+ sectionBreakConfig,
+ skeletonResourceReference,
+ nextPageNumber
+ );
+ allSkeletonPages.push(fillerPage);
+ nextPageNumber++;
+ }
+ curSkeletonPage = createSkeletonPage(
+ ctx,
+ sectionBreakConfig,
+ skeletonResourceReference,
+ nextPageNumber
+ );
+ allSkeletonPages.push(curSkeletonPage);
+ }
+
+ state.sectionBreakConfig = sectionBreakConfig;
+ state.sectionInitialized = true;
+
+ if (layoutAnchor != null) {
+ state.paragraphIndex = 0;
+ for (let index = 0; index < sectionNode.children.length; index++) {
+ if (sectionNode.children[index].endIndex === layoutAnchor) {
+ state.paragraphIndex = index;
+ break;
+ }
+ }
+ }
+ }
+
+ private _restartDirtyIncrementalLayout(state: IIncrementalLayoutState): void {
+ const { ctx } = state;
+ const layoutAnchor = ctx.layoutStartPointer[''];
+
+ // Match the established full-layout retry bound, but keep every retry on the
+ // incremental scheduler. A wrapped floating object can invalidate lines that
+ // precede its anchor; completing that retry synchronously would reintroduce the
+ // exact long main-thread task that incremental pagination is meant to remove.
+ if (layoutAnchor == null || state.dirtyRetryCount >= 10) {
+ resetContext(ctx);
+ this._finishIncrementalLayout(state);
+ return;
+ }
+
+ state.dirtyRetryCount++;
+ resetContext(ctx);
+ ctx.layoutStartPointer[''] = null;
+
+ const sections = ctx.viewModel.getChildren();
+ let sectionIndex = sections.findIndex(({ startIndex, endIndex }) =>
+ layoutAnchor >= startIndex && layoutAnchor <= endIndex
+ );
+ if (sectionIndex < 0) {
+ sectionIndex = 0;
+ }
+ const section = sections[sectionIndex];
+ const paragraphIndex = Math.max(
+ 0,
+ section?.children.findIndex(({ endIndex }) => endIndex === layoutAnchor) ?? 0
+ );
+ const processedBeforeSection = sections
+ .slice(0, sectionIndex)
+ .reduce((count, item) => count + item.children.length, 0);
+
+ // dealWithSection has already rolled the active skeleton back to this
+ // paragraph. Resume from that checkpoint in a later scheduler slice.
+ state.sectionIndex = sectionIndex;
+ state.paragraphIndex = paragraphIndex;
+ state.sectionInitialized = false;
+ state.sectionBreakConfig = null;
+ state.layoutAnchor = layoutAnchor;
+ state.laidOutThrough = layoutAnchor - 1;
+ state.stableLaidOutThrough = -1;
+ state.processedBlockCount = processedBeforeSection + paragraphIndex;
+ state.pendingTableBuild = null;
+ state.pendingSlicedTableBuild = null;
+ state.pendingParagraphCheckpoint = null;
+ state.complete = false;
+ state.reusedTail = false;
+ state.tailConvergencePageCount = ctx.skeleton.pages.length;
+ state.interactionPageTail = null;
+ state.interactionPageComplete = false;
+ state.interactionWindowComplete = false;
+ state.interactionWindowResume = null;
+
+ const dirtyPageIndex = this._findBodyPageIndex(ctx.skeleton.pages, layoutAnchor);
+ const stablePrefixCount = Math.max(0, dirtyPageIndex);
+ state.stablePageCount = Math.min(state.stablePageCount, stablePrefixCount);
+ state.finalizedPageCount = Math.min(state.finalizedPageCount, stablePrefixCount);
+ state.lastPublishedPageCount = Math.min(state.lastPublishedPageCount, stablePrefixCount);
+ state.lastPublishedBlockCount = Math.min(state.lastPublishedBlockCount, state.processedBlockCount);
+ if (state.priorityPageIndex >= stablePrefixCount) {
+ state.anchorPublished = false;
+ }
+ }
+
+ private _finishIncrementalLayout(state: IIncrementalLayoutState): void {
+ const { ctx } = state;
+ const { skeleton } = ctx;
+ if (state.mode === 'continuous') {
+ const fragmentGeometry = skeleton.pages.map(clonePageFlowForPublish);
+ updateBlockIndex(fragmentGeometry, -1, ctx.docsConfig.documentCompatibilityPolicy);
+ fragmentGeometry.forEach((geometry, index) => {
+ const page = skeleton.pages[index];
+ if (page != null) {
+ page.height = geometry.height;
+ page.width = geometry.width;
+ }
+ });
+ }
+ removeDupPages(ctx);
+ mergeContinuousDuplicatePages(skeleton.pages, state.mode === 'continuous');
+ if (state.mode === 'continuous') {
+ updateBlockIndex(skeleton.pages, -1, ctx.docsConfig.documentCompatibilityPolicy);
+ updateInlineDrawingCoordsAndBorder(ctx, skeleton.pages);
+ }
+ for (const hSkeMap of skeleton.skeHeaders.values()) {
+ for (const page of hSkeMap.values()) {
+ updateInlineDrawingCoordsAndBorder(ctx, [page]);
+ }
+ }
+ for (const fSkeMap of skeleton.skeFooters.values()) {
+ for (const page of fSkeMap.values()) {
+ updateInlineDrawingCoordsAndBorder(ctx, [page]);
+ }
+ }
+ setPageParent(skeleton.pages, skeleton);
+ state.complete = true;
+ state.stableLaidOutThrough = state.laidOutThrough;
+ this._iteratorCount = 0;
+ }
+
private _prepareLayoutContext(): ILayoutContext {
const viewModel = this.getViewModel();
const dataModel = viewModel.getDataModel();
@@ -1715,7 +4691,10 @@ export class DocumentSkeleton extends Skeleton {
this._iteratorCount = 0;
removeDupPages(ctx);
updateBlockIndex(skeleton.pages, -1, ctx.docsConfig.documentCompatibilityPolicy);
- mergeContinuousDuplicatePages(skeleton.pages);
+ mergeContinuousDuplicatePages(
+ skeleton.pages,
+ ctx.dataModel.documentStyle.documentFlavor === DocumentFlavor.MODERN
+ );
// Calculate inline drawing position and update.
updateInlineDrawingCoordsAndBorder(ctx, skeleton.pages);
for (const hSkeMap of skeleton.skeHeaders.values()) {
diff --git a/packages/engine-render/src/components/docs/layout/document-layout-page-patch.ts b/packages/engine-render/src/components/docs/layout/document-layout-page-patch.ts
new file mode 100644
index 0000000000..501958f2fc
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/document-layout-page-patch.ts
@@ -0,0 +1,729 @@
+/**
+ * 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 { IDocDrawingBase, IDocumentData, IReferenceSource, ITable, ITableRow } from '@univerjs/core';
+import type {
+ IDocumentSkeletonCached,
+ IDocumentSkeletonColumn,
+ IDocumentSkeletonColumnGroup,
+ IDocumentSkeletonColumnGroupColumn,
+ IDocumentSkeletonDivide,
+ IDocumentSkeletonDrawing,
+ IDocumentSkeletonGlyph,
+ IDocumentSkeletonLine,
+ IDocumentSkeletonPage,
+ IDocumentSkeletonRow,
+ IDocumentSkeletonSection,
+ IDocumentSkeletonTable,
+} from '../../../basics/i-document-skeleton-cached';
+
+export type IDocumentSkeletonGlyphPatch = Omit<IDocumentSkeletonGlyph, 'parent'>;
+
+export interface IDocumentSkeletonDividePatch extends Omit<IDocumentSkeletonDivide, 'glyphGroup' | 'parent'> {
+ glyphGroup: IDocumentSkeletonGlyphPatch[];
+}
+
+export interface IDocumentSkeletonLinePatch extends Omit<IDocumentSkeletonLine, 'divides' | 'parent'> {
+ divides: IDocumentSkeletonDividePatch[];
+}
+
+export interface IDocumentSkeletonColumnPatch extends Omit<IDocumentSkeletonColumn, 'lines' | 'parent'> {
+ lines: IDocumentSkeletonLinePatch[];
+}
+
+export interface IDocumentSkeletonSectionPatch extends Omit<IDocumentSkeletonSection, 'columns' | 'parent'> {
+ columns: IDocumentSkeletonColumnPatch[];
+}
+
+export interface IDocumentSkeletonDrawingPatch extends Omit<IDocumentSkeletonDrawing, 'drawingOrigin'> {
+ drawingOrigin?: IDocDrawingBase;
+}
+
+export interface IDocumentSkeletonRowPatch extends Omit<IDocumentSkeletonRow, 'cells' | 'parent' | 'rowSource'> {
+ cells: IDocumentSkeletonPagePatch[];
+ rowSource?: ITableRow;
+ rowSourceIndex?: number;
+}
+
+export interface IDocumentSkeletonTablePatch extends Omit<IDocumentSkeletonTable, 'rows' | 'parent' | 'tableSource'> {
+ rows: IDocumentSkeletonRowPatch[];
+ tableSource?: ITable;
+ tableSourceId?: string;
+}
+
+export interface IDocumentSkeletonColumnGroupColumnPatch extends Omit<IDocumentSkeletonColumnGroupColumn, 'page' | 'parent'> {
+ page: IDocumentSkeletonPagePatch;
+}
+
+export interface IDocumentSkeletonColumnGroupPatch extends Omit<IDocumentSkeletonColumnGroup, 'columns' | 'parent'> {
+ columns: IDocumentSkeletonColumnGroupColumnPatch[];
+}
+
+export interface IDocumentSkeletonPagePatch extends Omit<
+ IDocumentSkeletonPage,
+ 'sections' | 'skeDrawings' | 'skeTables' | 'skeColumnGroups' | 'parent'
+> {
+ sections: IDocumentSkeletonSectionPatch[];
+ skeDrawings: Array<[string, IDocumentSkeletonDrawingPatch]>;
+ skeTables: Array<[string, IDocumentSkeletonTablePatch]>;
+ skeColumnGroups: Array<[string, IDocumentSkeletonColumnGroupPatch]>;
+}
+
+export type IDocumentSkeletonPageGeometryPatch = Omit<
+ IDocumentSkeletonPagePatch,
+ 'sections' | 'skeDrawings' | 'skeTables' | 'skeColumnGroups'
+>;
+
+export type IDocumentSkeletonSectionGeometryPatch = Omit<IDocumentSkeletonSectionPatch, 'columns'>;
+export type IDocumentSkeletonColumnGeometryPatch = Omit<IDocumentSkeletonColumnPatch, 'lines'>;
+
+export interface IDocumentSkeletonContinuousFlowPatch {
+ sectionIndex: number;
+ section: IDocumentSkeletonSectionGeometryPatch;
+ columnIndex: number;
+ column: IDocumentSkeletonColumnGeometryPatch;
+ lineIndex: number;
+ lines: IDocumentSkeletonLinePatch[];
+ trailingColumns: IDocumentSkeletonColumnPatch[];
+ trailingSections: IDocumentSkeletonSectionPatch[];
+}
+
+export interface IDocumentSkeletonContinuousBlockPatch {
+ pageIndex: number;
+ page: IDocumentSkeletonPageGeometryPatch;
+ flow: IDocumentSkeletonContinuousFlowPatch;
+ skeDrawings: Array<[string, IDocumentSkeletonDrawingPatch]>;
+ skeTables: Array<[string, IDocumentSkeletonTablePatch]>;
+ skeColumnGroups: Array<[string, IDocumentSkeletonColumnGroupPatch]>;
+ previousHeight: number;
+ heightDelta: number;
+}
+
+export interface IDocumentSkeletonContinuousSnapshot {
+ height: number;
+ lineEnds: number[];
+}
+
+function withoutParent<T extends { parent?: unknown }>(value: T): Omit<T, 'parent'> {
+ const copy = { ...value };
+ delete copy.parent;
+ return copy;
+}
+
+function serializeDivide(source: IDocumentSkeletonDivide): IDocumentSkeletonDividePatch {
+ return {
+ ...withoutParent(source),
+ glyphGroup: source.glyphGroup.map(withoutParent),
+ };
+}
+
+export function serializeDocumentSkeletonLine(source: IDocumentSkeletonLine): IDocumentSkeletonLinePatch {
+ const line = {
+ ...withoutParent(source),
+ divides: source.divides.map(serializeDivide),
+ };
+ return source.bullet == null
+ ? line
+ : { ...line, bullet: { ...source.bullet } };
+}
+
+function serializeColumn(source: IDocumentSkeletonColumn): IDocumentSkeletonColumnPatch {
+ return {
+ ...withoutParent(source),
+ lines: source.lines.map(serializeDocumentSkeletonLine),
+ };
+}
+
+function serializeSection(source: IDocumentSkeletonSection): IDocumentSkeletonSectionPatch {
+ return {
+ ...withoutParent(source),
+ columns: source.columns.map(serializeColumn),
+ };
+}
+
+function serializeDrawing(
+ source: IDocumentSkeletonDrawing,
+ omitResourceSources: boolean
+): IDocumentSkeletonDrawingPatch {
+ const drawing = { ...source };
+ if (!omitResourceSources) {
+ return drawing;
+ }
+ const { drawingOrigin: _drawingOrigin, ...geometry } = drawing;
+ return geometry;
+}
+
+function serializeTable(
+ source: IDocumentSkeletonTable,
+ omitResourceSources: boolean
+): IDocumentSkeletonTablePatch {
+ const table = withoutParent(source);
+ const { tableSource, ...geometry } = table;
+ return {
+ ...geometry,
+ ...(!omitResourceSources ? { tableSource } : {}),
+ tableSourceId: tableSource.tableId,
+ rows: source.rows.map((row) => {
+ const serializedRow = withoutParent(row);
+ const { rowSource, ...rowGeometry } = serializedRow;
+ return {
+ ...rowGeometry,
+ ...(!omitResourceSources ? { rowSource } : {}),
+ rowSourceIndex: row.index,
+ cells: row.cells.map((cell) => serializeDocumentSkeletonPage(cell, omitResourceSources)),
+ };
+ }),
+ };
+}
+
+function serializeColumnGroup(
+ source: IDocumentSkeletonColumnGroup,
+ omitResourceSources: boolean
+): IDocumentSkeletonColumnGroupPatch {
+ return {
+ ...withoutParent(source),
+ columns: source.columns.map((column) => ({
+ ...withoutParent(column),
+ page: serializeDocumentSkeletonPage(column.page, omitResourceSources),
+ })),
+ };
+}
+
+export function serializeDocumentSkeletonPage(
+ source: IDocumentSkeletonPage,
+ omitResourceSources = false
+): IDocumentSkeletonPagePatch {
+ return {
+ ...withoutParent(source),
+ sections: source.sections.map(serializeSection),
+ skeDrawings: [...source.skeDrawings].map(([drawingId, drawing]) => [
+ drawingId,
+ serializeDrawing(drawing, omitResourceSources),
+ ]),
+ skeTables: [...source.skeTables].map(([tableId, table]) => [
+ tableId,
+ serializeTable(table, omitResourceSources),
+ ]),
+ skeColumnGroups: [...source.skeColumnGroups].map(([groupId, group]) => [
+ groupId,
+ serializeColumnGroup(group, omitResourceSources),
+ ]),
+ };
+}
+
+function hydrateDivide(source: IDocumentSkeletonDividePatch, parent: IDocumentSkeletonLine): IDocumentSkeletonDivide {
+ const divide: IDocumentSkeletonDivide = {
+ ...source,
+ glyphGroup: [],
+ parent,
+ };
+ divide.glyphGroup = source.glyphGroup.map((glyph) => ({ ...glyph, parent: divide }));
+ return divide;
+}
+
+export function hydrateDocumentSkeletonLine(
+ source: IDocumentSkeletonLinePatch,
+ parent: IDocumentSkeletonColumn
+): IDocumentSkeletonLine {
+ const line: IDocumentSkeletonLine = {
+ ...source,
+ divides: [],
+ parent,
+ };
+ line.divides = source.divides.map((divide) => hydrateDivide(divide, line));
+ return line;
+}
+
+function hydrateColumn(source: IDocumentSkeletonColumnPatch, parent: IDocumentSkeletonSection): IDocumentSkeletonColumn {
+ const column: IDocumentSkeletonColumn = {
+ ...source,
+ lines: [],
+ parent,
+ };
+ column.lines = source.lines.map((line) => hydrateDocumentSkeletonLine(line, column));
+ return column;
+}
+
+function hydrateSection(source: IDocumentSkeletonSectionPatch, parent: IDocumentSkeletonPage): IDocumentSkeletonSection {
+ const section: IDocumentSkeletonSection = {
+ ...source,
+ columns: [],
+ parent,
+ };
+ section.columns = source.columns.map((column) => hydrateColumn(column, section));
+ return section;
+}
+
+function getDocumentReferenceSource(
+ snapshot: IDocumentData,
+ segmentId: string
+): IReferenceSource {
+ return snapshot.headers?.[segmentId] ?? snapshot.footers?.[segmentId] ?? snapshot;
+}
+
+function requireDrawingOrigin(
+ source: IDocumentSkeletonDrawingPatch,
+ snapshot: IDocumentData | undefined,
+ segmentId: string
+): IDocDrawingBase {
+ const drawingOrigin = source.drawingOrigin ?? (snapshot == null
+ ? undefined
+ : getDocumentReferenceSource(snapshot, segmentId).drawings?.[source.drawingId] ??
+ snapshot.drawings?.[source.drawingId]);
+ if (drawingOrigin == null) {
+ throw new Error(`Document layout publication is missing drawing source "${source.drawingId}".`);
+ }
+ return drawingOrigin;
+}
+
+function hydrateDrawing(
+ source: IDocumentSkeletonDrawingPatch,
+ snapshot: IDocumentData | undefined,
+ segmentId: string
+): IDocumentSkeletonDrawing {
+ return {
+ ...source,
+ drawingOrigin: requireDrawingOrigin(source, snapshot, segmentId),
+ };
+}
+
+function requireTableSource(
+ source: IDocumentSkeletonTablePatch,
+ snapshot: IDocumentData | undefined,
+ segmentId: string
+): ITable {
+ const sourceId = source.tableSourceId ?? source.tableId;
+ const tableSource = source.tableSource ?? (snapshot == null
+ ? undefined
+ : getDocumentReferenceSource(snapshot, segmentId).tableSource?.[sourceId] ??
+ snapshot.tableSource?.[sourceId]);
+ if (tableSource == null) {
+ throw new Error(`Document layout publication is missing table source "${sourceId}".`);
+ }
+ return tableSource;
+}
+
+function hydrateTable(
+ source: IDocumentSkeletonTablePatch,
+ parent: IDocumentSkeletonPage,
+ snapshot: IDocumentData | undefined,
+ segmentId: string
+): IDocumentSkeletonTable {
+ const tableSource = requireTableSource(source, snapshot, segmentId);
+ const {
+ tableSource: _tableSource,
+ tableSourceId: _tableSourceId,
+ rows: sourceRows,
+ ...tableGeometry
+ } = source;
+ const table: IDocumentSkeletonTable = {
+ ...tableGeometry,
+ tableSource,
+ rows: [],
+ parent,
+ };
+ table.rows = sourceRows.map((sourceRow) => {
+ const rowSource = sourceRow.rowSource ?? tableSource.tableRows[sourceRow.rowSourceIndex ?? sourceRow.index];
+ if (rowSource == null) {
+ throw new Error(
+ `Document layout publication is missing row source ${sourceRow.rowSourceIndex ?? sourceRow.index} ` +
+ `for table "${tableSource.tableId}".`
+ );
+ }
+ const {
+ rowSource: _rowSource,
+ rowSourceIndex: _rowSourceIndex,
+ cells: sourceCells,
+ ...rowGeometry
+ } = sourceRow;
+ const row: IDocumentSkeletonRow = {
+ ...rowGeometry,
+ rowSource,
+ cells: [],
+ parent: table,
+ };
+ row.cells = sourceCells.map((cell) => hydrateDocumentSkeletonPageInternal(
+ cell,
+ row,
+ snapshot,
+ segmentId
+ ));
+ return row;
+ });
+ return table;
+}
+
+function hydrateColumnGroup(
+ source: IDocumentSkeletonColumnGroupPatch,
+ parent: IDocumentSkeletonPage,
+ snapshot: IDocumentData | undefined,
+ segmentId: string
+): IDocumentSkeletonColumnGroup {
+ const group: IDocumentSkeletonColumnGroup = {
+ ...source,
+ columns: [],
+ parent,
+ };
+ group.columns = source.columns.map((sourceColumn) => {
+ const page = hydrateDocumentSkeletonPageInternal(
+ sourceColumn.page,
+ undefined,
+ snapshot,
+ segmentId
+ );
+ const column: IDocumentSkeletonColumnGroupColumn = {
+ ...sourceColumn,
+ page,
+ parent: group,
+ };
+ page.parent = column;
+ return column;
+ });
+ return group;
+}
+
+export function hydrateDocumentSkeletonPage(
+ source: IDocumentSkeletonPagePatch,
+ parent?: IDocumentSkeletonCached | IDocumentSkeletonRow | IDocumentSkeletonColumnGroupColumn,
+ snapshot?: IDocumentData
+): IDocumentSkeletonPage {
+ return hydrateDocumentSkeletonPageInternal(source, parent, snapshot, source.segmentId);
+}
+
+export function hydrateDocumentSkeletonPagePlaceholder(
+ source: IDocumentSkeletonPagePatch,
+ parent?: IDocumentSkeletonCached
+): IDocumentSkeletonPage {
+ const {
+ sections: _sections,
+ skeDrawings: _skeDrawings,
+ skeTables: _skeTables,
+ skeColumnGroups: _skeColumnGroups,
+ ...geometry
+ } = source;
+ return {
+ ...geometry,
+ isLayoutPlaceholder: true,
+ sections: [],
+ st: -1,
+ ed: -1,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ skeColumnGroups: new Map(),
+ parent,
+ };
+}
+
+export function hydrateDocumentSkeletonPageMaterializationPlaceholder(
+ source: IDocumentSkeletonPagePatch,
+ parent?: IDocumentSkeletonCached
+): IDocumentSkeletonPage {
+ const placeholder = hydrateDocumentSkeletonPagePlaceholder(source, parent);
+ delete placeholder.isLayoutPlaceholder;
+ placeholder.isMaterializationPlaceholder = true;
+ placeholder.st = source.st;
+ placeholder.ed = source.ed;
+ return placeholder;
+}
+
+function hydrateDocumentSkeletonPageInternal(
+ source: IDocumentSkeletonPagePatch,
+ parent: IDocumentSkeletonCached | IDocumentSkeletonRow | IDocumentSkeletonColumnGroupColumn | undefined,
+ snapshot: IDocumentData | undefined,
+ resourceSegmentId: string
+): IDocumentSkeletonPage {
+ const page: IDocumentSkeletonPage = {
+ ...source,
+ sections: [],
+ skeDrawings: new Map(source.skeDrawings.map(([drawingId, drawing]) => [
+ drawingId,
+ hydrateDrawing(drawing, snapshot, resourceSegmentId),
+ ])),
+ skeTables: new Map(),
+ skeColumnGroups: new Map(),
+ parent,
+ };
+ page.sections = source.sections.map((section) => hydrateSection(section, page));
+ page.skeTables = new Map(source.skeTables.map(([tableId, table]) => [
+ tableId,
+ hydrateTable(table, page, snapshot, resourceSegmentId),
+ ]));
+ page.skeColumnGroups = new Map(source.skeColumnGroups.map(([groupId, group]) => [
+ groupId,
+ hydrateColumnGroup(group, page, snapshot, resourceSegmentId),
+ ]));
+ return page;
+}
+
+interface IDocumentSkeletonFlowCursor {
+ sectionIndex: number;
+ columnIndex: number;
+ lineIndex: number;
+}
+
+function collectFlowLineEnds(page: IDocumentSkeletonPage): number[] {
+ const lineEnds: number[] = [];
+ for (const section of page.sections) {
+ for (const column of section.columns) {
+ for (const line of column.lines) {
+ lineEnds.push(line.ed);
+ }
+ }
+ }
+ return lineEnds;
+}
+
+function countFlowLines(page: IDocumentSkeletonPage): number {
+ let lineCount = 0;
+ for (const section of page.sections) {
+ for (const column of section.columns) {
+ lineCount += column.lines.length;
+ }
+ }
+ return lineCount;
+}
+
+function collectFlowLineEndsFromCursor(
+ page: IDocumentSkeletonPage,
+ cursor: IDocumentSkeletonFlowCursor
+): number[] {
+ const lineEnds: number[] = [];
+ for (let sectionIndex = cursor.sectionIndex; sectionIndex < page.sections.length; sectionIndex++) {
+ const section = page.sections[sectionIndex];
+ const firstColumnIndex = sectionIndex === cursor.sectionIndex ? cursor.columnIndex : 0;
+ for (let columnIndex = firstColumnIndex; columnIndex < section.columns.length; columnIndex++) {
+ const column = section.columns[columnIndex];
+ const firstLineIndex = sectionIndex === cursor.sectionIndex && columnIndex === cursor.columnIndex
+ ? cursor.lineIndex
+ : 0;
+ for (let lineIndex = firstLineIndex; lineIndex < column.lines.length; lineIndex++) {
+ lineEnds.push(column.lines[lineIndex].ed);
+ }
+ }
+ }
+ return lineEnds;
+}
+
+function findFlowLineIndex(lineEnds: number[], offset: number): number {
+ const index = lineEnds.findIndex((lineEnd) => lineEnd >= offset);
+ return index < 0 ? lineEnds.length : index;
+}
+
+function resolveFlowCursor(page: IDocumentSkeletonPage, flowLineIndex: number): IDocumentSkeletonFlowCursor {
+ let remaining = flowLineIndex;
+ for (let sectionIndex = 0; sectionIndex < page.sections.length; sectionIndex++) {
+ const section = page.sections[sectionIndex];
+ for (let columnIndex = 0; columnIndex < section.columns.length; columnIndex++) {
+ const lineCount = section.columns[columnIndex].lines.length;
+ if (remaining < lineCount) {
+ return { sectionIndex, columnIndex, lineIndex: remaining };
+ }
+ remaining -= lineCount;
+ }
+ }
+
+ const sectionIndex = Math.max(0, page.sections.length - 1);
+ const section = page.sections[sectionIndex];
+ const columnIndex = Math.max(0, (section?.columns.length ?? 1) - 1);
+ return {
+ sectionIndex,
+ columnIndex,
+ lineIndex: section?.columns[columnIndex]?.lines.length ?? 0,
+ };
+}
+
+function serializePageGeometry(source: IDocumentSkeletonPage): IDocumentSkeletonPageGeometryPatch {
+ const serialized = withoutParent(source);
+ const {
+ sections: _sections,
+ skeDrawings: _skeDrawings,
+ skeTables: _skeTables,
+ skeColumnGroups: _skeColumnGroups,
+ ...page
+ } = serialized;
+ return page;
+}
+
+/**
+ * Serializes only the changed suffix of a continuous document's logical page.
+ * The boundary line is deliberately republished because paragraph spacing can
+ * alter it when the next block is appended.
+ */
+export function serializeDocumentSkeletonContinuousBlock(
+ currentPage: IDocumentSkeletonPage,
+ previousSnapshot: IDocumentSkeletonContinuousSnapshot | null,
+ replacementOffset?: number,
+ omitResourceSources = false
+): { block: IDocumentSkeletonContinuousBlockPatch; snapshot: IDocumentSkeletonContinuousSnapshot } {
+ const previousLineCount = previousSnapshot?.lineEnds.length ?? 0;
+ let currentLineEnds: number[];
+ let replacementLineIndex: number;
+ let cursor: IDocumentSkeletonFlowCursor;
+ if (previousSnapshot != null && replacementOffset == null) {
+ replacementLineIndex = Math.max(0, Math.min(previousLineCount, countFlowLines(currentPage)) - 1);
+ cursor = resolveFlowCursor(currentPage, replacementLineIndex);
+ const appendedLineEnds = collectFlowLineEndsFromCursor(currentPage, cursor);
+ currentLineEnds = previousSnapshot.lineEnds;
+ currentLineEnds.splice(
+ replacementLineIndex,
+ currentLineEnds.length - replacementLineIndex,
+ ...appendedLineEnds
+ );
+ } else {
+ currentLineEnds = collectFlowLineEnds(currentPage);
+ const replacementStart = replacementOffset ?? 0;
+ replacementLineIndex = previousSnapshot == null
+ ? 0
+ : Math.min(
+ findFlowLineIndex(previousSnapshot.lineEnds, replacementStart),
+ findFlowLineIndex(currentLineEnds, replacementStart)
+ );
+ cursor = resolveFlowCursor(currentPage, replacementLineIndex);
+ }
+ const section = currentPage.sections[cursor.sectionIndex];
+ const column = section?.columns[cursor.columnIndex];
+ if (section == null || column == null) {
+ throw new Error('Continuous document layout requires at least one section and column.');
+ }
+
+ const serializedSection = withoutParent(section);
+ const serializedColumn = withoutParent(column);
+ const { columns: _columns, ...sectionGeometry } = serializedSection;
+ const { lines: _lines, ...columnGeometry } = serializedColumn;
+
+ const snapshot: IDocumentSkeletonContinuousSnapshot = {
+ height: currentPage.height,
+ lineEnds: currentLineEnds,
+ };
+
+ return {
+ snapshot,
+ block: {
+ pageIndex: 0,
+ page: serializePageGeometry(currentPage),
+ flow: {
+ sectionIndex: cursor.sectionIndex,
+ section: sectionGeometry,
+ columnIndex: cursor.columnIndex,
+ column: columnGeometry,
+ lineIndex: cursor.lineIndex,
+ lines: column.lines.slice(cursor.lineIndex).map(serializeDocumentSkeletonLine),
+ trailingColumns: section.columns.slice(cursor.columnIndex + 1).map(serializeColumn),
+ trailingSections: currentPage.sections.slice(cursor.sectionIndex + 1).map(serializeSection),
+ },
+ skeDrawings: [...currentPage.skeDrawings].map(([drawingId, drawing]) => [
+ drawingId,
+ serializeDrawing(drawing, omitResourceSources),
+ ]),
+ skeTables: [...currentPage.skeTables].map(([tableId, table]) => [
+ tableId,
+ serializeTable(table, omitResourceSources),
+ ]),
+ skeColumnGroups: [...currentPage.skeColumnGroups].map(([groupId, group]) => [
+ groupId,
+ serializeColumnGroup(group, omitResourceSources),
+ ]),
+ previousHeight: previousSnapshot?.height ?? 0,
+ heightDelta: currentPage.height - (previousSnapshot?.height ?? 0),
+ },
+ };
+}
+
+export function applyDocumentSkeletonContinuousBlock(
+ target: IDocumentSkeletonCached,
+ patch: IDocumentSkeletonContinuousBlockPatch,
+ snapshot?: IDocumentData
+): IDocumentSkeletonPage {
+ const { flow } = patch;
+ let page = target.pages[patch.pageIndex];
+ if (page == null) {
+ page = hydrateDocumentSkeletonPage({
+ ...patch.page,
+ sections: [{
+ ...flow.section,
+ columns: [{
+ ...flow.column,
+ lines: flow.lines,
+ }, ...flow.trailingColumns],
+ }, ...flow.trailingSections],
+ skeDrawings: patch.skeDrawings,
+ skeTables: patch.skeTables,
+ skeColumnGroups: patch.skeColumnGroups,
+ }, target, snapshot);
+ target.pages[patch.pageIndex] = page;
+ return page;
+ }
+
+ const sections = page.sections;
+ const existingSection = sections[flow.sectionIndex];
+ if (existingSection == null) {
+ sections.splice(flow.sectionIndex, sections.length - flow.sectionIndex, hydrateSection({
+ ...flow.section,
+ columns: [{
+ ...flow.column,
+ lines: flow.lines,
+ }, ...flow.trailingColumns],
+ }, page), ...flow.trailingSections.map((section) => hydrateSection(section, page)));
+ } else {
+ const columns = existingSection.columns;
+ const existingColumn = columns[flow.columnIndex];
+ Object.assign(existingSection, flow.section, { columns, parent: page });
+ if (existingColumn == null) {
+ columns.splice(flow.columnIndex, columns.length - flow.columnIndex, hydrateColumn({
+ ...flow.column,
+ lines: flow.lines,
+ }, existingSection), ...flow.trailingColumns.map((column) => hydrateColumn(column, existingSection)));
+ } else {
+ const lines = existingColumn.lines;
+ Object.assign(existingColumn, flow.column, { lines, parent: existingSection });
+ lines.splice(
+ flow.lineIndex,
+ lines.length - flow.lineIndex,
+ ...flow.lines.map((line) => hydrateDocumentSkeletonLine(line, existingColumn))
+ );
+ columns.splice(
+ flow.columnIndex + 1,
+ columns.length - flow.columnIndex - 1,
+ ...flow.trailingColumns.map((column) => hydrateColumn(column, existingSection))
+ );
+ }
+ sections.splice(
+ flow.sectionIndex + 1,
+ sections.length - flow.sectionIndex - 1,
+ ...flow.trailingSections.map((section) => hydrateSection(section, page))
+ );
+ }
+
+ Object.assign(page, patch.page, {
+ sections,
+ skeDrawings: new Map(patch.skeDrawings.map(([drawingId, drawing]) => [
+ drawingId,
+ hydrateDrawing(drawing, snapshot, page.segmentId),
+ ])),
+ skeTables: new Map(patch.skeTables.map(([tableId, table]) => [
+ tableId,
+ hydrateTable(table, page, snapshot, page.segmentId),
+ ])),
+ skeColumnGroups: new Map(
+ patch.skeColumnGroups.map(([groupId, group]) => [
+ groupId,
+ hydrateColumnGroup(group, page, snapshot, page.segmentId),
+ ])
+ ),
+ parent: target,
+ });
+ return page;
+}
diff --git a/packages/engine-render/src/components/docs/layout/document-layout-publication.ts b/packages/engine-render/src/components/docs/layout/document-layout-publication.ts
new file mode 100644
index 0000000000..0d9280e1ea
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/document-layout-publication.ts
@@ -0,0 +1,59 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentSkeletonDrawingAnchor, IParagraphList } from '../../../basics/i-document-skeleton-cached';
+import type { IDocumentSkeletonContinuousBlockPatch, IDocumentSkeletonPagePatch } from './document-layout-page-patch';
+
+export type IDocumentLayoutListLevelPublication = Array<[string, IParagraphList[][]]>;
+export type IDocumentLayoutDrawingAnchorPublication = Array<[
+ string,
+ Array<[number, Omit<IDocumentSkeletonDrawingAnchor, 'elements'>]>
+]>;
+
+export interface IDocumentLayoutPagePublication {
+ pageIndex: number;
+ page: IDocumentSkeletonPagePatch;
+}
+
+export interface IDocumentLayoutResourcePublication {
+ reset: boolean;
+ skeHeaders: Array<[string, Array<[number, IDocumentSkeletonPagePatch]>]>;
+ skeFooters: Array<[string, Array<[number, IDocumentSkeletonPagePatch]>]>;
+ skeListLevel: IDocumentLayoutListLevelPublication | null;
+ drawingAnchor: IDocumentLayoutDrawingAnchorPublication | null;
+}
+
+interface IDocumentLayoutGeometryPublicationBase {
+ left: number;
+ top: number;
+ st: number;
+ ed?: number;
+ resources: IDocumentLayoutResourcePublication;
+}
+
+export interface IDocumentLayoutPageGeometryPublication extends IDocumentLayoutGeometryPublicationBase {
+ kind: 'page';
+ pages: IDocumentLayoutPagePublication[];
+}
+
+export interface IDocumentLayoutBlockGeometryPublication extends IDocumentLayoutGeometryPublicationBase {
+ kind: 'block';
+ block: IDocumentSkeletonContinuousBlockPatch;
+}
+
+export type IDocumentLayoutGeometryPublication =
+ | IDocumentLayoutPageGeometryPublication
+ | IDocumentLayoutBlockGeometryPublication;
diff --git a/packages/engine-render/src/components/docs/layout/document-layout-types.ts b/packages/engine-render/src/components/docs/layout/document-layout-types.ts
new file mode 100644
index 0000000000..5ea447c53d
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/document-layout-types.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.
+ */
+
+export type DocumentLayoutMode = 'paginated' | 'continuous';
+export type DocumentLayoutReason = 'initial' | 'edit';
+
+export interface IDocumentLayoutInvalidation {
+ /** First offset changed in the pre-mutation document. */
+ oldStart: number;
+ /** Exclusive end of the changed range in the pre-mutation document. */
+ oldEnd: number;
+ /** Exclusive end of the changed range in the post-mutation document. */
+ newEnd: number;
+}
+
+export interface IDocumentLayoutProtectedPageRange {
+ mode: 'paginated';
+ startPageIndex: number;
+ endPageIndex: number;
+}
+
+export type IDocumentLayoutPageRange = Pick<
+ IDocumentLayoutProtectedPageRange,
+ 'startPageIndex' | 'endPageIndex'
+>;
+
+export interface IDocumentLayoutProtectedContinuousRange {
+ mode: 'continuous';
+ startOffset: number;
+ endOffset: number;
+}
+
+export type IDocumentLayoutProtectedRange =
+ | IDocumentLayoutProtectedPageRange
+ | IDocumentLayoutProtectedContinuousRange;
+
+export interface IDocumentLayoutApplyResult {
+ didReplaceProtectedPages: boolean;
+}
+
+export interface IDocumentLayoutProgress {
+ generation: number;
+ publicationRevision: number;
+ didPublish: boolean;
+ /** The publication atomically replaced the page containing the edit anchor. */
+ didPublishAnchor: boolean;
+ publishedPageCount: number;
+ reason: DocumentLayoutReason;
+ mode: DocumentLayoutMode;
+ complete: boolean;
+ cancelled: boolean;
+ anchorReady: boolean;
+ laidOutThrough: number;
+ /** Last logical offset whose exit geometry cannot be changed by the next block. */
+ stableLaidOutThrough: number;
+ pageCount: number;
+ processedBlockCount: number;
+ totalBlockCount: number;
+ estimatedPageCount: number;
+ estimatedHeight: number;
+ elapsedTime: number;
+ maxBlockDuration: number;
+ /** Main has sealed the protected interaction page and should hand the remaining suffix to Worker. */
+ interactionWindowComplete?: boolean;
+}
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 bee5a91596..1311654725 100644
--- a/packages/engine-render/src/components/docs/layout/model/page.ts
+++ b/packages/engine-render/src/components/docs/layout/model/page.ts
@@ -457,25 +457,17 @@ function isVerticallyCoveredGridColumn(table: ITable, row: number, gridColumn: n
return false;
}
-export function createSkeletonCellPages(
+function getCellLineGridOptions(
ctx: ILayoutContext,
- viewModel: DocumentViewModel,
cellNode: DataStreamTreeNode,
- sectionBreakConfig: ISectionBreakConfig,
- tableConfig: ITable,
- row: number,
- col: number,
- availableHeight: number = Number.POSITIVE_INFINITY,
- maxCellPageHeight: number = Number.POSITIVE_INFINITY
-) {
- // Table cell only has one section.
- const sectionNode = cellNode.children[0];
+ 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 usesLineGrid = sectionBreakConfig.gridType === GridType.LINES ||
+ sectionBreakConfig.gridType === GridType.LINES_AND_CHARS;
const documentCompatibilityPolicy = sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy();
- const isTraditionalLineGrid = isTraditionalDocumentCompatibility(documentCompatibilityPolicy) &&
- usesLineGrid;
+ const isTraditionalLineGrid = isTraditionalDocumentCompatibility(documentCompatibilityPolicy) && usesLineGrid;
const usesNextDocumentGridLine = (paragraph: IParagraph) => {
const paragraphStyle = paragraph.paragraphStyle;
const lineSpacing = paragraphStyle?.lineSpacing;
@@ -499,6 +491,29 @@ export function createSkeletonCellPages(
usesNextDocumentGridLine(paragraph)
)) === true;
+ return { enableDocumentTableLineGrid, inheritDocumentLinePitch };
+}
+
+export function createSkeletonCellPages(
+ ctx: ILayoutContext,
+ viewModel: DocumentViewModel,
+ cellNode: DataStreamTreeNode,
+ sectionBreakConfig: ISectionBreakConfig,
+ tableConfig: ITable,
+ row: number,
+ col: number,
+ availableHeight: number = Number.POSITIVE_INFINITY,
+ maxCellPageHeight: number = Number.POSITIVE_INFINITY
+) {
+ // Table cell only has one section.
+ const sectionNode = cellNode.children[0];
+ const body = ctx.dataModel?.getBody?.();
+ const { enableDocumentTableLineGrid, inheritDocumentLinePitch } = getCellLineGridOptions(
+ ctx,
+ cellNode,
+ sectionBreakConfig
+ );
+
const { page: areaPage, sectionBreakConfig: cellSectionBreakConfig } = createNullCellPage(
ctx,
sectionBreakConfig,
@@ -565,6 +580,133 @@ export function createSkeletonCellPages(
return pages;
}
+export interface ICellSkeletonBuildState {
+ ctx: ILayoutContext;
+ viewModel: DocumentViewModel;
+ cellNode: DataStreamTreeNode;
+ sectionNode: DataStreamTreeNode;
+ sectionBreakConfig: ISectionBreakConfig;
+ cellSectionBreakConfig: ISectionBreakConfig;
+ tableConfig: ITable;
+ paragraphIndex: number;
+ layoutAnchor: Nullable<number>;
+ pages: IDocumentSkeletonPage[];
+ complete: boolean;
+ requiresSyncFallback: boolean;
+}
+
+export function startSkeletonCellPagesBuild(
+ ctx: ILayoutContext,
+ viewModel: DocumentViewModel,
+ cellNode: DataStreamTreeNode,
+ sectionBreakConfig: ISectionBreakConfig,
+ tableConfig: ITable,
+ row: number,
+ col: number,
+ availableHeight: number = Number.POSITIVE_INFINITY,
+ maxCellPageHeight: number = Number.POSITIVE_INFINITY
+): ICellSkeletonBuildState {
+ const sectionNode = cellNode.children[0];
+ const { enableDocumentTableLineGrid, inheritDocumentLinePitch } = getCellLineGridOptions(
+ ctx,
+ cellNode,
+ sectionBreakConfig
+ );
+ const { page, sectionBreakConfig: cellSectionBreakConfig } = createNullCellPage(
+ ctx,
+ sectionBreakConfig,
+ tableConfig,
+ row,
+ col,
+ availableHeight,
+ maxCellPageHeight,
+ inheritDocumentLinePitch,
+ enableDocumentTableLineGrid
+ );
+ page.type = DocumentSkeletonPageType.CELL;
+ page.segmentId = tableConfig.tableId;
+
+ const layoutAnchor = ctx.layoutStartPointer[tableConfig.tableId];
+ ctx.layoutStartPointer[tableConfig.tableId] = null;
+
+ return {
+ ctx,
+ viewModel,
+ cellNode,
+ sectionNode,
+ sectionBreakConfig,
+ cellSectionBreakConfig,
+ tableConfig,
+ paragraphIndex: 0,
+ layoutAnchor,
+ pages: [page],
+ complete: false,
+ requiresSyncFallback: false,
+ };
+}
+
+export function stepSkeletonCellPagesBuild(state: ICellSkeletonBuildState): boolean {
+ if (state.complete) {
+ return true;
+ }
+
+ const currentPage = state.pages[state.pages.length - 1];
+ const result = dealWithSection(
+ state.ctx,
+ state.viewModel,
+ state.sectionNode,
+ currentPage,
+ state.cellSectionBreakConfig,
+ state.layoutAnchor,
+ {
+ startParagraphIndex: state.paragraphIndex,
+ maxParagraphs: 1,
+ }
+ );
+
+ if (result.pages[0] === currentPage) {
+ result.pages.shift();
+ }
+ state.pages.push(...result.pages);
+ state.paragraphIndex = result.nextParagraphIndex;
+ state.layoutAnchor = null;
+
+ if (state.ctx.isDirty) {
+ state.requiresSyncFallback = true;
+ state.complete = true;
+ return true;
+ }
+
+ if (result.complete) {
+ for (const page of state.pages) {
+ page.type = DocumentSkeletonPageType.CELL;
+ page.segmentId = state.tableConfig.tableId;
+ }
+ updateBlockIndex(
+ state.pages,
+ state.cellNode.startIndex,
+ state.sectionBreakConfig.documentCompatibilityPolicy ?? getDocumentCompatibilityPolicy()
+ );
+ applyTrailingBlockRangeSpaceBelow(
+ state.pages,
+ state.ctx.dataModel?.getBody?.(),
+ state.cellNode.endIndex
+ );
+ applyTrailingCellParagraphSpaceBelow(
+ state.pages,
+ state.ctx.dataModel?.getBody?.(),
+ state.cellNode.endIndex,
+ state.cellSectionBreakConfig
+ );
+ updateInlineDrawingCoordsAndBorder(state.ctx, state.pages);
+ expandCellPageHeightForInlineDrawings(state.pages);
+ expandCellPageHeightForFlowTables(state.pages);
+ state.complete = true;
+ }
+
+ return state.complete;
+}
+
function applyTrailingCellParagraphSpaceBelow(
pages: IDocumentSkeletonPage[],
body: Nullable<IDocumentBody>,
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 40fd2f0f4c..3b2afc5590 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
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { FontCache } from '../font-cache';
describe('font cache', () => {
@@ -25,6 +25,42 @@ describe('font cache', () => {
(FontCache as any)._context = null;
});
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('measures text with OffscreenCanvas when the DOM is unavailable', () => {
+ const measureText = vi.fn(() => ({
+ width: 16,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 2,
+ }));
+
+ vi.stubGlobal('document', undefined);
+ vi.stubGlobal('OffscreenCanvas', class {
+ getContext() {
+ return {
+ font: '',
+ textBaseline: 'alphabetic',
+ measureText,
+ };
+ }
+ });
+
+ const result = FontCache.getMeasureText('W', '12px Arial');
+
+ expect(result).toEqual({
+ width: 16,
+ fontBoundingBoxAscent: 9,
+ fontBoundingBoxDescent: 3,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 2,
+ });
+ expect(measureText).toHaveBeenCalledWith('W');
+ });
+
it('handles measure cache lifecycle and fallback metrics', () => {
const fakeContext = {
font: '',
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 6835cf385c..cae46559e3 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
@@ -61,7 +61,7 @@ interface IGlyphHorizonData {
export class FontCache {
private static _getTextHeightCache: { [key: string]: { width: number; height: number } } = {};
- private static _context: CanvasRenderingContext2D;
+ private static _context: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null;
private static _fontDataMap: Map<string, IFontData> = new Map();
@@ -105,7 +105,6 @@ export class FontCache {
static autoCleanFontMeasureCache(cacheLimit: number = 1000000) {
let allSize = 0;
let isDelete = false;
- let i = 0;
for (const item of this._globalFontMeasureCache) {
const [, values] = item;
@@ -114,7 +113,6 @@ export class FontCache {
isDelete = true;
break;
}
- i++;
}
if (isDelete) {
@@ -169,6 +167,13 @@ export class FontCache {
return this._getTextHeightCache[fontStyle];
}
+ if (typeof document === 'undefined') {
+ return {
+ width: 0,
+ height: this._getFontSizeFromStyle(fontStyle),
+ };
+ }
+
let dom = document.getElementById('universheetTextSizeTest');
const defaultStyle = 'float:left;white-space:nowrap;visibility:hidden;margin:0;padding:0;';
if (!dom) {
@@ -213,8 +218,7 @@ export class FontCache {
*/
static getMeasureText(content: string, fontString: string): IMeasureTextCache {
if (!this._context) {
- const canvas = document.createElement('canvas');
- this._context = canvas.getContext('2d')!;
+ this._context = this._createMeasureContext();
}
if (!this._context) {
return {
@@ -260,7 +264,10 @@ export class FontCache {
Number.isNaN(fontBoundingBoxAscent) ||
Number.isNaN(fontBoundingBoxDescent)
) {
- const oneLineTextHeight = this.getTextSizeByDom(DEFAULT_MEASURE_TEXT, fontString).height;
+ const measuredHeight = actualBoundingBoxAscent + actualBoundingBoxDescent;
+ const oneLineTextHeight = typeof document === 'undefined' && typeof OffscreenCanvas !== 'undefined' && Number.isFinite(measuredHeight) && measuredHeight > 0
+ ? measuredHeight
+ : this.getTextSizeByDom(DEFAULT_MEASURE_TEXT, fontString).height;
if (ctx.textBaseline === 'top') {
cache.fontBoundingBoxAscent = cache.actualBoundingBoxAscent = oneLineTextHeight;
@@ -279,6 +286,23 @@ export class FontCache {
return cache;
}
+ private static _createMeasureContext(): CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null {
+ if (typeof document !== 'undefined') {
+ return document.createElement('canvas').getContext('2d');
+ }
+
+ if (typeof OffscreenCanvas !== 'undefined') {
+ return new OffscreenCanvas(1, 1).getContext('2d');
+ }
+
+ return null;
+ }
+
+ private static _getFontSizeFromStyle(fontStyle: string): number {
+ const match = /(?:^|\s)(\d+(?:\.\d+)?)px(?:\s|\/|$)/.exec(fontStyle);
+ return match == null ? 0 : Number(match[1]);
+ }
+
private static _clearMeasureCache(limit: number, values: Map<string, IMeasureTextCache>) {
let valueIndex = 0;
for (const txtItem of values) {
diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.ts
index 6ea7f3cd11..9e90f71283 100644
--- a/packages/engine-render/src/components/docs/layout/tools.ts
+++ b/packages/engine-render/src/components/docs/layout/tools.ts
@@ -374,12 +374,69 @@ export function getCharSpaceConfig(sectionBreakConfig: ISectionBreakConfig, para
};
}
+/**
+ * Reconciles visible glyph flow with the model's paragraph endpoint.
+ *
+ * Imported documents can contain non-rendering flow tokens between paragraphs.
+ * Counting only visible glyphs then shifts every following caret and hit-test
+ * offset. A complete paragraph provides a model-owned checkpoint from which its
+ * visible range can be derived without changing the layout algorithm.
+ */
+function getParagraphLogicalStartAnchors(pages: IDocumentSkeletonPage[]): Map<IDocumentSkeletonLine, number> {
+ const paragraphs = new Map<number, {
+ firstLine: IDocumentSkeletonLine;
+ glyphCount: number;
+ terminal?: string;
+ }>();
+
+ for (const page of pages) {
+ 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 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,
+ terminal: lastGlyph?.raw ?? lastGlyph?.streamType,
+ });
+ }
+ }
+ }
+ }
+
+ const anchors = new Map<IDocumentSkeletonLine, number>();
+ for (const [paragraphIndex, paragraph] of paragraphs) {
+ const { firstLine, glyphCount, terminal } = paragraph;
+ if (!firstLine.paragraphStart || paragraphIndex < 0) {
+ continue;
+ }
+
+ if (
+ terminal !== DataStreamTreeTokenType.PARAGRAPH &&
+ terminal !== DataStreamTreeTokenType.SECTION_BREAK &&
+ terminal !== DataStreamTreeTokenType.DOCS_END
+ ) {
+ continue;
+ }
+
+ anchors.set(firstLine, paragraphIndex - glyphCount + 1);
+ }
+
+ return anchors;
+}
+
export function updateBlockIndex(
pages: IDocumentSkeletonPage[],
start: number = -1,
documentCompatibilityPolicy?: IDocumentCompatibilityPolicy
) {
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
// content width; otherwise a sheet cell editor may stretch to the far edge of the canvas.
@@ -420,6 +477,10 @@ export function updateBlockIndex(
lineStartIndex = table.ed;
}
}
+ const paragraphLogicalStart = paragraphLogicalStartAnchors.get(line);
+ if (paragraphLogicalStart != null) {
+ lineStartIndex = Math.max(lineStartIndex, paragraphLogicalStart - 1);
+ }
if (line.type === LineType.BLOCK && divides.length === 0) {
line.st = Math.max(line.st, lineStartIndex + 1);
@@ -767,10 +828,11 @@ export function documentSkeletonTableIterator(
unitId = '',
} = options;
const contexts: IDocumentSkeletonTableContext[] = [];
+ let rootPageDocumentTop = docsTop;
pages.forEach((rootPage, pageIndex) => {
const rootPageHeight = rootPage.pageHeight === Infinity ? 0 : rootPage.pageHeight;
- const rootPageTop = (rootPageHeight + pageMarginTop) * pageIndex + rootPage.marginTop + docsTop;
+ const rootPageTop = rootPageDocumentTop + rootPage.marginTop;
const rootPageLeft = rootPage.marginLeft + docsLeft;
collectPageTables({
@@ -788,7 +850,6 @@ export function documentSkeletonTableIterator(
unitId,
});
- const rootPageDocumentTop = rootPageTop - rootPage.marginTop;
const rootPageDocumentLeft = docsLeft + rootPage.marginLeft;
const headerPage = rootPage.headerId == null ? undefined : skeHeaders?.get(rootPage.headerId)?.get(rootPage.pageWidth);
if (headerPage != null) {
@@ -848,6 +909,8 @@ export function documentSkeletonTableIterator(
});
});
});
+
+ rootPageDocumentTop += rootPageHeight + pageMarginTop;
});
return contexts;
@@ -1698,6 +1761,18 @@ export interface ILayoutContext {
sectionBreakConfigCache: Map<number, ISectionBreakConfig>;
paragraphsOpenNewPage: Set<number>;
paginationMetrics?: IDocumentPaginationMetrics;
+ /**
+ * Incremental layout may defer an expensive split-table calculation after
+ * the normal line-layout path has resolved its exact pagination context.
+ * Synchronous callers leave this unset.
+ */
+ deferSlicedTableLayout?: (request: {
+ curPage: IDocumentSkeletonPage;
+ viewModel: DocumentViewModel;
+ tableNode: DataStreamTreeNode;
+ sectionBreakConfig: ISectionBreakConfig;
+ availableHeight: number;
+ }) => boolean;
// Use for hyphenation.
hyphen: Hyphen;
// Use for detect language for paragraph content.
diff --git a/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.ts b/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.ts
index fab1683560..fc318e6f95 100644
--- a/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.ts
+++ b/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.ts
@@ -14,12 +14,49 @@
* limitations under the License.
*/
-import type { Nullable } from '@univerjs/core';
import type { DataStreamTreeNode } from '../data-stream-tree-node';
-import { DataStreamTreeNodeType, DataStreamTreeTokenType } from '@univerjs/core';
+import { DataStreamTreeNodeType, DataStreamTreeTokenType, DocumentDataModel, JSONX, TextX, TextXActionType } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
import { DocumentEditArea, DocumentViewModel, parseDataStreamToTree } from '../document-view-model';
+interface ITreeNodeSnapshot {
+ blocks: number[];
+ children: ITreeNodeSnapshot[];
+ content: string | undefined;
+ endIndex: number;
+ nodeType: DataStreamTreeNodeType;
+ startIndex: number;
+}
+
+function snapshotTreeNode(node: DataStreamTreeNode): ITreeNodeSnapshot {
+ return {
+ blocks: [...node.blocks],
+ children: node.children.map(snapshotTreeNode),
+ content: node.content,
+ endIndex: node.endIndex,
+ nodeType: node.nodeType,
+ startIndex: node.startIndex,
+ };
+}
+
+function createPlainTextActions(offset: number, deleteCount: number, insertText: string) {
+ const textX = new TextX();
+ if (offset > 0) {
+ textX.push({ t: TextXActionType.RETAIN, len: offset });
+ }
+ if (deleteCount > 0) {
+ textX.push({ t: TextXActionType.DELETE, len: deleteCount });
+ }
+ if (insertText.length > 0) {
+ textX.push({
+ t: TextXActionType.INSERT,
+ len: insertText.length,
+ body: { dataStream: insertText },
+ });
+ }
+ return JSONX.getInstance().editOp(textX.serialize(), ['body']);
+}
+
function createDocumentDataModel(overrides?: {
body?: Record<string, unknown>;
snapshot?: Record<string, unknown>;
@@ -50,7 +87,7 @@ function createDocumentDataModel(overrides?: {
} as any;
}
-function findFirstNodeByType(node: any, type: DataStreamTreeNodeType): Nullable<any> {
+function findFirstNodeByType(node: any, type: DataStreamTreeNodeType): any | null {
if (!node) return null;
if (node.nodeType === type) return node;
for (const child of node.children ?? []) {
@@ -294,6 +331,399 @@ describe('DocumentViewModel', () => {
});
describe('DocumentViewModel class', () => {
+ it('updates the data stream tree incrementally for plain text edits', () => {
+ const model = createDocumentDataModel({
+ body: {
+ dataStream: `AB${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,
+ textRuns: [{ st: 0, ed: 2, ts: { fs: 10 } }],
+ paragraphs: [{ startIndex: 0, paragraphId: 'plain-edit-paragraph' }],
+ sectionBreaks: [{ sectionId: 'plain-edit-section', startIndex: 3 }],
+ },
+ });
+ const viewModel = new DocumentViewModel(model);
+ const insertTextX = new TextX();
+ insertTextX.push({ t: TextXActionType.RETAIN, len: 1 });
+ insertTextX.push({
+ t: TextXActionType.INSERT,
+ len: 1,
+ body: { dataStream: 'X' },
+ });
+ const insertActions = JSONX.getInstance().editOp(insertTextX.serialize(), ['body']);
+ const body = model.getBody();
+ body.dataStream = `AXB${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`;
+ body.textRuns = [{ st: 0, ed: 3, ts: { fs: 10 } }];
+ body.sectionBreaks = [{ sectionId: 'plain-edit-section', startIndex: 4 }];
+
+ expect(viewModel.resetByValidatedTextMutation(model, insertActions)).toBe(true);
+ expect(viewModel.getChildren()[0].children[0].content).toBe(`AXB${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`);
+ expect(viewModel.getChildren()[0].endIndex).toBe(4);
+ expect(viewModel.getTextRun(2)?.ed).toBe(3);
+ expect(viewModel.getSectionBreak(4)?.sectionId).toBe('plain-edit-section');
+ expect(viewModel.getSectionBreak(3)).toBeUndefined();
+
+ const deleteTextX = new TextX();
+ deleteTextX.push({ t: TextXActionType.RETAIN, len: 1 });
+ deleteTextX.push({ t: TextXActionType.DELETE, len: 1 });
+ const deleteActions = JSONX.getInstance().editOp(deleteTextX.serialize(), ['body']);
+ body.dataStream = `AB${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`;
+ body.textRuns = [{ st: 0, ed: 2, ts: { fs: 10 } }];
+ body.sectionBreaks = [{ sectionId: 'plain-edit-section', startIndex: 3 }];
+
+ expect(viewModel.resetByValidatedTextMutation(model, deleteActions)).toBe(true);
+ expect(viewModel.getChildren()[0].children[0].content).toBe(`AB${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`);
+ expect(viewModel.getChildren()[0].endIndex).toBe(3);
+ expect(viewModel.getTextRun(2)).toBeUndefined();
+ expect(viewModel.getSectionBreak(3)?.sectionId).toBe('plain-edit-section');
+ expect(viewModel.getSectionBreak(4)).toBeUndefined();
+ });
+
+ it('updates nested table-cell and column-group paragraphs without rebuilding their element trees', () => {
+ const T = DataStreamTreeTokenType;
+ const tableStream = [
+ T.TABLE_START,
+ T.TABLE_ROW_START,
+ T.TABLE_CELL_START,
+ 'AB',
+ T.PARAGRAPH,
+ T.SECTION_BREAK,
+ T.TABLE_CELL_END,
+ T.TABLE_ROW_END,
+ T.TABLE_END,
+ T.PARAGRAPH,
+ T.SECTION_BREAK,
+ ].join('');
+ const tableModel = createDocumentDataModel({
+ body: {
+ dataStream: tableStream,
+ paragraphs: [
+ { startIndex: tableStream.indexOf(T.PARAGRAPH), paragraphId: 'table-cell-paragraph' },
+ { startIndex: tableStream.lastIndexOf(T.PARAGRAPH), paragraphId: 'after-table-paragraph' },
+ ],
+ sectionBreaks: [
+ { startIndex: tableStream.indexOf(T.SECTION_BREAK), sectionId: 'table-cell-section' },
+ { startIndex: tableStream.lastIndexOf(T.SECTION_BREAK), sectionId: 'table-body-section' },
+ ],
+ },
+ });
+ const tableViewModel = new DocumentViewModel(tableModel);
+ const tableInsertOffset = tableStream.indexOf('B');
+ const tableInsert = new TextX();
+ tableInsert.push({ t: TextXActionType.RETAIN, len: tableInsertOffset });
+ tableInsert.push({ t: TextXActionType.INSERT, len: 1, body: { dataStream: 'X' } });
+ const tableActions = JSONX.getInstance().editOp(tableInsert.serialize(), ['body']);
+ const tableBody = tableModel.getBody();
+ tableBody.dataStream = `${tableStream.slice(0, tableInsertOffset)}X${tableStream.slice(tableInsertOffset)}`;
+ tableBody.paragraphs = [
+ { startIndex: tableStream.indexOf(T.PARAGRAPH) + 1, paragraphId: 'table-cell-paragraph' },
+ { startIndex: tableStream.lastIndexOf(T.PARAGRAPH) + 1, paragraphId: 'after-table-paragraph' },
+ ];
+ tableBody.sectionBreaks = [
+ { startIndex: tableStream.indexOf(T.SECTION_BREAK) + 1, sectionId: 'table-cell-section' },
+ { startIndex: tableStream.lastIndexOf(T.SECTION_BREAK) + 1, sectionId: 'table-body-section' },
+ ];
+
+ expect(tableViewModel.resetByValidatedTextMutation(tableModel, tableActions)).toBe(true);
+ const tableCell = findFirstNodeByType(tableViewModel.getChildren()[0], DataStreamTreeNodeType.TABLE_CELL);
+ const tableCellParagraph = findFirstNodeByType(tableCell, DataStreamTreeNodeType.PARAGRAPH);
+ expect(tableCellParagraph?.content).toBe(`AXB${T.PARAGRAPH}${T.SECTION_BREAK}`);
+ expect(tableCell?.endIndex).toBe(tableStream.indexOf(T.TABLE_CELL_END) + 1);
+ expect(tableViewModel.getParagraph(tableStream.indexOf(T.PARAGRAPH) + 1)?.paragraphId)
+ .toBe('table-cell-paragraph');
+
+ const columnStream = [
+ T.COLUMN_GROUP_START,
+ T.COLUMN_START,
+ `Left${T.PARAGRAPH}`,
+ T.COLUMN_END,
+ T.COLUMN_START,
+ `Right${T.PARAGRAPH}`,
+ T.COLUMN_END,
+ T.COLUMN_GROUP_END,
+ T.SECTION_BREAK,
+ ].join('');
+ const columnModel = createDocumentDataModel({
+ body: {
+ dataStream: columnStream,
+ paragraphs: [
+ { startIndex: columnStream.indexOf(T.PARAGRAPH), paragraphId: 'left-column-paragraph' },
+ { startIndex: columnStream.lastIndexOf(T.PARAGRAPH), paragraphId: 'right-column-paragraph' },
+ ],
+ sectionBreaks: [{
+ startIndex: columnStream.lastIndexOf(T.SECTION_BREAK),
+ sectionId: 'column-body-section',
+ }],
+ },
+ });
+ const columnViewModel = new DocumentViewModel(columnModel);
+ const columnInsertOffset = columnStream.indexOf('Right') + 2;
+ const columnInsert = new TextX();
+ columnInsert.push({ t: TextXActionType.RETAIN, len: columnInsertOffset });
+ columnInsert.push({ t: TextXActionType.INSERT, len: 1, body: { dataStream: 'X' } });
+ const columnActions = JSONX.getInstance().editOp(columnInsert.serialize(), ['body']);
+ const columnBody = columnModel.getBody();
+ columnBody.dataStream = `${columnStream.slice(0, columnInsertOffset)}X${columnStream.slice(columnInsertOffset)}`;
+ columnBody.paragraphs = [
+ { startIndex: columnStream.indexOf(T.PARAGRAPH), paragraphId: 'left-column-paragraph' },
+ { startIndex: columnStream.lastIndexOf(T.PARAGRAPH) + 1, paragraphId: 'right-column-paragraph' },
+ ];
+ columnBody.sectionBreaks = [{
+ startIndex: columnStream.lastIndexOf(T.SECTION_BREAK) + 1,
+ sectionId: 'column-body-section',
+ }];
+
+ expect(columnViewModel.resetByValidatedTextMutation(columnModel, columnActions)).toBe(true);
+ const columnGroup = findFirstNodeByType(
+ columnViewModel.getChildren()[0],
+ DataStreamTreeNodeType.COLUMN_GROUP
+ );
+ const rightColumnParagraph = findFirstNodeByType(
+ columnGroup?.children[1],
+ DataStreamTreeNodeType.PARAGRAPH
+ );
+ expect(rightColumnParagraph?.content).toBe(`RiXght${T.PARAGRAPH}`);
+ expect(columnGroup?.endIndex).toBe(columnStream.indexOf(T.COLUMN_GROUP_END) + 1);
+ expect(columnViewModel.getParagraph(columnStream.lastIndexOf(T.PARAGRAPH) + 1)?.paragraphId)
+ .toBe('right-column-paragraph');
+ });
+
+ it('matches a fresh Main view model after sequential edits in body, table, columns, and trailing content', () => {
+ const T = DataStreamTreeTokenType;
+ const tableId = 'incremental-differential-table';
+ const columnGroupId = 'incremental-differential-columns';
+ const tableStream = [
+ T.TABLE_START,
+ T.TABLE_ROW_START,
+ T.TABLE_CELL_START,
+ `Table cell text${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ T.TABLE_CELL_END,
+ T.TABLE_ROW_END,
+ T.TABLE_END,
+ ].join('');
+ const columnGroupStream = [
+ T.COLUMN_GROUP_START,
+ T.COLUMN_START,
+ `Left column${T.PARAGRAPH}`,
+ T.COLUMN_END,
+ T.COLUMN_START,
+ `Right column${T.PARAGRAPH}`,
+ T.COLUMN_END,
+ T.COLUMN_GROUP_END,
+ ].join('');
+ const dataStream = [
+ `Top paragraph${T.PARAGRAPH}`,
+ tableStream,
+ T.PARAGRAPH,
+ columnGroupStream,
+ T.PARAGRAPH,
+ `Tail paragraph${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ ].join('');
+ const tableStart = dataStream.indexOf(T.TABLE_START);
+ const columnGroupStart = dataStream.indexOf(T.COLUMN_GROUP_START);
+ const model = new DocumentDataModel({
+ id: 'incremental-differential-document',
+ body: {
+ dataStream,
+ paragraphs: [...dataStream.matchAll(new RegExp(T.PARAGRAPH, 'g'))].map((match, index) => ({
+ startIndex: match.index,
+ paragraphId: `incremental-differential-paragraph-${index}`,
+ })),
+ sectionBreaks: [
+ {
+ sectionId: 'incremental-differential-table-section',
+ startIndex: tableStart + tableStream.indexOf(T.SECTION_BREAK),
+ },
+ {
+ sectionId: 'incremental-differential-body-section',
+ startIndex: dataStream.length - 1,
+ },
+ ],
+ tables: [{
+ startIndex: tableStart,
+ endIndex: tableStart + tableStream.length,
+ tableId,
+ }],
+ columnGroups: [{
+ startIndex: columnGroupStart,
+ endIndex: columnGroupStart + columnGroupStream.length - 1,
+ columnGroupId,
+ columns: [
+ { columnId: 'incremental-differential-left', widthRatio: 1 },
+ { columnId: 'incremental-differential-right', widthRatio: 1 },
+ ],
+ }],
+ textRuns: [
+ { st: 0, ed: dataStream.indexOf(T.PARAGRAPH), ts: { fs: 12 } },
+ {
+ st: dataStream.indexOf('Table cell text'),
+ ed: dataStream.indexOf('Table cell text') + 'Table cell text'.length,
+ ts: { fs: 14 },
+ },
+ ],
+ },
+ documentStyle: {},
+ });
+ const incrementalViewModel = new DocumentViewModel(model);
+ const operations = [
+ { deleteCount: 0, insertText: ' inserted', locate: (stream: string) => stream.indexOf(' paragraph') },
+ { deleteCount: 5, insertText: '', locate: (stream: string) => stream.indexOf('cell text') },
+ { deleteCount: 0, insertText: '宽字符', locate: (stream: string) => stream.indexOf('Right column') + 5 },
+ { deleteCount: 4, insertText: 'ending', locate: (stream: string) => stream.indexOf('Tail paragraph') + 5 },
+ ];
+
+ for (const operation of operations) {
+ const body = model.getBody();
+ if (body == null) {
+ throw new Error('Expected the differential document body');
+ }
+ const offset = operation.locate(body.dataStream);
+ expect(offset).toBeGreaterThanOrEqual(0);
+ const actions = createPlainTextActions(offset, operation.deleteCount, operation.insertText);
+ model.apply(actions);
+
+ expect(incrementalViewModel.resetByValidatedTextMutation(model, actions)).toBe(true);
+ const rebuiltViewModel = new DocumentViewModel(model);
+ expect(incrementalViewModel.getChildren().map(snapshotTreeNode)).toEqual(
+ rebuiltViewModel.getChildren().map(snapshotTreeNode)
+ );
+ const incrementalTableNode = incrementalViewModel.findTableNodeById(tableId);
+ const rebuiltTableNode = rebuiltViewModel.findTableNodeById(tableId);
+ if (incrementalTableNode == null || rebuiltTableNode == null) {
+ throw new Error('Expected both differential table nodes');
+ }
+ expect(snapshotTreeNode(incrementalTableNode)).toEqual(snapshotTreeNode(rebuiltTableNode));
+ const currentBody = model.getBody();
+ if (currentBody == null) {
+ throw new Error('Expected the mutated differential document body');
+ }
+ const currentColumnGroupStart = currentBody.columnGroups?.[0]?.startIndex;
+ if (currentColumnGroupStart == null) {
+ throw new Error('Expected the differential column group metadata');
+ }
+ expect(incrementalViewModel.getColumnGroupByStartIndex(currentColumnGroupStart)?.columnGroup).toEqual(
+ rebuiltViewModel.getColumnGroupByStartIndex(currentColumnGroupStart)?.columnGroup
+ );
+ for (let index = 0; index < currentBody.dataStream.length; index++) {
+ expect(incrementalViewModel.getParagraph(index)).toEqual(rebuiltViewModel.getParagraph(index));
+ expect(incrementalViewModel.getSectionBreak(index)).toEqual(rebuiltViewModel.getSectionBreak(index));
+ expect(incrementalViewModel.getTextRun(index)).toEqual(rebuiltViewModel.getTextRun(index));
+ }
+ rebuiltViewModel.dispose();
+ }
+
+ incrementalViewModel.dispose();
+ model.dispose();
+ });
+
+ it('matches a fresh Main view model for disjoint edits and falls back across paragraph boundaries', () => {
+ const T = DataStreamTreeTokenType;
+ const dataStream = `Alpha${T.PARAGRAPH}Beta${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const model = new DocumentDataModel({
+ id: 'incremental-disjoint-document',
+ body: {
+ dataStream,
+ paragraphs: [
+ { startIndex: dataStream.indexOf(T.PARAGRAPH), paragraphId: 'incremental-disjoint-first' },
+ { startIndex: dataStream.lastIndexOf(T.PARAGRAPH), paragraphId: 'incremental-disjoint-second' },
+ ],
+ sectionBreaks: [{
+ startIndex: dataStream.length - 1,
+ sectionId: 'incremental-disjoint-section',
+ }],
+ },
+ documentStyle: {},
+ });
+ const incrementalViewModel = new DocumentViewModel(model);
+ const disjointTextX = new TextX();
+ disjointTextX.push({ t: TextXActionType.RETAIN, len: 2 });
+ disjointTextX.push({ t: TextXActionType.INSERT, len: 1, body: { dataStream: 'X' } });
+ disjointTextX.push({ t: TextXActionType.RETAIN, len: 6 });
+ disjointTextX.push({ t: TextXActionType.INSERT, len: 1, body: { dataStream: 'Y' } });
+ const disjointActions = JSONX.getInstance().editOp(disjointTextX.serialize(), ['body']);
+ model.apply(disjointActions);
+ expect(incrementalViewModel.resetByValidatedTextMutation(model, disjointActions)).toBe(true);
+
+ const rebuiltAfterDisjoint = new DocumentViewModel(model);
+ expect(incrementalViewModel.getChildren().map(snapshotTreeNode)).toEqual(
+ rebuiltAfterDisjoint.getChildren().map(snapshotTreeNode)
+ );
+ rebuiltAfterDisjoint.dispose();
+
+ const currentDataStream = model.getBody()?.dataStream;
+ if (currentDataStream == null) {
+ throw new Error('Expected the disjoint document body');
+ }
+ const paragraphBoundary = currentDataStream.indexOf(T.PARAGRAPH);
+ const crossingActions = createPlainTextActions(paragraphBoundary - 1, 3, 'Z');
+ model.apply(crossingActions);
+ expect(incrementalViewModel.resetByValidatedTextMutation(model, crossingActions)).toBe(false);
+ incrementalViewModel.reset(model);
+
+ const rebuiltAfterFallback = new DocumentViewModel(model);
+ expect(incrementalViewModel.getChildren().map(snapshotTreeNode)).toEqual(
+ rebuiltAfterFallback.getChildren().map(snapshotTreeNode)
+ );
+ rebuiltAfterFallback.dispose();
+ incrementalViewModel.dispose();
+ model.dispose();
+ });
+
+ it('resolves shifted paragraph metadata without rebuilding whole-document caches', () => {
+ const model = createDocumentDataModel({
+ body: {
+ dataStream: `A${DataStreamTreeTokenType.PARAGRAPH}B${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,
+ paragraphs: [
+ { startIndex: 0, paragraphId: 'first' },
+ { startIndex: 2, paragraphId: 'second' },
+ ],
+ sectionBreaks: [{ sectionId: 'section', startIndex: 4 }],
+ },
+ });
+ const viewModel = new DocumentViewModel(model);
+ const insertTextX = new TextX();
+ insertTextX.push({ t: TextXActionType.RETAIN, len: 1 });
+ insertTextX.push({
+ t: TextXActionType.INSERT,
+ len: 1,
+ body: { dataStream: 'X' },
+ });
+ const actions = JSONX.getInstance().editOp(insertTextX.serialize(), ['body']);
+ const body = model.getBody();
+ body.dataStream = `AX${DataStreamTreeTokenType.PARAGRAPH}B${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`;
+ body.paragraphs = [
+ { startIndex: 0, paragraphId: 'first' },
+ { startIndex: 3, paragraphId: 'second' },
+ ];
+ body.sectionBreaks = [{ sectionId: 'section', startIndex: 5 }];
+
+ expect(viewModel.resetByValidatedTextMutation(model, actions)).toBe(true);
+ expect(viewModel.getParagraph(3)?.paragraphId).toBe('second');
+ expect(viewModel.getParagraph(2)).toBeUndefined();
+ expect(viewModel.getSectionBreak(5)?.sectionId).toBe('section');
+ });
+
+ it('indexes long and overlapping text runs by range buckets', () => {
+ const content = 'A'.repeat(2005);
+ const model = createDocumentDataModel({
+ body: {
+ dataStream: `${content}${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,
+ textRuns: [
+ { st: 0, ed: content.length, ts: { fs: 10 } },
+ { st: 995, ed: 1005, ts: { fs: 20 } },
+ { st: 1500, ed: 1500, ts: { fs: 30 } },
+ ],
+ },
+ });
+
+ const viewModel = new DocumentViewModel(model);
+ expect(viewModel.getTextRun(0)?.ts?.fs).toBe(10);
+ expect(viewModel.getTextRun(994)?.ts?.fs).toBe(10);
+ expect(viewModel.getTextRun(995)?.ts?.fs).toBe(20);
+ expect(viewModel.getTextRun(1004)?.ts?.fs).toBe(20);
+ expect(viewModel.getTextRun(1005)?.ts?.fs).toBe(10);
+ expect(viewModel.getTextRun(2004)?.ts?.fs).toBe(10);
+ expect(viewModel.getTextRun(2005)).toBeUndefined();
+ });
+
it('covers cache/interceptor/reset/header-footer flows', () => {
const headerModel = createDocumentDataModel({
body: {
@@ -383,6 +813,9 @@ describe('DocumentViewModel', () => {
viewModel.reset(newModel);
expect(viewModel.getDataModel()).toBe(newModel);
expect(viewModel.getTextRun(0)?.ed).toBe(1);
+ expect(viewModel.getSectionBreak(2)).toBeUndefined();
+ expect(viewModel.getCustomBlock(1)).toBeUndefined();
+ expect(viewModel.getTableByStartIndex(3)).toBeUndefined();
expect(viewModel.findTableNodeById('not-exists')).toBeUndefined();
const maps = viewModel.getHeaderFooterTreeMap();
diff --git a/packages/engine-render/src/components/docs/view-model/document-view-model.ts b/packages/engine-render/src/components/docs/view-model/document-view-model.ts
index 219ae9cf76..14436e3b8f 100644
--- a/packages/engine-render/src/components/docs/view-model/document-view-model.ts
+++ b/packages/engine-render/src/components/docs/view-model/document-view-model.ts
@@ -14,22 +14,16 @@
* limitations under the License.
*/
-import type {
- DocumentDataModel,
- IColumnGroup,
- ICustomBlock,
- ICustomColumnGroup,
- ICustomDecorationForInterceptor,
- ICustomRangeForInterceptor,
- ICustomTable,
- IDisposable,
- IParagraph,
- ISectionBreak,
- ITable,
- ITextRun,
- Nullable,
+import type { DocumentDataModel, IColumnGroup, ICustomBlock, ICustomColumnGroup, ICustomDecorationForInterceptor, ICustomRangeForInterceptor, ICustomTable, IDisposable, IParagraph, ISectionBreak, ITable, ITextRun, JSONXActions, JSONXPath, Nullable } from '@univerjs/core';
+import {
+ DataStreamTreeNodeType,
+ DataStreamTreeTokenType,
+ getRichTextEditPath,
+ JSON1,
+ TextX,
+ TextXActionType,
+ toDisposable,
} from '@univerjs/core';
-import { DataStreamTreeNodeType, DataStreamTreeTokenType, toDisposable } from '@univerjs/core';
import { BehaviorSubject } from 'rxjs';
import { DataStreamTreeNode } from './data-stream-tree-node';
@@ -42,6 +36,165 @@ interface ITableNodeCache {
table: DataStreamTreeNode;
}
+interface ITextRunCacheBucket {
+ runs: ITextRun[];
+ isOrderedAndDisjoint: boolean;
+}
+
+interface IDataStreamMutationEdit {
+ offset: number;
+ deleteCount: number;
+ insertText: string;
+}
+
+interface IStartIndexedItem {
+ startIndex: number;
+}
+
+function isOrderedByStartIndex(items: readonly IStartIndexedItem[]): boolean {
+ for (let index = 1; index < items.length; index++) {
+ if (items[index - 1].startIndex > items[index].startIndex) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+function findByStartIndex<T extends IStartIndexedItem>(
+ items: readonly T[],
+ startIndex: number,
+ isOrdered: boolean
+): T | undefined {
+ if (!isOrdered) {
+ return items.find((item) => item.startIndex === startIndex);
+ }
+
+ let low = 0;
+ let high = items.length - 1;
+ while (low <= high) {
+ const middle = Math.floor((low + high) / 2);
+ const item = items[middle];
+ if (startIndex < item.startIndex) {
+ high = middle - 1;
+ } else if (startIndex > item.startIndex) {
+ low = middle + 1;
+ } else {
+ return item;
+ }
+ }
+}
+
+function findOrderedTextRun(textRuns: readonly ITextRun[], index: number): ITextRun | undefined {
+ let low = 0;
+ let high = textRuns.length - 1;
+ while (low <= high) {
+ const middle = Math.floor((low + high) / 2);
+ const textRun = textRuns[middle];
+ if (index < textRun.st) {
+ high = middle - 1;
+ } else if (index >= textRun.ed) {
+ low = middle + 1;
+ } else {
+ return textRun;
+ }
+ }
+}
+
+function findFirstNodeStartingAtOrAfter(nodes: readonly DataStreamTreeNode[], startIndex: number): number {
+ let low = 0;
+ let high = nodes.length;
+ while (low < high) {
+ const middle = Math.floor((low + high) / 2);
+ if (nodes[middle].startIndex < startIndex) {
+ low = middle + 1;
+ } else {
+ high = middle;
+ }
+ }
+ return low;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value != null && !Array.isArray(value);
+}
+
+function pathsEqual(left: JSONXPath, right: JSONXPath): boolean {
+ return left.length === right.length && left.every((item, index) => item === right[index]);
+}
+
+const DATA_STREAM_TREE_TOKEN_PATTERN_SOURCE = `[${[
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.SECTION_BREAK,
+ DataStreamTreeTokenType.TABLE_START,
+ DataStreamTreeTokenType.TABLE_ROW_START,
+ DataStreamTreeTokenType.TABLE_CELL_START,
+ DataStreamTreeTokenType.TABLE_CELL_END,
+ DataStreamTreeTokenType.TABLE_ROW_END,
+ DataStreamTreeTokenType.TABLE_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_START,
+ DataStreamTreeTokenType.COLUMN_START,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_END,
+ DataStreamTreeTokenType.BLOCK_START,
+ DataStreamTreeTokenType.BLOCK_END,
+ DataStreamTreeTokenType.CUSTOM_BLOCK,
+].join('')}]`;
+
+function getDataStreamMutationEdits(
+ actions: JSONXActions,
+ expectedPath: JSONXPath
+): IDataStreamMutationEdit[] | null {
+ const cursor = JSON1.type.readCursor(actions);
+ const edits: IDataStreamMutationEdit[] = [];
+ let currentOffset = 0;
+ let componentCount = 0;
+ let isSupported = true;
+
+ cursor.traverse(null, (component) => {
+ componentCount++;
+ if (
+ componentCount !== 1 ||
+ component.et !== TextX.id ||
+ !pathsEqual(cursor.getPath(), expectedPath) ||
+ !Array.isArray(component.e)
+ ) {
+ isSupported = false;
+ return;
+ }
+
+ for (const action of component.e) {
+ if (!isRecord(action) || typeof action.len !== 'number' || !Number.isFinite(action.len) || action.len < 0) {
+ isSupported = false;
+ return;
+ }
+
+ if (action.t === TextXActionType.RETAIN) {
+ currentOffset += action.len;
+ } else if (action.t === TextXActionType.DELETE) {
+ edits.push({ offset: currentOffset, deleteCount: action.len, insertText: '' });
+ } else if (action.t === TextXActionType.INSERT) {
+ const dataStream = isRecord(action.body) ? action.body.dataStream : undefined;
+ if (
+ typeof dataStream !== 'string' ||
+ dataStream.length !== action.len ||
+ new RegExp(DATA_STREAM_TREE_TOKEN_PATTERN_SOURCE).test(dataStream)
+ ) {
+ isSupported = false;
+ return;
+ }
+ edits.push({ offset: currentOffset, deleteCount: 0, insertText: dataStream });
+ currentOffset += action.len;
+ } else {
+ isSupported = false;
+ return;
+ }
+ }
+ });
+
+ return isSupported && componentCount === 1 ? edits : null;
+}
+
export interface ICustomRangeInterceptor {
getCustomRange: (index: number) => Nullable<ICustomRangeForInterceptor>;
getCustomDecoration: (index: number) => Nullable<ICustomDecorationForInterceptor>;
@@ -74,10 +227,18 @@ function batchParent(
}
export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[]) {
- let content = '';
- const dataStreamLen = dataStream.length;
+ let contentStartIndex = 0;
const sectionList: DataStreamTreeNode[] = [];
const tableNodeCache: Map<string, ITableNodeCache> = new Map();
+ const tablesByRange = new Map<number, Map<number, ICustomTable>>();
+ for (const table of tables ?? []) {
+ let tablesByEnd = tablesByRange.get(table.startIndex);
+ if (tablesByEnd == null) {
+ tablesByEnd = new Map();
+ tablesByRange.set(table.startIndex, tablesByEnd);
+ }
+ tablesByEnd.set(table.endIndex, table);
+ }
// Only use to cache the outer paragraphs.
const paragraphList: DataStreamTreeNode[] = [];
// Each open table cell owns its paragraphs. A single shared list makes an
@@ -114,11 +275,13 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[
return false;
};
- for (let i = 0; i < dataStreamLen; i++) {
- const char = dataStream[i];
+ const tokenPattern = new RegExp(DATA_STREAM_TREE_TOKEN_PATTERN_SOURCE, 'g');
+ for (const match of dataStream.matchAll(tokenPattern)) {
+ const i = match.index;
+ const char = match[0];
if (char === DataStreamTreeTokenType.PARAGRAPH) {
- content += DataStreamTreeTokenType.PARAGRAPH;
+ const content = dataStream.slice(contentStartIndex, i + 1);
const paragraphNode = DataStreamTreeNode.create(DataStreamTreeNodeType.PARAGRAPH, content);
let wrappedTableStartIndex: number | undefined;
@@ -129,21 +292,21 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[
batchParent(paragraphNode, [lastTableCache.table], DataStreamTreeNodeType.PARAGRAPH);
wrappedTableStartIndex = lastTableCache.table.startIndex;
- if (tables) {
- const table = tables.find((table) => table.startIndex === lastTableCache.table.startIndex && table.endIndex === lastTableCache.table.endIndex + 1);
- if (table) {
- tableNodeCache.set(table.tableId, { table: lastTableCache.table });
- }
+ const table = tablesByRange
+ .get(lastTableCache.table.startIndex)
+ ?.get(lastTableCache.table.endIndex + 1);
+ if (table) {
+ tableNodeCache.set(table.tableId, { table: lastTableCache.table });
}
tableList.pop();
}
// Paragraph start and end index is from the first char of the paragraph to the last char of the paragraph. not include the Table content.
- paragraphNode.setIndexRange(wrappedTableStartIndex ?? i - content.length + 1, i);
+ paragraphNode.setIndexRange(wrappedTableStartIndex ?? contentStartIndex, i);
paragraphNode.addBlocks(currentBlocks);
currentBlocks.length = 0;
- content = '';
+ contentStartIndex = i + 1;
if (tableCellList.length > 0) {
cellParagraphLists[cellParagraphLists.length - 1].push(paragraphNode);
@@ -154,6 +317,7 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[
}
} else if (char === DataStreamTreeTokenType.SECTION_BREAK) {
const sectionNode = DataStreamTreeNode.create(DataStreamTreeNodeType.SECTION_BREAK);
+ const content = dataStream.slice(contentStartIndex, i);
const tempParagraphList = tableCellList.length > 0
? cellParagraphLists[cellParagraphLists.length - 1]
: columnGroupList.length > 0
@@ -172,7 +336,6 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[
blockParagraph.addBlocks(currentBlocks);
tempParagraphList.push(blockParagraph);
currentBlocks.length = 0;
- content = '';
}
if (tempParagraphList.length === 0) {
@@ -200,6 +363,7 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[
}
tempParagraphList.length = 0;
+ contentStartIndex = i + 1;
} else if (char === DataStreamTreeTokenType.TABLE_START) {
const tableNode = DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE);
@@ -207,24 +371,28 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[
table: tableNode,
isFinished: false,
});
+ contentStartIndex = i + 1;
} else if (char === DataStreamTreeTokenType.TABLE_ROW_START) {
const rowNode = DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE_ROW);
tableRowList.push(rowNode);
+ contentStartIndex = i + 1;
} else if (char === DataStreamTreeTokenType.TABLE_CELL_START) {
const cellNode = DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE_CELL);
tableCellList.push(cellNode);
cellParagraphLists.push([]);
+ contentStartIndex = i + 1;
} else if (char === DataStreamTreeTokenType.TABLE_END) {
const lastTable = tableList[tableList.length - 1];
lastTable.isFinished = true;
- content = '';
+ contentStartIndex = i + 1;
} else if (char === DataStreamTreeTokenType.TABLE_ROW_END) {
const rowNode = tableRowList.pop();
const lastTableCache = tableList[tableList.length - 1];
batchParent(lastTableCache.table, [rowNode!], DataStreamTreeNodeType.TABLE);
+ contentStartIndex = i + 1;
} else if (char === DataStreamTreeTokenType.TABLE_CELL_END) {
const cellNode = tableCellList.pop();
cellParagraphLists.pop();
@@ -232,16 +400,19 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[
const lastRow = tableRowList[tableRowList.length - 1];
batchParent(lastRow, [cellNode!], DataStreamTreeNodeType.TABLE_ROW);
+ contentStartIndex = i + 1;
} else if (char === DataStreamTreeTokenType.COLUMN_GROUP_START) {
const columnGroupNode = DataStreamTreeNode.create(DataStreamTreeNodeType.COLUMN_GROUP);
columnGroupNode.setIndexRange(i, i);
columnGroupList.push(columnGroupNode);
+ contentStartIndex = i + 1;
} else if (char === DataStreamTreeTokenType.COLUMN_START) {
const columnNode = DataStreamTreeNode.create(DataStreamTreeNodeType.COLUMN);
columnNode.setIndexRange(i, i);
columnList.push(columnNode);
+ contentStartIndex = i + 1;
} else if (char === DataStreamTreeTokenType.COLUMN_END) {
const columnNode = columnList[columnList.length - 1];
const columnChildren = columnSectionList.length > 0 ? columnSectionList : columnParagraphList;
@@ -251,6 +422,7 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[
columnNode.setIndexRange(columnStartIndex, i);
columnParagraphList.length = 0;
columnSectionList.length = 0;
+ contentStartIndex = i + 1;
} else if (char === DataStreamTreeTokenType.COLUMN_GROUP_END) {
const columnGroupNode = columnGroupList.pop();
const columnGroupStartIndex = columnGroupNode!.startIndex;
@@ -261,18 +433,13 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[
columnList.length = 0;
columnParagraphList.length = 0;
columnSectionList.length = 0;
- content = '';
- } else if (char === DataStreamTreeTokenType.BLOCK_START) {
- content += char;
+ contentStartIndex = i + 1;
} else if (char === DataStreamTreeTokenType.BLOCK_END) {
- if (content.length > 0 || !appendToPreviousParagraph(char)) {
- content += char;
+ if (contentStartIndex === i && appendToPreviousParagraph(char)) {
+ contentStartIndex = i + 1;
}
} else if (char === DataStreamTreeTokenType.CUSTOM_BLOCK) {
currentBlocks.push(i);
- content += char;
- } else {
- content += char;
}
}
@@ -294,7 +461,7 @@ export class DocumentViewModel implements IDisposable {
private _cacheSize = 1000;
- private _textRunsCache: Map<number, Map<number, ITextRun>> = new Map();
+ private _textRunsCache: Map<number, ITextRunCacheBucket> = new Map();
private _paragraphCache: Map<number, IParagraph> = new Map();
@@ -310,6 +477,28 @@ export class DocumentViewModel implements IDisposable {
private _children: DataStreamTreeNode[] = [];
+ private _treeNodes: DataStreamTreeNode[] = [];
+
+ private _treeNodesByStartIndex: DataStreamTreeNode[] = [];
+
+ private _plainTopLevelParagraphNodes: DataStreamTreeNode[] = [];
+
+ private _metadataCachesDirty = false;
+
+ private _textRunsOrderedAndDisjoint = true;
+
+ private _paragraphsOrdered = true;
+
+ private _sectionBreaksOrdered = true;
+
+ private _customBlocksOrdered = true;
+
+ private _tablesOrdered = true;
+
+ private _columnGroupsOrdered = true;
+
+ private _lastTextRun: Nullable<ITextRun> = null;
+
private _editArea: DocumentEditArea = DocumentEditArea.BODY;
private readonly _editAreaChange$ = new BehaviorSubject<Nullable<DocumentEditArea>>(null);
@@ -329,10 +518,10 @@ export class DocumentViewModel implements IDisposable {
const body = _documentDataModel.getBody()!;
const { sectionList, tableNodeCache } = parseDataStreamToTree(body.dataStream, body.tables);
- this._buildAllCache();
-
this._children = sectionList;
this._tableNodeCache = tableNodeCache;
+ this._rebuildTreeNodes();
+ this._buildAllCache();
this._buildHeaderFooterViewModel();
}
@@ -355,6 +544,10 @@ export class DocumentViewModel implements IDisposable {
this._tableCache.clear();
this._columnGroupCache.clear();
this._tableNodeCache.clear();
+ this._treeNodes = [];
+ this._treeNodesByStartIndex = [];
+ this._plainTopLevelParagraphNodes = [];
+ this._lastTextRun = null;
// this._headerTreeMap.clear();
// this._footerTreeMap.clear();
this._segmentViewModels$.complete();
@@ -412,6 +605,15 @@ export class DocumentViewModel implements IDisposable {
}
reset(documentDataModel: DocumentDataModel) {
+ this._children.forEach((child) => child.dispose());
+ this._textRunsCache.clear();
+ this._paragraphCache.clear();
+ this._sectionBreakCache.clear();
+ this._customBlockCache.clear();
+ this._tableCache.clear();
+ this._columnGroupCache.clear();
+ this._tableNodeCache.clear();
+
this._documentDataModel = documentDataModel;
const body = documentDataModel.getBody()!;
@@ -421,27 +623,100 @@ export class DocumentViewModel implements IDisposable {
this._children = sectionList;
this._tableNodeCache = tableNodeCache;
+ this._rebuildTreeNodes();
this._buildAllCache();
this._buildHeaderFooterViewModel();
}
+ resetByValidatedTextMutation(documentDataModel: DocumentDataModel, actions: JSONXActions): boolean {
+ const edits = getDataStreamMutationEdits(actions, getRichTextEditPath(documentDataModel));
+ if (edits == null) {
+ return false;
+ }
+
+ for (const edit of edits) {
+ if (edit.deleteCount > 0 && !this._deletePlainText(edit.offset, edit.deleteCount)) {
+ return false;
+ }
+ if (edit.insertText.length > 0 && !this._insertPlainText(edit.offset, edit.insertText)) {
+ return false;
+ }
+ }
+
+ this._documentDataModel = documentDataModel;
+ this._metadataCachesDirty = true;
+ this._lastTextRun = null;
+ if (!this._textRunsOrderedAndDisjoint) {
+ this._buildTextRunsCache();
+ }
+ return true;
+ }
+
getSectionBreak(index: number) {
+ if (this._metadataCachesDirty) {
+ return findByStartIndex(this.getBody()?.sectionBreaks ?? [], index, this._sectionBreaksOrdered);
+ }
return this._sectionBreakCache.get(index);
}
getParagraph(index: number) {
+ if (this._metadataCachesDirty) {
+ return findByStartIndex(this.getBody()?.paragraphs ?? [], index, this._paragraphsOrdered);
+ }
return this._paragraphCache.get(index);
}
getTextRun(index: number): Nullable<ITextRun> {
+ if (this._metadataCachesDirty && this._textRunsOrderedAndDisjoint) {
+ if (this._lastTextRun != null && index >= this._lastTextRun.st && index < this._lastTextRun.ed) {
+ return this._lastTextRun;
+ }
+
+ const textRun = findOrderedTextRun(this.getBody()?.textRuns ?? [], index);
+ this._lastTextRun = textRun ?? null;
+ return textRun;
+ }
+
const cacheIndex = Math.floor(index / this._cacheSize);
- const textRunsCache = this._textRunsCache.get(cacheIndex);
+ const bucket = this._textRunsCache.get(cacheIndex);
+ if (bucket == null) {
+ return;
+ }
+
+ if (bucket.isOrderedAndDisjoint) {
+ let low = 0;
+ let high = bucket.runs.length - 1;
+ while (low <= high) {
+ const middle = Math.floor((low + high) / 2);
+ const textRun = bucket.runs[middle];
+ if (index < textRun.st) {
+ high = middle - 1;
+ } else if (index >= textRun.ed) {
+ low = middle + 1;
+ } else {
+ return textRun;
+ }
+ }
- return textRunsCache?.get(index % this._cacheSize);
+ return;
+ }
+
+ // The previous per-character cache assigned runs in source order, so an
+ // overlapping later run won. Preserve that behavior without materializing
+ // one Map entry for every styled character in a large document.
+ for (let runIndex = bucket.runs.length - 1; runIndex >= 0; runIndex--) {
+ const textRun = bucket.runs[runIndex];
+ if (index >= textRun.st && index < textRun.ed) {
+ return textRun;
+ }
+ }
}
getCustomBlock(index: number) {
+ if (this._metadataCachesDirty) {
+ return findByStartIndex(this.getBody()?.customBlocks ?? [], index, this._customBlocksOrdered);
+ }
return this._customBlockCache.get(index);
}
@@ -459,10 +734,43 @@ export class DocumentViewModel implements IDisposable {
}
getTableByStartIndex(index: number) {
+ if (this._metadataCachesDirty) {
+ const table = findByStartIndex(this.getBody()?.tables ?? [], index, this._tablesOrdered);
+ const tableSource = table == null
+ ? undefined
+ : (this._tableSource ?? this.getSnapshot().tableSource)?.[table.tableId];
+ if (table == null || tableSource == null) {
+ return;
+ }
+
+ return { table, tableSource };
+ }
return this._tableCache.get(index);
}
getColumnGroupByStartIndex(index: number) {
+ if (this._metadataCachesDirty) {
+ const columnGroup = findByStartIndex(
+ this.getBody()?.columnGroups ?? [],
+ index,
+ this._columnGroupsOrdered
+ );
+ if (columnGroup?.columns == null) {
+ return;
+ }
+
+ const cachedColumnGroup = Array.from(this._columnGroupCache.values()).find(
+ (value) => value.columnGroup.columnGroupId === columnGroup.columnGroupId
+ );
+ if (cachedColumnGroup == null) {
+ return;
+ }
+
+ return {
+ columnGroup,
+ columnGroupSource: cachedColumnGroup.columnGroupSource,
+ };
+ }
return this._columnGroupCache.get(index);
}
@@ -515,6 +823,8 @@ export class DocumentViewModel implements IDisposable {
}
private _buildAllCache() {
+ this._metadataCachesDirty = false;
+ this._lastTextRun = null;
this._buildTextRunsCache();
this._buildParagraphCache();
this._buildSectionBreakCache();
@@ -523,10 +833,126 @@ export class DocumentViewModel implements IDisposable {
this._buildColumnGroupCache();
}
+ private _insertPlainText(offset: number, text: string): boolean {
+ const target = this._findParagraphNode(offset, offset);
+ if (target == null) {
+ return false;
+ }
+
+ const nodePath = this._collectNodePath(target);
+
+ target.insertText(text, offset);
+ const suffixStart = findFirstNodeStartingAtOrAfter(this._treeNodesByStartIndex, offset);
+ for (let index = suffixStart; index < this._treeNodesByStartIndex.length; index++) {
+ this._treeNodesByStartIndex[index].plus(text.length);
+ }
+ for (const { node, startIndex } of nodePath) {
+ if (startIndex < offset) {
+ node.selfPlus(text.length, offset);
+ } else if (startIndex === offset) {
+ // The suffix shift already updated the end and block offsets.
+ // A containing node keeps its start when text is inserted at its
+ // boundary, so restore only that coordinate.
+ node.startIndex -= text.length;
+ }
+ }
+ return true;
+ }
+
+ private _deletePlainText(offset: number, deleteCount: number): boolean {
+ const endOffset = offset + deleteCount;
+ const target = this._findParagraphNode(offset, endOffset);
+ if (target == null) {
+ return false;
+ }
+
+ const nodePath = this._collectNodePath(target);
+
+ target.minus(offset, endOffset - 1);
+ target.blocks = target.blocks
+ .filter((blockOffset) => blockOffset < offset || blockOffset >= endOffset)
+ .map((blockOffset) => blockOffset >= endOffset ? blockOffset - deleteCount : blockOffset);
+ const suffixStart = findFirstNodeStartingAtOrAfter(this._treeNodesByStartIndex, endOffset);
+ for (let index = suffixStart; index < this._treeNodesByStartIndex.length; index++) {
+ this._treeNodesByStartIndex[index].plus(-deleteCount);
+ }
+ for (const { node, startIndex } of nodePath.slice(1)) {
+ if (startIndex < endOffset) {
+ node.selfPlus(-deleteCount, endOffset);
+ }
+ }
+ return true;
+ }
+
+ private _findParagraphNode(startOffset: number, endOffset: number): DataStreamTreeNode | null {
+ let low = 0;
+ let high = this._plainTopLevelParagraphNodes.length - 1;
+ while (low <= high) {
+ const middle = Math.floor((low + high) / 2);
+ const node = this._plainTopLevelParagraphNodes[middle];
+ const containsEmptyPosition = node.startIndex === startOffset && node.endIndex === startOffset - 1;
+ if (startOffset < node.startIndex) {
+ high = middle - 1;
+ } else if (startOffset > node.endIndex && !containsEmptyPosition) {
+ low = middle + 1;
+ } else if (endOffset <= startOffset || endOffset - 1 <= node.endIndex) {
+ return node;
+ } else {
+ break;
+ }
+ }
+
+ let match: DataStreamTreeNode | null = null;
+ for (const node of this._treeNodes) {
+ if (node.nodeType !== DataStreamTreeNodeType.PARAGRAPH) {
+ continue;
+ }
+
+ const containsStart = node.startIndex <= startOffset && startOffset <= node.endIndex;
+ const containsEmptyPosition = node.startIndex === startOffset && node.endIndex === startOffset - 1;
+ const containsEnd = endOffset <= startOffset || endOffset - 1 <= node.endIndex;
+ if ((!containsStart && !containsEmptyPosition) || !containsEnd) {
+ continue;
+ }
+
+ if (match == null || node.endIndex - node.startIndex < match.endIndex - match.startIndex) {
+ match = node;
+ }
+ }
+ return match;
+ }
+
+ private _rebuildTreeNodes(): void {
+ const nodes: DataStreamTreeNode[] = [];
+ const visit = (node: DataStreamTreeNode): void => {
+ nodes.push(node);
+ node.children.forEach(visit);
+ };
+ this._children.forEach(visit);
+ this._treeNodes = nodes;
+ this._treeNodesByStartIndex = nodes.toSorted((left, right) => left.startIndex - right.startIndex);
+ this._plainTopLevelParagraphNodes = this._children.flatMap((section) =>
+ section.children.filter(
+ (node) => node.nodeType === DataStreamTreeNodeType.PARAGRAPH && node.children.length === 0
+ )
+ );
+ }
+
+ private _collectNodePath(node: DataStreamTreeNode): Array<{ node: DataStreamTreeNode; startIndex: number }> {
+ const nodePath: Array<{ node: DataStreamTreeNode; startIndex: number }> = [];
+ let current: Nullable<DataStreamTreeNode> = node;
+ while (current != null) {
+ nodePath.push({ node: current, startIndex: current.startIndex });
+ current = current.parent;
+ }
+ return nodePath;
+ }
+
private _buildParagraphCache() {
this._paragraphCache.clear();
const paragraphs = this.getBody()?.paragraphs ?? [];
+ this._paragraphsOrdered = isOrderedByStartIndex(paragraphs);
for (const paragraph of paragraphs) {
const { startIndex } = paragraph;
@@ -537,6 +963,7 @@ export class DocumentViewModel implements IDisposable {
private _buildSectionBreakCache() {
this._sectionBreakCache.clear();
const sectionBreaks = this.getBody()?.sectionBreaks ?? [];
+ this._sectionBreaksOrdered = isOrderedByStartIndex(sectionBreaks);
for (const sectionBreak of sectionBreaks) {
const { startIndex } = sectionBreak;
@@ -547,6 +974,7 @@ export class DocumentViewModel implements IDisposable {
private _buildCustomBlockCache() {
this._customBlockCache.clear();
const customBlocks = this.getBody()?.customBlocks ?? [];
+ this._customBlocksOrdered = isOrderedByStartIndex(customBlocks);
for (const customBlock of customBlocks) {
const { startIndex } = customBlock;
@@ -558,6 +986,7 @@ export class DocumentViewModel implements IDisposable {
this._tableCache.clear();
const tables = this.getBody()?.tables;
+ this._tablesOrdered = isOrderedByStartIndex(tables ?? []);
const tableConfig = this._tableSource ?? this.getSnapshot().tableSource;
if (tables == null || tableConfig == null) {
return;
@@ -582,6 +1011,7 @@ export class DocumentViewModel implements IDisposable {
this._columnGroupCache.clear();
const columnGroups = this.getBody()?.columnGroups;
+ this._columnGroupsOrdered = isOrderedByStartIndex(columnGroups ?? []);
if (columnGroups == null) {
return;
}
@@ -602,18 +1032,40 @@ export class DocumentViewModel implements IDisposable {
private _buildTextRunsCache() {
const textRuns = this.getBody()?.textRuns ?? [];
this._textRunsCache.clear();
+ this._textRunsOrderedAndDisjoint = true;
+ let previousStart = Number.NEGATIVE_INFINITY;
+ let furthestEnd = Number.NEGATIVE_INFINITY;
for (const textRun of textRuns) {
const { st, ed } = textRun;
+ if (previousStart > st || furthestEnd > st) {
+ this._textRunsOrderedAndDisjoint = false;
+ }
+ previousStart = st;
+ furthestEnd = Math.max(furthestEnd, ed);
+ if (ed <= st) {
+ continue;
+ }
- for (let i = st; i < ed; i++) {
- const cacheIndex = Math.floor(i / this._cacheSize);
-
- if (!this._textRunsCache.has(cacheIndex)) {
- this._textRunsCache.set(cacheIndex, new Map());
+ const startCacheIndex = Math.floor(st / this._cacheSize);
+ const endCacheIndex = Math.floor((ed - 1) / this._cacheSize);
+ for (let cacheIndex = startCacheIndex; cacheIndex <= endCacheIndex; cacheIndex++) {
+ let bucket = this._textRunsCache.get(cacheIndex);
+ if (bucket == null) {
+ bucket = { runs: [], isOrderedAndDisjoint: true };
+ this._textRunsCache.set(cacheIndex, bucket);
}
- this._textRunsCache.get(cacheIndex)!.set(i % this._cacheSize, textRun);
+ bucket.runs.push(textRun);
+ }
+ }
+
+ for (const bucket of this._textRunsCache.values()) {
+ for (let runIndex = 1; runIndex < bucket.runs.length; runIndex++) {
+ if (bucket.runs[runIndex - 1].ed > bucket.runs[runIndex].st) {
+ bucket.isOrderedAndDisjoint = false;
+ break;
+ }
}
}
}
diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.ts
index 9466184340..c08abbd58d 100644
--- a/packages/engine-render/src/index.ts
+++ b/packages/engine-render/src/index.ts
@@ -60,6 +60,18 @@ export {
export * from './components/docs/layout/doc-simple-skeleton';
export { DocumentSkeleton } from './components/docs/layout/doc-skeleton';
export type { IFindNodeRestrictions } from './components/docs/layout/doc-skeleton';
+export type { IDocumentLayoutPagePublication } from './components/docs/layout/document-layout-publication';
+export type {
+ DocumentLayoutMode,
+ DocumentLayoutReason,
+ IDocumentLayoutApplyResult,
+ IDocumentLayoutInvalidation,
+ IDocumentLayoutPageRange,
+ IDocumentLayoutProgress,
+ IDocumentLayoutProtectedContinuousRange,
+ IDocumentLayoutProtectedPageRange,
+ IDocumentLayoutProtectedRange,
+} from './components/docs/layout/document-layout-types';
export {
compareDocumentSkeletonNestedPagePathOrder,
documentSkeletonLineIterator,
@@ -115,3 +127,5 @@ export * from './scroll-timer';
export { CanvasColorService, DumbCanvasColorService, ICanvasColorService } from './services/canvas-color.service';
export * from './shape';
export * from './viewport';
+export { DocumentLayoutSession } from './worker-layout';
+export type { IDocumentLayoutSessionStartOptions, IDocumentLayoutStepResult } from './worker-layout';
diff --git a/packages/engine-render/src/scene.transformer.ts b/packages/engine-render/src/scene.transformer.ts
index 7846f0cfc4..d95761ef43 100644
--- a/packages/engine-render/src/scene.transformer.ts
+++ b/packages/engine-render/src/scene.transformer.ts
@@ -1985,6 +1985,9 @@ export class Transformer extends Disposable implements ITransformerConfig {
const targetObject = this._findGroupObject(applyObject);
if (this._selectedObjectMap.has(targetObject.oKey)) {
+ if (!this._transformerControlMap.has(targetObject.oKey)) {
+ this._createControl(targetObject);
+ }
return;
}
diff --git a/packages/engine-render/src/worker-layout.ts b/packages/engine-render/src/worker-layout.ts
new file mode 100644
index 0000000000..0aa0ea6a93
--- /dev/null
+++ b/packages/engine-render/src/worker-layout.ts
@@ -0,0 +1,326 @@
+/**
+ * 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, LocaleService, Nullable } from '@univerjs/core';
+import type { IDocumentSkeletonCached, IDocumentSkeletonPage } from './basics/i-document-skeleton-cached';
+import type { IDocumentSkeletonContinuousSnapshot, IDocumentSkeletonPagePatch } from './components/docs/layout/document-layout-page-patch';
+import type {
+ IDocumentLayoutGeometryPublication,
+ IDocumentLayoutPagePublication,
+ IDocumentLayoutResourcePublication,
+} from './components/docs/layout/document-layout-publication';
+import type { DocumentLayoutReason, IDocumentLayoutInvalidation, IDocumentLayoutProgress } from './components/docs/layout/document-layout-types';
+import { Disposable } from '@univerjs/core';
+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';
+
+export interface IDocumentLayoutSessionStartOptions {
+ reason?: DocumentLayoutReason;
+ anchor?: number;
+ priorityAnchor?: number;
+ invalidation?: IDocumentLayoutInvalidation;
+}
+
+export interface IDocumentLayoutStepResult {
+ progress: IDocumentLayoutProgress;
+ publication: IDocumentLayoutGeometryPublication | null;
+}
+
+/**
+ * Worker-safe owner of the document view model and incremental layout state.
+ * Scheduling, transport, presentation and model revision ordering belong to callers.
+ */
+export class DocumentLayoutSession extends Disposable {
+ private readonly _viewModel: DocumentViewModel;
+ private readonly _skeleton: DocumentSkeleton;
+ private _lastPublishedPageCount = 0;
+ private _layoutReason: DocumentLayoutReason = 'initial';
+ private _didPublishEditAnchor = false;
+ private _continuousPageSnapshot: IDocumentSkeletonContinuousSnapshot | null = null;
+ private _continuousReplacementOffset: number | undefined;
+ private readonly _publishedHeaderPages = new Map<string, Map<number, IDocumentSkeletonPage>>();
+ private readonly _publishedFooterPages = new Map<string, Map<number, IDocumentSkeletonPage>>();
+ private _resetPublishedResources = true;
+ private _pendingPaginatedCompletion: IDocumentLayoutProgress | null = null;
+
+ constructor(dataModel: DocumentDataModel, localeService: LocaleService) {
+ super();
+ this._viewModel = new DocumentViewModel(dataModel);
+ this._skeleton = DocumentSkeleton.create(this._viewModel, localeService, {
+ isolateIncrementalPublications: false,
+ });
+ }
+
+ start(options?: IDocumentLayoutSessionStartOptions): number {
+ this._lastPublishedPageCount = 0;
+ this._layoutReason = options?.reason ?? 'initial';
+ this._didPublishEditAnchor = false;
+ this._publishedHeaderPages.clear();
+ this._publishedFooterPages.clear();
+ this._resetPublishedResources = true;
+ this._pendingPaginatedCompletion = null;
+ if (options?.reason !== 'edit') {
+ this._continuousPageSnapshot = null;
+ }
+ this._continuousReplacementOffset = options?.reason === 'edit'
+ ? options.invalidation?.oldStart ?? options.anchor
+ : undefined;
+ const generation = this._skeleton.startIncrementalLayout({
+ ...options,
+ reuseUnaffectedTail: true,
+ });
+ const progress = this._skeleton.getLayoutProgress();
+ this._lastPublishedPageCount = progress?.mode === 'paginated'
+ ? progress.publishedPageCount
+ : 0;
+ return generation;
+ }
+
+ step(
+ generation: number,
+ budgetMs = 8,
+ maxWorkUnits = Number.POSITIVE_INFINITY
+ ): IDocumentLayoutStepResult {
+ if (this._pendingPaginatedCompletion?.generation === generation) {
+ return this._publishPaginatedCompletionBacklog();
+ }
+ return this._collectPublications(
+ this._skeleton.stepIncrementalLayout(generation, budgetMs, maxWorkUnits)
+ );
+ }
+
+ publishBacklog(generation: number): IDocumentLayoutStepResult {
+ if (this._pendingPaginatedCompletion?.generation === generation) {
+ return this._publishPaginatedCompletionBacklog();
+ }
+ return this._collectPublications(this._skeleton.publishIncrementalLayoutBacklog(generation));
+ }
+
+ getPage(pageIndex: number): IDocumentLayoutPagePublication | null {
+ const page = this._skeleton.getSkeletonData()?.pages[pageIndex];
+ if (page == null || page.isLayoutPlaceholder) {
+ return null;
+ }
+ return {
+ pageIndex,
+ page: serializeDocumentSkeletonPage(page, true),
+ };
+ }
+
+ cancel(generation?: number): void {
+ if (generation == null || this._pendingPaginatedCompletion?.generation === generation) {
+ this._pendingPaginatedCompletion = null;
+ }
+ this._skeleton.cancelIncrementalLayout(generation);
+ }
+
+ resetDataModel(dataModel: DocumentDataModel): void {
+ this.cancel();
+ this._viewModel.reset(dataModel);
+ this._skeleton.makeDirty(true);
+ this._lastPublishedPageCount = 0;
+ this._continuousReplacementOffset = undefined;
+ this._pendingPaginatedCompletion = null;
+ }
+
+ getProgress(): Nullable<IDocumentLayoutProgress> {
+ return this._skeleton.getLayoutProgress();
+ }
+
+ static hydratePage(
+ publication: IDocumentLayoutPagePublication,
+ snapshot?: ReturnType<DocumentDataModel['getSnapshot']>
+ ): IDocumentSkeletonPage {
+ return hydrateDocumentSkeletonPage(publication.page, undefined, snapshot);
+ }
+
+ override dispose(): void {
+ this._skeleton.dispose();
+ super.dispose();
+ }
+
+ private _collectPublications(progress: IDocumentLayoutProgress): IDocumentLayoutStepResult {
+ if (!progress.didPublish) {
+ return { progress, publication: null };
+ }
+
+ if (
+ progress.complete &&
+ progress.mode === 'paginated' &&
+ progress.publishedPageCount > this._lastPublishedPageCount + 1
+ ) {
+ this._pendingPaginatedCompletion = progress;
+ return this._publishPaginatedCompletionBacklog();
+ }
+
+ return this._collectPublication(progress);
+ }
+
+ private _publishPaginatedCompletionBacklog(): IDocumentLayoutStepResult {
+ const completion = this._pendingPaginatedCompletion;
+ if (completion == null) {
+ throw new Error('Document layout has no paginated completion backlog.');
+ }
+ const publishedPageCount = Math.min(
+ completion.publishedPageCount,
+ this._lastPublishedPageCount + 1
+ );
+ const complete = publishedPageCount === completion.publishedPageCount;
+ const progress: IDocumentLayoutProgress = {
+ ...completion,
+ publicationRevision: completion.publicationRevision + publishedPageCount,
+ didPublish: true,
+ didPublishAnchor: completion.didPublishAnchor && !this._didPublishEditAnchor,
+ publishedPageCount,
+ complete,
+ };
+ if (complete) {
+ this._pendingPaginatedCompletion = null;
+ }
+ return this._collectPublication(progress);
+ }
+
+ private _collectPublication(progress: IDocumentLayoutProgress): IDocumentLayoutStepResult {
+ const skeletonData = this._skeleton.getSkeletonData();
+ if (skeletonData == null) {
+ throw new Error('Document layout reported a publication without skeleton data.');
+ }
+
+ const resources = this._collectResourcePublication(skeletonData, progress.complete);
+
+ if (progress.mode === 'continuous') {
+ const page = skeletonData.pages[0];
+ if (page == null) {
+ throw new Error('Continuous document layout reported a publication without a logical page.');
+ }
+ const { block, snapshot } = serializeDocumentSkeletonContinuousBlock(
+ page,
+ this._continuousPageSnapshot,
+ this._continuousReplacementOffset,
+ true
+ );
+ this._continuousPageSnapshot = snapshot;
+ this._continuousReplacementOffset = undefined;
+ return {
+ progress,
+ publication: {
+ kind: 'block',
+ left: skeletonData.left,
+ top: skeletonData.top,
+ st: skeletonData.st,
+ ...(skeletonData.ed == null ? {} : { ed: skeletonData.ed }),
+ block,
+ resources,
+ },
+ };
+ }
+
+ const endPageIndex = progress.publishedPageCount;
+ const publishEditAnchor = this._layoutReason === 'edit' &&
+ progress.didPublishAnchor &&
+ !this._didPublishEditAnchor;
+ const startPageIndex = publishEditAnchor
+ ? Math.min(this._lastPublishedPageCount, Math.max(0, endPageIndex - 1))
+ : this._lastPublishedPageCount;
+ const pages = skeletonData.pages
+ .slice(startPageIndex, endPageIndex)
+ .map((page, offset): IDocumentLayoutPagePublication => ({
+ pageIndex: startPageIndex + offset,
+ page: serializeDocumentSkeletonPage(page, true),
+ }));
+ this._lastPublishedPageCount = Math.max(this._lastPublishedPageCount, endPageIndex);
+ this._didPublishEditAnchor ||= publishEditAnchor;
+
+ return {
+ progress,
+ publication: {
+ kind: 'page',
+ left: skeletonData.left,
+ top: skeletonData.top,
+ st: skeletonData.st,
+ ...(skeletonData.ed == null ? {} : { ed: skeletonData.ed }),
+ pages,
+ resources,
+ },
+ };
+ }
+
+ private _collectResourcePublication(
+ skeletonData: IDocumentSkeletonCached,
+ complete: boolean
+ ): IDocumentLayoutResourcePublication {
+ // Width-dependent header/footer pages can be created speculatively while
+ // pagination converges and then removed from the final source cache. Delta
+ // publications cannot express that removal, so the completion publication
+ // is an authoritative resource snapshot rather than another additive patch.
+ if (complete) {
+ this._publishedHeaderPages.clear();
+ this._publishedFooterPages.clear();
+ }
+ const collect = (
+ source: typeof skeletonData.skeHeaders,
+ published: Map<string, Map<number, IDocumentSkeletonPage>>
+ ): IDocumentLayoutResourcePublication['skeHeaders'] => {
+ const patches: IDocumentLayoutResourcePublication['skeHeaders'] = [];
+ for (const [segmentId, pagesByWidth] of source) {
+ let publishedPagesByWidth = published.get(segmentId);
+ if (publishedPagesByWidth == null) {
+ publishedPagesByWidth = new Map();
+ published.set(segmentId, publishedPagesByWidth);
+ }
+
+ const pagePatches: Array<[number, IDocumentSkeletonPagePatch]> = [];
+ for (const [width, page] of pagesByWidth) {
+ if (publishedPagesByWidth.get(width) === page) {
+ continue;
+ }
+ publishedPagesByWidth.set(width, page);
+ pagePatches.push([width, serializeDocumentSkeletonPage(page, true)]);
+ }
+ if (pagePatches.length > 0) {
+ patches.push([segmentId, pagePatches]);
+ }
+ }
+ return patches;
+ };
+ const reset = this._resetPublishedResources || complete;
+ this._resetPublishedResources = false;
+ return {
+ reset,
+ skeHeaders: collect(skeletonData.skeHeaders, this._publishedHeaderPages),
+ skeFooters: collect(skeletonData.skeFooters, this._publishedFooterPages),
+ skeListLevel: complete
+ ? [...(skeletonData.skeListLevel ?? [])].map(([listId, levels]) => [
+ listId,
+ levels.map((level) => level.map(({ bullet, paragraph }) => ({ bullet, paragraph }))),
+ ])
+ : null,
+ drawingAnchor: complete
+ ? [...(skeletonData.drawingAnchor ?? [])].map(([segmentId, anchors]) => [
+ segmentId,
+ [...anchors].map(([paragraphIndex, anchor]) => [
+ paragraphIndex,
+ {
+ paragraphIndex: anchor.paragraphIndex,
+ top: anchor.top,
+ },
+ ]),
+ ])
+ : null,
+ };
+ }
+}
diff --git a/packages/rpc/src/services/rpc/__tests__/rpc.service.edge.spec.ts b/packages/rpc/src/services/rpc/__tests__/rpc.service.edge.spec.ts
index b8d3e6237b..306d3a94e9 100644
--- a/packages/rpc/src/services/rpc/__tests__/rpc.service.edge.spec.ts
+++ b/packages/rpc/src/services/rpc/__tests__/rpc.service.edge.spec.ts
@@ -175,10 +175,23 @@ describe('rpc.service edge cases', () => {
protocol.emit({ seq: subscribeSeq, type: SUBSCRIBE_COMPLETE });
stream.unsubscribe();
- (client as unknown as { _disposed: boolean })._disposed = true;
+ const pendingCall = channel.call('pending');
+ const subscriptionError = vi.fn();
+ channel.subscribe('pending$').subscribe({ error: subscriptionError });
+ client.dispose();
+
+ await expect(pendingCall).rejects.toThrow('[ChannelClient]: client is disposed!');
+ expect(subscriptionError).toHaveBeenCalledWith(expect.objectContaining({
+ message: '[ChannelClient]: client is disposed!',
+ }));
await expect(channel.call('disposed')).rejects.toThrow('[ChannelClient]: client is disposed!');
expect(() => channel.subscribe('disposed$')).toThrow('[ChannelClient]: client is disposed!');
client.dispose();
+
+ const uninitializedClient = new ChannelClient(new TestMessageProtocol() as IMessageProtocol);
+ const waitingCall = uninitializedClient.getChannel('waiting').call('pending');
+ uninitializedClient.dispose();
+ await expect(waitingCall).rejects.toThrow('[ChannelClient]: client is disposed!');
});
it('ChannelServer should handle request branches, call/subscribe failures and unsubscription', async () => {
@@ -260,6 +273,15 @@ describe('rpc.service edge cases', () => {
protocol.emit({ type: UNSUBSCRIBE, seq: 30, channelName: 'stream', method: 'stream$' });
expect(unsubscribed).toBe(true);
+ let disposedSubscription = false;
+ server.registerChannel('dispose-stream', {
+ call: async () => true,
+ subscribe: () => new Observable<string>(() => () => {
+ disposedSubscription = true;
+ }),
+ } as IChannel);
+ protocol.emit({ type: SUBSCRIBE, seq: 31, channelName: 'dispose-stream', method: 'stream$' });
server.dispose();
+ expect(disposedSubscription).toBe(true);
});
});
diff --git a/packages/rpc/src/services/rpc/rpc.service.ts b/packages/rpc/src/services/rpc/rpc.service.ts
index 4865552768..8f5813677d 100644
--- a/packages/rpc/src/services/rpc/rpc.service.ts
+++ b/packages/rpc/src/services/rpc/rpc.service.ts
@@ -180,6 +180,7 @@ interface IRPCResponse {
interface IResponseHandler {
handle(response: IRPCResponse): void;
+ dispose(error: Error): void;
}
/**
@@ -199,7 +200,17 @@ export class ChannelClient extends RxDisposable implements IChannelClient {
}
override dispose(): void {
+ if (this._disposed) {
+ return;
+ }
+
+ const error = new Error('[ChannelClient]: client is disposed!');
+ this._initialized.error(error);
+ for (const responseHandler of this._pendingRequests.values()) {
+ responseHandler.dispose(error);
+ }
this._pendingRequests.clear();
+ super.dispose();
}
getChannel<T extends IChannel>(channelName: string): T {
@@ -263,6 +274,9 @@ export class ChannelClient extends RxDisposable implements IChannelClient {
throw new Error('[ChannelClient]: unknown response type!');
}
},
+ dispose(error: Error) {
+ reject(error);
+ },
};
this._pendingRequests.set(sequence, responseHandler);
@@ -295,6 +309,9 @@ export class ChannelClient extends RxDisposable implements IChannelClient {
throw new Error('[ChannelClient]: unknown response type!');
}
},
+ dispose(error: Error) {
+ subscriber.error(error);
+ },
};
this._pendingRequests.set(sequence, responseHandler);
@@ -364,6 +381,9 @@ export class ChannelServer extends RxDisposable implements IChannelServer {
override dispose(): void {
super.dispose();
+ for (const subscription of this._subscriptions.values()) {
+ subscription.unsubscribe();
+ }
this._subscriptions.clear();
this._channels.clear();
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f3576074b8..f31aa02a44 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -809,6 +809,9 @@ importers:
'@univerjs/protocol':
specifier: workspace:*
version: link:../protocol
+ '@univerjs/rpc':
+ specifier: workspace:*
+ version: link:../rpc
devDependencies:
'@univerjs-infra/shared':
specifier: workspace:*