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.

perf(docs): localize incremental layout work (#7630)

Univerdee08c357c97
diff --git a/packages/docs-ui/src/controllers/__tests__/doc-mutation-layout.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-mutation-layout.spec.ts
new file mode 100644
index 0000000000..5c92fc6e62
--- /dev/null
+++ b/packages/docs-ui/src/controllers/__tests__/doc-mutation-layout.spec.ts
@@ -0,0 +1,57 @@
+/**
+ * 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 { JSONX } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { getDocumentMutationLayoutImpact } from '../render-controllers/doc-mutation-layout';
+
+describe('document mutation layout range index', () => {
+ it('indexes table ranges once for a composed table mutation', () => {
+ const tableCount = 1_000;
+ let indexedReads = 0;
+ const tables = new Proxy(Array.from({ length: tableCount }, (_, index) => ({
+ tableId: `table-${index}`,
+ startIndex: index * 10,
+ endIndex: index * 10 + 9,
+ })), {
+ get(target, property, receiver) {
+ if (typeof property === 'string' && /^\d+$/.test(property)) {
+ indexedReads++;
+ }
+ return Reflect.get(target, property, receiver);
+ },
+ });
+ const jsonX = JSONX.getInstance();
+ const actions = JSONX.compose(JSONX.compose(
+ jsonX.replaceOp(['tableSource', 'table-999', 'tableColumns', 0], { width: 100 }, { width: 110 }),
+ jsonX.replaceOp(['tableSource', 'table-999', 'tableColumns', 1], { width: 100 }, { width: 120 })
+ ), jsonX.replaceOp(['tableSource', 'table-999', 'tableColumns', 2], { width: 100 }, { width: 130 }));
+ indexedReads = 0;
+
+ const impact = getDocumentMutationLayoutImpact(actions, {
+ body: { dataStream: '', tables } as unknown as NonNullable<IDocumentData['body']>,
+ styles: {},
+ });
+
+ expect(impact).toEqual({
+ global: false,
+ range: { start: 9_990, end: 9_999 },
+ unresolvedLocal: false,
+ });
+ expect(indexedReads).toBeLessThanOrEqual(tableCount + 1);
+ });
+});
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 50746f25bf..a8a49f7d0a 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
@@ -16,9 +16,9 @@
// @vitest-environment jsdom
-import type { ICommandInfo, IExecutionOptions } from '@univerjs/core';
+import type { ICommandInfo, IDocumentData, IExecutionOptions } from '@univerjs/core';
import type { IDocLayoutMountIdentity } from '@univerjs/docs';
-import { CustomDecorationType, CustomRangeType, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DocumentFlavor, JSONX, PositionedObjectLayoutType } from '@univerjs/core';
+import { CustomDecorationType, CustomRangeType, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DocumentFlavor, JSONX, PositionedObjectLayoutType, TextXActionType } from '@univerjs/core';
import { DocLayoutSessionStatus, RichTextEditingMutation } from '@univerjs/docs';
import { BehaviorSubject, Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
@@ -166,6 +166,7 @@ function createControllerFixture(options?: {
drawings?: Record<string, {
layoutType: PositionedObjectLayoutType;
}>;
+ snapshot?: Partial<IDocumentData>;
hasCompleteLayout?: boolean;
initialSkeletonDataMissing?: boolean;
useWorker?: boolean;
@@ -309,6 +310,7 @@ function createControllerFixture(options?: {
documentFlavor: options?.documentFlavor ?? DocumentFlavor.TRADITIONAL,
},
drawings: options?.drawings,
+ ...options?.snapshot,
})),
},
scene: {
@@ -666,6 +668,36 @@ describe('doc render controller', () => {
expect(skeletonManager.getSkeleton().startIncrementalLayout).toHaveBeenCalledTimes(1);
});
+ it('preserves a bounded changeset invalidation instead of restarting at zero', async () => {
+ const { commandCallbacks, skeletonManager } = createControllerFixture({
+ snapshot: {
+ body: {
+ dataStream: 'x'.repeat(10_000),
+ tables: [{ tableId: 'table-1', startIndex: 4_000, endIndex: 8_000 }],
+ },
+ },
+ });
+ const mutation = {
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: JSONX.getInstance().replaceOp(
+ ['tableSource', 'table-1', 'tableColumns', 0, 'size', 'width', 'v'],
+ 100,
+ 120
+ ),
+ },
+ } satisfies ICommandInfo;
+
+ commandCallbacks[0](mutation, { fromChangeset: true });
+ await Promise.resolve();
+
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).toHaveBeenCalledWith(expect.objectContaining({
+ anchor: 4_000,
+ invalidation: { oldStart: 4_000, oldEnd: 8_000, newEnd: 8_000 },
+ }));
+ });
+
it('does not start document layout when an overlay-only drawing moves', () => {
const { commandCallbacks, skeletonManager } = createControllerFixture({
drawings: {
@@ -691,6 +723,24 @@ describe('doc render controller', () => {
expect(skeletonManager.recalculate).not.toHaveBeenCalled();
});
+ it('does not start document layout when only the drawing stacking order changes', () => {
+ const { commandCallbacks, skeletonManager } = createControllerFixture();
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: JSONX.getInstance().moveOp(
+ ['drawingsOrder', 0],
+ ['drawingsOrder', 1]
+ ),
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).not.toHaveBeenCalled();
+ expect(skeletonManager.recalculate).not.toHaveBeenCalled();
+ });
+
it.each([
PositionedObjectLayoutType.INLINE,
PositionedObjectLayoutType.WRAP_SQUARE,
@@ -720,6 +770,32 @@ describe('doc render controller', () => {
}));
});
+ it.each([
+ PositionedObjectLayoutType.INLINE,
+ PositionedObjectLayoutType.WRAP_SQUARE,
+ ])('does not reflow when only drawing accessibility metadata changes (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', 'title'],
+ 'Old title',
+ 'New title'
+ ),
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).not.toHaveBeenCalled();
+ expect(skeletonManager.recalculate).not.toHaveBeenCalled();
+ });
+
it('reflows when a drawing switches between wrapping and overlay layout', () => {
const { commandCallbacks, skeletonManager } = createControllerFixture({
drawings: {
@@ -1717,6 +1793,313 @@ describe('doc render controller', () => {
expect(backScrollController.scrollToRange).not.toHaveBeenCalled();
});
+ it('derives the incremental invalidation from a body TextX edit composed with table metadata', () => {
+ const { commandCallbacks, skeletonManager } = createControllerFixture({
+ snapshot: {
+ body: {
+ dataStream: 'x'.repeat(2_000),
+ tables: [{ tableId: 'table-1', startIndex: 1_200, endIndex: 1_800 }],
+ },
+ },
+ });
+ const textAction = JSONX.getInstance().editOp([
+ { t: TextXActionType.RETAIN, len: 1_500 },
+ { t: TextXActionType.INSERT, len: 1, body: { dataStream: 'Z' } },
+ ], ['body']);
+ const tableAction = JSONX.getInstance().replaceOp(
+ ['tableSource', 'table-1', 'tableRows', 0, 'trHeight', 'val', 'v'],
+ 20,
+ 24
+ );
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ textRanges: null,
+ actions: JSONX.compose(textAction, tableAction),
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).toHaveBeenCalledWith(expect.objectContaining({
+ anchor: 1_200,
+ invalidation: {
+ oldStart: 1_200,
+ oldEnd: 1_799,
+ newEnd: 1_800,
+ },
+ }));
+ });
+
+ it('keeps a deleted table on its TextX invalidation instead of restarting at zero', () => {
+ const { commandCallbacks, skeletonManager } = createControllerFixture({
+ snapshot: {
+ body: {
+ dataStream: 'x'.repeat(6_000),
+ tables: [],
+ },
+ },
+ });
+ const textAction = JSONX.getInstance().editOp([
+ { t: TextXActionType.RETAIN, len: 4_000 },
+ { t: TextXActionType.DELETE, len: 1_000 },
+ ], ['body']);
+ const tableAction = JSONX.getInstance().removeOp(['tableSource', 'table-1'], { tableId: 'table-1' });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ textRanges: [{ startOffset: 4_000, endOffset: 4_000, collapsed: true }],
+ actions: JSONX.compose(textAction, tableAction),
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).toHaveBeenCalledWith(expect.objectContaining({
+ anchor: 4_000,
+ invalidation: {
+ oldStart: 4_000,
+ oldEnd: 5_000,
+ newEnd: 4_000,
+ },
+ }));
+ });
+
+ it.each([
+ {
+ name: 'table metadata',
+ actions: JSONX.getInstance().replaceOp(
+ ['tableSource', 'table-1', 'tableColumns', 0, 'size', 'width', 'v'],
+ 100,
+ 120
+ ),
+ snapshot: {
+ body: {
+ dataStream: 'x'.repeat(10_000),
+ tables: [{ tableId: 'table-1', startIndex: 4_000, endIndex: 8_000 }],
+ },
+ },
+ expected: { oldStart: 4_000, oldEnd: 8_000, newEnd: 8_000 },
+ },
+ {
+ name: 'column-group metadata',
+ actions: JSONX.getInstance().replaceOp(
+ ['body', 'columnGroups', 0, 'columns', 0, 'widthRatio'],
+ 1,
+ 2
+ ),
+ snapshot: {
+ body: {
+ dataStream: 'x'.repeat(10_000),
+ columnGroups: [{
+ columnGroupId: 'columns-1',
+ startIndex: 3_000,
+ endIndex: 6_999,
+ columns: [],
+ }],
+ },
+ },
+ expected: { oldStart: 3_000, oldEnd: 7_000, newEnd: 7_000 },
+ },
+ {
+ name: 'block-range metadata',
+ actions: JSONX.getInstance().replaceOp(
+ ['body', 'blockRanges', 0, 'blockType'],
+ 'quote',
+ 'code'
+ ),
+ snapshot: {
+ body: {
+ dataStream: 'x'.repeat(10_000),
+ blockRanges: [{
+ blockId: 'block-1',
+ blockType: 'code',
+ startIndex: 2_500,
+ endIndex: 2_999,
+ }],
+ },
+ },
+ expected: { oldStart: 2_500, oldEnd: 3_000, newEnd: 3_000 },
+ },
+ {
+ name: 'layout-participating drawing metadata',
+ actions: JSONX.getInstance().replaceOp(
+ ['drawings', 'drawing-1', 'docTransform', 'size', 'height'],
+ 100,
+ 140
+ ),
+ snapshot: {
+ body: {
+ dataStream: 'x'.repeat(10_000),
+ customBlocks: [{ blockId: 'drawing-1', startIndex: 7_500 }],
+ },
+ drawings: {
+ 'drawing-1': {
+ drawingId: 'drawing-1',
+ layoutType: PositionedObjectLayoutType.INLINE,
+ },
+ },
+ },
+ expected: { oldStart: 7_500, oldEnd: 7_501, newEnd: 7_501 },
+ },
+ {
+ name: 'list metadata',
+ actions: JSONX.getInstance().replaceOp(
+ ['lists', 'list-1', 'nestingLevel', 0, 'glyphFormat'],
+ '%1.',
+ '(%1)'
+ ),
+ snapshot: {
+ body: {
+ dataStream: 'x'.repeat(10_000),
+ paragraphs: [{
+ paragraphId: 'paragraph-1',
+ startIndex: 2_000,
+ bullet: { listId: 'list-1', listType: 'ordered', nestingLevel: 0 },
+ }, {
+ paragraphId: 'paragraph-2',
+ startIndex: 8_000,
+ bullet: { listId: 'list-1', listType: 'ordered', nestingLevel: 0 },
+ }],
+ },
+ },
+ expected: { oldStart: 2_000, oldEnd: 8_001, newEnd: 8_001 },
+ },
+ {
+ name: 'a rendered page break',
+ actions: JSONX.getInstance().replaceOp(
+ ['body', 'renderedPageBreaks', 0],
+ 5_000,
+ 5_100
+ ),
+ snapshot: {
+ body: {
+ dataStream: 'x'.repeat(10_000),
+ renderedPageBreaks: [5_100],
+ },
+ },
+ expected: { oldStart: 5_000, oldEnd: 5_101, newEnd: 5_101 },
+ },
+ {
+ name: 'a referenced document style and its dependent style',
+ actions: JSONX.getInstance().replaceOp(
+ ['styles', 'base-style', 'paragraphStyle', 'spaceBelow', 'v'],
+ 0,
+ 12
+ ),
+ snapshot: {
+ body: {
+ dataStream: 'x'.repeat(10_000),
+ paragraphs: [{
+ paragraphId: 'paragraph-1',
+ startIndex: 3_000,
+ styleId: 'base-style',
+ }, {
+ paragraphId: 'paragraph-2',
+ startIndex: 7_000,
+ styleId: 'dependent-style',
+ }],
+ },
+ styles: {
+ 'base-style': { name: 'Base', type: 1 },
+ 'dependent-style': { name: 'Dependent', type: 1, basedOn: 'base-style' },
+ },
+ },
+ expected: { oldStart: 3_000, oldEnd: 7_001, newEnd: 7_001 },
+ },
+ ])('derives a bounded invalidation for $name', ({ actions, expected, snapshot }) => {
+ const { commandCallbacks, skeletonManager } = createControllerFixture({
+ snapshot: snapshot as Partial<IDocumentData>,
+ drawings: snapshot.drawings as never,
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ textRanges: null,
+ actions,
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).toHaveBeenCalledWith(expect.objectContaining({
+ anchor: expected.oldStart,
+ invalidation: expected,
+ }));
+ });
+
+ it('hands the bounded table invalidation to the Worker instead of restarting at zero', async () => {
+ vi.useFakeTimers();
+ try {
+ const { commandCallbacks, controller, layoutExecutorService } = createControllerFixture({
+ useWorker: true,
+ snapshot: {
+ body: {
+ dataStream: 'x'.repeat(10_000),
+ tables: [{ tableId: 'table-1', startIndex: 4_000, endIndex: 8_000 }],
+ },
+ },
+ 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: JSONX.getInstance().replaceOp(
+ ['tableSource', 'table-1', 'tableColumns', 0, 'size', 'width', 'v'],
+ 100,
+ 120
+ ),
+ },
+ } satisfies ICommandInfo);
+ await vi.advanceTimersByTimeAsync(150);
+
+ expect(layoutExecutorService.startLayout).toHaveBeenCalledWith(
+ expect.anything(),
+ {
+ reason: 'edit',
+ anchor: 4_000,
+ priorityAnchor: 4_000,
+ invalidation: { oldStart: 4_000, oldEnd: 8_000, newEnd: 8_000 },
+ },
+ expect.any(Number)
+ );
+ controller.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps document-wide mutations on the conservative document-start path', () => {
+ const { commandCallbacks, skeletonManager } = createControllerFixture();
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: JSONX.getInstance().replaceOp(
+ ['documentStyle', 'marginTop'],
+ 72,
+ 96
+ ),
+ },
+ } satisfies ICommandInfo);
+
+ expect(skeletonManager.getSkeleton().startIncrementalLayout).toHaveBeenCalledWith(expect.objectContaining({
+ anchor: 0,
+ invalidation: undefined,
+ }));
+ });
+
it('marks layout-metadata-only mutations as safe for structural tail reuse', () => {
const { commandCallbacks, controller, skeletonManager } = createControllerFixture({
pages: [
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-mutation-layout.ts b/packages/docs-ui/src/controllers/render-controllers/doc-mutation-layout.ts
new file mode 100644
index 0000000000..2ab2db59e6
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-mutation-layout.ts
@@ -0,0 +1,411 @@
+/**
+ * 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 { IDocStyles, IDocumentBody, IDocumentData, JSONXActions } from '@univerjs/core';
+import type { IDocumentLayoutInvalidation } from '@univerjs/engine-render';
+import { JSON1, TextX } from '@univerjs/core';
+
+interface IDocumentLayoutRange {
+ end: number;
+ start: number;
+}
+
+export interface IDocumentMutationLayoutImpact {
+ global: boolean;
+ range?: IDocumentLayoutRange;
+ unresolvedLocal?: boolean;
+}
+
+const BODY_RANGE_COLLECTIONS = new Set<keyof IDocumentBody>([
+ 'blockRanges',
+ 'columnGroups',
+ 'customBlocks',
+ 'customDecorations',
+ 'customRanges',
+ 'paragraphs',
+ 'renderedPageBreaks',
+ 'sectionBreaks',
+ 'tables',
+ 'textRuns',
+]);
+
+class DocumentMutationLayoutIndex {
+ private _tableRanges: Map<string, IDocumentLayoutRange> | null = null;
+ private _drawingRanges: Map<string, IDocumentLayoutRange> | null = null;
+ private _listRanges: Map<string, IDocumentLayoutRange> | null = null;
+ private _styleRanges: Map<string, IDocumentLayoutRange> | null = null;
+ private _styleDependents: Map<string, string[]> | null = null;
+
+ constructor(
+ private readonly _body: IDocumentBody | undefined,
+ private readonly _styles: IDocStyles | undefined
+ ) {}
+
+ getTableRange(tableId: string): IDocumentLayoutRange | undefined {
+ if (this._tableRanges == null) {
+ this._tableRanges = new Map();
+ for (const table of this._body?.tables ?? []) {
+ if (!this._tableRanges.has(table.tableId)) {
+ this._tableRanges.set(table.tableId, { start: table.startIndex, end: table.endIndex });
+ }
+ }
+ }
+ return this._tableRanges.get(tableId);
+ }
+
+ getDrawingRange(drawingId: string): IDocumentLayoutRange | undefined {
+ if (this._drawingRanges == null) {
+ this._drawingRanges = new Map();
+ for (const block of this._body?.customBlocks ?? []) {
+ if (!this._drawingRanges.has(block.blockId)) {
+ this._drawingRanges.set(block.blockId, { start: block.startIndex, end: block.startIndex + 1 });
+ }
+ }
+ }
+ return this._drawingRanges.get(drawingId);
+ }
+
+ getListRange(listIds: Set<string>): IDocumentLayoutRange | undefined {
+ this._ensureParagraphRanges();
+ return mergeRangesById(this._listRanges!, listIds);
+ }
+
+ getStyleRange(styleIds: Set<string>): IDocumentLayoutRange | undefined {
+ this._ensureParagraphRanges();
+ if (this._styleDependents == null) {
+ this._styleDependents = new Map();
+ for (const [styleId, style] of Object.entries(this._styles ?? {})) {
+ if (style.basedOn == null) {
+ continue;
+ }
+ const dependents = this._styleDependents.get(style.basedOn) ?? [];
+ dependents.push(styleId);
+ this._styleDependents.set(style.basedOn, dependents);
+ }
+ }
+
+ const affectedStyleIds = new Set(styleIds);
+ const pendingStyleIds = [...styleIds];
+ while (pendingStyleIds.length > 0) {
+ const styleId = pendingStyleIds.pop()!;
+ for (const dependent of this._styleDependents.get(styleId) ?? []) {
+ if (!affectedStyleIds.has(dependent)) {
+ affectedStyleIds.add(dependent);
+ pendingStyleIds.push(dependent);
+ }
+ }
+ }
+ return mergeRangesById(this._styleRanges!, affectedStyleIds);
+ }
+
+ private _ensureParagraphRanges(): void {
+ if (this._listRanges != null && this._styleRanges != null) {
+ return;
+ }
+ this._listRanges = new Map();
+ this._styleRanges = new Map();
+ for (const paragraph of this._body?.paragraphs ?? []) {
+ const paragraphRange = { start: paragraph.startIndex, end: paragraph.startIndex + 1 };
+ const listId = paragraph.bullet?.listId;
+ if (listId != null) {
+ this._listRanges.set(listId, mergeLayoutRange(this._listRanges.get(listId), paragraphRange)!);
+ }
+ if (paragraph.styleId != null) {
+ this._styleRanges.set(
+ paragraph.styleId,
+ mergeLayoutRange(this._styleRanges.get(paragraph.styleId), paragraphRange)!
+ );
+ }
+ }
+ }
+}
+
+function mergeRangesById(
+ ranges: Map<string, IDocumentLayoutRange>,
+ ids: Set<string>
+): IDocumentLayoutRange | undefined {
+ let range: IDocumentLayoutRange | undefined;
+ for (const id of ids) {
+ range = mergeLayoutRange(range, ranges.get(id));
+ }
+ return range;
+}
+
+export function getBodyTextXActions(actions: JSONXActions, segmentId?: string): unknown[] | undefined {
+ if (segmentId || actions == null) {
+ return undefined;
+ }
+
+ let result: unknown[] | undefined;
+ let duplicate = false;
+ try {
+ const cursor = JSON1.type.readCursor(actions);
+ cursor.traverse(null, (component) => {
+ const path = cursor.getPath();
+ if (
+ path.length !== 1 ||
+ path[0] !== 'body' ||
+ component.et !== TextX.name ||
+ !Array.isArray(component.e)
+ ) {
+ return;
+ }
+
+ if (result != null) {
+ duplicate = true;
+ } else {
+ result = component.e;
+ }
+ });
+ } catch {
+ return undefined;
+ }
+
+ return duplicate ? undefined : result;
+}
+
+export function getSingleBodyTextXActions(actions: JSONXActions, segmentId?: string): unknown[] | undefined {
+ return actions != null && actions.length === 2 && actions[0] === 'body'
+ ? getBodyTextXActions(actions, segmentId)
+ : undefined;
+}
+
+export function getDocumentMutationLayoutImpact(
+ actions: JSONXActions,
+ snapshot: Pick<IDocumentData, 'body' | 'styles'>
+): IDocumentMutationLayoutImpact {
+ if (actions == null) {
+ return { global: true };
+ }
+
+ let global = false;
+ let range: IDocumentLayoutRange | undefined;
+ let sawComponent = false;
+ let unresolvedLocal = false;
+ const { body, styles } = snapshot;
+ const index = new DocumentMutationLayoutIndex(body, styles);
+ try {
+ const cursor = JSON1.type.readCursor(actions);
+ cursor.traverse(null, (component) => {
+ sawComponent = true;
+ const impact = getComponentLayoutImpact(cursor.getPath(), component, body, index);
+ global ||= impact.global;
+ unresolvedLocal ||= impact.unresolvedLocal === true;
+ range = mergeLayoutRange(range, impact.range);
+ });
+ } catch {
+ return { global: true };
+ }
+
+ return { global: global || !sawComponent, range, unresolvedLocal };
+}
+
+function getComponentLayoutImpact(
+ path: (string | number)[],
+ component: Record<string, unknown>,
+ body: IDocumentBody | undefined,
+ index: DocumentMutationLayoutIndex
+): IDocumentMutationLayoutImpact {
+ const root = path[0];
+ if (root === 'drawingsOrder') {
+ return { global: false };
+ }
+ if (root === 'body') {
+ return getBodyComponentLayoutImpact(path, component, body);
+ }
+ if (root === 'tableSource') {
+ const tableId = path[1];
+ const range = typeof tableId === 'string' ? index.getTableRange(tableId) : undefined;
+ return { global: false, range, unresolvedLocal: range == null };
+ }
+ if (root === 'drawings') {
+ const drawingId = path[1];
+ const range = typeof drawingId === 'string' ? index.getDrawingRange(drawingId) : undefined;
+ return { global: false, range, unresolvedLocal: range == null };
+ }
+ if (root === 'lists') {
+ const range = body == null ? undefined : index.getListRange(getChangedRecordKeys(path, component));
+ return { global: false, range, unresolvedLocal: range == null };
+ }
+ if (root === 'styles') {
+ const range = body == null ? undefined : index.getStyleRange(getChangedRecordKeys(path, component));
+ return { global: false, range, unresolvedLocal: range == null };
+ }
+ return { global: true };
+}
+
+function getBodyComponentLayoutImpact(
+ path: (string | number)[],
+ component: Record<string, unknown>,
+ body: IDocumentBody | undefined
+): IDocumentMutationLayoutImpact {
+ if (path.length === 1 && component.et === TextX.name && Array.isArray(component.e)) {
+ return { global: false };
+ }
+ const collection = path[1];
+ if (typeof collection !== 'string' || !BODY_RANGE_COLLECTIONS.has(collection as keyof IDocumentBody)) {
+ return { global: true };
+ }
+ const range = body == null ? undefined : getBodyCollectionRange(body, path, component);
+ return { global: false, range, unresolvedLocal: range == null };
+}
+
+export function mergeMutationLayoutInvalidation(
+ textInvalidation: IDocumentLayoutInvalidation | undefined,
+ structuralRange: IDocumentLayoutRange | undefined
+): IDocumentLayoutInvalidation | undefined {
+ if (structuralRange == null) {
+ return textInvalidation;
+ }
+ if (textInvalidation == null) {
+ return {
+ oldStart: structuralRange.start,
+ oldEnd: structuralRange.end,
+ newEnd: structuralRange.end,
+ };
+ }
+
+ return {
+ oldStart: Math.min(textInvalidation.oldStart, mapCurrentOffsetToPrevious(structuralRange.start, textInvalidation)),
+ oldEnd: Math.max(textInvalidation.oldEnd, mapCurrentOffsetToPrevious(structuralRange.end, textInvalidation)),
+ newEnd: Math.max(textInvalidation.newEnd, structuralRange.end),
+ };
+}
+
+export function resolveMutationLayoutRequest(
+ textInvalidation: IDocumentLayoutInvalidation | undefined,
+ impact: IDocumentMutationLayoutImpact,
+ bodyRangeStarts: number[]
+): { anchor: number | undefined; invalidation: IDocumentLayoutInvalidation | undefined } {
+ if (impact.global) {
+ return { anchor: undefined, invalidation: undefined };
+ }
+ if (impact.unresolvedLocal && textInvalidation == null) {
+ return { anchor: undefined, invalidation: undefined };
+ }
+
+ const invalidation = mergeMutationLayoutInvalidation(textInvalidation, impact.range);
+ return {
+ anchor: invalidation?.oldStart ?? (bodyRangeStarts.length > 0 ? Math.min(...bodyRangeStarts) : undefined),
+ invalidation,
+ };
+}
+
+function getBodyCollectionRange(
+ body: IDocumentBody,
+ path: (string | number)[],
+ component: Record<string, unknown>
+): IDocumentLayoutRange | undefined {
+ const collection = path[1];
+ if (typeof collection !== 'string' || !BODY_RANGE_COLLECTIONS.has(collection as keyof IDocumentBody)) {
+ return undefined;
+ }
+ if ('p' in component || 'd' in component) {
+ return undefined;
+ }
+
+ const index = path[2];
+ if (typeof index === 'number') {
+ const replacesWholeItem = path.length === 3 && ('r' in component || 'i' in component);
+ let range = replacesWholeItem
+ ? undefined
+ : getIndexedBodyRange(body, collection as keyof IDocumentBody, index);
+ range = mergeLayoutRange(range, getBodyItemRange(component.r, collection as keyof IDocumentBody));
+ return mergeLayoutRange(range, getBodyItemRange(component.i, collection as keyof IDocumentBody));
+ }
+
+ let range: IDocumentLayoutRange | undefined;
+ for (const value of [component.r, component.i]) {
+ if (!Array.isArray(value)) {
+ continue;
+ }
+ for (const item of value) {
+ range = mergeLayoutRange(range, getBodyItemRange(item, collection as keyof IDocumentBody));
+ }
+ }
+ return range;
+}
+
+function getIndexedBodyRange(
+ body: IDocumentBody,
+ collection: keyof IDocumentBody,
+ index: number
+): IDocumentLayoutRange | undefined {
+ const items = body[collection];
+ return Array.isArray(items) ? getBodyItemRange(items[index], collection) : undefined;
+}
+
+function getBodyItemRange(item: unknown, collection: keyof IDocumentBody): IDocumentLayoutRange | undefined {
+ if (collection === 'renderedPageBreaks' && typeof item === 'number') {
+ return { start: item, end: item + 1 };
+ }
+ if (typeof item !== 'object' || item == null) {
+ return undefined;
+ }
+ if ('st' in item && 'ed' in item && typeof item.st === 'number' && typeof item.ed === 'number') {
+ return { start: item.st, end: item.ed };
+ }
+ if (!('startIndex' in item) || typeof item.startIndex !== 'number') {
+ return undefined;
+ }
+
+ const end = 'endIndex' in item && typeof item.endIndex === 'number'
+ ? item.endIndex + (collection === 'tables' ? 0 : 1)
+ : item.startIndex + 1;
+ return { start: item.startIndex, end };
+}
+
+function getChangedRecordKeys(
+ path: (string | number)[],
+ component: Record<string, unknown>
+): Set<string> {
+ const keys = new Set<string>();
+ if (typeof path[1] === 'string') {
+ keys.add(path[1]);
+ return keys;
+ }
+ for (const value of [component.r, component.i]) {
+ if (typeof value === 'object' && value != null && !Array.isArray(value)) {
+ Object.keys(value).forEach((key) => keys.add(key));
+ }
+ }
+ return keys;
+}
+
+function mergeLayoutRange(
+ current: IDocumentLayoutRange | undefined,
+ next: IDocumentLayoutRange | undefined
+): IDocumentLayoutRange | undefined {
+ if (next == null) {
+ return current;
+ }
+ return current == null
+ ? next
+ : {
+ start: Math.min(current.start, next.start),
+ end: Math.max(current.end, next.end),
+ };
+}
+
+function mapCurrentOffsetToPrevious(offset: number, invalidation: IDocumentLayoutInvalidation): number {
+ if (offset < invalidation.oldStart) {
+ return offset;
+ }
+ if (offset < invalidation.newEnd) {
+ return invalidation.oldStart;
+ }
+ return offset - (invalidation.newEnd - invalidation.oldEnd);
+}
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 319560ab78..f8fe34cc07 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
@@ -47,7 +47,6 @@ import {
JSON1,
PositionedObjectLayoutType,
RxDisposable,
- TextX,
TextXActionType,
ThemeService,
Tools,
@@ -86,26 +85,7 @@ 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;
-}
+import { getBodyTextXActions, getDocumentMutationLayoutImpact, getSingleBodyTextXActions, resolveMutationLayoutRequest } from './doc-mutation-layout';
function getTextXActionLength(action: unknown): number | undefined {
if (typeof action !== 'object' || action == null || !('t' in action) || !('len' in action)) {
@@ -153,7 +133,7 @@ function omitLayoutMetadata(value: Record<string, unknown>): Record<string, unkn
}
function isLayoutMetadataOnlyMutation(actions: JSONXActions, segmentId?: string): boolean {
- const textActions = getBodyTextXActions(actions, segmentId);
+ const textActions = getSingleBodyTextXActions(actions, segmentId);
return textActions != null && textActions.length > 0 && textActions.every((action) => {
if (typeof action !== 'object' || action == null || !('t' in action) || action.t !== TextXActionType.RETAIN) {
return false;
@@ -419,13 +399,15 @@ function findContinuousLayoutEndOffset(
}
type DocLayoutCoordinatorCallbacks = Parameters<DocLayoutCoordinatorService['schedule']>[2];
+const DRAWING_METADATA_FIELDS = new Set(['title', 'description']);
/**
- * Returns false only when a mutation is proven to touch overlay-only drawings.
+ * Returns false only when a mutation is proven not to affect text layout.
*
* 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
+ * geometry without starting a document layout generation. Accessibility metadata
+ * never participates in layout, regardless of wrapping mode. Every uncertain case
* remains conservative and reflows.
*/
export function doesDocMutationRequireLayout(
@@ -445,11 +427,17 @@ export function doesDocMutationRequireLayout(
cursor.traverse(null, (component) => {
sawComponent = true;
const path = cursor.getPath();
+ if (path[0] === 'drawingsOrder') {
+ return;
+ }
const drawingId = path[1];
if (path[0] !== 'drawings' || typeof drawingId !== 'string') {
drawingOnly = false;
return;
}
+ if (path.length >= 3 && DRAWING_METADATA_FIELDS.has(String(path[2]))) {
+ return;
+ }
const transition = transitions.get(drawingId) ?? {};
if (path.length === 2) {
@@ -469,10 +457,14 @@ export function doesDocMutationRequireLayout(
return true;
}
- if (!sawComponent || !drawingOnly || transitions.size === 0) {
+ if (!sawComponent || !drawingOnly) {
return true;
}
+ if (transitions.size === 0) {
+ return false;
+ }
+
for (const [drawingId, transition] of transitions) {
const currentLayoutType = drawings?.[drawingId]?.layoutType;
const before = transition.before ?? currentLayoutType;
@@ -492,6 +484,7 @@ export function doesDocMutationRequireLayout(
export class DocRenderController extends RxDisposable implements IRenderModule {
private _changesetRenderScheduled = false;
+ private _pendingChangesetLayoutRequest: IDocLayoutWorkerEditBatch | null = null;
private readonly _layoutCoordinator: DocLayoutCoordinatorService;
private _layoutRequestId = 0;
private _workerHandoffTimer: ReturnType<typeof setTimeout> | null = null;
@@ -629,6 +622,7 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
}
this._pendingWorkerHandoff = null;
this._pendingWorkerEditBatch = null;
+ this._pendingChangesetLayoutRequest = null;
this._latestLayoutRestart = null;
this._pendingImeLayoutRestart = null;
this._pendingMaterializedPageRange = null;
@@ -1728,19 +1722,25 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
return;
}
- if (executionOptions?.fromChangeset) {
- this._scheduleChangesetRender();
+ const snapshot = this._context.unit.getSnapshot();
+ if (!doesDocMutationRequireLayout(params.actions, snapshot.drawings)) {
return;
}
-
- if (!doesDocMutationRequireLayout(params.actions, this._context.unit.getSnapshot().drawings)) {
+ const bodyRanges = textRanges?.filter((range) => !range.segmentId) ?? [];
+ const textInvalidation = getBodyMutationInvalidation(params.actions, params.segmentId);
+ const mutationLayoutImpact = getDocumentMutationLayoutImpact(
+ params.actions,
+ snapshot
+ );
+ const { anchor, invalidation } = resolveMutationLayoutRequest(
+ textInvalidation,
+ mutationLayoutImpact,
+ bodyRanges.map((range) => range.startOffset)
+ );
+ if (executionOptions?.fromChangeset) {
+ this._scheduleChangesetRender(anchor, invalidation);
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
@@ -1813,7 +1813,19 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
}));
}
- private _scheduleChangesetRender(): void {
+ private _scheduleChangesetRender(
+ anchor: number | undefined,
+ invalidation: IDocumentLayoutInvalidation | undefined
+ ): void {
+ const pending = this._pendingChangesetLayoutRequest;
+ this._pendingChangesetLayoutRequest = pending == null
+ ? { anchor, invalidation }
+ : {
+ anchor: pending.anchor == null || anchor == null
+ ? undefined
+ : Math.min(pending.anchor, anchor),
+ invalidation: mergeDocumentLayoutInvalidations(pending.invalidation, invalidation),
+ };
if (this._changesetRenderScheduled) {
return;
}
@@ -1825,7 +1837,13 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
return;
}
- this.reRender(this._context.unitId);
+ const request = this._pendingChangesetLayoutRequest;
+ this._pendingChangesetLayoutRequest = null;
+ this.reRender(
+ this._context.unitId,
+ request?.anchor,
+ request?.invalidation
+ );
});
}
diff --git a/packages/docs/src/commands/mutations/__tests__/doc-structure-mutation-validation.spec.ts b/packages/docs/src/commands/mutations/__tests__/doc-structure-mutation-validation.spec.ts
index a558894711..117545f9f9 100644
--- a/packages/docs/src/commands/mutations/__tests__/doc-structure-mutation-validation.spec.ts
+++ b/packages/docs/src/commands/mutations/__tests__/doc-structure-mutation-validation.spec.ts
@@ -44,4 +44,27 @@ describe('validateDocStructureMutation', () => {
expect(validateDocStructureMutation(model, '', actions, undoActions)).toBe(true);
expect(getSelfOrHeaderFooterModel).not.toHaveBeenCalled();
});
+
+ it('skips body structure scans for named-style metadata updates', () => {
+ const getSelfOrHeaderFooterModel = vi.fn(() => {
+ throw new Error('body structure should not be scanned');
+ });
+ const model = {
+ getSnapshot: () => ({}),
+ getSelfOrHeaderFooterModel,
+ } as unknown as DocumentDataModel;
+ const actions = JSONX.getInstance().replaceOp(
+ ['styles', 'heading-1', 'paragraphStyle', 'spaceBelow', 'v'],
+ 0,
+ 12
+ );
+ const undoActions = JSONX.getInstance().replaceOp(
+ ['styles', 'heading-1', 'paragraphStyle', 'spaceBelow', 'v'],
+ 12,
+ 0
+ );
+
+ expect(validateDocStructureMutation(model, '', actions, undoActions)).toBe(true);
+ expect(getSelfOrHeaderFooterModel).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/docs/src/commands/mutations/doc-structure-mutation-validation.ts b/packages/docs/src/commands/mutations/doc-structure-mutation-validation.ts
index 0ab53ad1fc..cd8447bc94 100644
--- a/packages/docs/src/commands/mutations/doc-structure-mutation-validation.ts
+++ b/packages/docs/src/commands/mutations/doc-structure-mutation-validation.ts
@@ -65,6 +65,7 @@ const NON_STRUCTURAL_ROOT_FIELDS = new Set<string>([
'resources',
'rev',
'settings',
+ 'styles',
'tableSource',
'title',
]);
diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.ts
index 348c24aeff..7b384062c9 100644
--- a/packages/docs/src/index.ts
+++ b/packages/docs/src/index.ts
@@ -90,6 +90,7 @@ export type {
IDocLayoutCustomRangePresentation,
IDocLayoutCustomRangePresentationContext,
IDocLayoutCustomRangePresentationEntry,
+ IDocLayoutCustomRangePresentationPatch,
IDocLayoutDisposeMountRequest,
IDocLayoutDisposeSessionRequest,
IDocLayoutExecutor,
@@ -99,6 +100,7 @@ export type {
IDocLayoutPageRequest,
IDocLayoutPageResult,
IDocLayoutPerformanceMetrics,
+ IDocLayoutRecordPatch,
IDocLayoutStartOptions,
IDocLayoutStartRequest,
IDocLayoutStartResult,
diff --git a/packages/docs/src/layout-worker/__tests__/worker-runtime.spec.ts b/packages/docs/src/layout-worker/__tests__/worker-runtime.spec.ts
index e15ef60287..a36a12e8cb 100644
--- a/packages/docs/src/layout-worker/__tests__/worker-runtime.spec.ts
+++ b/packages/docs/src/layout-worker/__tests__/worker-runtime.spec.ts
@@ -123,6 +123,32 @@ describe('DocsLayoutWorkerRuntime', () => {
expect(dataModel.getBody()?.customRanges?.[0]).toMatchObject({ glyphWidthEm: 1 });
expect(dataModel.getSelfOrHeaderFooterModel('header-1')?.getBody()?.customRanges?.[0]).toMatchObject({ glyphWidthEm: 2 });
expect(dataModel.getSelfOrHeaderFooterModel('footer-1')?.getBody()?.customRanges?.[0]).toMatchObject({ glyphWidthEm: 3 });
+
+ await runtime.startLayout({
+ unitId,
+ mountId: 'mount-1',
+ mountEpoch: 1,
+ viewportEpoch: 1,
+ metricsRevision: 2,
+ baseRevision: 0,
+ modelRevision: 0,
+ mutations: [],
+ customBlockViewportPatch: { removals: [], upserts: {} },
+ customRangePresentationPatch: {
+ removals: [{ segmentId: '', rangeId: 'shared-range' }],
+ upserts: [{
+ segmentId: 'header-1',
+ rangeId: 'shared-range',
+ presentation: { glyphWidthEm: 4 },
+ }],
+ },
+ reason: 'edit',
+ budgetMs: 0,
+ });
+
+ expect(dataModel.getBody()?.customRanges?.[0]).not.toHaveProperty('glyphWidthEm');
+ expect(dataModel.getSelfOrHeaderFooterModel('header-1')?.getBody()?.customRanges?.[0]).toMatchObject({ glyphWidthEm: 4 });
+ expect(dataModel.getSelfOrHeaderFooterModel('footer-1')?.getBody()?.customRanges?.[0]).toMatchObject({ glyphWidthEm: 3 });
});
it('applies many presentations with one bounded pass over each segment range list', () => {
@@ -187,7 +213,7 @@ describe('DocsLayoutWorkerRuntime', () => {
});
await expect(runtime.getCapabilities()).resolves.toMatchObject({
- protocolVersion: 3,
+ protocolVersion: 4,
executor: 'worker',
offscreenCanvas: true,
structuredClone: true,
@@ -297,6 +323,46 @@ describe('DocsLayoutWorkerRuntime', () => {
}
expect(JSON.stringify(customBlockStart.step.publication)).toContain('"width":222');
+ const updatedCustomBlockStart = await runtime.startLayout({
+ ...mountIdentity,
+ unitId: customBlockSnapshot.id,
+ mountId: 'custom-block-mount',
+ metricsRevision: 2,
+ baseRevision: 0,
+ modelRevision: 0,
+ mutations: [],
+ customBlockViewportPatch: {
+ removals: [],
+ upserts: { 'embed-1': { width: 333, height: 111, layoutWidth: 333 } },
+ },
+ reason: 'edit',
+ budgetMs: 32,
+ });
+ if (updatedCustomBlockStart.status !== DocLayoutSessionStatus.ACCEPTED) {
+ throw new Error('Expected the updated custom block layout session to start.');
+ }
+ expect(JSON.stringify(updatedCustomBlockStart.step.publication)).toContain('"width":333');
+
+ const resetCustomBlockStart = await runtime.startLayout({
+ ...mountIdentity,
+ unitId: customBlockSnapshot.id,
+ mountId: 'custom-block-mount',
+ metricsRevision: 3,
+ baseRevision: 0,
+ modelRevision: 0,
+ mutations: [],
+ customBlockViewportPatch: {
+ removals: ['embed-1'],
+ upserts: {},
+ },
+ reason: 'edit',
+ budgetMs: 32,
+ });
+ if (resetCustomBlockStart.status !== DocLayoutSessionStatus.ACCEPTED) {
+ throw new Error('Expected the reset custom block layout session to start.');
+ }
+ expect(JSON.stringify(resetCustomBlockStart.step.publication)).toContain('"width":100');
+
const secondMountStart = await runtime.startLayout({
...mountIdentity,
unitId,
diff --git a/packages/docs/src/layout-worker/protocol.ts b/packages/docs/src/layout-worker/protocol.ts
index 1d8b9289a3..f4f1bd1578 100644
--- a/packages/docs/src/layout-worker/protocol.ts
+++ b/packages/docs/src/layout-worker/protocol.ts
@@ -17,7 +17,7 @@
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 const DOCS_LAYOUT_WORKER_PROTOCOL_VERSION = 4;
export interface IDocsLayoutWorkerFontProbe {
content: string;
diff --git a/packages/docs/src/layout-worker/worker.ts b/packages/docs/src/layout-worker/worker.ts
index 8b7a953ad8..ab87c9c08e 100644
--- a/packages/docs/src/layout-worker/worker.ts
+++ b/packages/docs/src/layout-worker/worker.ts
@@ -17,7 +17,7 @@
import type { ICustomRangeForInterceptor } from '@univerjs/core';
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 { IDocLayoutCancelRequest, IDocLayoutCreateSessionRequest, IDocLayoutCustomRangePresentationEntry, 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';
@@ -43,6 +43,7 @@ interface IDocsLayoutWorkerSession {
layoutSessions: Map<string, IDocsLayoutWorkerMount>;
localeService: LocaleService;
modelRevision: number;
+ customRangePresentations: Map<string, IDocLayoutCustomRangePresentationEntry>;
}
interface IDocsLayoutWorkerMount {
@@ -73,6 +74,25 @@ function createDocsLayoutWorkerMessageProtocol(
};
}
+function getCustomRangePresentationKey(
+ entry: Pick<IDocLayoutCustomRangePresentationEntry, 'segmentId' | 'rangeId'>
+): string {
+ return JSON.stringify([entry.segmentId, entry.rangeId]);
+}
+
+function applyRecordPatch<T>(
+ target: Record<string, T>,
+ patch: { removals: string[]; upserts: Record<string, T> } | undefined
+): void {
+ if (patch == null) {
+ return;
+ }
+ for (const key of patch.removals) {
+ delete target[key];
+ }
+ Object.assign(target, patch.upserts);
+}
+
export class DocsLayoutWorkerRuntime implements IDocsLayoutWorkerRuntime {
private readonly _sessions = new Map<string, IDocsLayoutWorkerSession>();
readonly type = DocLayoutExecutorType.WORKER;
@@ -135,6 +155,7 @@ export class DocsLayoutWorkerRuntime implements IDocsLayoutWorkerRuntime {
layoutSessions: new Map(),
localeService,
modelRevision: request.modelRevision,
+ customRangePresentations: new Map(),
});
}
@@ -158,7 +179,8 @@ export class DocsLayoutWorkerRuntime implements IDocsLayoutWorkerRuntime {
};
}
- this._applyCustomRangePresentations(session.dataModel, request.customRangePresentations ?? []);
+ this._updateCustomRangePresentations(session, request);
+ this._applyCustomRangePresentations(session.dataModel, Array.from(session.customRangePresentations.values()));
let mount = session.layoutSessions.get(request.mountId);
if (
@@ -175,10 +197,12 @@ export class DocsLayoutWorkerRuntime implements IDocsLayoutWorkerRuntime {
mount = undefined;
}
if (mount == null) {
+ const customBlockViewports = { ...request.customBlockViewports };
+ applyRecordPatch(customBlockViewports, request.customBlockViewportPatch);
mount = {
mountId: request.mountId,
layoutSession: new DocumentLayoutSession(session.dataModel, session.localeService),
- customBlockViewports: request.customBlockViewports,
+ customBlockViewports,
metricsRevision: request.metricsRevision,
mountEpoch: request.mountEpoch,
viewportEpoch: request.viewportEpoch,
@@ -187,7 +211,10 @@ export class DocsLayoutWorkerRuntime implements IDocsLayoutWorkerRuntime {
};
session.layoutSessions.set(request.mountId, mount);
} else {
- mount.customBlockViewports = request.customBlockViewports;
+ if (request.customBlockViewports != null) {
+ mount.customBlockViewports = { ...request.customBlockViewports };
+ }
+ applyRecordPatch(mount.customBlockViewports, request.customBlockViewportPatch);
mount.metricsRevision = request.metricsRevision;
mount.viewportEpoch = request.viewportEpoch;
}
@@ -268,6 +295,27 @@ export class DocsLayoutWorkerRuntime implements IDocsLayoutWorkerRuntime {
}
}
+ private _updateCustomRangePresentations(
+ session: IDocsLayoutWorkerSession,
+ request: IDocLayoutStartRequest
+ ): void {
+ if (request.customRangePresentations != null) {
+ session.customRangePresentations.clear();
+ for (const entry of request.customRangePresentations) {
+ const key = getCustomRangePresentationKey(entry);
+ if (!session.customRangePresentations.has(key)) {
+ session.customRangePresentations.set(key, entry);
+ }
+ }
+ }
+ for (const removal of request.customRangePresentationPatch?.removals ?? []) {
+ session.customRangePresentations.delete(getCustomRangePresentationKey(removal));
+ }
+ for (const entry of request.customRangePresentationPatch?.upserts ?? []) {
+ session.customRangePresentations.set(getCustomRangePresentationKey(entry), entry);
+ }
+ }
+
async stepLayout(request: IDocLayoutStepRequest): Promise<IDocLayoutStepResult> {
const session = this._getSession(request.unitId);
const mount = this._getLayoutMount(session, request);
diff --git a/packages/docs/src/services/__tests__/doc-layout-executor.service.spec.ts b/packages/docs/src/services/__tests__/doc-layout-executor.service.spec.ts
index 8f96d15210..6e190157d4 100644
--- a/packages/docs/src/services/__tests__/doc-layout-executor.service.spec.ts
+++ b/packages/docs/src/services/__tests__/doc-layout-executor.service.spec.ts
@@ -611,12 +611,14 @@ describe('DocLayoutExecutorService', () => {
const service = injector.get(DocLayoutExecutorService);
const executor = createExecutor();
service.register(executor);
+ let extraWidth = 10;
+ let viewportEnabled = true;
const unregister = setDocsCustomBlockRenderViewportProvider((unitId, blockId, input) => {
- if (unitId !== 'traditional-doc' || blockId !== 'embed-1') {
+ if (!viewportEnabled || unitId !== 'traditional-doc' || blockId !== 'embed-1') {
return null;
}
return {
- width: input.fallbackWidth + 10,
+ width: input.fallbackWidth + extraWidth,
height: input.fallbackHeight + 20,
contentWidth: 640,
contentHeight: 480,
@@ -626,7 +628,10 @@ describe('DocLayoutExecutorService', () => {
documentData.body = {
dataStream: '\b\r\n',
paragraphs: [{ paragraphId: 'paragraph-1', startIndex: 1 }],
- customBlocks: [{ startIndex: 0, blockId: 'embed-1' }],
+ customBlocks: [
+ { startIndex: 0, blockId: 'embed-1' },
+ { startIndex: 0, blockId: 'missing-drawing' },
+ ],
};
documentData.drawings = {
'embed-1': {
@@ -658,6 +663,35 @@ describe('DocLayoutExecutorService', () => {
},
},
}));
+
+ await service.startLayout(createMountIdentity(), { reason: 'edit' }, 32);
+ expect(vi.mocked(executor.startLayout).mock.lastCall?.[0]).not.toHaveProperty('customBlockViewportPatch');
+ expect(vi.mocked(executor.startLayout).mock.lastCall?.[0]).not.toHaveProperty('customBlockViewports');
+
+ extraWidth = 20;
+ await service.startLayout(createMountIdentity(), { reason: 'edit' }, 32);
+ expect(vi.mocked(executor.startLayout).mock.lastCall?.[0]).toEqual(expect.objectContaining({
+ customBlockViewportPatch: {
+ removals: [],
+ upserts: {
+ 'embed-1': {
+ width: 120,
+ height: 100,
+ contentWidth: 640,
+ contentHeight: 480,
+ },
+ },
+ },
+ }));
+
+ viewportEnabled = false;
+ await service.startLayout(createMountIdentity(), { reason: 'edit' }, 32);
+ expect(vi.mocked(executor.startLayout).mock.lastCall?.[0]).toEqual(expect.objectContaining({
+ customBlockViewportPatch: {
+ removals: ['embed-1'],
+ upserts: {},
+ },
+ }));
unregister();
});
@@ -666,8 +700,9 @@ describe('DocLayoutExecutorService', () => {
const service = injector.get(DocLayoutExecutorService);
const executor = createExecutor();
service.register(executor);
- service.registerCustomRangePresentationProvider((_unitId, range) => ({
- glyphWidthEm: range.startIndex + 1,
+ let glyphWidthOffset = 1;
+ const registration = service.registerCustomRangePresentationProvider((_unitId, range) => ({
+ glyphWidthEm: range.startIndex + glyphWidthOffset,
}));
const documentData = createDocumentData('traditional-doc', DocumentFlavor.TRADITIONAL);
documentData.body!.customRanges = [
@@ -738,6 +773,26 @@ describe('DocLayoutExecutorService', () => {
},
],
}));
+
+ await service.startLayout(createMountIdentity(), { reason: 'edit' }, 32);
+ expect(vi.mocked(executor.startLayout).mock.lastCall?.[0]).not.toHaveProperty('customRangePresentationPatch');
+ expect(vi.mocked(executor.startLayout).mock.lastCall?.[0]).not.toHaveProperty('customRangePresentations');
+
+ glyphWidthOffset = 10;
+ await service.startLayout(createMountIdentity(), { reason: 'edit' }, 32);
+ expect(vi.mocked(executor.startLayout).mock.lastCall?.[0]?.customRangePresentationPatch?.upserts).toEqual([
+ { segmentId: '', rangeId: 'shared-range', presentation: { glyphWidthEm: 10 } },
+ { segmentId: 'header-1', rangeId: 'shared-range', presentation: { glyphWidthEm: 11 } },
+ { segmentId: 'footer-1', rangeId: 'shared-range', presentation: { glyphWidthEm: 12 } },
+ ]);
+
+ registration.dispose();
+ await service.startLayout(createMountIdentity(), { reason: 'edit' }, 32);
+ expect(vi.mocked(executor.startLayout).mock.lastCall?.[0]?.customRangePresentationPatch?.removals).toEqual([
+ { segmentId: '', rangeId: 'shared-range' },
+ { segmentId: 'header-1', rangeId: 'shared-range' },
+ { segmentId: 'footer-1', rangeId: 'shared-range' },
+ ]);
});
it('skips queued layout starts that a newer edit superseded', async () => {
diff --git a/packages/docs/src/services/doc-layout-executor.service.ts b/packages/docs/src/services/doc-layout-executor.service.ts
index d336618e17..85e29924a0 100644
--- a/packages/docs/src/services/doc-layout-executor.service.ts
+++ b/packages/docs/src/services/doc-layout-executor.service.ts
@@ -126,11 +126,18 @@ export interface IDocLayoutStartRequest extends IDocLayoutMountIdentity {
anchor?: number;
priorityAnchor?: number;
invalidation?: IDocumentLayoutSessionStartOptions['invalidation'];
- customBlockViewports: Record<string, IDocsCustomBlockRenderViewport>;
+ customBlockViewports?: Record<string, IDocsCustomBlockRenderViewport>;
+ customBlockViewportPatch?: IDocLayoutRecordPatch<IDocsCustomBlockRenderViewport>;
customRangePresentations?: IDocLayoutCustomRangePresentationEntry[];
+ customRangePresentationPatch?: IDocLayoutCustomRangePresentationPatch;
budgetMs: number;
}
+export interface IDocLayoutRecordPatch<T> {
+ removals: string[];
+ upserts: Record<string, T>;
+}
+
export interface IDocLayoutCustomRangePresentation {
active?: boolean;
glyphAscentEm?: number;
@@ -145,6 +152,11 @@ export interface IDocLayoutCustomRangePresentationEntry {
presentation: IDocLayoutCustomRangePresentation;
}
+export interface IDocLayoutCustomRangePresentationPatch {
+ removals: Array<Pick<IDocLayoutCustomRangePresentationEntry, 'segmentId' | 'rangeId'>>;
+ upserts: IDocLayoutCustomRangePresentationEntry[];
+}
+
export interface IDocLayoutCustomRangePresentationContext {
segmentId: string;
body: IDocumentBody;
@@ -219,12 +231,91 @@ interface IDocLayoutManagedSession {
mountEpoch: number;
viewportEpoch: number;
}>;
+ customBlockViewportsByMount: Map<string, {
+ mountEpoch: number;
+ value: Record<string, IDocsCustomBlockRenderViewport>;
+ }>;
+ customRangePresentations: Map<string, IDocLayoutCustomRangePresentationEntry> | null;
queue: Promise<void>;
needsResnapshot: boolean;
disposed: boolean;
cancelPendingCreateTask: (() => void) | null;
}
+interface IDocLayoutProjectionPayload {
+ request: Pick<
+ IDocLayoutStartRequest,
+ 'customBlockViewports' |
+ 'customBlockViewportPatch' |
+ 'customRangePresentations' |
+ 'customRangePresentationPatch'
+ >;
+ customBlockViewports: Record<string, IDocsCustomBlockRenderViewport>;
+ customRangePresentations: Map<string, IDocLayoutCustomRangePresentationEntry>;
+}
+
+function areShallowRecordsEqual(
+ left: object,
+ right: object
+): boolean {
+ const leftRecord = left as Record<string, unknown>;
+ const rightRecord = right as Record<string, unknown>;
+ const leftKeys = Object.keys(leftRecord);
+ const rightKeys = Object.keys(rightRecord);
+ return leftKeys.length === rightKeys.length && leftKeys.every((key) => leftRecord[key] === rightRecord[key]);
+}
+
+function createRecordPatch<T extends object>(
+ previous: Record<string, T>,
+ current: Record<string, T>
+): IDocLayoutRecordPatch<T> {
+ const upserts: Record<string, T> = {};
+ const removals: string[] = [];
+ for (const [key, value] of Object.entries(current)) {
+ if (previous[key] == null || !areShallowRecordsEqual(previous[key], value)) {
+ upserts[key] = value;
+ }
+ }
+ for (const key of Object.keys(previous)) {
+ if (current[key] == null) {
+ removals.push(key);
+ }
+ }
+ return { removals, upserts };
+}
+
+function getCustomRangePresentationKey(
+ entry: Pick<IDocLayoutCustomRangePresentationEntry, 'segmentId' | 'rangeId'>
+): string {
+ return JSON.stringify([entry.segmentId, entry.rangeId]);
+}
+
+function toCustomRangePresentationMap(
+ entries: IDocLayoutCustomRangePresentationEntry[]
+): Map<string, IDocLayoutCustomRangePresentationEntry> {
+ return new Map(entries.map((entry) => [getCustomRangePresentationKey(entry), entry]));
+}
+
+function createCustomRangePresentationPatch(
+ previous: Map<string, IDocLayoutCustomRangePresentationEntry>,
+ current: Map<string, IDocLayoutCustomRangePresentationEntry>
+): IDocLayoutCustomRangePresentationPatch {
+ const upserts: IDocLayoutCustomRangePresentationEntry[] = [];
+ const removals: IDocLayoutCustomRangePresentationPatch['removals'] = [];
+ for (const [key, entry] of current) {
+ const previousEntry = previous.get(key);
+ if (previousEntry == null || !areShallowRecordsEqual(previousEntry.presentation, entry.presentation)) {
+ upserts.push(entry);
+ }
+ }
+ for (const [key, entry] of previous) {
+ if (!current.has(key)) {
+ removals.push({ segmentId: entry.segmentId, rangeId: entry.rangeId });
+ }
+ }
+ return { removals, upserts };
+}
+
function isRichTextEditingMutationParams(value: unknown): value is IRichTextEditingMutationParams {
return typeof value === 'object' && value != null &&
'unitId' in value && typeof value.unitId === 'string' &&
@@ -250,7 +341,7 @@ function collectCustomBlockViewports(dataModel: DocumentDataModel): Record<strin
pageWidth: documentStyle.pageSize?.width,
});
if (viewport != null) {
- viewports[customBlock.blockId] = viewport;
+ viewports[customBlock.blockId] = { ...viewport };
}
}
@@ -528,6 +619,7 @@ export class DocLayoutExecutorService extends Disposable {
latestStart.viewportEpoch === request.viewportEpoch
) {
session?.latestStarts.delete(request.mountId);
+ session?.customBlockViewportsByMount.delete(request.mountId);
}
return executor == null ? Promise.resolve() : executor.disposeLayoutMount(request);
}
@@ -634,14 +726,18 @@ export class DocLayoutExecutorService extends Disposable {
}
const mutations = session.pendingMutations.slice();
+ const projections = this._createLayoutProjectionPayload(
+ session,
+ identity,
+ this._getRequiredModel(unitId)
+ );
const request: IDocLayoutStartRequest = {
...identity,
metricsRevision: startId,
baseRevision: session.workerRevision,
modelRevision: session.modelRevision,
mutations,
- customBlockViewports: collectCustomBlockViewports(this._getRequiredModel(unitId)),
- customRangePresentations: this._collectCustomRangePresentations(this._getRequiredModel(unitId)),
+ ...projections.request,
budgetMs,
...options,
};
@@ -649,6 +745,11 @@ export class DocLayoutExecutorService extends Disposable {
if (result.status === DocLayoutSessionStatus.ACCEPTED) {
session.workerRevision = request.modelRevision;
session.pendingMutations.splice(0, mutations.length);
+ session.customBlockViewportsByMount.set(mountId, {
+ mountEpoch: identity.mountEpoch,
+ value: projections.customBlockViewports,
+ });
+ session.customRangePresentations = projections.customRangePresentations;
} else {
session.needsResnapshot = true;
}
@@ -664,6 +765,38 @@ export class DocLayoutExecutorService extends Disposable {
return startTask;
}
+ private _createLayoutProjectionPayload(
+ session: IDocLayoutManagedSession,
+ identity: IDocLayoutMountIdentity,
+ dataModel: DocumentDataModel
+ ): IDocLayoutProjectionPayload {
+ const customBlockViewports = collectCustomBlockViewports(dataModel);
+ const previousCustomBlockViewports = session.customBlockViewportsByMount.get(identity.mountId);
+ const customRangePresentations = this._collectCustomRangePresentations(dataModel);
+ const customRangePresentationMap = toCustomRangePresentationMap(customRangePresentations);
+ const request: IDocLayoutProjectionPayload['request'] = {};
+ if (previousCustomBlockViewports == null || previousCustomBlockViewports.mountEpoch !== identity.mountEpoch) {
+ request.customBlockViewports = customBlockViewports;
+ } else {
+ const patch = createRecordPatch(previousCustomBlockViewports.value, customBlockViewports);
+ if (patch.removals.length > 0 || Object.keys(patch.upserts).length > 0) {
+ request.customBlockViewportPatch = patch;
+ }
+ }
+ if (session.customRangePresentations == null) {
+ request.customRangePresentations = customRangePresentations;
+ } else {
+ const patch = createCustomRangePresentationPatch(
+ session.customRangePresentations,
+ customRangePresentationMap
+ );
+ if (patch.removals.length > 0 || patch.upserts.length > 0) {
+ request.customRangePresentationPatch = patch;
+ }
+ }
+ return { request, customBlockViewports, customRangePresentations: customRangePresentationMap };
+ }
+
private async _replaceSession(dataModel: DocumentDataModel): Promise<IDocLayoutManagedSession> {
const executor = this._requireExecutor();
const unitId = dataModel.getUnitId();
@@ -680,6 +813,8 @@ export class DocLayoutExecutorService extends Disposable {
workerRevision: modelRevision,
pendingMutations: [],
latestStarts: new Map(),
+ customBlockViewportsByMount: new Map(),
+ customRangePresentations: null,
queue: Promise.resolve(),
needsResnapshot: false,
disposed: false,
@@ -749,7 +884,11 @@ export class DocLayoutExecutorService extends Disposable {
for (const provider of providers) {
const presentation = provider(dataModel.getUnitId(), range, { segmentId, body });
if (presentation != null) {
- presentations.push({ segmentId, rangeId: range.rangeId, presentation });
+ presentations.push({
+ segmentId,
+ rangeId: range.rangeId,
+ presentation: { ...presentation },
+ });
break;
}
}
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 d84471d211..20fa1951d4 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
@@ -403,6 +403,33 @@ describe('DocumentViewModel', () => {
expect(viewModel.getTableByStartIndex(0)?.tableSource).toEqual({ id: 'after' });
});
+ it('refreshes named styles without rebuilding the document tree', () => {
+ const model = createDocumentDataModel({
+ snapshot: {
+ styles: {
+ 'heading-1': {
+ name: 'Heading 1',
+ type: 1,
+ paragraphStyle: { spaceBelow: { v: 0 } },
+ },
+ },
+ },
+ });
+ const viewModel = new DocumentViewModel(model);
+ const children = viewModel.getChildren();
+ const snapshot = model.getSnapshot();
+ snapshot.styles!['heading-1'].paragraphStyle!.spaceBelow = { v: 12 };
+ const actions = JSONX.getInstance().replaceOp(
+ ['styles', 'heading-1', 'paragraphStyle', 'spaceBelow', 'v'],
+ 0,
+ 12
+ );
+
+ expect(viewModel.resetByValidatedMetadataMutation(model, actions)).toBe(true);
+ expect(viewModel.getChildren()).toBe(children);
+ expect(viewModel.getSnapshot()?.styles?.['heading-1'].paragraphStyle?.spaceBelow).toEqual({ v: 12 });
+ });
+
it('updates nested table-cell and column-group paragraphs without rebuilding their element trees', () => {
const T = DataStreamTreeTokenType;
const tableStream = [
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 4a0852f33e..f688bedf9c 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
@@ -61,6 +61,7 @@ const NON_STRUCTURAL_ROOT_FIELDS = new Set<string>([
'resources',
'rev',
'settings',
+ 'styles',
'tableSource',
'title',
]);