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): support persistent heading collapse in modern mode (#7923)

Univerfb1aacf09f80
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/invert.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/invert.spec.ts
index 3a73361274..45e9149c91 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/invert.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/invert.spec.ts
@@ -14,11 +14,12 @@
* limitations under the License.
*/
-import type { IDocumentBody } from '../../../../types/interfaces';
-import type { TextXAction } from '../action-types';
import { describe, expect, it } from 'vitest';
+import type { IDocumentBody } from '../../../../types/interfaces/i-document-data';
+import type { TextXAction } from '../action-types';
import { UpdateDocsAttributeType } from '../../../../shared/command-enum';
-import { BooleanNumber } from '../../../../types/enum';
+import { Tools } from '../../../../shared/tools';
+import { BooleanNumber } from '../../../../types/enum/text-style';
import { TextXActionType } from '../action-types';
import { TextX } from '../text-x';
@@ -138,6 +139,8 @@ describe('test TextX static methods invert and makeInvertible', () => {
it('test TextX static method makeInvertible when `retain` action occur', () => {
const docBody: IDocumentBody = {
dataStream: 'hello\r\n',
+ customRanges: [],
+ customDecorations: [],
textRuns: [
{
st: 0,
@@ -163,6 +166,7 @@ describe('test TextX static methods invert and makeInvertible', () => {
}, UpdateDocsAttributeType.COVER);
TextX.makeInvertible(textX.serialize(), docBody);
+ const original = Tools.deepClone(docBody);
const expectedActions = [{
t: TextXActionType.RETAIN,
@@ -179,8 +183,6 @@ describe('test TextX static methods invert and makeInvertible', () => {
},
oldBody: {
dataStream: '',
- paragraphs: undefined,
- sectionBreaks: [],
textRuns: [{
st: 0,
ed: 3,
@@ -188,14 +190,14 @@ describe('test TextX static methods invert and makeInvertible', () => {
bl: BooleanNumber.TRUE,
},
}],
- customRanges: [],
- customDecorations: [],
- customBlocks: undefined,
},
coverType: UpdateDocsAttributeType.COVER,
}];
expect(textX.serialize()).toEqual(expectedActions);
+ TextX.apply(docBody, textX.serialize());
+ TextX.apply(docBody, TextX.invert(textX.serialize()));
+ expect(docBody).toEqual(original);
});
it('test TextX static method makeInvertible when `delete` action occur', () => {
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts
index bdba7574ad..363e10e66b 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
+import { describe, expect, it } from 'vitest';
import type { IDocumentBody, IDocumentData } from '../../../../types/interfaces/i-document-data';
import type { IInsertAction, IRetainAction } from '../action-types';
-import { describe, expect, it } from 'vitest';
import { UpdateDocsAttributeType } from '../../../../shared/command-enum';
import { Tools } from '../../../../shared/tools';
import { BooleanNumber } from '../../../../types/enum/text-style';
@@ -33,6 +33,38 @@ import { TextX } from '../text-x';
import { composeBody } from '../utils';
describe('test TextX methods and branches', () => {
+ it('keeps peer formatting and nested fields when undoing heading metadata without text edits', () => {
+ const body: IDocumentBody = {
+ dataStream: 'Heading\rTail\r\n',
+ paragraphs: [{ paragraphId: 'heading', startIndex: 7 }, { paragraphId: 'tail', startIndex: 12 }],
+ textRuns: [{ st: 0, ed: 13, ts: { fs: 12 } }],
+ customRanges: [
+ { startIndex: 0, endIndex: 12, rangeId: 'outer', rangeType: CustomRangeType.FIELD },
+ { startIndex: 2, endIndex: 4, rangeId: 'inner', rangeType: CustomRangeType.FIELD },
+ ],
+ };
+ const originalParagraphs = Tools.deepClone(body.paragraphs);
+ const fold = new TextX().retain(7).retain(1, {
+ dataStream: '',
+ paragraphs: [{ startIndex: 0, paragraphId: 'heading', headingCollapsed: true }],
+ }).serialize();
+ TextX.makeInvertible(fold, body);
+ TextX.apply(body, fold);
+ TextX.apply(body, new TextX().retain(7).retain(1, {
+ dataStream: '',
+ textRuns: [{ st: 0, ed: 1, ts: { it: BooleanNumber.TRUE } }],
+ }).serialize());
+ TextX.apply(body, new TextX().updateCustomRangeProperties(body.customRanges![0], {
+ locked: BooleanNumber.TRUE,
+ }).serialize());
+ const expected = Tools.deepClone(body);
+ expected.paragraphs = originalParagraphs;
+
+ TextX.apply(body, TextX.invert(fold));
+
+ expect(body).toEqual(expected);
+ });
+
it('keeps scalar identity distinct from adjacent typing, different controls and document snapshots', () => {
const value = { t: TextXActionType.INSERT, len: 1, body: { dataStream: 'A' }, valueRangeId: 'first' } as IInsertAction;
const edit = new TextX().insert(1, { dataStream: 'X' }).push(value).delete(1).serialize();
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/transform-utils.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/transform-utils.spec.ts
new file mode 100644
index 0000000000..76f13add3e
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/__tests__/transform-utils.spec.ts
@@ -0,0 +1,96 @@
+/**
+ * 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 type { IDocumentBody, IParagraph } from '../../../../types/interfaces/i-document-data';
+import type { IRetainAction } from '../action-types';
+import { UpdateDocsAttributeType } from '../../../../shared/command-enum';
+import { Tools } from '../../../../shared/tools';
+import { PresetListType } from '../../preset-list-type';
+import { TextXActionType } from '../action-types';
+import { updateAttribute } from '../apply-utils/update-apply';
+import { transformBody } from '../transform-utils';
+
+function createBody(): IDocumentBody {
+ return { dataStream: 'Heading\rBody\r\n', paragraphs: [{
+ startIndex: 7,
+ paragraphId: 'heading',
+ styleId: 'inherited-heading',
+ sourceBullet: { listId: 'imported', listType: PresetListType.ORDER_LIST, nestingLevel: 0 },
+ directBullet: null,
+ }, { startIndex: 12, paragraphId: 'body' }] };
+}
+
+function createAction(paragraph: IParagraph, coverType: UpdateDocsAttributeType): IRetainAction {
+ return { t: TextXActionType.RETAIN, len: 1, coverType, body: { dataStream: '', paragraphs: [paragraph] } };
+}
+
+function apply(body: IDocumentBody, action: Pick<IRetainAction, 'body' | 'coverType'>): void {
+ updateAttribute(body, Tools.deepClone(action.body!), 1, 7, action.coverType ?? UpdateDocsAttributeType.COVER);
+}
+
+describe('paragraph metadata transforms', () => {
+ it.each([true, false])('preserves inherited heading and imported numbering when a fold races with full formatting (priority: %s)', (priority) => {
+ const initial = createBody();
+ const folded = Tools.deepClone(initial);
+ const formatted = Tools.deepClone(initial);
+ const fold = createAction({ startIndex: 0, paragraphId: 'heading', headingCollapsed: true }, UpdateDocsAttributeType.COVER);
+ const format = createAction({
+ ...Tools.deepClone(initial.paragraphs![0]),
+ startIndex: 0,
+ paragraphStyle: { spaceAbove: { v: 12 } },
+ }, UpdateDocsAttributeType.REPLACE);
+
+ apply(folded, fold);
+ apply(formatted, format);
+ apply(folded, transformBody(fold, format, priority));
+ apply(formatted, transformBody(format, fold, !priority));
+
+ expect(folded).toEqual(formatted);
+ expect(folded.paragraphs![0]).toEqual({
+ ...initial.paragraphs![0],
+ paragraphStyle: { spaceAbove: { v: 12 } },
+ headingCollapsed: true,
+ });
+ expect(folded.paragraphs![1]).toEqual(initial.paragraphs![1]);
+ expect(folded.dataStream).toBe(initial.dataStream);
+ });
+
+ it.each([true, false])('keeps the winning replacement metadata and its explicit numbering reset (priority: %s)', (priority) => {
+ const initial = createBody();
+ const first = Tools.deepClone(initial);
+ const second = Tools.deepClone(initial);
+ const replacement = createAction({
+ startIndex: 0,
+ paragraphId: 'heading',
+ styleId: 'replacement-style',
+ sourceBullet: null,
+ directBullet: { listId: 'direct', listType: PresetListType.BULLET_LIST, nestingLevel: 1 },
+ headingCollapsed: true,
+ }, UpdateDocsAttributeType.REPLACE);
+ const clear = createAction({ startIndex: 0, paragraphId: 'heading' }, UpdateDocsAttributeType.REPLACE);
+
+ apply(first, replacement);
+ apply(second, clear);
+ apply(first, transformBody(replacement, clear, priority));
+ apply(second, transformBody(clear, replacement, !priority));
+
+ expect(first).toEqual(second);
+ expect(first.paragraphs![0]).toEqual(priority
+ ? { ...replacement.body!.paragraphs![0], startIndex: 7 }
+ : { startIndex: 7, paragraphId: 'heading' });
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/__tests__/update-apply.spec.ts b/packages/core/src/docs/data-model/text-x/apply-utils/__tests__/update-apply.spec.ts
index f416f5932b..99cc5ff20d 100644
--- a/packages/core/src/docs/data-model/text-x/apply-utils/__tests__/update-apply.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/__tests__/update-apply.spec.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { IDocumentBody, ISdtCustomRange } from '../../../../../types/interfaces';
import { describe, expect, it } from 'vitest';
+import type { IDocumentBody, ISdtCustomRange } from '../../../../../types/interfaces';
import { UpdateDocsAttributeType } from '../../../../../shared';
import { CustomRangeType } from '../../../../../types/interfaces';
import { updateAttribute } from '../update-apply';
@@ -71,3 +71,20 @@ describe('retained SDT metadata boundaries', () => {
});
});
});
+
+describe('retained heading collapse metadata', () => {
+ it.each([true, false])('preserves the fold flag through paragraph formatting (%s)', (headingCollapsed) => {
+ const body: IDocumentBody = { dataStream: 'A\rB\r\n', paragraphs: [
+ { paragraphId: 'a', startIndex: 1, headingCollapsed, styleId: 'heading-style' },
+ { paragraphId: 'b', startIndex: 3 },
+ ] };
+ updateAttribute(body, {
+ dataStream: '',
+ paragraphs: [{ paragraphId: 'a', startIndex: 0, paragraphStyle: { outlineLevel: 0 } }],
+ }, 1, 1, UpdateDocsAttributeType.COVER);
+ expect(body.paragraphs?.[0].headingCollapsed).toBe(headingCollapsed);
+ expect(body.paragraphs?.[0].styleId).toBe('heading-style');
+ expect(body.paragraphs?.[0].paragraphStyle?.outlineLevel).toBe(0);
+ expect(body.paragraphs?.[1].headingCollapsed).toBeUndefined();
+ });
+});
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 4c28f0ef6f..983d2f3664 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
@@ -267,6 +267,9 @@ function updateParagraphs(
} = removeParagraph;
let newParagraphStyle;
let newBullet;
+ const paragraphAttributes = coverType === UpdateDocsAttributeType.COVER
+ ? { ...removeParagraph, ...updateParagraph }
+ : { ...updateParagraph, ...removeParagraph };
if (coverType === UpdateDocsAttributeType.COVER) {
newParagraphStyle = { ...removeParagraphStyle, ...updateParagraphStyle };
@@ -292,10 +295,11 @@ function updateParagraphs(
if (updateStartIndex === removeStartIndex) {
splitUpdateParagraphs.push({
+ ...paragraphAttributes,
startIndex: updateStartIndex,
paragraphId: updateParagraphId ?? removeParagraphId,
paragraphStyle: newParagraphStyle,
- bullet: newBullet,
+ bullet: removeBullet == null && updateBullet == null ? undefined : newBullet,
});
break;
}
diff --git a/packages/core/src/docs/data-model/text-x/text-x.ts b/packages/core/src/docs/data-model/text-x/text-x.ts
index f4f9622e10..360ded72cf 100644
--- a/packages/core/src/docs/data-model/text-x/text-x.ts
+++ b/packages/core/src/docs/data-model/text-x/text-x.ts
@@ -418,12 +418,11 @@ export class TextX {
if (action.t === TextXActionType.RETAIN && action.body != null) {
const body = getBodySlice(doc, index, index + action.len, true);
- // A partial slice clips enclosing structural ranges. Restoring
- // those ranges would duplicate/truncate a table (or container)
- // when undoing an unrelated comment or text-formatting change.
- for (const field of ['tables', 'columnGroups', 'blockRanges'] as const) {
- if (action.body[field] == null) {
- delete body[field];
+ // Restoring untouched attributes can overwrite peer formatting or
+ // reinsert clipped enclosing ranges. Paragraph identities need separate handling below.
+ for (const field of Object.keys(body) as Array<keyof IDocumentBody>) {
+ if (field !== 'dataStream' && field !== 'paragraphs' && action.body[field] == null) {
+ Reflect.deleteProperty(body, field);
}
}
diff --git a/packages/core/src/docs/data-model/text-x/transform-utils.ts b/packages/core/src/docs/data-model/text-x/transform-utils.ts
index 10eb0a213b..ad073743ce 100644
--- a/packages/core/src/docs/data-model/text-x/transform-utils.ts
+++ b/packages/core/src/docs/data-model/text-x/transform-utils.ts
@@ -260,9 +260,7 @@ function transformCustomRanges(
}
}
-// At present, only the two properties of paragraphStyle and bullet are handled,
-// paragraphStyle is treated separately, while bullet is treated as a whole because
-// the properties in bullet are related
+// Paragraph styles merge property-by-property; numbering and other paragraph metadata remain atomic.
// eslint-disable-next-line complexity, max-lines-per-function
function transformParagraph(
@@ -361,6 +359,24 @@ function transformParagraph(
}
}
+ for (const key of ['headingCollapsed', 'styleId', 'sourceBullet', 'directBullet'] as const) {
+ const origin = originParagraph[key];
+ const target = targetParagraph[key];
+ let value: IParagraph[typeof key];
+ if (originCoverType === UpdateDocsAttributeType.REPLACE && targetCoverType === UpdateDocsAttributeType.REPLACE) {
+ value = transformType === TextXTransformType.COVER_ONLY_NOT_EXISTED ? origin : target;
+ } else if (origin === undefined) {
+ value = target;
+ } else if (originCoverType === UpdateDocsAttributeType.REPLACE || targetCoverType === UpdateDocsAttributeType.REPLACE) {
+ value = transformType === TextXTransformType.COVER && target !== undefined ? target : origin;
+ } else if (transformType === TextXTransformType.COVER) {
+ value = target;
+ }
+ if (value !== undefined) {
+ Object.assign(paragraph, { [key]: Tools.deepClone(value) });
+ }
+ }
+
if (paragraph.bullet === undefined) {
delete paragraph.bullet;
}
diff --git a/packages/core/src/services/instance/__tests__/instance.service.spec.ts b/packages/core/src/services/instance/__tests__/instance.service.spec.ts
index d2d0dc5801..2c57c5dea2 100644
--- a/packages/core/src/services/instance/__tests__/instance.service.spec.ts
+++ b/packages/core/src/services/instance/__tests__/instance.service.spec.ts
@@ -14,11 +14,11 @@
* limitations under the License.
*/
+import { BehaviorSubject } from 'rxjs';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import type { Nullable } from '../../../shared/types';
import type { IWorkbookData } from '../../../sheets/typedef';
import type { IDocumentData } from '../../../types/interfaces/i-document-data';
-import { BehaviorSubject } from 'rxjs';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { Injector } from '../../../common/di';
import { UnitModel, UniverInstanceType } from '../../../common/unit';
import { DocumentDataModel } from '../../../docs/data-model/document-data-model';
@@ -83,12 +83,13 @@ class MockBoardUnit extends UnitModel {
}
describe('UniverInstanceService', () => {
+ let injector: Injector;
let service: UniverInstanceService;
let contextService: ContextService;
let logService: DesktopLogService;
beforeEach(() => {
- const injector = new Injector();
+ injector = new Injector();
injector.add([IContextService, { useClass: ContextService }]);
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
@@ -184,19 +185,38 @@ describe('UniverInstanceService', () => {
});
it('should dispose units while resetting focus and current', () => {
+ const subject = injector.get(IUniverInstanceService);
+ const focusedIds: Array<Nullable<string>> = [];
const disposed: string[] = [];
- service.getTypeOfUnitDisposed$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).subscribe((unit) => {
+ subject.focused$.subscribe((unitId) => focusedIds.push(unitId));
+ subject.getTypeOfUnitDisposed$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).subscribe((unit) => {
disposed.push(unit.getUnitId());
});
- const doc = service.createUnit<Partial<IDocumentData>, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData());
- service.focusUnit(doc.getUnitId());
+ const doc = subject.createUnit<Partial<IDocumentData>, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData());
+ subject.focusUnit(doc.getUnitId());
- expect(service.disposeUnit('doc-unit')).toBe(true);
+ expect(subject.disposeUnit('doc-unit')).toBe(true);
expect(disposed).toEqual(['doc-unit']);
- expect(service.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)).toBeNull();
- expect(service.getFocusedUnit()).toBeUndefined();
- expect(service.disposeUnit('missing')).toBe(false);
+ expect(subject.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)).toBeNull();
+ expect(focusedIds).toEqual([null, 'doc-unit', null]);
+ expect(subject.getFocusedUnit()).toBeNull();
+ expect(contextService.getContextValue(FOCUSING_DOC)).toBe(false);
+ expect(subject.disposeUnit('missing')).toBe(false);
+
+ const replacement = subject.createUnit<Partial<IDocumentData>, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createDocData('replacement-doc')
+ );
+ subject.focusUnit(replacement.getUnitId());
+ const background = subject.createUnit<Partial<IWorkbookData>, Workbook>(
+ UniverInstanceType.UNIVER_SHEET,
+ createWorkbookData(),
+ { makeCurrent: false }
+ );
+ expect(subject.disposeUnit(background.getUnitId())).toBe(true);
+ expect(subject.getFocusedUnit()).toBe(replacement);
+ expect(focusedIds).toEqual([null, 'doc-unit', null, 'replacement-doc']);
});
it('should throw on duplicate unit id and support current type stream', () => {
diff --git a/packages/core/src/services/instance/instance.service.ts b/packages/core/src/services/instance/instance.service.ts
index 30670fb23a..b951a2cde1 100644
--- a/packages/core/src/services/instance/instance.service.ts
+++ b/packages/core/src/services/instance/instance.service.ts
@@ -15,10 +15,10 @@
*/
import type { Observable } from 'rxjs';
+import { BehaviorSubject, distinctUntilChanged, filter, map, Subject } from 'rxjs';
import type { IDisposable } from '../../common/di';
import type { UnitModel } from '../../common/unit';
-import type { Nullable } from '../../shared';
-import { BehaviorSubject, distinctUntilChanged, filter, map, Subject } from 'rxjs';
+import type { Nullable } from '../../shared/types';
import { createIdentifier, Inject, Injector } from '../../common/di';
import { UniverInstanceType } from '../../common/unit';
import { DocumentDataModel } from '../../docs/data-model/document-data-model';
@@ -353,8 +353,8 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
}
private _tryResetFocusOnRemoval(unitId: string): void {
- if (this.focused?.getUnitId() === unitId) {
- this._focused$.next(null);
+ if (this._focused$.getValue() === unitId) {
+ this.focusUnit(null);
}
};
diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.ts
index f99c5afd33..2a341066fe 100644
--- a/packages/core/src/types/interfaces/i-document-data.ts
+++ b/packages/core/src/types/interfaces/i-document-data.ts
@@ -17,7 +17,15 @@
import type { ImageSourceType } from '../../services/image-io/image-io.service';
import type { IResources } from '../../services/resource-manager/type';
import type { ISize } from '../../shared/shape';
-import type { BooleanNumber, CellValueType, HorizontalAlign, LocaleType, TextDirection, VerticalAlign, WrapStrategy } from '../enum';
+import type {
+ BooleanNumber,
+ CellValueType,
+ HorizontalAlign,
+ LocaleType,
+ TextDirection,
+ VerticalAlign,
+ WrapStrategy,
+} from '../enum';
import type { IDrawingParam } from './i-drawing';
import type { IMention } from './i-mention';
import type { IColorStyle, IGlowEffect, IShadowEffect, IStyleBase } from './i-style-data';
@@ -892,6 +900,8 @@ export interface IParagraph {
// elements: IElement[]; // elements
startIndex: number;
paragraphId: string;
+ /** Collapse the following heading section in modern documents; content remains in the snapshot. */
+ headingCollapsed?: boolean;
/** Optional stable named-style reference. Direct paragraph style has higher precedence. */
styleId?: string;
paragraphStyle?: IParagraphStyle; // paragraphStyle
diff --git a/packages/docs-ui/README.md b/packages/docs-ui/README.md
index a05ece521d..48201ee09f 100644
--- a/packages/docs-ui/README.md
+++ b/packages/docs-ui/README.md
@@ -56,6 +56,29 @@ Preset integrations can pass the same option to `UniverDocsCorePreset({ containe
When enabled, the outline collapses if there is insufficient space or table content overlaps it,
and reopens when the layout provides enough space without overlap.
+## Heading collapse
+
+Modern documents show a Canvas triangle beside visible Heading 1 through Heading 5 paragraphs
+that have section content. Click it to collapse or expand the section. This is independent of
+the document outline's `toc` setting. Traditional documents and embedded text editors do not
+show these controls.
+
+Collapsing keeps the heading visible and hides its following section, including nested headings,
+tables, and images. Expanding the parent retains each nested heading's own collapse state.
+Hidden content remains in the document snapshot. Collapse changes participate in undo/redo and
+collaboration, so other editors share the state. Selections inside hidden content move to a
+visible heading, and caret navigation skips hidden content. Collaborative table edits and history
+can update hidden cells without drawing a rectangular selection over that heading.
+
+The paragraph menu leaves the Canvas arrow accessible when constrained against the canvas edge,
+including headings resolved through inherited styles. The triangle and its tooltip are drawn on Canvas. Colors follow `ThemeService`, including
+runtime theme changes. After a 500 ms hover, the control shows the localized “Collapse”
+or “Expand” tooltip above it; if the viewport clips the top, the tooltip appears below.
+Scrolling, zooming, leaving the control, or activating it clears the tooltip.
+
+See [the snapshot and command contract](../docs/README.md#heading-collapse-in-modern-documents)
+to change collapse state programmatically through `SetHeadingCollapsedCommand`.
+
## Format painter
Use the shared Start ribbon format painter to copy character formatting. Include a paragraph
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 dccd49aaad..ac7195e0da 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
@@ -15,9 +15,33 @@
*/
import type { DocumentDataModel, ICommand, IDocumentData, Injector } from '@univerjs/core';
-import { awaitTime, CustomRangeType, DataStreamTreeTokenType, DocumentBlockRangeType, DocumentFlavor, ICommandService, IUniverInstanceService, NamedStyleType, PresetListType, Univer, UniverInstanceType } from '@univerjs/core';
-import { DocSelectionManagerService, DocStateChangeManagerService, DocStateEmitService, InsertTextCommand, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
-import { IRenderManagerService, NORMAL_TEXT_SELECTION_PLUGIN_STYLE, RenderManagerService } from '@univerjs/engine-render';
+import {
+ awaitTime,
+ CustomRangeType,
+ DataStreamTreeTokenType,
+ DocumentBlockRangeType,
+ DocumentFlavor,
+ ICommandService,
+ IUniverInstanceService,
+ NamedStyleType,
+ PresetListType,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ DocSelectionManagerService,
+ DocStateChangeManagerService,
+ DocStateEmitService,
+ InsertTextCommand,
+ RichTextEditingMutation,
+ SetTextSelectionsOperation,
+ UniverDocsPlugin,
+} from '@univerjs/docs';
+import {
+ IRenderManagerService,
+ NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ RenderManagerService,
+} from '@univerjs/engine-render';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { DocMenuStyleService } from '../../../services/doc-menu-style.service';
import { BreakLineCommand, BreakLineInsertionMode } from '../break-line.command';
@@ -442,3 +466,42 @@ describe('break line command', () => {
expect(selectionManager.getActiveTextRange()?.startOffset).toBe(tableEnd + 2);
});
});
+
+it.each([
+ NamedStyleType.HEADING_1,
+ NamedStyleType.NORMAL_TEXT,
+ NamedStyleType.TITLE,
+ NamedStyleType.SUBTITLE,
+].flatMap((namedStyleType) => [2, 3].map((offset) => ({ namedStyleType, offset }))))(
+ 'allows Enter at $offset when a snapshot retains a fold flag on named style $namedStyleType',
+ ({ namedStyleType, offset }) => {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ univer.registerPlugin(UniverDocsPlugin);
+ injector.add([DocMenuStyleService]);
+ const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: 'fold-enter',
+ documentStyle: { documentFlavor: DocumentFlavor.MODERN },
+ body: { dataStream: 'One\rText\r\n', paragraphs: [
+ { paragraphId: 'one', startIndex: 3, headingCollapsed: true, paragraphStyle: { namedStyleType, headingId: 'heading-one' } },
+ { paragraphId: 'text', startIndex: 8 },
+ ] },
+ });
+ try {
+ injector.get(IUniverInstanceService).focusUnit(model.getUnitId());
+ const commands = injector.get(ICommandService);
+ commands.registerCommand(BreakLineCommand);
+ const selections = injector.get(DocSelectionManagerService);
+ selections.__TEST_ONLY_setCurrentSelection({ unitId: model.getUnitId(), subUnitId: model.getUnitId() });
+ selections.__TEST_ONLY_add([{ startOffset: offset, endOffset: offset, collapsed: true, isActive: true }]);
+ expect(commands.syncExecuteCommand(BreakLineCommand.id)).toBe(true);
+ expect(model.getBody()?.dataStream).toBe(offset === 3 ? 'One\r\rText\r\n' : 'On\re\rText\r\n');
+ if (namedStyleType === NamedStyleType.HEADING_1) {
+ expect(model.getBody()?.paragraphs?.some((paragraph) => paragraph.headingCollapsed === true)).toBe(false);
+ }
+ } finally {
+ univer.dispose();
+ }
+ }
+);
diff --git a/packages/docs-ui/src/commands/commands/__tests__/doc-delete.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/doc-delete.command.spec.ts
index 4ee023278d..81c3ca669b 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/doc-delete.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/doc-delete.command.spec.ts
@@ -15,12 +15,14 @@
*/
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
+import type { RenderUnit } from '@univerjs/engine-render';
import {
DeleteDirection,
DocumentFlavor,
HorizontalAlign,
ICommandService,
IUniverInstanceService,
+ NamedStyleType,
RANGE_DIRECTION,
RedoCommand,
UndoCommand,
@@ -35,15 +37,17 @@ import {
DocStateChangeManagerService,
DocStateEmitService,
RichTextEditingMutation,
+ UniverDocsPlugin,
UpdateTextCommand,
} from '@univerjs/docs';
import {
+ CanvasColorService,
+ ICanvasColorService,
IRenderManagerService,
NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
RenderManagerService,
} from '@univerjs/engine-render';
import { describe, expect, it } from 'vitest';
-
import { DocMoveCursorController } from '../../../controllers/doc-move-cursor.controller';
import { EditorService, IEditorService } from '../../../services/editor/editor-manager.service';
import { MoveSelectionOperation } from '../../operations/doc-cursor.operation';
@@ -213,3 +217,43 @@ describe('boundary deletion', () => {
}
});
});
+
+describe('folded heading deletion boundaries', () => {
+ it.each([
+ { command: DeleteRightCommand, offset: 3 },
+ { command: DeleteLeftCommand, offset: 9 },
+ ])('$command.id expands hidden content before deleting', async ({ command, offset }) => {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ univer.registerPlugin(UniverDocsPlugin);
+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: 'fold-delete',
+ documentStyle: { documentFlavor: DocumentFlavor.MODERN },
+ body: { dataStream: 'One\rText\rTwo\rTail\r\n', paragraphs: [
+ { startIndex: 3, paragraphId: 'one', headingCollapsed: true, paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ { startIndex: 8, paragraphId: 'text' },
+ { startIndex: 12, paragraphId: 'two', paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ { startIndex: 17, paragraphId: 'tail' },
+ ] },
+ });
+ const render = injector.get(IRenderManagerService).createRender(model.getUnitId()) as RenderUnit;
+ render.deactivate();
+ render.addRenderDependencies([[DocSkeletonManagerService]]);
+ try {
+ injector.get(IUniverInstanceService).focusUnit(model.getUnitId());
+ const commands = injector.get(ICommandService);
+ commands.registerCommand(command);
+ const selections = injector.get(DocSelectionManagerService);
+ selections.__TEST_ONLY_setCurrentSelection({ unitId: model.getUnitId(), subUnitId: model.getUnitId() });
+ selections.__TEST_ONLY_add([{ startOffset: offset, endOffset: offset, collapsed: true, isActive: true }]);
+ const before = model.getBody()!.dataStream;
+ expect(await commands.executeCommand(command.id)).toBe(true);
+ expect(model.getBody()!.dataStream).toBe(before);
+ expect(model.getBody()!.paragraphs![0].headingCollapsed).toBe(false);
+ } finally {
+ univer.dispose();
+ }
+ });
+});
diff --git a/packages/docs-ui/src/commands/commands/break-line.command.ts b/packages/docs-ui/src/commands/commands/break-line.command.ts
index 24bb1a450e..e9fcb19bde 100644
--- a/packages/docs-ui/src/commands/commands/break-line.command.ts
+++ b/packages/docs-ui/src/commands/commands/break-line.command.ts
@@ -14,10 +14,37 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ICommand, IDocumentBody, IMutationInfo, IParagraphBorder, ITextRangeParam } from '@univerjs/core';
+import type {
+ DocumentDataModel,
+ ICommand,
+ IDocumentBody,
+ IMutationInfo,
+ IParagraphBorder,
+ ITextRangeParam,
+} from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
-import { BuildTextUtils, CommandType, DataStreamTreeTokenType, getRichTextEditPath, ICommandService, IUniverInstanceService, JSONX, PresetListType, TextX, TextXActionType, UniverInstanceType, UpdateDocsAttributeType } from '@univerjs/core';
-import { DocSelectionManagerService, generateParagraphs, RichTextEditingMutation } from '@univerjs/docs';
+import {
+ BuildTextUtils,
+ CommandType,
+ DataStreamTreeTokenType,
+ DocumentFlavor,
+ getRichTextEditPath,
+ ICommandService,
+ IUniverInstanceService,
+ JSONX,
+ PresetListType,
+ TextX,
+ TextXActionType,
+ UniverInstanceType,
+ UpdateDocsAttributeType,
+} from '@univerjs/core';
+import {
+ DocSelectionManagerService,
+ generateParagraphs,
+ RichTextEditingMutation,
+ SetHeadingCollapsedCommand,
+} from '@univerjs/docs';
+import { DocumentViewModel } from '@univerjs/engine-render';
import { getTextRunAtPosition, isTopLevelStructuralGap } from '../../basics/paragraph';
import { DocMenuStyleService } from '../../services/doc-menu-style.service';
@@ -75,7 +102,7 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {
const docDataModel = params?.unitId
? univerInstanceService.getUnit<DocumentDataModel>(params.unitId, UniverInstanceType.UNIVER_DOC)
: univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
- const originBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId ?? '')?.getBody();
+ let originBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId ?? '')?.getBody();
if (docDataModel == null || originBody == null) {
return false;
@@ -89,13 +116,33 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {
const isBareStructuralGap = isTopLevelStructuralGap(originBody.dataStream, startOffset) &&
originBody.dataStream[startOffset] !== DataStreamTreeTokenType.PARAGRAPH;
const insertsAtStructuralGap = insertionMode === BreakLineInsertionMode.InsertGap || isBareStructuralGap;
- const prevParagraph = insertsAtStructuralGap
+ let prevParagraph = insertsAtStructuralGap
? undefined
: paragraphs.find((p) => p.startIndex >= startOffset);
if (!prevParagraph && !insertsAtStructuralGap) {
return false;
}
+ if (!segmentId && prevParagraph?.headingCollapsed &&
+ docDataModel.getSnapshot().documentStyle.documentFlavor === DocumentFlavor.MODERN) {
+ const paragraphId = prevParagraph.paragraphId;
+ const viewModel = new DocumentViewModel(docDataModel);
+ try {
+ const isHeading = viewModel.getHeadingSections().some((section) => section.paragraphId === paragraphId);
+ if (isHeading) {
+ if (!commandService.syncExecuteCommand(SetHeadingCollapsedCommand.id, { unitId, paragraphId, collapsed: false })) {
+ return false;
+ }
+ originBody = docDataModel.getBody();
+ prevParagraph = originBody?.paragraphs?.find((paragraph) => paragraph.startIndex >= startOffset);
+ if (!originBody || !prevParagraph) {
+ return false;
+ }
+ }
+ } finally {
+ viewModel.dispose();
+ }
+ }
const isAtParagraphEnd = startOffset === prevParagraph?.startIndex;
const prevParagraphIndex = prevParagraph?.startIndex;
const defaultTextStyle = docMenuStyleService.getDefaultStyle();
diff --git a/packages/docs-ui/src/commands/commands/doc-delete.command.ts b/packages/docs-ui/src/commands/commands/doc-delete.command.ts
index 9c6f7a1203..c4a9574e68 100644
--- a/packages/docs-ui/src/commands/commands/doc-delete.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-delete.command.ts
@@ -62,10 +62,10 @@ import {
DocHistoryAction,
DocSelectionManagerService,
RichTextEditingMutation,
+ SetHeadingCollapsedCommand,
UpdateTextCommand,
} from '@univerjs/docs';
import { getParagraphByGlyph, hasListGlyph, isFirstGlyph, isIndentByGlyph } from '@univerjs/engine-render';
-
import { DocAutoFormatService } from '../../services/doc-auto-format.service';
import { DocMenuStyleService } from '../../services/doc-menu-style.service';
import { IEditorService } from '../../services/editor/editor-manager.service';
@@ -520,6 +520,17 @@ export const DeleteLeftCommand: ICommand<IDeleteBoundaryParams> = {
return false;
}
+ if (activeRange.collapsed && !segmentId) {
+ const hidden = docSkeletonManagerService?.getViewModel().getCollapsedHeadingAtOffset(activeRange.startOffset - 1);
+ if (hidden) {
+ return commandService.executeCommand(SetHeadingCollapsedCommand.id, {
+ unitId,
+ paragraphId: hidden.paragraphId,
+ collapsed: false,
+ });
+ }
+ }
+
const originalLength = body.dataStream.length;
const typingStyle = captureDeletedTypingStyle(accessor, docDataModel, body, activeRange);
const actualRange = activeRange;
@@ -755,6 +766,17 @@ export const DeleteRightCommand: ICommand<IDeleteBoundaryParams> = {
return false;
}
+ if (activeRange.collapsed && !segmentId) {
+ const hidden = docSkeletonManagerService?.getViewModel().getCollapsedHeadingAtOffset(activeRange.startOffset + 1);
+ if (hidden) {
+ return commandService.executeCommand(SetHeadingCollapsedCommand.id, {
+ unitId: docDataModel.getUnitId(),
+ paragraphId: hidden.paragraphId,
+ collapsed: false,
+ });
+ }
+ }
+
const actualRange = activeRange;
const { startOffset, endOffset, collapsed } = actualRange;
if (collapsed && shouldResetEmptyCenteredParagraphAlignment(accessor, docDataModel)) {
diff --git a/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts
index 9048362103..4c7bc95a6f 100644
--- a/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts
+++ b/packages/docs-ui/src/controllers/__tests__/doc-move-cursor.controller.spec.ts
@@ -14,8 +14,25 @@
* limitations under the License.
*/
-import { DataStreamTreeTokenType, Direction } from '@univerjs/core';
-import { DocumentSkeletonPageType, LineType } from '@univerjs/engine-render';
+import {
+ DataStreamTreeTokenType,
+ Direction,
+ DocumentDataModel,
+ DocumentFlavor,
+ LocaleService,
+ NamedStyleType,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { UniverDocsPlugin } from '@univerjs/docs';
+import {
+ DocumentSkeleton,
+ DocumentSkeletonPageType,
+ DocumentViewModel,
+ IRenderManagerService,
+ LineType,
+ RenderManagerService,
+} from '@univerjs/engine-render';
import { describe, expect, it, vi } from 'vitest';
import { DocMoveCursorController } from '../doc-move-cursor.controller';
@@ -25,8 +42,10 @@ function createControllerHarness() {
function createOffsetSkeleton(validOffsets: number[]) {
const validOffsetSet = new Set(validOffsets);
+ const view = new DocumentViewModel(new DocumentDataModel({ id: 'cursor-offsets', documentStyle: {}, body: { dataStream: '\r\n', paragraphs: [{ startIndex: 0, paragraphId: 'empty' }] } }));
return {
+ getViewModel: () => view,
findNodePositionByCharIndex: vi.fn((offset: number) => validOffsetSet.has(offset) ? { offset } : undefined),
};
}
@@ -636,3 +655,35 @@ function createColumnGroup(columns: object[], bodyPage: ReturnType<typeof create
return columnGroup;
}
+
+it('navigates across hidden sections and returns to the heading at a folded document end', () => {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ univer.registerPlugin(UniverDocsPlugin);
+ injector.add([DocMoveCursorController]);
+ const model = univer.createUnit(UniverInstanceType.UNIVER_DOC, {
+ id: 'fold-cursor',
+ documentStyle: { documentFlavor: DocumentFlavor.MODERN },
+ body: { dataStream: 'One\rText\rTwo\rTail\r\n', paragraphs: [
+ { paragraphId: 'one', startIndex: 3, headingCollapsed: true, paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ { paragraphId: 'text', startIndex: 8 },
+ { paragraphId: 'two', startIndex: 12, headingCollapsed: true, paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ { paragraphId: 'tail', startIndex: 17 },
+ ] },
+ }) as DocumentDataModel;
+ const view = new DocumentViewModel(model);
+ const skeleton = DocumentSkeleton.create(view, injector.get(LocaleService));
+ try {
+ skeleton.calculate();
+ const controller = injector.get(DocMoveCursorController);
+ const normalize = Reflect.get(controller, '_normalizeRenderableCursorOffset').bind(controller);
+ const stream = model.getBody()!.dataStream;
+ expect(normalize(skeleton, stream, [], 4, Direction.RIGHT, '', -1)).toBe(9);
+ expect(normalize(skeleton, stream, [], 8, Direction.LEFT, '', -1)).toBe(3);
+ expect(normalize(skeleton, stream, [], 13, Direction.RIGHT, '', -1)).toBe(12);
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+});
diff --git a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
index b166b742fc..e7161bbc45 100644
--- a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
@@ -29,7 +29,6 @@ import type {
INodeSearch,
} from '@univerjs/engine-render';
import type { Subscription } from 'rxjs';
-import type { DocCursorMoveGranularity, IMoveCursorOperationParams } from '../commands/operations/doc-cursor.operation';
import {
DataStreamTreeTokenType,
Direction,
@@ -42,6 +41,7 @@ import {
} from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
import { DocumentSkeletonPageType, IRenderManagerService, LineType } from '@univerjs/engine-render';
+import type { DocCursorMoveGranularity, IMoveCursorOperationParams } from '../commands/operations/doc-cursor.operation';
import { neoGetDocObject } from '../basics/component-tools';
import {
findTableAfterLine,
@@ -579,7 +579,7 @@ export class DocMoveCursorController extends Disposable {
segmentId: string,
resume: () => void
): boolean {
- if (segmentId !== '') {
+ if (segmentId !== '' || skeleton.getViewModel().getCollapsedHeadingAtOffset(offset)) {
return false;
}
const pageIndex = skeleton.findBodyPageIndexByCharIndex(offset);
@@ -850,6 +850,13 @@ export class DocMoveCursorController extends Disposable {
while (current >= 0 && current < dataStream.length && !visited.has(current)) {
visited.add(current);
+ if (!segmentId) {
+ const hidden = skeleton.getViewModel().getCollapsedHeadingAtOffset(current);
+ if (hidden) {
+ current = step < 0 ? hidden.paragraphIndex : hidden.endOffset;
+ continue;
+ }
+ }
const normalizedCursor = this._normalizeCursorOffset(dataStream, customRanges, current, direction);
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts
index 46f22972e5..329f1ea740 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts
@@ -19,8 +19,6 @@
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
import type { IDocLayoutExecutor } from '@univerjs/docs';
import type { Documents, IPointerEvent, RenderUnit } from '@univerjs/engine-render';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
import {
BooleanNumber,
CustomRangeType,
@@ -30,6 +28,7 @@ import {
HorizontalAlign,
ICommandService,
IUniverInstanceService,
+ NamedStyleType,
ObjectRelativeFromH,
ObjectRelativeFromV,
PositionedObjectLayoutType,
@@ -44,6 +43,7 @@ import {
DocStateEmitService,
InsertTextCommand,
RichTextEditingMutation,
+ SetHeadingCollapsedCommand,
SetTextSelectionsOperation,
} from '@univerjs/docs';
import {
@@ -54,6 +54,8 @@ import {
RenderManagerService,
} from '@univerjs/engine-render';
import { CanvasPopupService, ContextMenuService, ICanvasPopupService, IContextMenuService, ILayoutService } from '@univerjs/ui';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { VIEWPORT_KEY } from '../../../basics/docs-view-key';
import { AfterSpaceCommand } from '../../../commands/commands/auto-format.command';
@@ -355,6 +357,56 @@ describe('DocRenderController bounded input publication', () => {
}
});
+ it('preserves a scrolled Modern viewport across heading reversals while Worker initialization is pending', async () => {
+ let elapsed = 0;
+ vi.spyOn(performance, 'now').mockImplementation(() => ++elapsed);
+ const editor = createEditor(100, true, false, DocumentFlavor.MODERN);
+ try {
+ await vi.dynamicImportSettled();
+ editor.commands.registerCommand(SetHeadingCollapsedCommand);
+ const paragraphs = editor.model.getBody()!.paragraphs!;
+ const parent = paragraphs[41];
+ parent.paragraphStyle = { namedStyleType: NamedStyleType.HEADING_1 };
+ paragraphs[81].paragraphStyle = { namedStyleType: NamedStyleType.HEADING_1 };
+ editor.skeleton.getViewModel().reset(editor.model);
+ editor.skeleton.makeDirty(true);
+ editor.skeleton.calculate();
+ expect(editor.skeleton.getSkeletonData()!.pages[0].skeDrawings.size).toBe(1);
+ const viewport = editor.render.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN)!;
+ const docsComponent = editor.render.mainComponent as Documents;
+ const parentLine = editor.skeleton.getSkeletonData()!.pages[0].sections.flatMap((section) => section.columns.flatMap((column) => column.lines)).find((line) => line.paragraphIndex === parent.startIndex)!;
+ viewport.scrollToViewportPos({ viewportScrollY: parentLine.top + docsComponent.getOffsetConfig().docsTop - 40 });
+ const minimumHeight = viewport.calcViewportInfo().viewBound.bottom - docsComponent.getOffsetConfig().docsTop;
+ expect(minimumHeight).toBeGreaterThan(0);
+ const publishedHeights: number[] = [];
+ const subscription = editor.skeleton.layoutProgress$.subscribe((progress) => {
+ if (progress.didPublish && !progress.complete && progress.reason === 'edit') {
+ publishedHeights.push(editor.skeleton.getSkeletonData()!.pages[0].height);
+ }
+ });
+ try {
+ for (const collapsed of [true, false, true, false]) {
+ expect(editor.commands.syncExecuteCommand(SetHeadingCollapsedCommand.id, {
+ unitId: editor.unitId,
+ paragraphId: parent.paragraphId,
+ collapsed,
+ })).toBe(true);
+ expect(editor.skeleton.getSkeletonData()!.pages[0].height).toBeGreaterThanOrEqual(minimumHeight);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(editor.model.getBody()!.customBlocks).toEqual([{ blockId: 'inline-drawing', startIndex: 12 }]);
+ }
+ expect(publishedHeights.length).toBeGreaterThan(0);
+ expect(publishedHeights.every((height) => height >= minimumHeight)).toBe(true);
+ expect(editor.skeleton.findNodePositionByCharIndex(parent.startIndex)).toBeDefined();
+ expect(editor.skeleton.getSkeletonData()!.pages.flatMap((page) => [...page.skeDrawings.keys()])).toEqual(['inline-drawing']);
+ } finally {
+ subscription.unsubscribe();
+ }
+ } finally {
+ editor.dispose();
+ }
+ });
+
it('keeps short Modern edits and spaces complete while Worker initialization is pending', async () => {
const editor = createEditor(3, false, false, DocumentFlavor.MODERN);
try {
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 5ba2444759..b20a7f6691 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
@@ -850,9 +850,18 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
skeleton,
options.invalidation
);
+ const viewport = this._context.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+ const docsComponent = this._context.mainComponent;
+ const minimumPublicationHeight = this._context.unit.documentStyle.documentFlavor === DocumentFlavor.MODERN &&
+ viewport != null && docsComponent instanceof Documents
+ ? Math.max(0, viewport.calcViewportInfo().viewBound.bottom - docsComponent.getOffsetConfig().docsTop)
+ : undefined;
this._layoutCoordinator.schedule(skeleton, {
...options,
anchor: interactionAnchor,
+ ...(minimumPublicationHeight != null && Number.isFinite(minimumPublicationHeight) && minimumPublicationHeight > 0
+ ? { minimumPublicationHeight }
+ : {}),
...(foregroundEndOffset == null ? {} : { foregroundEndOffset }),
preserveInteractionWindow: interactionAnchor != null && interactionAnchor !== options.anchor,
// The authoritative Worker recomputes the suffix after the protected
diff --git a/packages/docs-ui/src/locale/ar-SA.ts b/packages/docs-ui/src/locale/ar-SA.ts
index 47aac90590..024e214b3d 100644
--- a/packages/docs-ui/src/locale/ar-SA.ts
+++ b/packages/docs-ui/src/locale/ar-SA.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: 'لون النص الافتراضي',
noBackground: 'بدون خلفية',
},
+ heading: {
+ collapse: 'طي',
+ expand: 'توسيع',
+ },
'page-settings': {
'document-setting': 'إعداد المستند',
'modern-width': 'عرض المحتوى',
diff --git a/packages/docs-ui/src/locale/ca-ES.ts b/packages/docs-ui/src/locale/ca-ES.ts
index fe97725b94..d6764faecd 100644
--- a/packages/docs-ui/src/locale/ca-ES.ts
+++ b/packages/docs-ui/src/locale/ca-ES.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: 'Color de text predeterminat',
noBackground: 'Sense fons',
},
+ heading: {
+ collapse: 'Redueix',
+ expand: 'Expandeix',
+ },
'page-settings': {
'document-setting': 'Configuració de document',
'modern-width': 'Amplada del contingut',
diff --git a/packages/docs-ui/src/locale/de-DE.ts b/packages/docs-ui/src/locale/de-DE.ts
index 3b19de01d9..82ea146a8d 100644
--- a/packages/docs-ui/src/locale/de-DE.ts
+++ b/packages/docs-ui/src/locale/de-DE.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: 'Standardtextfarbe',
noBackground: 'Kein Hintergrund',
},
+ heading: {
+ collapse: 'Einklappen',
+ expand: 'Ausklappen',
+ },
'page-settings': {
'document-setting': 'Dokumenteneinstellung',
'modern-width': 'Inhaltsbreite',
diff --git a/packages/docs-ui/src/locale/en-US.ts b/packages/docs-ui/src/locale/en-US.ts
index 879c8eab32..20b21b7bac 100644
--- a/packages/docs-ui/src/locale/en-US.ts
+++ b/packages/docs-ui/src/locale/en-US.ts
@@ -242,6 +242,10 @@ const locale = {
defaultTextColor: 'Default text color',
noBackground: 'No background',
},
+ heading: {
+ collapse: 'Collapse',
+ expand: 'Expand',
+ },
'page-settings': {
'document-setting': 'Page Setup',
'modern-width': 'Content width',
diff --git a/packages/docs-ui/src/locale/es-ES.ts b/packages/docs-ui/src/locale/es-ES.ts
index 3b48c8312d..12b32a0f9c 100644
--- a/packages/docs-ui/src/locale/es-ES.ts
+++ b/packages/docs-ui/src/locale/es-ES.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: 'Color de texto predeterminado',
noBackground: 'Sin fondo',
},
+ heading: {
+ collapse: 'Contraer',
+ expand: 'Expandir',
+ },
'page-settings': {
'document-setting': 'Configuración de documento',
'modern-width': 'Ancho del contenido',
diff --git a/packages/docs-ui/src/locale/fa-IR.ts b/packages/docs-ui/src/locale/fa-IR.ts
index 1f91f29277..77be4c833d 100644
--- a/packages/docs-ui/src/locale/fa-IR.ts
+++ b/packages/docs-ui/src/locale/fa-IR.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: 'رنگ پیش‌فرض متن',
noBackground: 'بدون پس‌زمینه',
},
+ heading: {
+ collapse: 'جمع کردن',
+ expand: 'باز کردن',
+ },
'page-settings': {
'document-setting': 'تنظیمات سند',
'modern-width': 'عرض محتوا',
diff --git a/packages/docs-ui/src/locale/fr-FR.ts b/packages/docs-ui/src/locale/fr-FR.ts
index 0ca19bac3d..307d64586b 100644
--- a/packages/docs-ui/src/locale/fr-FR.ts
+++ b/packages/docs-ui/src/locale/fr-FR.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: 'Couleur de texte par défaut',
noBackground: 'Aucun arrière-plan',
},
+ heading: {
+ collapse: 'Réduire',
+ expand: 'Développer',
+ },
'page-settings': {
'document-setting': 'Paramètres du document',
'modern-width': 'Largeur du contenu',
diff --git a/packages/docs-ui/src/locale/id-ID.ts b/packages/docs-ui/src/locale/id-ID.ts
index f26e048e9f..852dfcfa99 100644
--- a/packages/docs-ui/src/locale/id-ID.ts
+++ b/packages/docs-ui/src/locale/id-ID.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: 'Warna teks default',
noBackground: 'Tanpa latar belakang',
},
+ heading: {
+ collapse: 'Ciutkan',
+ expand: 'Perluas',
+ },
'page-settings': {
'document-setting': 'Pengaturan Dokumen',
'modern-width': 'Lebar konten',
diff --git a/packages/docs-ui/src/locale/it-IT.ts b/packages/docs-ui/src/locale/it-IT.ts
index 7191483aa7..8e7a8d845a 100644
--- a/packages/docs-ui/src/locale/it-IT.ts
+++ b/packages/docs-ui/src/locale/it-IT.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: 'Colore testo predefinito',
noBackground: 'Nessuno sfondo',
},
+ heading: {
+ collapse: 'Comprimi',
+ expand: 'Espandi',
+ },
'page-settings': {
'document-setting': 'Impostazione Documento',
'modern-width': 'Larghezza contenuto',
diff --git a/packages/docs-ui/src/locale/ja-JP.ts b/packages/docs-ui/src/locale/ja-JP.ts
index 7a48aa9807..ef8366609d 100644
--- a/packages/docs-ui/src/locale/ja-JP.ts
+++ b/packages/docs-ui/src/locale/ja-JP.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: 'デフォルトの文字色',
noBackground: '背景なし',
},
+ heading: {
+ collapse: '折りたたむ',
+ expand: '展開する',
+ },
'page-settings': {
'document-setting': '文書設定',
'modern-width': 'コンテンツ幅',
diff --git a/packages/docs-ui/src/locale/ko-KR.ts b/packages/docs-ui/src/locale/ko-KR.ts
index 451a759e71..2e84a869fd 100644
--- a/packages/docs-ui/src/locale/ko-KR.ts
+++ b/packages/docs-ui/src/locale/ko-KR.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: '기본 텍스트 색상',
noBackground: '배경 없음',
},
+ heading: {
+ collapse: '접기',
+ expand: '펼치기',
+ },
'page-settings': {
'document-setting': '문서 설정',
'modern-width': '콘텐츠 너비',
diff --git a/packages/docs-ui/src/locale/pl-PL.ts b/packages/docs-ui/src/locale/pl-PL.ts
index de41600157..cbf516444b 100644
--- a/packages/docs-ui/src/locale/pl-PL.ts
+++ b/packages/docs-ui/src/locale/pl-PL.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: 'Domyślny kolor tekstu',
noBackground: 'Brak tła',
},
+ heading: {
+ collapse: 'Zwiń',
+ expand: 'Rozwiń',
+ },
'page-settings': {
'document-setting': 'Ustawienia dokumentu',
'modern-width': 'Szerokość treści',
diff --git a/packages/docs-ui/src/locale/pt-BR.ts b/packages/docs-ui/src/locale/pt-BR.ts
index 5aad82a04b..8cdd55e2dc 100644
--- a/packages/docs-ui/src/locale/pt-BR.ts
+++ b/packages/docs-ui/src/locale/pt-BR.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: 'Cor de texto padrão',
noBackground: 'Sem plano de fundo',
},
+ heading: {
+ collapse: 'Recolher',
+ expand: 'Expandir',
+ },
'page-settings': {
'document-setting': 'Configuração do documento',
'modern-width': 'Largura do conteúdo',
diff --git a/packages/docs-ui/src/locale/ru-RU.ts b/packages/docs-ui/src/locale/ru-RU.ts
index 0b58b7ded3..09f2c30e1a 100644
--- a/packages/docs-ui/src/locale/ru-RU.ts
+++ b/packages/docs-ui/src/locale/ru-RU.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: 'Цвет текста по умолчанию',
noBackground: 'Без фона',
},
+ heading: {
+ collapse: 'Свернуть',
+ expand: 'Развернуть',
+ },
'page-settings': {
'document-setting': 'Настройки документа',
'modern-width': 'Ширина содержимого',
diff --git a/packages/docs-ui/src/locale/sk-SK.ts b/packages/docs-ui/src/locale/sk-SK.ts
index 20b502bf72..deea89ad83 100644
--- a/packages/docs-ui/src/locale/sk-SK.ts
+++ b/packages/docs-ui/src/locale/sk-SK.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: 'Predvolená farba textu',
noBackground: 'Bez pozadia',
},
+ heading: {
+ collapse: 'Zbaliť',
+ expand: 'Rozbaliť',
+ },
'page-settings': {
'document-setting': 'Nastavenia dokumentu',
'modern-width': 'Šírka obsahu',
diff --git a/packages/docs-ui/src/locale/vi-VN.ts b/packages/docs-ui/src/locale/vi-VN.ts
index 5ae7faf4e5..87744eee0a 100644
--- a/packages/docs-ui/src/locale/vi-VN.ts
+++ b/packages/docs-ui/src/locale/vi-VN.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: 'Màu văn bản mặc định',
noBackground: 'Không có nền',
},
+ heading: {
+ collapse: 'Thu gọn',
+ expand: 'Mở rộng',
+ },
'page-settings': {
'document-setting': 'Cài đặt tài liệu',
'modern-width': 'Độ rộng nội dung',
diff --git a/packages/docs-ui/src/locale/zh-CN.ts b/packages/docs-ui/src/locale/zh-CN.ts
index 9fa3739294..39d0f0b57b 100644
--- a/packages/docs-ui/src/locale/zh-CN.ts
+++ b/packages/docs-ui/src/locale/zh-CN.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: '默认文字颜色',
noBackground: '无背景色',
},
+ heading: {
+ collapse: '收起',
+ expand: '展开',
+ },
'page-settings': {
'document-setting': '页面设置',
'modern-width': '内容宽度',
diff --git a/packages/docs-ui/src/locale/zh-HK.ts b/packages/docs-ui/src/locale/zh-HK.ts
index 6fa608c2ef..c3d0f67f3f 100644
--- a/packages/docs-ui/src/locale/zh-HK.ts
+++ b/packages/docs-ui/src/locale/zh-HK.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: '預設文字顏色',
noBackground: '無背景色',
},
+ heading: {
+ collapse: '收合',
+ expand: '展開',
+ },
'page-settings': {
'document-setting': '文件設定',
'modern-width': '內容寬度',
diff --git a/packages/docs-ui/src/locale/zh-TW.ts b/packages/docs-ui/src/locale/zh-TW.ts
index 9686972dc3..845d0d3d78 100644
--- a/packages/docs-ui/src/locale/zh-TW.ts
+++ b/packages/docs-ui/src/locale/zh-TW.ts
@@ -244,6 +244,10 @@ const locale: typeof enUS = {
defaultTextColor: '預設文字顏色',
noBackground: '無背景色',
},
+ heading: {
+ collapse: '收合',
+ expand: '展開',
+ },
'page-settings': {
'document-setting': '文件設定',
'modern-width': '內容寬度',
diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.ts
index 70608f7f78..886de48daf 100644
--- a/packages/docs-ui/src/plugin.ts
+++ b/packages/docs-ui/src/plugin.ts
@@ -15,7 +15,6 @@
*/
import type { Dependency, DocumentDataModel } from '@univerjs/core';
-import type { IUniverDocsUIConfig } from './config/config';
import {
DependentOn,
ICommandService,
@@ -37,6 +36,7 @@ import {
} from '@univerjs/docs';
import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
import { IShortcutService } from '@univerjs/ui';
+import type { IUniverDocsUIConfig } from './config/config';
import pkg from '../package.json';
import { AfterSpaceCommand, EnterCommand, TabCommand } from './commands/commands/auto-format.command';
import { BreakLineCommand } from './commands/commands/break-line.command';
@@ -196,6 +196,7 @@ import { DocHtmlExportService } from './services/clipboard/udm-to-html/doc-html-
import { DocAutoFormatService } from './services/doc-auto-format.service';
import { DocContextualRibbonService } from './services/doc-contextual-ribbon.service';
import { DocEventManagerService } from './services/doc-event-manager.service';
+import { DocHeadingCollapseService } from './services/doc-heading-collapse.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';
@@ -541,6 +542,7 @@ export class UniverDocsUIPlugin extends Plugin {
[DocFloatMenuService],
[DocPasteOptionsRenderController],
[DocParagraphMenuService],
+ [DocHeadingCollapseService],
[DocHeaderFooterController],
[DocHeaderFooterRibbonController],
[DocResizeRenderController],
diff --git a/packages/docs-ui/src/services/__tests__/doc-heading-collapse.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-heading-collapse.service.spec.ts
new file mode 100644
index 0000000000..3faa561763
--- /dev/null
+++ b/packages/docs-ui/src/services/__tests__/doc-heading-collapse.service.spec.ts
@@ -0,0 +1,211 @@
+/**
+ * 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 { RenderUnit } from '@univerjs/engine-render';
+import {
+ DocumentFlavor,
+ ICommandService,
+ LocaleService,
+ LocaleType,
+ NamedStyleType,
+ ThemeService,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ DocSelectionManagerService,
+ DocSkeletonManagerService,
+ SetHeadingCollapsedCommand,
+ UniverDocsPlugin,
+} from '@univerjs/docs';
+import {
+ CanvasColorService,
+ Documents,
+ ICanvasColorService,
+ IRenderManagerService,
+ RenderManagerService,
+ ScrollBar,
+ UniverRenderingContext,
+ Vector2,
+ Viewport,
+} from '@univerjs/engine-render';
+import {
+ DesktopLayoutService,
+ ILayoutService,
+} from '@univerjs/ui';
+import { describe, expect, it, onTestFinished, vi } from 'vitest';
+import enUS from '../../locale/en-US';
+import { HeadingCollapseShape } from '../../views/heading-collapse-shape';
+import { DocEventManagerService } from '../doc-event-manager.service';
+import { DocHeadingCollapseService } from '../doc-heading-collapse.service';
+
+function createTestBed(documentFlavor = DocumentFlavor.MODERN, nested = false) {
+ const context = new Proxy({ font: '', measureText: (text: string) => ({ width: text.length * 8, actualBoundingBoxAscent: 8, actualBoundingBoxDescent: 2 }) }, {
+ get: (target, key) => key in target ? Reflect.get(target, key) : () => {},
+ });
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context as never);
+ const univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: enUS } });
+ onTestFinished(() => {
+ univer.dispose();
+ vi.restoreAllMocks();
+ });
+ univer.registerPlugin(UniverDocsPlugin);
+ const injector = univer.__getInjector();
+ injector.get(LocaleService).setDirection('ltr');
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);
+ const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: 'heading-controls',
+ documentStyle: { documentFlavor, pageSize: { width: 400, height: 600 }, marginLeft: 40, marginTop: 20 },
+ body: { dataStream: 'One\rText\rTwo\rTail\r\n', paragraphs: [
+ { paragraphId: 'one', startIndex: 3, paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ { paragraphId: 'text', startIndex: 8 },
+ { paragraphId: 'two', startIndex: 12, paragraphStyle: { namedStyleType: nested ? NamedStyleType.HEADING_2 : NamedStyleType.HEADING_1 } },
+ { paragraphId: 'tail', startIndex: 17 },
+ ] },
+ });
+ const render = injector.get(IRenderManagerService).createRender(model.getUnitId()) as RenderUnit;
+ render.deactivate();
+ render.engine.resizeBySize(400, 600);
+ const canvas = render.engine.getCanvasElement();
+ canvas.style.width = '400px';
+ Object.defineProperty(canvas, 'clientHeight', { configurable: true, value: 600 });
+ vi.spyOn(canvas, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 400, 600));
+ const viewport = new Viewport('viewMain', render.scene, { left: 0, top: 0, width: 400, height: 600 });
+ onTestFinished(() => viewport.dispose());
+ render.addRenderDependencies([[DocSkeletonManagerService]]);
+ const manager = render.with(DocSkeletonManagerService);
+ const documents = new Documents('heading-controls-documents', manager.getSkeleton());
+ render.mainComponent = documents;
+ render.scene.addObject(documents);
+ render.addRenderDependencies([[DocEventManagerService], [DocHeadingCollapseService]]);
+ const service = render.with(DocHeadingCollapseService);
+ const buttons = () => render.scene.getAllObjects().filter((object): object is HeadingCollapseShape => object instanceof HeadingCollapseShape);
+ return { injector, manager, model, service, render, viewport, buttons, context };
+}
+
+describe('DocHeadingCollapseService', () => {
+ it('updates Canvas geometry after folding and disposes every button', () => {
+ const { injector, manager, service, buttons } = createTestBed();
+ expect(buttons()).toHaveLength(2);
+ const second = buttons().find((button) => button.oKey.endsWith('two'))!;
+ const initialTop = second.top;
+ expect(injector.get(ICommandService).syncExecuteCommand(SetHeadingCollapsedCommand.id, { unitId: 'heading-controls', paragraphId: 'one', collapsed: true })).toBe(true);
+ manager.recalculate();
+ expect(buttons()).toHaveLength(2);
+ expect(second.top).toBeLessThan(initialTop);
+ service.dispose();
+ service.dispose();
+ expect(buttons()).toHaveLength(0);
+ });
+
+ it('activates through the Canvas hit target without starting document selection', () => {
+ const { model, buttons } = createTestBed();
+ const first = buttons()[0];
+ const preventDefault = vi.fn();
+ expect(first.onPointerDown$.emitEvent({ button: 0, preventDefault } as never).stopPropagation).toBe(true);
+ expect(first.onPointerUp$.emitEvent({ button: 0, preventDefault } as never).stopPropagation).toBe(true);
+ expect(model.getBody()!.paragraphs![0].headingCollapsed).toBe(true);
+ expect(preventDefault).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps world coordinates and Canvas hit targets aligned after scrolling and zooming', () => {
+ const { render, viewport, buttons } = createTestBed();
+ render.scene.width = 1600;
+ render.scene.height = 1600;
+ const scrollBar = new ScrollBar(viewport, { enableHorizontal: true });
+ onTestFinished(() => scrollBar.dispose());
+ const button = buttons()[1];
+ const left = button.left;
+ const top = button.top;
+ render.scene.scale(1.75, 1.75);
+ viewport.scrollToViewportPos({ viewportScrollY: 20, viewportScrollX: 5 });
+ const point = new Vector2(
+ (left + button.width / 2 - viewport.viewportScrollX) * 1.75,
+ (top + button.height / 2 - viewport.viewportScrollY) * 1.75
+ );
+ expect(render.scene.pick(point)).toBe(button);
+ expect(button.left).toBe(left);
+ expect(button.top).toBe(top);
+ });
+
+ it('keeps a hovered arrow blue during background resizing and unchanged scroll notifications', () => {
+ const { injector, render, viewport, buttons, context } = createTestBed();
+ const button = buttons()[0];
+ const ctx = new UniverRenderingContext(context as never);
+ const theme = injector.get(ThemeService);
+ button.onPointerEnter$.emitEvent({ buttons: 0 } as never);
+ render.scene.transformByState({ height: 1600 });
+ render.scene.scale(1, 1);
+ viewport.onScrollAfter$.emitEvent({ scrollX: 0, scrollY: 0, viewportScrollX: 0, viewportScrollY: 0 });
+ button.render(ctx);
+ expect(Reflect.get(context, 'fillStyle')).toBe(theme.getColorFromTheme('primary.600'));
+ render.scene.scale(1.75, 1.75);
+ button.render(ctx);
+ expect(Reflect.get(context, 'fillStyle')).toBe(theme.getColorFromTheme('gray.900'));
+ button.onPointerEnter$.emitEvent({ buttons: 0 } as never);
+ viewport.onScrollAfter$.emitEvent({ scrollX: 0, scrollY: 5, viewportScrollX: 0, viewportScrollY: 5 });
+ button.render(ctx);
+ expect(Reflect.get(context, 'fillStyle')).toBe(theme.getColorFromTheme('gray.900'));
+ });
+
+ it('removes hidden child controls and cancels their pending tooltips', () => {
+ const { injector, manager, buttons } = createTestBed(DocumentFlavor.MODERN, true);
+ vi.useFakeTimers();
+ onTestFinished(() => {
+ vi.useRealTimers();
+ });
+ const parent = buttons()[0];
+ const child = buttons()[1];
+ child.onPointerEnter$.emitEvent({ buttons: 0 } as never);
+ const clearTimeoutSpy = vi.spyOn(globalThis, 'clearTimeout');
+ injector.get(ICommandService).syncExecuteCommand(SetHeadingCollapsedCommand.id, {
+ unitId: 'heading-controls',
+ paragraphId: 'one',
+ collapsed: true,
+ });
+ manager.recalculate();
+ expect(buttons()).toEqual([parent]);
+ expect(clearTimeoutSpy).toHaveBeenCalled();
+ vi.advanceTimersByTime(500);
+ injector.get(ICommandService).syncExecuteCommand(SetHeadingCollapsedCommand.id, {
+ unitId: 'heading-controls',
+ paragraphId: 'one',
+ collapsed: false,
+ });
+ manager.recalculate();
+ expect(buttons()).toHaveLength(2);
+ expect(buttons().find((button) => button.oKey.endsWith('two'))).not.toBe(child);
+ });
+
+ it('moves a programmatic selection out of hidden content', () => {
+ const { injector, manager, render } = createTestBed();
+ const selections = injector.get(DocSelectionManagerService);
+ selections.__TEST_ONLY_setCurrentSelection({ unitId: 'heading-controls', subUnitId: 'heading-controls' });
+ injector.get(ICommandService).syncExecuteCommand(SetHeadingCollapsedCommand.id, { unitId: 'heading-controls', paragraphId: 'one', collapsed: true });
+ manager.recalculate();
+ selections.__TEST_ONLY_add([{ startOffset: 6, endOffset: 6, collapsed: true, isActive: true }]);
+ render.scene.render();
+ expect(selections.getActiveTextRange()).toMatchObject({ startOffset: 3, endOffset: 3, collapsed: true });
+ });
+
+ it('creates no controls in traditional mode', () => {
+ const { buttons } = createTestBed(DocumentFlavor.TRADITIONAL);
+ expect(buttons()).toHaveLength(0);
+ });
+});
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 fb77ef8e1f..8f37947777 100644
--- a/packages/docs-ui/src/services/doc-event-manager.service.ts
+++ b/packages/docs-ui/src/services/doc-event-manager.service.ts
@@ -1248,6 +1248,11 @@ export class DocEventManagerService extends Disposable implements IRenderModule
}
findParagraphBoundByIndex(index: number) {
+ this._buildParagraphBounds();
+ const paragraph = this._paragraphBounds.get(index);
+ if (paragraph) {
+ return paragraph;
+ }
this._buildTableBounds();
this._buildTableCellsForDocumentRange(index, index);
let tableParagraph = this._tableParagraphBoundsByIndex.get(index);
@@ -1275,12 +1280,6 @@ export class DocEventManagerService extends Disposable implements IRenderModule
if (tableParagraph) {
return tableParagraph;
}
-
- this._buildParagraphBounds();
- const paragraph = this._paragraphBounds.get(index);
- if (paragraph) {
- return paragraph;
- }
}
findParagraphBoundsInRange(startIndex: number, endIndex: number): IMutiPageParagraphBound[] {
diff --git a/packages/docs-ui/src/services/doc-heading-collapse.service.ts b/packages/docs-ui/src/services/doc-heading-collapse.service.ts
new file mode 100644
index 0000000000..f95dc6f92d
--- /dev/null
+++ b/packages/docs-ui/src/services/doc-heading-collapse.service.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 } from '@univerjs/core';
+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import {
+ Disposable,
+ DocumentFlavor,
+ ICommandService,
+ Inject,
+ isInternalEditorID,
+ LocaleService,
+ ThemeService,
+} from '@univerjs/core';
+import { DocSelectionManagerService, DocSkeletonManagerService, SetHeadingCollapsedCommand } from '@univerjs/docs';
+import { ILayoutService } from '@univerjs/ui';
+import type { LocaleKey } from '../locale/types';
+import type { IHeadingCollapseColors } from '../views/heading-collapse-shape';
+import { VIEWPORT_KEY } from '../basics/docs-view-key';
+import { HeadingCollapseShape } from '../views/heading-collapse-shape';
+import { DocEventManagerService } from './doc-event-manager.service';
+import { TEXT_RANGE_LAYER_INDEX } from './selection/text-range';
+
+export class DocHeadingCollapseService extends Disposable implements IRenderModule {
+ private readonly _buttons = new Map<string, HeadingCollapseShape>();
+ private _colors: IHeadingCollapseColors;
+ private _expandLabel = '';
+ private _collapseLabel = '';
+
+ constructor(
+ private readonly _context: IRenderContext<DocumentDataModel>,
+ @Inject(DocSkeletonManagerService) private readonly _skeletonManager: DocSkeletonManagerService,
+ @Inject(DocEventManagerService) private readonly _eventManager: DocEventManagerService,
+ @Inject(DocSelectionManagerService) private readonly _selections: DocSelectionManagerService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @ILayoutService private readonly _layoutService: ILayoutService,
+ @Inject(ThemeService) themeService: ThemeService,
+ @Inject(LocaleService) localeService: LocaleService
+ ) {
+ super();
+ this._colors = this._getColors(themeService);
+ if (isInternalEditorID(_context.unitId)) {
+ return;
+ }
+ this.disposeWithMe(themeService.currentTheme$.subscribe(() => {
+ this._colors = this._getColors(themeService);
+ this._update();
+ }));
+ this.disposeWithMe(localeService.currentLocale$.subscribe(() => {
+ this._expandLabel = localeService.t<LocaleKey>('docs-ui.heading.expand');
+ this._collapseLabel = localeService.t<LocaleKey>('docs-ui.heading.collapse');
+ this._update();
+ }));
+ this.disposeWithMe(_context.scene.beforeRender$.subscribe(() => this._update()));
+ this.disposeWithMe(this._skeletonManager.currentSkeleton$.subscribe(() => this._update()));
+ this.disposeWithMe(this._skeletonManager.getSkeleton().dirty$.subscribe(() => this._update()));
+ const resetHover = () => this._buttons.forEach((button) => button.resetHover());
+ const viewport = _context.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+ if (viewport) {
+ let scrollX = viewport.viewportScrollX;
+ let scrollY = viewport.viewportScrollY;
+ this.disposeWithMe(viewport.onScrollAfter$.subscribeEvent((event) => {
+ if (event.viewportScrollX !== scrollX || event.viewportScrollY !== scrollY) {
+ resetHover();
+ scrollX = event.viewportScrollX;
+ scrollY = event.viewportScrollY;
+ }
+ }));
+ }
+ this.disposeWithMe(_context.scene.onPointerCancel$.subscribeEvent(resetHover));
+ this.disposeWithMe(_context.scene.onTransformChange$.subscribeEvent(({ value, preValue }) => {
+ if ((value.scaleX != null && value.scaleX !== preValue.scaleX) ||
+ (value.scaleY != null && value.scaleY !== preValue.scaleY)) {
+ resetHover();
+ }
+ }));
+ this.disposeWithMe(_context.scene.onPointerLeave$.subscribeEvent(resetHover));
+ this.disposeWithMe(this._selections.textSelection$.subscribe(({ unitId }) => {
+ if (unitId === _context.unitId) {
+ this._normalizeSelection();
+ }
+ }));
+ }
+
+ private _getColors(themeService: ThemeService): IHeadingCollapseColors {
+ return {
+ normal: themeService.getColorFromTheme('gray.900'),
+ hover: themeService.getColorFromTheme('primary.600'),
+ tooltipBackground: themeService.getColorFromTheme('gray.700'),
+ tooltipText: themeService.getColorFromTheme('gray.0'),
+ };
+ }
+
+ private _normalizeSelection(): void {
+ const target = { unitId: this._context.unitId, subUnitId: this._context.unitId };
+ const info = this._selections.getSelectionInfo(target);
+ if (!info || info.segmentId) {
+ return;
+ }
+ const viewModel = this._skeletonManager.getViewModel();
+ const hiddenRect = info.rectRanges.find((range) => !range.segmentId && range.startOffset != null &&
+ viewModel.getCollapsedHeadingAtOffset(range.startOffset));
+ if (hiddenRect?.startOffset != null) {
+ const offset = viewModel.getCollapsedHeadingAtOffset(hiddenRect.startOffset)!.paragraphIndex;
+ const textRanges = [{ startOffset: offset, endOffset: offset, collapsed: true, isActive: true }];
+ this._selections.replaceSelectionInfoWithoutRefresh({ ...info, textRanges, rectRanges: [] }, target);
+ this._selections.replaceDocRanges(textRanges, target, false, { forceFocus: false });
+ return;
+ }
+ let changed = false;
+ const textRanges = info.textRanges.map((range) => {
+ if (range.segmentId) {
+ return range;
+ }
+ const startOffset = viewModel.getCollapsedHeadingAtOffset(range.startOffset)?.paragraphIndex ?? range.startOffset;
+ const endOffset = viewModel.getCollapsedHeadingAtOffset(range.endOffset)?.paragraphIndex ?? range.endOffset;
+ if (startOffset === range.startOffset && endOffset === range.endOffset) {
+ return range;
+ }
+ changed = true;
+ return { ...range, startOffset, endOffset, collapsed: startOffset === endOffset, startNodePosition: undefined, endNodePosition: undefined };
+ });
+ if (changed) {
+ this._selections.replaceSelectionInfoWithoutRefresh({ ...info, textRanges }, target);
+ this._selections.replaceDocRanges([...textRanges, ...info.rectRanges], target, false, { forceFocus: false });
+ }
+ }
+
+ private _update(): void {
+ this._normalizeSelection();
+ const active = new Set<string>();
+ const viewModel = this._skeletonManager.getViewModel();
+ if (this._context.unit.getSnapshot().documentStyle.documentFlavor === DocumentFlavor.MODERN) {
+ for (const heading of viewModel.getHeadingSections()) {
+ if (heading.startOffset >= heading.endOffset || viewModel.getCollapsedHeadingAtOffset(heading.paragraphIndex)) {
+ continue;
+ }
+ const bound = this._eventManager.findParagraphBoundByIndex(heading.paragraphIndex);
+ if (!bound || bound.segmentId) {
+ continue;
+ }
+ active.add(heading.paragraphId);
+ let button = this._buttons.get(heading.paragraphId);
+ if (!button) {
+ button = new HeadingCollapseShape(`__DocHeadingCollapse__${heading.paragraphId}`, this._colors, () => {
+ const paragraph = this._context.unit.getBody()?.paragraphs?.find((item) => item.paragraphId === heading.paragraphId);
+ if (paragraph && this._commandService.syncExecuteCommand(SetHeadingCollapsedCommand.id, {
+ unitId: this._context.unitId,
+ paragraphId: heading.paragraphId,
+ collapsed: paragraph.headingCollapsed !== true,
+ })) {
+ this._layoutService.focus(this._context.unitId);
+ }
+ });
+ this._buttons.set(heading.paragraphId, button);
+ this._context.scene.addObject(button, TEXT_RANGE_LAYER_INDEX);
+ }
+ const left = bound.firstLine.left - button.width;
+ const top = (bound.firstLine.top + bound.firstLine.bottom - button.height) / 2;
+ if (button.left !== left || button.top !== top) {
+ button.resetHover();
+ button.transformByState({ left, top });
+ }
+ button.update(heading.collapsed, heading.collapsed ? this._expandLabel : this._collapseLabel, this._colors);
+ }
+ }
+ for (const [id, button] of this._buttons) {
+ if (!active.has(id)) {
+ button.dispose();
+ this._buttons.delete(id);
+ }
+ }
+ }
+
+ override dispose(): void {
+ super.dispose();
+ this._buttons.forEach((button) => button.dispose());
+ this._buttons.clear();
+ }
+}
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 0173b20747..8c36882509 100644
--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
@@ -24,14 +24,13 @@ import type {
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';
import {
BlockType,
DataStreamTreeTokenType,
Disposable,
DOC_RANGE_TYPE,
DocumentBlockType,
+ DocumentFlavor,
getParagraphContentStartOffset,
IContextService,
Inject,
@@ -47,6 +46,8 @@ import {
} from '@univerjs/docs';
import { DocumentEditArea } from '@univerjs/engine-render';
import { BehaviorSubject, combineLatest, first, Subject, throttleTime } from 'rxjs';
+import type { IMutiPageParagraphBound, ITableBound, ITableParagraphBound } from './doc-event-manager.service';
+import type { IEditorInputConfig } from './selection/doc-selection-render.service';
import { VIEWPORT_KEY } from '../basics/docs-view-key';
import { isHorizontalLineParagraph } from '../utils/horizontal-line';
import {
@@ -571,11 +572,14 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
? getBlockRangeAnchorRect(this._docEventManagerService, blockRange, paragraph)
: latestParagraphBound.firstLine ?? paragraph.firstLine;
+ const isHeading = this._context.unit.getSnapshot().documentStyle?.documentFlavor === DocumentFlavor.MODERN &&
+ this._docSkeletonManagerService.getViewModel().getHeadingSections().some((heading) => heading.paragraphIndex === targetParagraph.startIndex && heading.startOffset < heading.endOffset);
+ const menuAnchor = isHeading ? { ...baseAnchor, left: baseAnchor.left - 24, right: baseAnchor.right - 24 } : baseAnchor;
if (!target.cellRange) {
- return baseAnchor;
+ return menuAnchor;
}
- return getTableCellParagraphAnchorRect(this._docEventManagerService, latestParagraphBound, baseAnchor);
+ return getTableCellParagraphAnchorRect(this._docEventManagerService, latestParagraphBound, menuAnchor);
};
const disposable = this._docPopupManagerService.attachPopupToRect(
diff --git a/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts b/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts
index 2080cd815f..5ec733b81e 100644
--- a/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts
+++ b/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts
@@ -375,9 +375,9 @@ describe('selection utils', () => {
vi.restoreAllMocks();
});
- it('creates text and rect ranges from char indexes', () => {
- const startPosition = { glyph: 0 };
- const endPosition = { glyph: 1 };
+ it.each([0, 1])('creates text and rect ranges from char indexes ending in cell %s', (endCell) => {
+ const startPosition = createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 0]);
+ const endPosition = createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', endCell], 1);
const skeleton = {
findNodePositionByCharIndex: vi
.fn()
@@ -398,6 +398,30 @@ describe('selection utils', () => {
expect(rectRange?.focusNodePosition).toEqual(endPosition);
});
+ it.each(['start', 'end', 'both'])('ignores rect selections with a hidden %s boundary remapped to a heading', (hiddenBoundary) => {
+ vi.mocked(RectRange.prototype.refresh).mockRestore();
+ const cell = createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 0]);
+ const heading = createNodePosition(['pages', 0]);
+ const { skeleton } = createRectRangeConvertorHarness();
+ const resolvingSkeleton = {
+ ...skeleton,
+ findNodePositionByCharIndex: vi.fn()
+ .mockReturnValueOnce(hiddenBoundary === 'end' ? cell : heading)
+ .mockReturnValueOnce(hiddenBoundary === 'start' ? cell : heading),
+ };
+
+ expect(getRectRangeFromCharIndex(
+ 1,
+ 2,
+ {} as never,
+ createDocument(),
+ resolvingSkeleton as never,
+ {} as never,
+ '',
+ -1
+ )).toBeUndefined();
+ });
+
it('does not create ranges when a character boundary cannot be resolved', () => {
const skeleton = {
getSkeletonData: () => undefined,
diff --git a/packages/docs-ui/src/services/selection/selection-utils.ts b/packages/docs-ui/src/services/selection/selection-utils.ts
index c2f240829f..ad9afc7c35 100644
--- a/packages/docs-ui/src/services/selection/selection-utils.ts
+++ b/packages/docs-ui/src/services/selection/selection-utils.ts
@@ -27,13 +27,13 @@ import type {
ITextSelectionStyle,
Scene,
} from '@univerjs/engine-render';
-import type { IDocRange } from './range-interface';
import { DataStreamTreeNodeType, RANGE_DIRECTION, Tools } from '@univerjs/core';
import {
DocumentSkeletonPageType,
getDocumentSkeletonColumnPagePathInfo,
getOffsetRectForDom,
} from '@univerjs/engine-render';
+import type { IDocRange } from './range-interface';
import { isInSameTableCell, isInSameTableCellData, isValidRectRange } from './convert-rect-range';
import { compareNodePosition } from './convert-text-range';
import { convertPositionsToRectRanges, RectRange } from './rect-range';
@@ -171,7 +171,9 @@ export function getRectRangeFromCharIndex(
const startNodePosition = skeleton.findNodePositionByCharIndex(startOffset, true, segmentId, segmentPage);
const endNodePosition = skeleton.findNodePositionByCharIndex(endOffset, true, segmentId, segmentPage);
- if (startNodePosition == null || endNodePosition == null) {
+ // Hidden table offsets can resolve to their visible heading during layout.
+ if (startNodePosition == null || endNodePosition == null ||
+ startNodePosition.path.indexOf('cells') === -1 || endNodePosition.path.indexOf('cells') === -1) {
return;
}
diff --git a/packages/docs-ui/src/views/ParagraphMenu.tsx b/packages/docs-ui/src/views/ParagraphMenu.tsx
index 3ad4bcab0e..f8eaae2fa9 100644
--- a/packages/docs-ui/src/views/ParagraphMenu.tsx
+++ b/packages/docs-ui/src/views/ParagraphMenu.tsx
@@ -26,12 +26,10 @@ import type { IDocBlockMoveValidationContext } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IPopup, IValueOption, RectPopupDirection } from '@univerjs/ui';
import type { CSSProperties } from 'react';
-import type { LocaleKey } from '../locale/types';
-import type { IMutiPageParagraphBound } from '../services/doc-event-manager.service';
-import type { IDocBlockMenuTarget } from '../services/doc-paragraph-menu.service';
import {
DataStreamTreeTokenType,
DocumentBlockRangeType,
+ DocumentFlavor,
ICommandService,
ILogService,
IUniverInstanceService,
@@ -49,6 +47,7 @@ import {
DocBlockMoveValidatorService,
DocContentInsertService,
DocSelectionManagerService,
+ DocSkeletonManagerService,
RichTextEditingMutation,
} from '@univerjs/docs';
import { IRenderManagerService } from '@univerjs/engine-render';
@@ -62,6 +61,9 @@ import {
} from '@univerjs/ui';
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { BehaviorSubject } from 'rxjs';
+import type { LocaleKey } from '../locale/types';
+import type { IMutiPageParagraphBound } from '../services/doc-event-manager.service';
+import type { IDocBlockMenuTarget } from '../services/doc-paragraph-menu.service';
import {
DocCopyCommand,
DocCopyCurrentParagraphCommand,
@@ -927,6 +929,8 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
const paragraphObj = useMemo(() => doc?.getBody()?.paragraphs?.find((p) => p.startIndex === startIndex), [doc, startIndex]);
const isEmptyParagraph = currentActiveTarget?.emptyMode ?? isEmptyParagraphMenuTarget(dataStream, activeParagraphBound);
const namedStyleType = paragraphObj?.paragraphStyle?.namedStyleType;
+ const isModernHeading = doc?.getDocumentStyle().documentFlavor === DocumentFlavor.MODERN &&
+ startIndex != null && renderUnit?.with(DocSkeletonManagerService).getViewModel().getHeadingSections().some((heading) => heading.paragraphIndex === startIndex && heading.startOffset < heading.endOffset);
const targetIconKey = currentActiveTarget?.icon ?? getParagraphMenuTriggerIconKey(namedStyleType);
const TargetIcon = iconManager.get(targetIconKey);
const paragraphMenuType = useMemo(
@@ -1342,13 +1346,15 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
data-u-focused-table-menu={isFocusedTableMenu ? 'true' : undefined}
ref={anchorRef}
className={clsx(`
- univer-mr-1 univer-inline-flex univer-h-7 univer-cursor-pointer univer-items-center univer-gap-1
- univer-rounded-md univer-border univer-border-solid univer-border-gray-200 univer-bg-gray-0
- univer-px-2 univer-py-0 univer-shadow-sm univer-transition-colors
+ univer-inline-flex univer-h-7 univer-cursor-pointer univer-items-center univer-gap-1 univer-rounded-md
+ univer-border univer-border-solid univer-border-gray-200 univer-bg-gray-0 univer-px-2 univer-py-0
+ univer-shadow-sm univer-transition-colors
hover:univer-bg-gray-50 hover:univer-shadow-md
dark:!univer-border-gray-600 dark:!univer-bg-gray-900
dark:hover:!univer-bg-gray-800
`, {
+ // Outer spacing becomes a pointer target over the Canvas arrow when the popup is clamped.
+ 'univer-mr-1': !isModernHeading,
'univer-bg-gray-100 univer-shadow-md dark:!univer-bg-gray-800': visible,
})}
onMouseEnter={(e) => {
diff --git a/packages/docs-ui/src/views/__tests__/heading-collapse-shape.spec.ts b/packages/docs-ui/src/views/__tests__/heading-collapse-shape.spec.ts
new file mode 100644
index 0000000000..d14745a3cf
--- /dev/null
+++ b/packages/docs-ui/src/views/__tests__/heading-collapse-shape.spec.ts
@@ -0,0 +1,128 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IViewportInfo } from '@univerjs/engine-render';
+import { UniverRenderingContext } from '@univerjs/engine-render';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { HeadingCollapseShape } from '../heading-collapse-shape';
+
+function createButton() {
+ const fills: string[] = [];
+ const context = {
+ save: vi.fn(),
+ restore: vi.fn(),
+ transform: vi.fn(),
+ translate: vi.fn<(left: number, top: number) => void>(),
+ beginPath: vi.fn(),
+ closePath: vi.fn(),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ quadraticCurveTo: vi.fn(),
+ arc: vi.fn(),
+ rect: vi.fn(),
+ fill: () => fills.push(context.fillStyle),
+ fillStyle: '',
+ fillText: vi.fn(),
+ measureText: (text: string) => ({ width: text.length * 8 }),
+ };
+ const ctx = new UniverRenderingContext(context as unknown as CanvasRenderingContext2D);
+ const activate = vi.fn();
+ const colors = { normal: '#121212', hover: '#3355ff', tooltipBackground: '#222222', tooltipText: '#ffffff' };
+ const button = new HeadingCollapseShape('heading-button', colors, activate);
+ button.update(false, 'Collapse', colors);
+ return { button, ctx, context, fills, activate };
+}
+
+describe('HeadingCollapseShape', () => {
+ afterEach(() => vi.useRealTimers());
+
+ it('draws only the arrow until a 500ms hover, then draws its tooltip above', () => {
+ vi.useFakeTimers();
+ const { button, ctx, context, fills } = createButton();
+ button.render(ctx);
+ expect(fills).toEqual(['#121212']);
+ button.onPointerEnter$.emitEvent({ buttons: 0 } as never);
+ button.render(ctx);
+ expect(fills).toEqual(['#121212', '#3355ff']);
+ vi.advanceTimersByTime(499);
+ button.render(ctx);
+ expect(context.fillText).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ button.render(ctx);
+ expect(context.fillText).toHaveBeenCalledWith('Collapse', expect.any(Number), expect.any(Number));
+ expect(context.translate.mock.calls.some(([, top]) => top < 0)).toBe(true);
+ const preventDefault = vi.fn();
+ button.onPointerDown$.emitEvent({ button: 0, preventDefault } as never);
+ button.onPointerUp$.emitEvent({ button: 0, preventDefault } as never);
+ context.fillText.mockClear();
+ button.render(ctx);
+ expect(context.fillText).not.toHaveBeenCalled();
+ expect(fills[fills.length - 1]).toBe('#3355ff');
+ button.dispose();
+ });
+
+ it('keeps the tooltip inside the Canvas at its top edge', () => {
+ vi.useFakeTimers();
+ const { button, ctx, context } = createButton();
+ button.onPointerEnter$.emitEvent({ buttons: 0 } as never);
+ vi.advanceTimersByTime(500);
+ button.render(ctx, { viewBound: { left: 0, top: 0, right: 400, bottom: 600 } } as IViewportInfo);
+ expect(context.fillText).toHaveBeenCalled();
+ expect(context.translate.mock.calls.some(([, top]) => top > button.height)).toBe(true);
+ button.dispose();
+ });
+
+ it('cancels delayed tooltips on pointer leave, scroll reset and disposal', () => {
+ vi.useFakeTimers();
+ const { button, ctx, context } = createButton();
+ button.onPointerEnter$.emitEvent({ buttons: 0 } as never);
+ vi.advanceTimersByTime(300);
+ button.onPointerLeave$.emitEvent({} as never);
+ vi.advanceTimersByTime(500);
+ button.render(ctx);
+ expect(context.fillText).not.toHaveBeenCalled();
+ button.onPointerEnter$.emitEvent({ buttons: 0 } as never);
+ vi.advanceTimersByTime(499);
+ button.render(ctx);
+ expect(context.fillText).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ button.render(ctx);
+ expect(context.fillText).toHaveBeenCalledOnce();
+ button.resetHover();
+ context.fillText.mockClear();
+ button.render(ctx);
+ expect(context.fillText).not.toHaveBeenCalled();
+ button.onPointerEnter$.emitEvent({ buttons: 0 } as never);
+ expect(vi.getTimerCount()).toBe(1);
+ button.dispose();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('does not activate after dragging away or using the secondary button', () => {
+ const { button, activate } = createButton();
+ const preventDefault = vi.fn();
+ button.onPointerDown$.emitEvent({ button: 0, preventDefault } as never);
+ button.onPointerLeave$.emitEvent({} as never);
+ button.onPointerUp$.emitEvent({ button: 0, preventDefault } as never);
+ button.onPointerDown$.emitEvent({ button: 2, preventDefault } as never);
+ button.onPointerUp$.emitEvent({ button: 2, preventDefault } as never);
+ expect(activate).not.toHaveBeenCalled();
+ button.onPointerDown$.emitEvent({ button: 0, preventDefault } as never);
+ button.onPointerUp$.emitEvent({ button: 0, preventDefault } as never);
+ expect(activate).toHaveBeenCalledOnce();
+ button.dispose();
+ });
+});
diff --git a/packages/docs-ui/src/views/heading-collapse-shape.ts b/packages/docs-ui/src/views/heading-collapse-shape.ts
new file mode 100644
index 0000000000..71e8f5db82
--- /dev/null
+++ b/packages/docs-ui/src/views/heading-collapse-shape.ts
@@ -0,0 +1,150 @@
+/**
+ * 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 { IShapeProps, IViewportInfo, UniverRenderingContext } from '@univerjs/engine-render';
+import { CURSOR_TYPE, Rect, Shape } from '@univerjs/engine-render';
+
+export interface IHeadingCollapseColors {
+ normal: string;
+ hover: string;
+ tooltipBackground: string;
+ tooltipText: string;
+}
+
+export class HeadingCollapseShape extends Shape<IShapeProps> {
+ private _collapsed = false;
+ private _label = '';
+ private _colors: IHeadingCollapseColors;
+ private _hovered = false;
+ private _tooltipVisible = false;
+ private _tooltipTimer: ReturnType<typeof setTimeout> | null = null;
+ private _pressed = false;
+
+ constructor(key: string, colors: IHeadingCollapseColors, activate: () => void) {
+ super(key, { width: 24, height: 28, debounceParentDirty: false });
+ this._colors = colors;
+ this.cursor = CURSOR_TYPE.POINTER;
+ this.disposeWithMe(this.onPointerEnter$.subscribeEvent((event) => {
+ if (this._hovered || event.buttons) {
+ return;
+ }
+ this._hovered = true;
+ this._tooltipTimer = setTimeout(() => {
+ this._tooltipTimer = null;
+ this._tooltipVisible = true;
+ this.makeDirty(true);
+ }, 500);
+ this.makeDirty(true);
+ }));
+ this.disposeWithMe(this.onPointerLeave$.subscribeEvent(() => this.resetHover()));
+ this.disposeWithMe(this.onPointerDown$.subscribeEvent((event, state) => {
+ state.stopPropagation();
+ event.preventDefault();
+ this._pressed = event.button === 0;
+ }));
+ this.disposeWithMe(this.onPointerUp$.subscribeEvent((event, state) => {
+ state.stopPropagation();
+ event.preventDefault();
+ const activateButton = this._pressed && event.button === 0;
+ this._pressed = false;
+ this._hideTooltip();
+ if (activateButton) {
+ activate();
+ }
+ }));
+ this.disposeWithMe(this.onClick$.subscribeEvent((_event, state) => state.stopPropagation()));
+ this.disposeWithMe(this.onDblclick$.subscribeEvent((_event, state) => state.stopPropagation()));
+ }
+
+ update(collapsed: boolean, label: string, colors: IHeadingCollapseColors): void {
+ if (collapsed === this._collapsed && label === this._label && colors === this._colors) {
+ return;
+ }
+ this._collapsed = collapsed;
+ this._label = label;
+ this._colors = colors;
+ this.makeDirty(true);
+ }
+
+ resetHover(): void {
+ this._hideTooltip();
+ this._pressed = false;
+ if (this._hovered) {
+ this._hovered = false;
+ this.makeDirty(true);
+ }
+ }
+
+ private _hideTooltip(): void {
+ if (this._tooltipTimer !== null) {
+ clearTimeout(this._tooltipTimer);
+ this._tooltipTimer = null;
+ }
+ if (this._tooltipVisible) {
+ this._tooltipVisible = false;
+ this.makeDirty(true);
+ }
+ }
+
+ protected override _draw(ctx: UniverRenderingContext, bounds?: IViewportInfo): void {
+ ctx.fillStyle = this._hovered ? this._colors.hover : this._colors.normal;
+ ctx.beginPath();
+ if (this._collapsed) {
+ ctx.moveTo(9, 8);
+ ctx.lineTo(16, 14);
+ ctx.lineTo(9, 20);
+ } else {
+ ctx.moveTo(6, 11);
+ ctx.lineTo(18, 11);
+ ctx.lineTo(12, 18);
+ }
+ ctx.closePath();
+ ctx.fill();
+ if (!this._tooltipVisible) {
+ return;
+ }
+ ctx.save();
+ ctx.font = '12px sans-serif';
+ const width = ctx.measureText(this._label).width + 20;
+ const viewport = bounds?.viewBound;
+ const centeredLeft = (this.width - width) / 2;
+ const left = viewport
+ ? Math.max(viewport.left - this.left, Math.min(centeredLeft, viewport.right - this.left - width))
+ : centeredLeft;
+ // Canvas clips at the viewport edge, so keep the tooltip readable when there is no room above.
+ const below = viewport != null && this.top - 36 < viewport.top;
+ ctx.translate(left, below ? this.height + 8 : -36);
+ Rect.drawWith(ctx, { width, height: 28, radius: 6, fill: this._colors.tooltipBackground });
+ ctx.fillStyle = this._colors.tooltipBackground;
+ ctx.beginPath();
+ const arrow = this.width / 2 - left;
+ const arrowBase = below ? 0 : 28;
+ ctx.moveTo(arrow - 4, arrowBase);
+ ctx.lineTo(arrow, below ? -4 : 32);
+ ctx.lineTo(arrow + 4, arrowBase);
+ ctx.fill();
+ ctx.fillStyle = this._colors.tooltipText;
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.fillText(this._label, width / 2, 14);
+ ctx.restore();
+ }
+
+ override dispose(): void {
+ this.resetHover();
+ super.dispose();
+ }
+}
diff --git a/packages/docs/README.md b/packages/docs/README.md
index 8e70691439..8d9f9e3bf3 100644
--- a/packages/docs/README.md
+++ b/packages/docs/README.md
@@ -30,6 +30,56 @@ import { UniverDocsPlugin } from '@univerjs/docs';
univer.registerPlugin(UniverDocsPlugin);
```
+## Heading collapse in Modern documents
+
+Modern documents (`DocumentFlavor.MODERN`) support collapsing Heading 1 through Heading 5.
+The heading stays visible; its section extends to the next heading of the same or a higher
+level, or the end of its content flow. Each table cell and Modern column has its own heading
+hierarchy. Expanding a parent preserves the collapse flags of its nested headings.
+Traditional documents ignore these flags.
+
+`IParagraph.headingCollapsed` is an optional boolean in the document snapshot. Only `true`
+collapses a heading; `false` or an omitted flag leaves it expanded. Collapsing changes layout
+visibility without deleting the section's text, tables, images, or other snapshot content.
+Saving and reopening a Univer snapshot retains the flag. This contract does not establish
+preservation through Office import or export.
+
+### Change collapse state with a command
+
+`UniverDocsPlugin` registers `SetHeadingCollapsedCommand` (`doc.command.set-heading-collapsed`).
+After registering the plugin and creating the document, execute the registered command through
+the Facade API or `ICommandService`; do not call its handler or mutate the model directly.
+For an existing `univerAPI` instance:
+
+```ts
+import { SetHeadingCollapsedCommand } from '@univerjs/docs';
+
+const changed = await univerAPI.executeCommand(SetHeadingCollapsedCommand.id, {
+ unitId: documentId,
+ paragraphId: headingParagraphId,
+ collapsed: true,
+});
+```
+
+Pass the document's unit ID, the heading's stable paragraph ID, and the desired boolean state.
+Use `collapsed: false` to expand. The command returns `false` for a no-op or an invalid target,
+including Traditional or disabled documents, headings hidden by an ancestor, empty sections
+when collapsing, and targets without edit permission.
+
+Concurrent paragraph formatting preserves inherited style references and imported numbering metadata;
+a full replacement can still explicitly clear those fields.
+
+Collapse state is shared document state, not a personal view preference. The command uses the
+rich-text mutation path for undo/redo and collaboration. Undoing a fold preserves later peer
+character formatting and enclosing field or content-control properties that the fold did not edit.
+A selection hidden by a collapse moves to the visible heading. Worker layout uses the same flags
+after edits, undo/redo, and snapshot recovery; visibility changes rebuild the affected layout and retain the published viewport until
+replacement content is ready. Hidden tables and images are omitted from layout publications,
+while their source data remains in the snapshot. Rejected edits with empty operations do not
+advance the Worker mutation queue or force the next real edit to resnapshot the document.
+
+See [the editor interaction details](../docs-ui/README.md#heading-collapse) for the Canvas control.
+
## Resources
- [Documentation](https://docs.univer.ai)
diff --git a/packages/docs/src/commands/commands/__tests__/set-heading-collapsed.command.spec.ts b/packages/docs/src/commands/commands/__tests__/set-heading-collapsed.command.spec.ts
new file mode 100644
index 0000000000..3f1c84e5f6
--- /dev/null
+++ b/packages/docs/src/commands/commands/__tests__/set-heading-collapsed.command.spec.ts
@@ -0,0 +1,340 @@
+/**
+ * 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 { JSONXActions } from '@univerjs/core';
+import {
+ DocStyleType,
+ DocumentDataModel,
+ DocumentFlavor,
+ ICommandService,
+ IPermissionService,
+ JSONX,
+ NamedStyleType,
+ PRESERVE_INSERTED_PARAGRAPH_IDS,
+ PresetListType,
+ RedoCommand,
+ TextXActionType,
+ Tools,
+ UndoCommand,
+ UpdateDocsAttributeType,
+} from '@univerjs/core';
+import { DocumentViewModel } from '@univerjs/engine-render';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createDocumentData, createTestBed } from '../../../facade/__tests__/create-test-bed';
+import { DocSelectionManagerService } from '../../../services/doc-selection-manager.service';
+import { DocStateEmitService } from '../../../services/doc-state-emit.service';
+import { DocumentEditablePermission } from '../../../services/permission/permission-point/document/editable';
+import { RichTextEditingMutation } from '../../mutations/core-editing.mutation';
+import { SetHeadingCollapsedCommand } from '../set-heading-collapsed.command';
+import { UpdateDocumentParagraphStyleCommand } from '../update-document-paragraph-style.command';
+
+function createData() {
+ return createDocumentData('fold-doc', {
+ dataStream: 'Parent\rChild\rText\rPeer\rTail\r\n',
+ customRanges: [],
+ customDecorations: [],
+ paragraphs: [
+ { startIndex: 6, paragraphId: 'parent', paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ { startIndex: 12, paragraphId: 'child', paragraphStyle: { namedStyleType: NamedStyleType.HEADING_2 } },
+ { startIndex: 17, paragraphId: 'text' },
+ { startIndex: 22, paragraphId: 'peer', paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ { startIndex: 27, paragraphId: 'tail' },
+ ],
+ sectionBreaks: [{ startIndex: 28, sectionId: 'section' }],
+ });
+}
+
+function getLatestActions(bed: ReturnType<typeof createTestBed>): JSONXActions {
+ let actions: JSONXActions = null;
+ const subscription = bed.get(DocStateEmitService).docStateChangeParams$.subscribe((change) => {
+ actions = change?.redoState.actions ?? null;
+ });
+ subscription.unsubscribe();
+ expect(actions).not.toBeNull();
+ return actions;
+}
+
+function replayRemoteMutation(bed: ReturnType<typeof createTestBed>, actions: JSONXActions | undefined): void {
+ if (actions == null) {
+ return;
+ }
+ bed.get(ICommandService).syncExecuteCommand(RichTextEditingMutation.id, JSON.parse(JSON.stringify({
+ unitId: bed.doc.getUnitId(),
+ actions,
+ textRanges: null,
+ })), { fromCollab: true });
+}
+
+describe('SetHeadingCollapsedCommand', () => {
+ let bed: ReturnType<typeof createTestBed>;
+ beforeEach(() => {
+ const data = createData();
+ data.documentStyle.documentFlavor = DocumentFlavor.MODERN;
+ bed = createTestBed(data);
+ });
+ afterEach(() => bed.univer.dispose());
+ const set = (paragraphId: string, collapsed: boolean) => bed.get(ICommandService).syncExecuteCommand(
+ SetHeadingCollapsedCommand.id,
+ { unitId: 'fold-doc', paragraphId, collapsed }
+ );
+
+ it('round trips nested collapsed state through snapshots, undo and redo without changing content', async () => {
+ const originalBody = Tools.deepClone(bed.doc.getBody());
+ expect(set('child', true)).toBe(true);
+ expect(set('parent', true)).toBe(true);
+ const saved = JSON.parse(JSON.stringify(bed.doc.getSnapshot()));
+ const restored = new DocumentDataModel(saved);
+ const view = new DocumentViewModel(restored);
+ expect(view.getCollapsedHeadingAtOffset(15)?.paragraphId).toBe('parent');
+ expect(restored.getBody()?.dataStream).toBe(originalBody?.dataStream);
+ view.dispose();
+ restored.dispose();
+ await bed.get(ICommandService).executeCommand(UndoCommand.id);
+ expect(bed.doc.getBody()?.paragraphs?.[0].headingCollapsed).toBeUndefined();
+ expect(bed.doc.getBody()?.paragraphs?.[1].headingCollapsed).toBe(true);
+ await bed.get(ICommandService).executeCommand(RedoCommand.id);
+ expect(bed.doc.getBody()?.paragraphs?.[0].headingCollapsed).toBe(true);
+ expect(set('parent', false)).toBe(true);
+ const expanded = new DocumentViewModel(bed.doc);
+ expect(expanded.getCollapsedHeadingAtOffset(13)?.paragraphId).toBe('child');
+ expect(expanded.getCollapsedHeadingAtOffset(18)).toBeUndefined();
+ expect(bed.doc.getBody()?.dataStream).toBe(originalBody?.dataStream);
+ expanded.dispose();
+ });
+
+ it('replays serialized fold, expansion, undo and redo mutations on a peer', async () => {
+ const peer = createTestBed(Tools.deepClone(bed.doc.getSnapshot()));
+ const originalStream = bed.doc.getBody()!.dataStream;
+ const expectPeerConvergence = () => {
+ replayRemoteMutation(peer, getLatestActions(bed));
+ expect(peer.doc.getSnapshot()).toEqual(bed.doc.getSnapshot());
+ expect(peer.doc.getBody()!.dataStream).toBe(originalStream);
+ };
+ try {
+ expect(set('child', true)).toBe(true);
+ expectPeerConvergence();
+ expect(set('parent', true)).toBe(true);
+ expectPeerConvergence();
+ expect(set('parent', false)).toBe(true);
+ expectPeerConvergence();
+ const expanded = Tools.deepClone(peer.doc.getSnapshot());
+ await bed.get(ICommandService).executeCommand(UndoCommand.id);
+ expectPeerConvergence();
+ expect(peer.doc.getBody()!.paragraphs![0].headingCollapsed).toBe(true);
+ await bed.get(ICommandService).executeCommand(RedoCommand.id);
+ expectPeerConvergence();
+ expect(peer.doc.getSnapshot()).toEqual(expanded);
+ const restored = createTestBed(JSON.parse(JSON.stringify(peer.doc.getSnapshot())));
+ const view = new DocumentViewModel(restored.doc);
+ try {
+ expect(restored.doc.getSnapshot()).toEqual(bed.doc.getSnapshot());
+ expect(view.getCollapsedHeadingAtOffset(13)?.paragraphId).toBe('child');
+ expect(view.getCollapsedHeadingAtOffset(18)).toBeUndefined();
+ } finally {
+ view.dispose();
+ restored.univer.dispose();
+ }
+ } finally {
+ peer.univer.dispose();
+ }
+ });
+
+ it.each(['insert', 'delete', 'delete-heading', 'format'] as const)('converges through peer mutations when folding races with %s', (edit) => {
+ const peer = createTestBed(Tools.deepClone(bed.doc.getSnapshot()));
+ try {
+ expect(set('parent', true)).toBe(true);
+ const fold = Tools.deepClone(getLatestActions(bed));
+ const insertBody = { dataStream: 'Before\r', paragraphs: [{ paragraphId: 'before', startIndex: 6 }] };
+ Reflect.set(insertBody, PRESERVE_INSERTED_PARAGRAPH_IDS, true);
+ let actions: JSONXActions;
+ if (edit === 'insert') {
+ actions = JSONX.getInstance().editOp([{ t: TextXActionType.INSERT, len: 7, body: insertBody }], ['body']);
+ } else if (edit === 'delete') {
+ actions = JSONX.getInstance().editOp([
+ { t: TextXActionType.RETAIN, len: 7 },
+ { t: TextXActionType.DELETE, len: 6 },
+ ], ['body']);
+ } else if (edit === 'delete-heading') {
+ actions = JSONX.getInstance().editOp([{ t: TextXActionType.DELETE, len: 7 }], ['body']);
+ } else {
+ actions = JSONX.getInstance().editOp([
+ { t: TextXActionType.RETAIN, len: 6 },
+ { t: TextXActionType.RETAIN, len: 1, coverType: UpdateDocsAttributeType.COVER, body: {
+ dataStream: '',
+ paragraphs: [{ startIndex: 0, paragraphId: 'parent', paragraphStyle: { spaceAbove: { v: 12 } } }],
+ } },
+ ], ['body']);
+ }
+ peer.get(ICommandService).syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId: peer.doc.getUnitId(),
+ actions,
+ textRanges: null,
+ isEditing: false,
+ });
+ const peerEdit = Tools.deepClone(getLatestActions(peer));
+ replayRemoteMutation(bed, JSONX.transform(peerEdit, fold, 'left'));
+ replayRemoteMutation(peer, JSONX.transform(fold, peerEdit, 'right'));
+ expect(peer.doc.getSnapshot()).toEqual(bed.doc.getSnapshot());
+ const parent = bed.doc.getBody()!.paragraphs!.find((paragraph) => paragraph.paragraphId === 'parent');
+ if (edit === 'delete-heading') {
+ expect(parent).toBeUndefined();
+ expect(bed.doc.getBody()!.dataStream).toBe('Child\rText\rPeer\rTail\r\n');
+ expect(bed.doc.getBody()!.paragraphs![0]).toMatchObject({ paragraphId: 'child', startIndex: 5 });
+ expect(bed.doc.getBody()!.paragraphs![0].headingCollapsed).toBeUndefined();
+ return;
+ }
+ expect(parent).toMatchObject({
+ startIndex: edit === 'insert' ? 13 : 6,
+ headingCollapsed: true,
+ paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 },
+ });
+ expect(parent?.bullet).toBeUndefined();
+ if (edit === 'insert') {
+ expect(bed.doc.getBody()!.dataStream).toBe('Before\rParent\rChild\rText\rPeer\rTail\r\n');
+ } else if (edit === 'delete') {
+ expect(bed.doc.getBody()!.dataStream).toBe('Parent\rText\rPeer\rTail\r\n');
+ expect(bed.doc.getBody()!.paragraphs!.some((paragraph) => paragraph.paragraphId === 'child')).toBe(false);
+ } else {
+ expect(parent?.paragraphStyle?.spaceAbove).toEqual({ v: 12 });
+ }
+ } finally {
+ peer.univer.dispose();
+ }
+ });
+
+ it.each(['left', 'right'] as const)('converges when same-heading toggles race with %s priority', (priority) => {
+ const peer = createTestBed(Tools.deepClone(bed.doc.getSnapshot()));
+ const originalStream = bed.doc.getBody()!.dataStream;
+ try {
+ expect(set('parent', true)).toBe(true);
+ const fold = Tools.deepClone(getLatestActions(bed));
+ const peerCommands = peer.get(ICommandService);
+ expect(peerCommands.syncExecuteCommand(SetHeadingCollapsedCommand.id, {
+ unitId: peer.doc.getUnitId(),
+ paragraphId: 'parent',
+ collapsed: true,
+ })).toBe(true);
+ const peerFold = Tools.deepClone(getLatestActions(peer));
+ expect(peerCommands.syncExecuteCommand(SetHeadingCollapsedCommand.id, {
+ unitId: peer.doc.getUnitId(),
+ paragraphId: 'parent',
+ collapsed: false,
+ })).toBe(true);
+ const peerToggle = JSONX.compose(peerFold, Tools.deepClone(getLatestActions(peer)));
+ replayRemoteMutation(bed, JSONX.transform(peerToggle, fold, priority));
+ replayRemoteMutation(peer, JSONX.transform(fold, peerToggle, priority === 'left' ? 'right' : 'left'));
+ expect(peer.doc.getSnapshot()).toEqual(bed.doc.getSnapshot());
+ expect(bed.doc.getBody()!.paragraphs![0].headingCollapsed).toBe(priority === 'right');
+ expect(bed.doc.getBody()!.dataStream).toBe(originalStream);
+ } finally {
+ peer.univer.dispose();
+ }
+ });
+
+ it.each(['left', 'right'] as const)('retains inherited heading and numbering through concurrent formatting history replay (%s)', async (priority) => {
+ const parent = bed.doc.getBody()!.paragraphs![0];
+ parent.styleId = 'derived-heading';
+ parent.paragraphStyle = undefined;
+ parent.sourceBullet = { listId: 'imported', listType: PresetListType.ORDER_LIST, nestingLevel: 0 };
+ parent.directBullet = null;
+ bed.doc.getSnapshot().styles = {
+ heading: { type: DocStyleType.paragraph, name: 'Heading', paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ 'derived-heading': { type: DocStyleType.paragraph, name: 'Derived', basedOn: 'heading' },
+ };
+ const initial = Tools.deepClone(bed.doc.getSnapshot());
+ const peer = createTestBed(initial);
+ try {
+ const commands = bed.get(ICommandService);
+ expect(set('parent', true)).toBe(true);
+ await commands.executeCommand(UndoCommand.id);
+ expect(bed.doc.getSnapshot()).toEqual(initial);
+ await commands.executeCommand(RedoCommand.id);
+ const fold = Tools.deepClone(getLatestActions(bed));
+
+ const peerCommands = peer.get(ICommandService);
+ expect(peerCommands.syncExecuteCommand(UpdateDocumentParagraphStyleCommand.id, {
+ unitId: peer.doc.getUnitId(),
+ paragraphId: 'parent',
+ startOffset: 0,
+ endOffset: 6,
+ style: { spaceAbove: { v: 12 } },
+ })).toBe(true);
+ await peerCommands.executeCommand(UndoCommand.id);
+ expect(peer.doc.getSnapshot()).toEqual(initial);
+ await peerCommands.executeCommand(RedoCommand.id);
+ const format = Tools.deepClone(getLatestActions(peer));
+
+ replayRemoteMutation(bed, JSONX.transform(format, fold, priority));
+ replayRemoteMutation(peer, JSONX.transform(fold, format, priority === 'left' ? 'right' : 'left'));
+ expect(peer.doc.getSnapshot()).toEqual(bed.doc.getSnapshot());
+ expect(bed.doc.getBody()!.paragraphs![0]).toMatchObject({
+ styleId: 'derived-heading',
+ sourceBullet: parent.sourceBullet,
+ directBullet: null,
+ headingCollapsed: true,
+ paragraphStyle: { spaceAbove: { v: 12 } },
+ });
+ expect(bed.doc.getBody()!.dataStream).toBe(initial.body!.dataStream);
+
+ const restored = new DocumentDataModel(JSON.parse(JSON.stringify(bed.doc.getSnapshot())));
+ const view = new DocumentViewModel(restored);
+ try {
+ expect(view.getCollapsedHeadingAtOffset(15)?.paragraphId).toBe('parent');
+ expect(restored.getSnapshot()).toEqual(bed.doc.getSnapshot());
+ } finally {
+ view.dispose();
+ restored.dispose();
+ }
+ } finally {
+ peer.univer.dispose();
+ }
+ });
+
+ it('moves a hidden caret to the heading and restores it on undo', async () => {
+ const selections = bed.get(DocSelectionManagerService);
+ selections.__TEST_ONLY_setCurrentSelection({ unitId: 'fold-doc', subUnitId: 'fold-doc' });
+ selections.__TEST_ONLY_add([{ startOffset: 15, endOffset: 15, collapsed: true, isActive: true }]);
+ expect(set('parent', true)).toBe(true);
+ expect(selections.getActiveTextRange()).toMatchObject({ startOffset: 6, endOffset: 6 });
+ await bed.get(ICommandService).executeCommand(UndoCommand.id);
+ expect(selections.getActiveTextRange()).toMatchObject({ startOffset: 15, endOffset: 15 });
+ });
+
+ it('rejects non-headings, missing IDs, repeated changes and hidden child headings', () => {
+ expect(set('text', true)).toBe(false);
+ expect(set('missing', true)).toBe(false);
+ expect(set('parent', true)).toBe(true);
+ expect(set('parent', true)).toBe(false);
+ expect(set('child', true)).toBe(false);
+ });
+
+ it('does not modify traditional or disabled documents', () => {
+ bed.doc.updateDocumentStyle({ documentFlavor: DocumentFlavor.TRADITIONAL });
+ expect(set('parent', true)).toBe(false);
+ bed.doc.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });
+ bed.doc.getSnapshot().disabled = true;
+ expect(set('parent', true)).toBe(false);
+ });
+
+ it('respects document edit permission', () => {
+ const permissions = bed.get(IPermissionService);
+ const point = new DocumentEditablePermission('fold-doc');
+ permissions.addPermissionPoint(point);
+ permissions.updatePermissionPoint(point.id, false);
+ expect(set('parent', true)).toBe(false);
+ expect(bed.doc.getBody()?.paragraphs?.[0].headingCollapsed).toBeUndefined();
+ });
+});
diff --git a/packages/docs/src/commands/commands/set-heading-collapsed.command.ts b/packages/docs/src/commands/commands/set-heading-collapsed.command.ts
new file mode 100644
index 0000000000..8cc1027670
--- /dev/null
+++ b/packages/docs/src/commands/commands/set-heading-collapsed.command.ts
@@ -0,0 +1,107 @@
+/**
+ * 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, ICommand } from '@univerjs/core';
+import {
+ CommandType,
+ DocumentFlavor,
+ getParagraphContentStartOffset,
+ getRichTextEditPath,
+ ICommandService,
+ IPermissionService,
+ IUniverInstanceService,
+ JSONX,
+ TextX,
+ TextXActionType,
+ UniverInstanceType,
+ UpdateDocsAttributeType,
+} from '@univerjs/core';
+import { DocumentViewModel } from '@univerjs/engine-render';
+import { DocSelectionManagerService } from '../../services/doc-selection-manager.service';
+import { canEditDocumentTargets } from '../../services/permission/document-permission';
+import { getDocumentEditTargetObjectIds } from '../../services/permission/document-permission-resolver';
+import { RichTextEditingMutation } from '../mutations/core-editing.mutation';
+
+export interface ISetHeadingCollapsedCommandParams {
+ unitId: string;
+ paragraphId: string;
+ collapsed: boolean;
+}
+
+export const SetHeadingCollapsedCommand: ICommand<ISetHeadingCollapsedCommandParams> = {
+ id: 'doc.command.set-heading-collapsed',
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => {
+ if (!params || typeof params.collapsed !== 'boolean') {
+ return false;
+ }
+ const doc = accessor.get(IUniverInstanceService).getUnit<DocumentDataModel>(params.unitId, UniverInstanceType.UNIVER_DOC);
+ if (!doc || doc.getDisabled() || doc.getSnapshot().documentStyle.documentFlavor !== DocumentFlavor.MODERN) {
+ return false;
+ }
+ const body = doc.getBody();
+ const matches = body?.paragraphs?.filter((paragraph) => paragraph.paragraphId === params.paragraphId) ?? [];
+ const paragraph = matches[0];
+ if (!body || matches.length !== 1 || (paragraph.headingCollapsed === true) === params.collapsed) {
+ return false;
+ }
+ const viewModel = new DocumentViewModel(doc);
+ try {
+ const section = viewModel.getHeadingSections().find((section) => section.paragraphId === params.paragraphId);
+ if (!section || (params.collapsed && section.startOffset >= section.endOffset) || viewModel.getCollapsedHeadingAtOffset(paragraph.startIndex)) {
+ return false;
+ }
+ const targets = getDocumentEditTargetObjectIds(doc, '', {
+ startOffset: getParagraphContentStartOffset(body, paragraph),
+ endOffset: paragraph.startIndex + 1,
+ });
+ if (!canEditDocumentTargets(accessor.get(IPermissionService), params.unitId, targets)) {
+ return false;
+ }
+ const textX = new TextX();
+ if (paragraph.startIndex > 0) {
+ textX.push({ t: TextXActionType.RETAIN, len: paragraph.startIndex });
+ }
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len: 1,
+ coverType: UpdateDocsAttributeType.COVER,
+ body: {
+ dataStream: '',
+ paragraphs: [{ paragraphId: paragraph.paragraphId, startIndex: 0, headingCollapsed: params.collapsed }],
+ },
+ });
+ const actions = JSONX.getInstance().editOp(textX.serialize(), getRichTextEditPath(doc));
+ const selectionService = accessor.get(DocSelectionManagerService);
+ const selectionTarget = { unitId: params.unitId, subUnitId: params.unitId };
+ const ranges = selectionService.getDocRanges(selectionTarget) ?? [];
+ const hidesSelection = params.collapsed && !selectionService.getSelectionInfo(selectionTarget)?.segmentId && ranges.some((range) => !range.segmentId &&
+ range.startOffset != null && range.endOffset != null &&
+ range.endOffset >= section.startOffset && range.startOffset < section.endOffset);
+ return Boolean(accessor.get(ICommandService).syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId: params.unitId,
+ actions,
+ textRanges: hidesSelection ? [{ startOffset: paragraph.startIndex, endOffset: paragraph.startIndex, collapsed: true }] : null,
+ prevTextRanges: ranges,
+ noNeedSetTextRange: !hidesSelection,
+ isEditing: false,
+ trigger: SetHeadingCollapsedCommand.id,
+ }));
+ } finally {
+ viewModel.dispose();
+ }
+ },
+};
diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.ts
index fd6f571a23..9f171e9eef 100644
--- a/packages/docs/src/index.ts
+++ b/packages/docs/src/index.ts
@@ -36,6 +36,7 @@ export type { ISetDocumentNameCommandParams } from './commands/commands/set-docu
export { SetDocumentPermissionCommand } from './commands/commands/set-document-permission.command';
export type { ISetDocumentPermissionCommandParams } from './commands/commands/set-document-permission.command';
export { SetDocumentPermissionsCommand } from './commands/commands/set-document-permissions.command';
+export { SetHeadingCollapsedCommand } from './commands/commands/set-heading-collapsed.command';
export { SetSectionHeaderFooterLinkCommand } from './commands/commands/set-section-header-footer-link.command';
export type { ISetSectionHeaderFooterLinkCommandParams } from './commands/commands/set-section-header-footer-link.command';
export { UpdateDocumentParagraphStyleCommand } from './commands/commands/update-document-paragraph-style.command';
diff --git a/packages/docs/src/layout-worker/__tests__/worker.spec.ts b/packages/docs/src/layout-worker/__tests__/worker.spec.ts
index 0a973c9a23..a0ec4c362f 100644
--- a/packages/docs/src/layout-worker/__tests__/worker.spec.ts
+++ b/packages/docs/src/layout-worker/__tests__/worker.spec.ts
@@ -17,12 +17,21 @@
import {
createDocumentModelWithStyle,
CustomRangeType,
+ DataStreamTreeTokenType,
DocumentFlavor,
JSONX,
LocaleType,
+ NamedStyleType,
ObjectRelativeFromH,
ObjectRelativeFromV,
PositionedObjectLayoutType,
+ TableAlignmentType,
+ TableRowHeightRule,
+ TableSizeType,
+ TableTextWrapType,
+ TextX,
+ TextXActionType,
+ UpdateDocsAttributeType,
} from '@univerjs/core';
import { getFontStyleString, invalidateDocumentFontMetrics } from '@univerjs/engine-render';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -120,6 +129,195 @@ describe('DocsLayoutWorkerRuntime', () => {
}
});
+ it('preserves heading visibility through Worker edits, undo/redo, and snapshot recovery', async () => {
+ stubOffscreenCanvas();
+ const source = createDocumentModelWithStyle('Parent\rHidden\rPeer\rTail', {});
+ source.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });
+ const snapshot = structuredClone(source.getSnapshot());
+ snapshot.body!.paragraphs = [
+ { startIndex: 6, paragraphId: 'parent', headingCollapsed: false, paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ { startIndex: 13, paragraphId: 'hidden' },
+ { startIndex: 18, paragraphId: 'peer', paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ { startIndex: 23, paragraphId: 'tail' },
+ ];
+ const runtime = new DocsLayoutWorkerRuntime();
+ const identity = { unitId: source.getUnitId(), mountId: 'heading-mount', mountEpoch: 1, viewportEpoch: 1 };
+ const createSession = (sessionEpoch: number, modelRevision: number) => runtime.createSession({
+ unitId: identity.unitId,
+ sessionEpoch,
+ snapshot: structuredClone(snapshot),
+ modelRevision,
+ locale: LocaleType.EN_US,
+ direction: 'ltr',
+ });
+ await createSession(1, 0);
+ try {
+ for (let revision = 0; revision < 5; revision++) {
+ const collapsed = revision === 1 || revision >= 3;
+ const textX = new TextX();
+ textX.push({ t: TextXActionType.RETAIN, len: 6 });
+ textX.push({
+ t: TextXActionType.RETAIN,
+ len: 1,
+ coverType: UpdateDocsAttributeType.COVER,
+ body: { dataStream: '', paragraphs: [{ paragraphId: 'parent', startIndex: 0, headingCollapsed: collapsed }] },
+ });
+ if (revision === 4) {
+ snapshot.body!.paragraphs![0].headingCollapsed = true;
+ await createSession(2, revision);
+ }
+ const recovered = revision === 0 || revision === 4;
+ const start = await runtime.startLayout({
+ ...identity,
+ metricsRevision: revision + 1,
+ baseRevision: recovered ? revision : revision - 1,
+ modelRevision: revision,
+ mutations: recovered
+ ? []
+ : [{
+ baseRevision: revision - 1,
+ modelRevision: revision,
+ actions: JSONX.getInstance().editOp(textX.serialize(), ['body']),
+ }],
+ reason: recovered ? 'initial' : 'edit',
+ budgetMs: 0,
+ });
+ if (start.status !== DocLayoutSessionStatus.ACCEPTED) {
+ throw new Error('Expected Worker heading layout to start.');
+ }
+ let step = start.step;
+ await expect.poll(async () => {
+ if (!step.progress.complete) {
+ step = await runtime.stepLayout({ ...identity, generation: step.progress.generation, budgetMs: 8 });
+ }
+ return step.progress.complete;
+ }).toBe(true);
+ const result = await runtime.getLayoutPage({ ...identity, pageIndex: 0 });
+ const lines = result.page!.page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines));
+ expect(lines.map((line) => line.paragraphIndex)).toEqual(collapsed ? [6, 18, 23] : [6, 13, 18, 23]);
+ expect(lines.flatMap((line) => line.divides.flatMap((divide) => divide.glyphGroup))
+ .map((glyph) => glyph.raw).join('')).toContain('Peer');
+ }
+ } finally {
+ runtime.dispose();
+ source.dispose();
+ }
+ });
+
+ it('loads folded tables and images without publishing hidden resources and supersedes an unfinished expansion', async () => {
+ stubOffscreenCanvas();
+ const T = DataStreamTreeTokenType;
+ const prefix = 'Intro\rParent\r';
+ const table = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell\r\n${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const content = `${prefix}${T.CUSTOM_BLOCK}\r${table}\rPeer\r${'Visible tail\r'.repeat(50)}\n`;
+ const source = createDocumentModelWithStyle(content, {});
+ source.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });
+ const snapshot = structuredClone(source.getSnapshot());
+ const parentOffset = prefix.length - 1;
+ const peerOffset = content.indexOf('Peer') + 4;
+ snapshot.body!.paragraphs = [...content.matchAll(/\r/g)].map((match, index) => ({
+ startIndex: match.index,
+ paragraphId: `resource-p${index}`,
+ headingCollapsed: match.index === parentOffset,
+ paragraphStyle: match.index === parentOffset || match.index === peerOffset
+ ? { namedStyleType: NamedStyleType.HEADING_1 }
+ : undefined,
+ }));
+ snapshot.body!.sectionBreaks = [...content.matchAll(/\n/g)].map((match, index) => ({ startIndex: match.index, sectionId: `resource-s${index}` }));
+ snapshot.body!.customBlocks = [{ blockId: 'image', startIndex: prefix.length }];
+ snapshot.body!.tables = [{ tableId: 'table', startIndex: prefix.length + 2, endIndex: prefix.length + 2 + table.length }];
+ snapshot.drawings = { image: {
+ unitId: snapshot.id,
+ subUnitId: snapshot.id,
+ drawingId: 'image',
+ 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 },
+ },
+ } };
+ snapshot.tableSource = { table: {
+ tableId: 'table',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: { positionH: { relativeFrom: ObjectRelativeFromH.PAGE }, positionV: { relativeFrom: ObjectRelativeFromV.PAGE } },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 80 } },
+ cellMargin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } },
+ tableRows: [{ tableCells: [{}], trHeight: { val: { v: 0 }, hRule: TableRowHeightRule.AUTO } }],
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 80 } } }],
+ } };
+ const runtime = new DocsLayoutWorkerRuntime();
+ const identity = { unitId: snapshot.id, mountId: 'folded-resources', mountEpoch: 1, viewportEpoch: 1 };
+ await runtime.createSession({ unitId: snapshot.id, sessionEpoch: 1, snapshot, modelRevision: 0, locale: LocaleType.EN_US, direction: 'ltr' });
+ try {
+ let interruptedGeneration: number | undefined;
+ for (let revision = 0; revision < 5; revision++) {
+ const collapsed = revision % 2 === 0;
+ const textX = new TextX();
+ textX.push({ t: TextXActionType.RETAIN, len: parentOffset });
+ textX.push({ t: TextXActionType.RETAIN, len: 1, coverType: UpdateDocsAttributeType.COVER, body: {
+ dataStream: '',
+ paragraphs: [{ paragraphId: 'resource-p1', startIndex: 0, headingCollapsed: collapsed }],
+ } });
+ const start = await runtime.startLayout({
+ ...identity,
+ metricsRevision: revision + 1,
+ baseRevision: Math.max(0, revision - 1),
+ modelRevision: revision,
+ mutations: revision === 0 ? [] : [{ baseRevision: revision - 1, modelRevision: revision, actions: JSONX.getInstance().editOp(textX.serialize(), ['body']) }],
+ reason: revision === 0 ? 'initial' : 'edit',
+ anchor: parentOffset,
+ budgetMs: 0,
+ });
+ if (start.status !== DocLayoutSessionStatus.ACCEPTED) {
+ throw new Error('Expected folded resource layout to start.');
+ }
+ if (revision === 1) {
+ expect(start.step.progress.complete).toBe(false);
+ interruptedGeneration = start.step.progress.generation;
+ continue;
+ }
+ if (revision === 2) {
+ const superseded = await runtime.stepLayout({ ...identity, generation: interruptedGeneration!, budgetMs: 8 });
+ expect(superseded.progress.cancelled).toBe(true);
+ }
+ let step = start.step;
+ for (let index = 0; index < 500; index++) {
+ if (collapsed && step.publication?.kind === 'block') {
+ expect(step.publication.block.skeDrawings).toHaveLength(0);
+ expect(step.publication.block.skeTables).toHaveLength(0);
+ }
+ if (!collapsed && step.publication?.kind === 'block' && step.progress.stableLaidOutThrough >= peerOffset) {
+ expect(step.publication.block.skeDrawings).toHaveLength(1);
+ expect(step.publication.block.skeTables).toHaveLength(1);
+ }
+ if (step.progress.complete) {
+ break;
+ }
+ // Pattern imports need an event-loop turn; microtask-only stepping can starve them in CI.
+ await new Promise<void>((resolve) => {
+ setTimeout(resolve, 0);
+ });
+ step = await runtime.stepLayout({ ...identity, generation: step.progress.generation, budgetMs: 0 });
+ }
+ expect(step.progress.complete).toBe(true);
+ const result = await runtime.getLayoutPage({ ...identity, pageIndex: 0 });
+ expect(result.page!.page.skeTables).toHaveLength(collapsed ? 0 : 1);
+ expect(result.page!.page.skeDrawings).toHaveLength(collapsed ? 0 : 1);
+ expect(result.page!.page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines))
+ .some((line) => line.paragraphIndex === peerOffset)).toBe(true);
+ }
+ } finally {
+ runtime.dispose();
+ source.dispose();
+ }
+ });
+
it('applies custom range presentations to the matching body, header, and footer segments', async () => {
stubOffscreenCanvas();
const sourceModel = createDocumentModelWithStyle('Body\r', {});
diff --git a/packages/docs/src/plugin.ts b/packages/docs/src/plugin.ts
index d9e20ff361..d059e374a1 100644
--- a/packages/docs/src/plugin.ts
+++ b/packages/docs/src/plugin.ts
@@ -15,7 +15,6 @@
*/
import type { Dependency, ICommand } from '@univerjs/core';
-import type { IUniverDocsConfig } from './config/config';
import {
ICommandService,
IConfigService,
@@ -28,6 +27,7 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { UnitObject } from '@univerjs/protocol';
+import type { IUniverDocsConfig } from './config/config';
import pkg from '../package.json';
import { DeleteTextCommand, InsertTextCommand, UpdateTextCommand } from './commands/commands/core-editing.command';
import { CreateHeaderFooterCommand } from './commands/commands/create-header-footer.command';
@@ -37,6 +37,7 @@ import {
import { SetDocumentNameCommand } from './commands/commands/set-document-name.command';
import { SetDocumentPermissionCommand } from './commands/commands/set-document-permission.command';
import { SetDocumentPermissionsCommand } from './commands/commands/set-document-permissions.command';
+import { SetHeadingCollapsedCommand } from './commands/commands/set-heading-collapsed.command';
import { SetSectionHeaderFooterLinkCommand } from './commands/commands/set-section-header-footer-link.command';
import { UpdateDocumentParagraphStyleCommand } from './commands/commands/update-document-paragraph-style.command';
import {
@@ -126,6 +127,7 @@ export class UniverDocsPlugin extends Plugin {
SetDocumentPermissionsCommand,
SetDocumentDefaultParagraphStyleCommand,
SetDocumentNameCommand,
+ SetHeadingCollapsedCommand,
SetSectionHeaderFooterLinkCommand,
UpdateDocumentParagraphStyleCommand,
UpdateDocumentSectionCommand,
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 f3fa341faa..486b2650fe 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
@@ -15,7 +15,6 @@
*/
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
-import type { IDocLayoutExecutor, IDocLayoutMountIdentity, IDocLayoutStartResult } from '../doc-layout-executor.service';
import {
CustomRangeType,
DocumentFlavor,
@@ -38,6 +37,7 @@ import {
setDocsCustomBlockRenderViewportProvider,
} from '@univerjs/engine-render';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { IDocLayoutExecutor, IDocLayoutMountIdentity, IDocLayoutStartResult } from '../doc-layout-executor.service';
import { RichTextEditingMutation } from '../../commands/mutations/core-editing.mutation';
import { UniverDocsPlugin } from '../../plugin';
import {
@@ -511,7 +511,7 @@ describe('DocLayoutExecutorService', () => {
});
});
- it('projects committed mutations to the Worker in revision order before layout starts', async () => {
+ it.each([false, true])('projects committed mutations without resnapshot after empty operations: %s', async (emptyOperation) => {
const injector = univer.__getInjector();
const service = injector.get(DocLayoutExecutorService);
const executor = createExecutor();
@@ -524,6 +524,13 @@ describe('DocLayoutExecutorService', () => {
const commandService = injector.get(ICommandService);
for (const [offset, text] of [[5, 'A'], [6, 'B']] as const) {
+ if (emptyOperation) {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId: 'traditional-doc',
+ actions: [],
+ textRanges: [],
+ });
+ }
const textX = new TextX();
textX.push({ t: TextXActionType.RETAIN, len: offset });
textX.push({
diff --git a/packages/docs/src/services/doc-layout-executor.service.ts b/packages/docs/src/services/doc-layout-executor.service.ts
index c840626ff4..056f8fa263 100644
--- a/packages/docs/src/services/doc-layout-executor.service.ts
+++ b/packages/docs/src/services/doc-layout-executor.service.ts
@@ -31,7 +31,6 @@ import type {
IDocumentLayoutSessionStartOptions,
IDocumentLayoutStepResult,
} from '@univerjs/engine-render';
-import type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';
import {
Disposable,
DocumentFlavor,
@@ -51,6 +50,7 @@ import {
} from '@univerjs/core';
import { getDocsCustomBlockRenderViewport } from '@univerjs/engine-render';
import { BehaviorSubject } from 'rxjs';
+import type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';
import { RICH_TEXT_EDITING_MUTATION_ID } from '../commands/mutations/core-editing.mutation-id';
import { createDocumentLayoutSnapshot } from './document-layout-snapshot';
@@ -692,6 +692,9 @@ export class DocLayoutExecutorService extends Disposable {
if (executor == null || dataModel == null) {
return;
}
+ if (JSONX.isNoop(params.actions) || params.actions?.length === 0) {
+ return;
+ }
const session = this._sessions.get(params.unitId);
if (session == null) {
@@ -701,9 +704,6 @@ export class DocLayoutExecutorService extends Disposable {
return;
}
- if (JSONX.isNoop(params.actions)) {
- return;
- }
const sourceMutationRevision = dataModel.getMutationRevision();
if (sourceMutationRevision !== session.sourceMutationRevision + 1) {
session.needsResnapshot = true;
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 310193fe55..26c279444b 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
@@ -15,8 +15,6 @@
*/
import type { IDocumentData, IParagraph } from '@univerjs/core';
-import type { IDocumentLayoutSnapshot } from '../../document-layout-presentation';
-import type { IDocumentLayoutPageGeometryPublication } from '../document-layout-publication';
import {
BooleanNumber,
ColumnLayoutType,
@@ -33,6 +31,7 @@ import {
HorizontalAlign,
LocaleService,
LocaleType,
+ NamedStyleType,
ObjectRelativeFromH,
ObjectRelativeFromV,
PageOrientType,
@@ -52,6 +51,8 @@ import {
WrapTextType,
} from '@univerjs/core';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { IDocumentLayoutSnapshot } from '../../document-layout-presentation';
+import type { IDocumentLayoutPageGeometryPublication } from '../document-layout-publication';
import { DocumentSkeletonPageType, GlyphType, PageLayoutType } from '../../../../basics/i-document-skeleton-cached';
import { Vector2 } from '../../../../basics/vector2';
import { setDocsCustomBlockRenderViewportProvider } from '../../custom-block-render-viewport';
@@ -59,7 +60,7 @@ import { registerDocumentLayoutPresentation } from '../../document-layout-presen
import { setDocsTableRenderViewportProvider } from '../../table-render-viewport';
import { DocumentViewModel } from '../../view-model/document-view-model';
import { DocumentSkeleton } from '../doc-skeleton';
-import { serializeDocumentSkeletonPage } from '../document-layout-page-patch';
+import { serializeDocumentSkeletonContinuousBlock, serializeDocumentSkeletonPage } from '../document-layout-page-patch';
import { Hyphen } from '../hyphenation/hyphen';
import { Lang } from '../hyphenation/lang';
import { PATTERN_LOADERS } from '../hyphenation/pattern-loaders.gen';
@@ -2763,6 +2764,72 @@ describe('doc skeleton', () => {
univer.dispose();
});
+ it('commits a Worker continuation after its section is absent from the retained Main interaction window', () => {
+ const univer = new Univer();
+ const content = `Modern paragraph across imported pages.${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.PAGE_BREAK}`.repeat(40);
+ const model = createDocumentModelWithStyle(content, {});
+ model.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });
+ model.updateDocumentDataPageSize(240, 180);
+ model.getBody()!.sectionBreaks![0].pageSize = { width: 240, height: 180 };
+ const localeService = univer.__getInjector().get(LocaleService);
+ const main = DocumentSkeleton.create(new DocumentViewModel(model), localeService);
+ const worker = DocumentSkeleton.create(new DocumentViewModel(model), localeService);
+ try {
+ const mainGeneration = main.startIncrementalLayout({ reason: 'initial', anchor: 0 });
+ let mainProgress = main.stepIncrementalLayout(mainGeneration, 0);
+ for (let step = 0; step < 100 && !mainProgress.didPublishAnchor; step++) {
+ mainProgress = main.stepIncrementalLayout(mainGeneration, 0);
+ }
+ expect(mainProgress.didPublishAnchor).toBe(true);
+ const retainedPage = main.getSkeletonData()!.pages[0];
+ const protectedEnd = retainedPage.sections[0].columns[0].lines[0].ed;
+ main.beginExternalLayout({
+ reason: 'edit',
+ protectedRange: { mode: 'continuous', startOffset: 0, endOffset: protectedEnd },
+ });
+ const workerGeneration = worker.startIncrementalLayout({ reason: 'initial' });
+ let snapshot: ReturnType<typeof serializeDocumentSkeletonContinuousBlock>['snapshot'] | null = null;
+ let sawMissingBoundary = false;
+ let complete = false;
+ for (let step = 0; step < 1000; step++) {
+ const progress = worker.stepIncrementalLayout(workerGeneration, 0);
+ if (!progress.didPublish) {
+ continue;
+ }
+ const data = worker.getSkeletonData()!;
+ const serialized = serializeDocumentSkeletonContinuousBlock(data.pages[0], snapshot);
+ snapshot = serialized.snapshot;
+ const mainSection = main.getSkeletonData()!.pages[0].sections[serialized.block.flow.sectionIndex];
+ const missingBoundary = mainSection?.columns[serialized.block.flow.columnIndex] == null;
+ sawMissingBoundary ||= missingBoundary && !progress.complete;
+ expect(() => main.applyLayoutPublication({
+ kind: 'block',
+ left: data.left,
+ top: data.top,
+ st: data.st,
+ ed: data.ed,
+ block: serialized.block,
+ resources: { reset: step === 0, skeHeaders: [], skeFooters: [], skeListLevel: null, drawingAnchor: null },
+ }, progress)).not.toThrow();
+ if (!progress.complete) {
+ expect(main.getSkeletonData()!.pages[0]).toBe(retainedPage);
+ } else {
+ complete = true;
+ break;
+ }
+ }
+ expect(sawMissingBoundary).toBe(true);
+ expect(complete).toBe(true);
+ expect(serializeDocumentSkeletonPage(main.getSkeletonData()!.pages[0]))
+ .toEqual(serializeDocumentSkeletonPage(worker.getSkeletonData()!.pages[0]));
+ } finally {
+ main.dispose();
+ worker.dispose();
+ model.dispose();
+ univer.dispose();
+ }
+ });
+
it('hit-tests imported sections throughout a modern page while Worker layout is pending', () => {
const univer = new Univer();
const content = 'Modern paragraph with an empty paragraph below.\r\r'.repeat(30);
@@ -5637,6 +5704,153 @@ describe('doc skeleton', () => {
measureSpy.mockRestore();
});
+ it.each([false, true].flatMap((incremental) => [1, 2].map((columnCount) => ({ incremental, columnCount }))))('continues after the current inline table slice ($incremental/$columnCount columns)', ({ incremental, columnCount }) => {
+ mockCanvasTextMetrics();
+ const T = DataStreamTreeTokenType;
+ const rowStream = `${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}`;
+ const tableStream = `${T.TABLE_START}${rowStream}${rowStream}${T.TABLE_END}`;
+ const dataStream = `${tableStream}${T.PARAGRAPH}After${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const univer = new Univer();
+ const model = new DocumentDataModel({
+ id: 'unequal-inline-table-slices',
+ body: {
+ dataStream,
+ paragraphs: Array.from(dataStream).flatMap((token, startIndex) => token === T.PARAGRAPH
+ ? [{ startIndex, paragraphId: `p-${startIndex}` }]
+ : []),
+ sectionBreaks: Array.from(dataStream).flatMap((token, startIndex) => token === T.SECTION_BREAK
+ ? [{
+ startIndex,
+ sectionId: `s-${startIndex}`,
+ ...(startIndex === dataStream.length - 1 && columnCount === 2
+ ? { columnProperties: [{ width: 220, paddingEnd: 20 }, { width: 220, paddingEnd: 0 }] }
+ : {}),
+ }]
+ : []),
+ tables: [{ tableId: 'table', startIndex: 0, endIndex: tableStream.length }],
+ },
+ tableSource: {
+ table: {
+ tableId: 'table',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: {
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE },
+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE },
+ },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 200 } },
+ tableRows: [180, 40].map((height) => ({
+ cantSplit: BooleanNumber.TRUE,
+ tableCells: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 200 } } }],
+ trHeight: { val: { v: height }, hRule: TableRowHeightRule.EXACT },
+ })),
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 200 } } }],
+ },
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 500, height: 240 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ });
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));
+ if (incremental) {
+ completeIncrementalLayout(skeleton);
+ } else {
+ skeleton.calculate();
+ }
+ const pages = skeleton.getSkeletonData()!.pages;
+ expect(pages).toHaveLength(columnCount === 1 ? 2 : 1);
+ expect([...pages[0].skeTables.values()][0].height).toBe(180);
+ const lastPage = pages[pages.length - 1];
+ const lastTable = [...lastPage.skeTables.values()].find((table) => table.height === 40)!;
+ expect(lastTable.height).toBe(40);
+ const lines = lastPage.sections.flatMap((section) => section.columns.flatMap((column) => column.lines));
+ const blankLine = lines.find((line) => line.paragraphIndex === tableStream.length)!;
+ const followingLine = lines.find((line) => line.paragraphIndex === dataStream.length - 2)!;
+ expect(blankLine.top).toBeCloseTo(lastTable.top + lastTable.height);
+ expect(followingLine.top).toBeCloseTo(blankLine.top + blankLine.lineHeight);
+ skeleton.dispose();
+ univer.dispose();
+ });
+
+ it.each([false, true])('keeps tables before authored breaks clear of following modern content (incremental: %s)', (incremental) => {
+ mockCanvasTextMetrics();
+ const T = DataStreamTreeTokenType;
+ const cell = `${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cover${T.PARAGRAPH}${T.SECTION_BREAK}${T.TABLE_CELL_END}${T.TABLE_ROW_END}`;
+ const tableStream = `${T.TABLE_START}${cell}${T.TABLE_END}`;
+ const dataStream = `${tableStream}${T.PARAGRAPH}${tableStream}${T.PARAGRAPH}${T.PAGE_BREAK}Contents${T.PARAGRAPH}${T.SECTION_BREAK}`;
+ const contentsIndex = dataStream.lastIndexOf(T.PARAGRAPH);
+ const univer = new Univer();
+ const model = new DocumentDataModel({
+ id: 'modern-floating-cover',
+ body: {
+ dataStream,
+ paragraphs: Array.from(dataStream).flatMap((token, startIndex) => token === T.PARAGRAPH
+ ? [{ startIndex, paragraphId: `p-${startIndex}` }]
+ : []),
+ sectionBreaks: Array.from(dataStream).flatMap((token, startIndex) => token === T.SECTION_BREAK
+ ? [{ startIndex, sectionId: `s-${startIndex}` }]
+ : []),
+ tables: [
+ { tableId: 'cover', startIndex: 0, endIndex: tableStream.length },
+ { tableId: 'details', startIndex: tableStream.length + 1, endIndex: tableStream.length * 2 + 1 },
+ ],
+ },
+ tableSource: Object.fromEntries(['cover', 'details'].map((tableId, index) => [tableId, {
+ tableId,
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: index === 0 ? TableTextWrapType.WRAP : TableTextWrapType.NONE,
+ overlap: BooleanNumber.FALSE,
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ position: {
+ positionH: { relativeFrom: ObjectRelativeFromH.PAGE, posOffset: 0 },
+ positionV: { relativeFrom: ObjectRelativeFromV.PAGE, posOffset: 0 },
+ },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 600 } },
+ tableRows: [{
+ tableCells: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 600 } } }],
+ trHeight: { val: { v: index === 0 ? 500 : 120 }, hRule: TableRowHeightRule.EXACT },
+ }],
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 600 } } }],
+ }])),
+ documentStyle: {
+ documentFlavor: DocumentFlavor.MODERN,
+ pageSize: { width: 960, height: 400 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ });
+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));
+ if (incremental) {
+ completeIncrementalLayout(skeleton);
+ } else {
+ skeleton.calculate();
+ }
+ const pages = skeleton.getSkeletonData()!.pages;
+ expect(pages).toHaveLength(1);
+ const page = pages[0];
+ const cover = page.skeTables.get('cover')!;
+ const details = page.skeTables.get('details')!;
+ expect(details.top).toBeGreaterThanOrEqual(cover.top + cover.height);
+ const contentsSection = page.sections.find((section) => section.columns.some((column) =>
+ column.lines.some((line) => line.paragraphIndex === contentsIndex)))!;
+ const contentsLine = contentsSection.columns.flatMap((column) => column.lines)
+ .find((line) => line.paragraphIndex === contentsIndex)!;
+ expect(contentsSection.top + contentsLine.top).toBeGreaterThanOrEqual(details.top + details.height);
+ expect(page.height).toBeGreaterThanOrEqual(contentsSection.top + contentsLine.top + contentsLine.lineHeight);
+ skeleton.dispose();
+ univer.dispose();
+ });
+
it.each(['', 'Following paragraph', '\rFollowing paragraph'].flatMap((followingText) =>
[TableRowHeightRule.EXACT, TableRowHeightRule.AT_LEAST].flatMap((hRule) =>
[false, true].flatMap((incremental) =>
@@ -7818,3 +8032,209 @@ describe('doc skeleton', () => {
univer.dispose();
});
});
+
+describe('modern heading collapse', () => {
+ it('retains the visible layout until a fold generation fills the viewport, including interrupted reversals', () => {
+ const univer = new Univer();
+ const content = Array.from({ length: 100 }, (_, index) => `Paragraph ${index} fills the document.\r`).join('');
+ const model = createDocumentModelWithStyle(content, {});
+ model.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });
+ model.getBody()!.paragraphs = [...content.matchAll(/\r/g)].map((match, index) => ({ startIndex: match.index, paragraphId: `paragraph-${index}` }));
+ const paragraphs = model.getBody()!.paragraphs!;
+ paragraphs[40].paragraphStyle = { namedStyleType: NamedStyleType.HEADING_1 };
+ paragraphs[60].paragraphStyle = { namedStyleType: NamedStyleType.HEADING_1 };
+ const view = new DocumentViewModel(model);
+ const skeleton = DocumentSkeleton.create(view, univer.__getInjector().get(LocaleService));
+ skeleton.calculate();
+ const baseline = skeleton.getSkeletonData()!;
+ const baselineGeometry = normalizeSkeleton(baseline);
+ const minimumPublicationHeight = baseline.pages[0].height * 0.65;
+ try {
+ for (const collapsed of [true, false, true, false]) {
+ paragraphs[40].headingCollapsed = collapsed;
+ view.reset(model);
+ const previous = skeleton.getSkeletonData();
+ const generation = skeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor: paragraphs[40].startIndex,
+ minimumPublicationHeight,
+ });
+ let published = false;
+ for (let step = 0; step < 150; step++) {
+ const progress = skeleton.stepIncrementalLayout(generation, 0, 1);
+ if (!progress.didPublish) {
+ expect(skeleton.getSkeletonData()).toBe(previous);
+ } else {
+ published = true;
+ expect(progress.anchorReady).toBe(true);
+ expect(progress.complete).toBe(false);
+ expect(skeleton.getSkeletonData()!.pages[0].height).toBeGreaterThanOrEqual(minimumPublicationHeight);
+ expect(skeleton.findNodePositionByCharIndex(paragraphs[60].startIndex - 1)).toBeDefined();
+ break;
+ }
+ }
+ expect(published).toBe(true);
+ skeleton.cancelIncrementalLayout(generation);
+ }
+ completeIncrementalLayout(skeleton, paragraphs[40].startIndex);
+ expect(normalizeSkeleton(skeleton.getSkeletonData())).toEqual(baselineGeometry);
+ } finally {
+ skeleton.dispose();
+ model.dispose();
+ univer.dispose();
+ }
+ });
+
+ it.each([false, true])('omits folded content from geometry and preserves model offsets (incremental: %s)', (incremental) => {
+ const univer = new Univer();
+ const locale = univer.__getInjector().get(LocaleService);
+ const model = new DocumentDataModel({
+ id: 'fold-layout',
+ documentStyle: { documentFlavor: DocumentFlavor.MODERN, pageSize: { width: 400, height: Number.POSITIVE_INFINITY } },
+ body: {
+ dataStream: 'Parent\rChild\rHidden text\rPeer\rTail\r\n',
+ paragraphs: [
+ { startIndex: 6, paragraphId: 'parent', headingCollapsed: true, paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ { startIndex: 12, paragraphId: 'child', headingCollapsed: true, paragraphStyle: { namedStyleType: NamedStyleType.HEADING_2 } },
+ { startIndex: 24, paragraphId: 'hidden' },
+ { startIndex: 29, paragraphId: 'peer', paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ { startIndex: 34, paragraphId: 'tail' },
+ ],
+ sectionBreaks: [{ startIndex: 35, sectionId: 'section' }],
+ },
+ });
+ const view = new DocumentViewModel(model);
+ const skeleton = DocumentSkeleton.create(view, locale);
+ const layout = () => {
+ if (incremental) {
+ completeIncrementalLayout(skeleton, 6);
+ } else {
+ skeleton.calculate();
+ }
+ };
+ try {
+ layout();
+ const paragraphs = () => skeleton.getSkeletonData()!.pages.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines.map((line) => line.paragraphIndex))));
+ expect(paragraphs()).toEqual([6, 29, 34]);
+ expect(skeleton.findNodePositionByCharIndex(15)).toBeUndefined();
+ expect(skeleton.findNodeByCharIndex(25)?.content).toBe('P');
+ const collapsedHeight = skeleton.getSkeletonData()!.pages[0].height;
+ model.getBody()!.paragraphs![0].headingCollapsed = false;
+ view.reset(model);
+ skeleton.makeDirty(true);
+ layout();
+ expect(paragraphs()).toEqual([6, 12, 29, 34]);
+ expect(skeleton.findNodePositionByCharIndex(15)).toBeUndefined();
+ model.getBody()!.paragraphs![1].headingCollapsed = false;
+ view.reset(model);
+ skeleton.makeDirty(true);
+ layout();
+ expect(paragraphs()).toEqual([6, 12, 24, 29, 34]);
+ expect(skeleton.findNodePositionByCharIndex(15)).toBeDefined();
+ expect(skeleton.getSkeletonData()!.pages[0].height).toBeGreaterThan(collapsedHeight);
+ if (incremental) {
+ model.getBody()!.paragraphs![0].headingCollapsed = true;
+ view.reset(model);
+ const generation = skeleton.startIncrementalLayout({ reason: 'edit', anchor: 6 });
+ skeleton.stepIncrementalLayout(generation, 0, 1);
+ skeleton.cancelIncrementalLayout(generation);
+ completeIncrementalLayout(skeleton, 6);
+ expect(paragraphs()).toEqual([6, 29, 34]);
+ }
+ expect(model.getBody()!.dataStream).toBe('Parent\rChild\rHidden text\rPeer\rTail\r\n');
+ } finally {
+ skeleton.dispose();
+ view.dispose();
+ model.dispose();
+ univer.dispose();
+ }
+ });
+
+ it.each([false, true])('hides whole tables and columns without treating their headings as outer boundaries (%s)', (incremental) => {
+ const T = DataStreamTreeTokenType;
+ const prefix = 'Heading\r';
+ const table = `${T.TABLE_START}${T.TABLE_ROW_START}${T.TABLE_CELL_START}Cell\r\n${T.TABLE_CELL_END}${T.TABLE_ROW_END}${T.TABLE_END}`;
+ const columns = `${T.COLUMN_GROUP_START}${T.COLUMN_START}Left\r${T.COLUMN_END}${T.COLUMN_START}Right\r${T.COLUMN_END}${T.COLUMN_GROUP_END}`;
+ const dataStream = `${prefix}${table}\r${columns}Peer\rTail\r\n`;
+ const peerOffset = dataStream.indexOf('Peer');
+ const paragraphs = [...dataStream.matchAll(/\r/g)].map((match, index) => ({
+ startIndex: match.index,
+ paragraphId: `block-p${index}`,
+ headingCollapsed: index === 0,
+ paragraphStyle: match.index === 7 || match.index === peerOffset + 4 || index === 1
+ ? { namedStyleType: NamedStyleType.HEADING_1 }
+ : undefined,
+ }));
+ const model = new DocumentDataModel({
+ id: 'fold-blocks',
+ documentStyle: { documentFlavor: DocumentFlavor.MODERN, pageSize: { width: 400, height: Number.POSITIVE_INFINITY } },
+ body: {
+ dataStream,
+ paragraphs,
+ sectionBreaks: [...dataStream.matchAll(/\n/g)].map((match, index) => ({ startIndex: match.index, sectionId: `block-s${index}` })),
+ tables: [{ tableId: 'table', startIndex: prefix.length, endIndex: prefix.length + table.length }],
+ columnGroups: [{ columnGroupId: 'columns', startIndex: prefix.length + table.length + 1, endIndex: prefix.length + table.length + columns.length, columns: [{ columnId: 'left', widthRatio: 1 }, { columnId: 'right', widthRatio: 1 }] }],
+ },
+ tableSource: { table: {
+ tableId: 'table',
+ align: TableAlignmentType.START,
+ indent: { v: 0 },
+ textWrap: TableTextWrapType.NONE,
+ position: { positionH: { relativeFrom: ObjectRelativeFromH.PAGE }, positionV: { relativeFrom: ObjectRelativeFromV.PAGE } },
+ dist: { distT: 0, distB: 0, distL: 0, distR: 0 },
+ size: { type: TableSizeType.SPECIFIED, width: { v: 80 } },
+ cellMargin: { top: { v: 0 }, bottom: { v: 0 }, start: { v: 0 }, end: { v: 0 } },
+ tableRows: [{ tableCells: [{}], trHeight: { val: { v: 0 }, hRule: TableRowHeightRule.AUTO } }],
+ tableColumns: [{ size: { type: TableSizeType.SPECIFIED, width: { v: 80 } } }],
+ } },
+ });
+ const univer = new Univer();
+ const view = new DocumentViewModel(model);
+ const skeleton = DocumentSkeleton.create(view, univer.__getInjector().get(LocaleService));
+ const layout = () => {
+ if (incremental) {
+ completeIncrementalLayout(skeleton, 7);
+ } else {
+ skeleton.makeDirty(true);
+ skeleton.calculate();
+ }
+ };
+ try {
+ layout();
+ expect(skeleton.getSkeletonData()!.pages.every((page) => page.skeTables.size === 0 && page.skeColumnGroups.size === 0)).toBe(true);
+ expect(skeleton.findNodeByCharIndex(peerOffset)?.content).toBe('P');
+ model.getBody()!.paragraphs![0].headingCollapsed = false;
+ view.reset(model);
+ layout();
+ expect(skeleton.getSkeletonData()!.pages.some((page) => page.skeTables.size === 1)).toBe(true);
+ expect(skeleton.getSkeletonData()!.pages.some((page) => page.skeColumnGroups.size === 1)).toBe(true);
+ expect(model.getBody()!.dataStream).toBe(dataStream);
+ } finally {
+ skeleton.dispose();
+ univer.dispose();
+ }
+ });
+
+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.UNSPECIFIED])('ignores stored folds outside modern mode (%s)', (documentFlavor) => {
+ const univer = new Univer();
+ const model = new DocumentDataModel({
+ id: 'traditional-fold',
+ documentStyle: { documentFlavor, pageSize: { width: 400, height: 600 } },
+ body: { dataStream: 'A\rB\r\n', paragraphs: [
+ { paragraphId: 'a', startIndex: 1, headingCollapsed: true, paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ { paragraphId: 'b', startIndex: 3 },
+ ] },
+ });
+ const view = new DocumentViewModel(model);
+ const skeleton = DocumentSkeleton.create(view, univer.__getInjector().get(LocaleService));
+ try {
+ skeleton.calculate();
+ expect(skeleton.findNodePositionByCharIndex(2)).toBeDefined();
+ } finally {
+ skeleton.dispose();
+ view.dispose();
+ model.dispose();
+ univer.dispose();
+ }
+ });
+});
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts
index 2712f522b6..b207e43f83 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts
@@ -15,21 +15,6 @@
*/
import type { INumberUnit, IParagraphProperties, ITabStop, Nullable } from '@univerjs/core';
-import type {
- IDocumentSkeletonColumn,
- IDocumentSkeletonDivide,
- IDocumentSkeletonDrawing,
- IDocumentSkeletonGlyph,
- IDocumentSkeletonLine,
- IDocumentSkeletonPage,
- IDocumentSkeletonSection,
- IDocumentSkeletonTable,
-} from '../../../../../basics/i-document-skeleton-cached';
-import type { IParagraphConfig, IParagraphTableCache, ISectionBreakConfig } from '../../../../../basics/interfaces';
-import type {
- IFloatObject,
- ILayoutContext,
-} from '../../tools';
import {
BooleanNumber,
characterSpacingControlType,
@@ -47,6 +32,21 @@ import {
TabStopAlignment,
WrapStrategy,
} from '@univerjs/core';
+import type {
+ IDocumentSkeletonColumn,
+ IDocumentSkeletonDivide,
+ IDocumentSkeletonDrawing,
+ IDocumentSkeletonGlyph,
+ IDocumentSkeletonLine,
+ IDocumentSkeletonPage,
+ IDocumentSkeletonSection,
+ IDocumentSkeletonTable,
+} from '../../../../../basics/i-document-skeleton-cached';
+import type { IParagraphConfig, IParagraphTableCache, ISectionBreakConfig } from '../../../../../basics/interfaces';
+import type {
+ IFloatObject,
+ ILayoutContext,
+} from '../../tools';
import { cjk } from '../../../../../basics/cjk-regexp';
import {
DocumentSkeletonPageType,
@@ -1777,11 +1777,19 @@ function _lineOperator(
[...paragraphNonInlineSkeDrawings.values()].some(
(drawing) => drawing.drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM
);
+ // An inline table can move below a float without intersecting its old anchor line.
+ // Only the latest positioned slice on this page/column governs following flow.
+ let tableFlowTop = lineTop;
+ for (const item of skeTablesInParagraph ?? []) {
+ if (item.hasPositioned && item.table.parent === lastPage && item.table.tableSource.textWrap === TableTextWrapType.NONE) {
+ tableFlowTop = Math.max(lineTop, item.table.top + item.table.height - section.top);
+ }
+ }
const calculatedLineTop = positionedCustomBlockOnly
- ? lineTop
+ ? tableFlowTop
: calculateLineTopByDrawings(
lineHeight,
- lineTop,
+ tableFlowTop,
lastPage,
headerPage,
footerPage,
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/paragraph-layout.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/paragraph-layout.ts
index 56bc2899d4..7499a2a0b5 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/paragraph-layout.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/paragraph-layout.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
+import { BooleanNumber, DataStreamTreeNodeType } from '@univerjs/core';
import type { IDocumentSkeletonPage } from '../../../../../basics/i-document-skeleton-cached';
import type { ISectionBreakConfig } from '../../../../../basics/interfaces';
import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';
import type { DocumentViewModel } from '../../../view-model/document-view-model';
import type { ILayoutContext } from '../../tools';
-import { BooleanNumber, DataStreamTreeNodeType } from '@univerjs/core';
import { clearFontCreateConfigCache } from '../../tools';
import { createTableSkeleton } from '../table';
import { lineAdjustment } from './line-adjustment';
@@ -34,6 +34,9 @@ export function dealWidthParagraph(
sectionBreakConfig: ISectionBreakConfig,
nextParagraphNode?: DataStreamTreeNode
): IDocumentSkeletonPage[] {
+ if (viewModel.getCollapsedHeadingAtOffset(paragraphNode.startIndex)) {
+ return [curPage];
+ }
clearFontCreateConfigCache();
const { content = '', children } = paragraphNode;
let tableSkeleton = null;
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 fa21d4ff34..1f8edb5fdb 100644
--- a/packages/engine-render/src/components/docs/layout/block/section.ts
+++ b/packages/engine-render/src/components/docs/layout/block/section.ts
@@ -15,12 +15,12 @@
*/
import type { Nullable } from '@univerjs/core';
+import { DataStreamTreeNodeType } from '@univerjs/core';
import type { IDocumentSkeletonPage } from '../../../../basics/i-document-skeleton-cached';
import type { ISectionBreakConfig } from '../../../../basics/interfaces';
import type { DataStreamTreeNode } from '../../view-model/data-stream-tree-node';
import type { DocumentViewModel } from '../../view-model/document-view-model';
import type { ILayoutContext } from '../tools';
-import { DataStreamTreeNodeType } from '@univerjs/core';
import { createSkeletonPage } from '../model/page';
import { dealWithBlockError } from './block-error';
import { appendColumnGroupBlockLine, createColumnGroupSkeleton } from './column';
@@ -65,10 +65,9 @@ export function dealWithSection(
for (let i = paragraphStartIndex; i < paragraphEndIndex; i++) {
const paragraphNode = sectionNode.children[i];
- // const { paragraph, table, tableOfContents, blockType, customBlock, blockId } = block;
- // if (preRenderedBlockIdMap?.get(blockId)) {
- // continue;
- // }
+ if (viewModel.getCollapsedHeadingAtOffset(paragraphNode.startIndex)) {
+ continue;
+ }
let skeletonPages: IDocumentSkeletonPage[] = [];
let currentPageCache = curPage;
if (allCurrentSkeletonPages.length > 0) {
@@ -124,7 +123,6 @@ export function dealWithSection(
_pushPage(allCurrentSkeletonPages, skeletonPages);
- // renderedBlockIdMap.set(blockId, true);
if (ctx.isDirty) {
break;
}
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 0917db17a8..9906629f11 100644
--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
@@ -15,6 +15,19 @@
*/
import type { ColumnSeparatorType, ISectionColumnProperties, LocaleService, Nullable } from '@univerjs/core';
+import {
+ BaselineOffset,
+ BooleanNumber,
+ CustomRangeType,
+ DataStreamTreeNodeType,
+ DataStreamTreeTokenType,
+ DocumentFlavor,
+ PositionedObjectLayoutType,
+ PRESET_LIST_TYPE,
+ SectionType,
+ Skeleton,
+} from '@univerjs/core';
+import { Subject } from 'rxjs';
import type {
IDocumentSkeletonCached,
IDocumentSkeletonColumn,
@@ -62,19 +75,6 @@ import type {
IDocumentLayoutProtectedRange,
} from './document-layout-types';
import type { IDocumentPaginationMetrics, ILayoutContext } from './tools';
-import {
- BaselineOffset,
- BooleanNumber,
- CustomRangeType,
- DataStreamTreeNodeType,
- DataStreamTreeTokenType,
- DocumentFlavor,
- PositionedObjectLayoutType,
- PRESET_LIST_TYPE,
- SectionType,
- Skeleton,
-} from '@univerjs/core';
-import { Subject } from 'rxjs';
import {
BreakType,
DocumentSkeletonPageType,
@@ -337,6 +337,7 @@ interface IIncrementalLayoutState {
sectionBreakConfig: Nullable<ISectionBreakConfig>;
layoutAnchor: Nullable<number>;
priorityAnchor: Nullable<number>;
+ minimumPublicationHeight: number;
priorityPageIndex: number;
priorityPageEnd: Nullable<number>;
interactionPageTail: Nullable<IInteractionPageTail>;
@@ -1203,6 +1204,8 @@ export class DocumentSkeleton extends Skeleton {
private _completedPageCount: number | undefined;
private _lastCompleteSkeletonData: Nullable<IDocumentSkeletonCached> = null;
+ private _completedHeadingCollapseSignature = '[]';
+ private _publishedHeadingCollapseSignature = '[]';
private _pendingInvalidationAnchor: Nullable<number> = null;
@@ -1303,12 +1306,20 @@ export class DocumentSkeleton extends Skeleton {
ctx = retry;
}
this._lastCompleteSkeletonData = this._skeletonData;
+ this._completedHeadingCollapseSignature = this._getHeadingCollapseSignature();
+ this._publishedHeadingCollapseSignature = this._completedHeadingCollapseSignature;
this._completedPageCount = this._skeletonData?.pages.length;
this._pendingInvalidationAnchor = null;
this._paginationMetrics = ctx.paginationMetrics ?? null;
this._dirty$.next(true);
}
+ private _getHeadingCollapseSignature(): string {
+ return JSON.stringify(this.getViewModel().getHeadingSections()
+ .filter((heading) => heading.collapsed)
+ .map((heading) => [heading.paragraphId, heading.startOffset, heading.endOffset]));
+ }
+
startIncrementalLayout(options?: {
reason?: DocumentLayoutReason;
anchor?: number;
@@ -1317,6 +1328,8 @@ export class DocumentSkeleton extends Skeleton {
modernPageWidth?: number;
modernHorizontalMargin?: number;
bounds?: IViewportInfo;
+ /** Keep the current Modern viewport until a visibility change fills its replacement. */
+ minimumPublicationHeight?: number;
reuseUnaffectedTail?: boolean;
/** The caller proved this edit only changes offset-preserving render metadata. */
allowMetadataOnlyStructuralTailReuse?: boolean;
@@ -1324,26 +1337,33 @@ export class DocumentSkeleton extends Skeleton {
/** Cooperative schedulers wait for code-split dictionaries before publishing. */
waitForHyphenationPatterns?: boolean;
}): number {
- this._modernPageWidth = options?.modernPageWidth;
- this._modernHorizontalMargin = options?.modernHorizontalMargin;
+ // A fold changes the visibility of the suffix even when the heading's own geometry is unchanged.
+ const headingCollapseSignature = this._getHeadingCollapseSignature();
+ const headingVisibilityChanged = headingCollapseSignature !== this._completedHeadingCollapseSignature ||
+ headingCollapseSignature !== this._publishedHeadingCollapseSignature;
+ const layoutOptions = headingVisibilityChanged
+ ? { ...options, anchor: 0, priorityAnchor: options?.priorityAnchor ?? options?.anchor ?? 0, invalidation: undefined, reuseUnaffectedTail: false, preserveInteractionWindow: false }
+ : options;
+ this._modernPageWidth = layoutOptions?.modernPageWidth;
+ this._modernHorizontalMargin = layoutOptions?.modernHorizontalMargin;
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 reason = layoutOptions?.reason ?? (layoutOptions?.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 priorityAnchor = layoutOptions?.priorityAnchor ?? layoutOptions?.anchor;
const hasPublishedCheckpoint = this._skeletonData != null || this._lastCompleteSkeletonData != null;
const previousSkeleton = this._lastCompleteSkeletonData ?? this._skeletonData;
- const invalidation = options?.invalidation;
- const layoutAnchor = options?.anchor;
+ const invalidation = layoutOptions?.invalidation;
+ const layoutAnchor = layoutOptions?.anchor;
const invalidationAnchor = layoutAnchor == null
? this._pendingInvalidationAnchor ?? undefined
: Math.min(layoutAnchor, this._pendingInvalidationAnchor ?? layoutAnchor);
@@ -1381,8 +1401,8 @@ export class DocumentSkeleton extends Skeleton {
invalidationAnchor,
mode,
invalidation,
- options?.preserveInteractionWindow === true,
- options?.reuseUnaffectedTail === false
+ layoutOptions?.preserveInteractionWindow === true,
+ layoutOptions?.reuseUnaffectedTail === false
);
// The first-open anchor only prioritizes the initial viewport; it does not
// represent mutated content. Carry invalidation across generations only
@@ -1401,6 +1421,9 @@ export class DocumentSkeleton extends Skeleton {
sectionBreakConfig: null,
layoutAnchor: incrementalStart.layoutAnchor,
priorityAnchor: priorityAnchor ?? null,
+ minimumPublicationHeight: mode === 'continuous' && headingVisibilityChanged && this._skeletonData != null
+ ? layoutOptions?.minimumPublicationHeight ?? 0
+ : 0,
priorityPageIndex,
priorityPageEnd,
interactionPageTail: incrementalStart.interactionPageTail,
@@ -1427,16 +1450,16 @@ export class DocumentSkeleton extends Skeleton {
: 0,
lastPublishedBlockCount: incrementalStart.processedBlockCount,
publicationRevision: 0,
- reuseUnaffectedTail: options?.reuseUnaffectedTail !== false,
+ reuseUnaffectedTail: layoutOptions?.reuseUnaffectedTail !== false,
paginationRevision: 0,
- allowMetadataOnlyStructuralTailReuse: options?.allowMetadataOnlyStructuralTailReuse === true,
+ allowMetadataOnlyStructuralTailReuse: layoutOptions?.allowMetadataOnlyStructuralTailReuse === true,
reusedTail: false,
tailConvergencePageCount: incrementalStart.ctx.skeleton.pages.length,
dirtyRetries: new Map(),
preparedHyphenationNodes: new WeakSet(),
pendingHyphenation: null,
hyphenationError: null,
- waitForHyphenationPatterns: options?.waitForHyphenationPatterns === true,
+ waitForHyphenationPatterns: layoutOptions?.waitForHyphenationPatterns === true,
};
return generation;
@@ -2174,6 +2197,7 @@ export class DocumentSkeleton extends Skeleton {
const isFinalPublication = state.complete && publishedPageCount >= pageCount;
if (isFinalPublication) {
this._lastCompleteSkeletonData = state.ctx.skeleton;
+ this._completedHeadingCollapseSignature = this._getHeadingCollapseSignature();
this._completedPageCount = state.ctx.skeleton?.pages.length;
this._pendingInvalidationAnchor = null;
}
@@ -2182,6 +2206,7 @@ export class DocumentSkeleton extends Skeleton {
: !this._isolateIncrementalPublications && state.mode === 'paginated'
? this._createSharedPublishablePartialSkeleton(state, publishedPageCount)
: this._createPublishablePartialSkeleton(state, publishedPageCount);
+ this._publishedHeadingCollapseSignature = this._getHeadingCollapseSignature();
this._paginationMetrics = state.ctx.paginationMetrics ?? null;
this._dirty$.next(true);
didPublish = true;
@@ -2231,6 +2256,20 @@ export class DocumentSkeleton extends Skeleton {
// 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');
+ if (state.mode === 'continuous') {
+ // Inline objects otherwise appear only when the complete tail is finalized.
+ // Position publication-owned copies without moving the active layout's objects.
+ const paragraphConfigCache = new Map([...state.ctx.paragraphConfigCache].map(([segmentId, configs]) => [
+ segmentId,
+ new Map([...configs].map(([index, config]) => [index, config.paragraphInlineSkeDrawings?.size
+ ? {
+ ...config,
+ paragraphInlineSkeDrawings: new Map([...config.paragraphInlineSkeDrawings].map(([id, drawing]) => [id, { ...drawing }])),
+ }
+ : config])),
+ ]));
+ updateInlineDrawingCoordsAndBorder({ ...state.ctx, paragraphConfigCache }, activePages);
+ }
const flowPages = [...stablePages, ...activePages];
const currentPriorityPageIndex = state.priorityAnchor == null
@@ -2672,6 +2711,7 @@ export class DocumentSkeleton extends Skeleton {
if (progress.complete) {
setPageParent(skeletonData.pages, skeletonData);
this._lastCompleteSkeletonData = skeletonData;
+ this._completedHeadingCollapseSignature = this._getHeadingCollapseSignature();
this._completedPageCount = skeletonData?.pages.length;
this._pendingInvalidationAnchor = null;
this._externalProtectedContinuousLayout = null;
@@ -2817,6 +2857,7 @@ export class DocumentSkeleton extends Skeleton {
}
setPageParent(skeletonData.pages, skeletonData);
this._lastCompleteSkeletonData = skeletonData;
+ this._completedHeadingCollapseSignature = this._getHeadingCollapseSignature();
this._completedPageCount = skeletonData?.pages.length;
this._pendingInvalidationAnchor = null;
this._externalProtectedPages = null;
@@ -2825,6 +2866,7 @@ export class DocumentSkeleton extends Skeleton {
this._skeletonData = skeletonData;
this._externalLayoutProgress = progress.complete ? null : progress;
+ this._publishedHeadingCollapseSignature = this._getHeadingCollapseSignature();
this._dirty$.next(true);
this._layoutProgress$.next(progress);
return { didReplaceProtectedPages };
@@ -2924,7 +2966,9 @@ export class DocumentSkeleton extends Skeleton {
?.sections[flow.sectionIndex]
?.columns[flow.columnIndex];
if (existingColumn == null) {
- throw new Error('Continuous layout cannot merge a Worker tail without the Main interaction boundary.');
+ // A retained folded window can omit sections restored by this generation.
+ // Commit the queued canonical Worker geometry together when it completes.
+ return null;
}
const firstUnprotectedLine = flow.lines[firstUnprotectedLineOffset];
@@ -4270,7 +4314,31 @@ export class DocumentSkeleton extends Skeleton {
}
if (state.mode === 'continuous') {
- return state.laidOutThrough >= anchor;
+ if (state.laidOutThrough < anchor) {
+ return false;
+ }
+ if (state.minimumPublicationHeight <= 0) {
+ return true;
+ }
+ // Page heights are finalized on publication. Measure stable flow directly
+ // so a large document can hand off after filling the viewport, not its tail.
+ let height = 0;
+ for (const page of state.ctx.skeleton.pages) {
+ for (const section of page.sections) {
+ let sectionHeight = 0;
+ for (const column of section.columns) {
+ for (let index = column.lines.length - 1; index >= 0; index--) {
+ const line = column.lines[index];
+ if (line.paragraphIndex <= state.stableLaidOutThrough) {
+ sectionHeight = Math.max(sectionHeight, line.top + line.lineHeight);
+ break;
+ }
+ }
+ }
+ height += sectionHeight;
+ }
+ }
+ return height >= state.minimumPublicationHeight;
}
// A paginated page is not publishable merely because the edited paragraph
@@ -4594,7 +4662,7 @@ export class DocumentSkeleton extends Skeleton {
}
const paragraphNode = sectionNode.children[state.paragraphIndex];
- const tableNode = paragraphNode?.children.length === 1 &&
+ const tableNode = paragraphNode && !ctx.viewModel.getCollapsedHeadingAtOffset(paragraphNode.startIndex) && paragraphNode.children.length === 1 &&
paragraphNode.children[0].nodeType === DataStreamTreeNodeType.TABLE
? paragraphNode.children[0]
: null;
diff --git a/packages/engine-render/src/components/docs/view-model/__tests__/heading-sections.spec.ts b/packages/engine-render/src/components/docs/view-model/__tests__/heading-sections.spec.ts
new file mode 100644
index 0000000000..12aa9e231f
--- /dev/null
+++ b/packages/engine-render/src/components/docs/view-model/__tests__/heading-sections.spec.ts
@@ -0,0 +1,111 @@
+/**
+ * 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, IParagraph } from '@univerjs/core';
+import {
+ DataStreamTreeTokenType,
+ DocStyleType,
+ DocumentDataModel,
+ DocumentFlavor,
+ NamedStyleType,
+} from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { DocumentViewModel } from '../document-view-model';
+import { getHeadingSections } from '../heading-sections';
+
+function createView(dataStream: string, paragraphs: IParagraph[], documentFlavor = DocumentFlavor.MODERN) {
+ const model = new DocumentDataModel({ id: 'headings', body: { dataStream, paragraphs }, documentStyle: { documentFlavor } });
+ const view = new DocumentViewModel(model);
+ return { model, view, sections: () => getHeadingSections(view.getChildren(), (index) => view.getParagraph(index)) };
+}
+
+describe('heading sections', () => {
+ it('ends at the next same or higher heading, preserving nested fold state', () => {
+ const { view, sections } = createView('A\rB\rtext\rC\rD\r\n', [
+ { paragraphId: 'a', startIndex: 1, headingCollapsed: true, paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ { paragraphId: 'b', startIndex: 3, headingCollapsed: true, paragraphStyle: { namedStyleType: NamedStyleType.HEADING_3 } },
+ { paragraphId: 'text', startIndex: 8 },
+ { paragraphId: 'c', startIndex: 10, paragraphStyle: { namedStyleType: NamedStyleType.HEADING_2 } },
+ { paragraphId: 'd', startIndex: 12, paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ ]);
+ expect(sections().map(({ paragraphId, startOffset, endOffset }) => [paragraphId, startOffset, endOffset])).toEqual([
+ ['a', 2, 11],
+ ['b', 4, 9],
+ ['c', 11, 11],
+ ['d', 13, 13],
+ ]);
+ expect(view.getCollapsedHeadingAtOffset(3)?.paragraphId).toBe('a');
+ expect(view.getCollapsedHeadingAtOffset(10)?.paragraphId).toBe('a');
+ expect(view.getCollapsedHeadingAtOffset(11)).toBeUndefined();
+ view.dispose();
+ });
+
+ it('keeps headings in separate columns in independent scopes', () => {
+ const T = DataStreamTreeTokenType;
+ const dataStream = `${T.COLUMN_GROUP_START}${T.COLUMN_START}A\rone\r${T.COLUMN_END}${T.COLUMN_START}B\rtwo\r${T.COLUMN_END}${T.COLUMN_GROUP_END}After\r\n`;
+ const paragraphs: IParagraph[] = [];
+ for (let i = 0; i < dataStream.length; i++) {
+ if (dataStream[i] === '\r') {
+ paragraphs.push({ paragraphId: `p${i}`, startIndex: i });
+ }
+ }
+ paragraphs[0].paragraphStyle = { namedStyleType: NamedStyleType.HEADING_1 };
+ paragraphs[0].headingCollapsed = true;
+ paragraphs[2].paragraphStyle = { namedStyleType: NamedStyleType.HEADING_1 };
+ const { view } = createView(dataStream, paragraphs);
+ const headings = view.getHeadingSections();
+ expect(headings).toHaveLength(2);
+ expect(view.getCollapsedHeadingAtOffset(paragraphs[1].startIndex)?.paragraphId).toBe(paragraphs[0].paragraphId);
+ expect(view.getCollapsedHeadingAtOffset(paragraphs[2].startIndex)).toBeUndefined();
+ expect(view.getCollapsedHeadingAtOffset(paragraphs[4].startIndex)).toBeUndefined();
+ view.dispose();
+ });
+
+ it('uses inherited named heading styles and respects a direct normal-text override', () => {
+ const { model, view } = createView('A\rtext\rB\r\n', [
+ { paragraphId: 'a', startIndex: 1, styleId: 'derived', headingCollapsed: true },
+ { paragraphId: 'text', startIndex: 6 },
+ { paragraphId: 'b', startIndex: 8, styleId: 'heading' },
+ ]);
+ model.getSnapshot().styles = {
+ heading: { type: DocStyleType.paragraph, name: 'Heading', paragraphStyle: { namedStyleType: NamedStyleType.HEADING_2 } },
+ derived: { type: DocStyleType.paragraph, name: 'Derived', basedOn: 'heading' },
+ };
+ view.reset(model);
+ expect(view.getHeadingSections().map((heading) => heading.paragraphId)).toEqual(['a', 'b']);
+ expect(view.getCollapsedHeadingAtOffset(4)?.paragraphId).toBe('a');
+ model.getBody()!.paragraphs![0].paragraphStyle = { namedStyleType: NamedStyleType.NORMAL_TEXT };
+ view.reset(model);
+ expect(view.getCollapsedHeadingAtOffset(4)).toBeUndefined();
+ view.dispose();
+ });
+
+ it('ignores stored collapse flags outside modern documents and on non-headings', () => {
+ const { view, model } = createView('A\rB\r\n', [
+ { paragraphId: 'a', startIndex: 1, headingCollapsed: true, paragraphStyle: { namedStyleType: NamedStyleType.HEADING_1 } },
+ { paragraphId: 'b', startIndex: 3 },
+ ], DocumentFlavor.TRADITIONAL);
+ expect(view.getHeadingSections()).toEqual([]);
+ expect(view.getCollapsedHeadingAtOffset(2)).toBeUndefined();
+ const snapshot = model.getSnapshot() as IDocumentData;
+ snapshot.documentStyle.documentFlavor = DocumentFlavor.MODERN;
+ snapshot.body!.paragraphs![0].paragraphStyle!.namedStyleType = NamedStyleType.NORMAL_TEXT;
+ view.reset(model);
+ expect(view.getHeadingSections()).toEqual([]);
+ expect(view.getCollapsedHeadingAtOffset(2)).toBeUndefined();
+ view.dispose();
+ });
+});
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 f1bff01cfb..5b89741b98 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
@@ -26,27 +26,31 @@ import type {
JSONXPath,
Nullable,
} from '@univerjs/core';
-import type {
- IDocumentLayoutBody,
- IDocumentLayoutColumnGroup,
- IDocumentLayoutCustomColumnGroup,
- IDocumentLayoutParagraph,
- IDocumentLayoutSectionBreak,
- IDocumentLayoutSnapshot,
- IDocumentLayoutTextRun,
-} from '../document-layout-presentation';
import {
DataStreamTreeNodeType,
DataStreamTreeTokenType,
+ DocumentFlavor,
getRichTextEditPath,
JSON1,
+ resolveDocumentParagraphStyle,
TextX,
TextXActionType,
toDisposable,
} from '@univerjs/core';
import { BehaviorSubject } from 'rxjs';
+import type {
+ IDocumentLayoutBody,
+ IDocumentLayoutColumnGroup,
+ IDocumentLayoutCustomColumnGroup,
+ IDocumentLayoutParagraph,
+ IDocumentLayoutSectionBreak,
+ IDocumentLayoutSnapshot,
+ IDocumentLayoutTextRun,
+} from '../document-layout-presentation';
+import type { IHeadingSection } from './heading-sections';
import { getDocumentLayoutPresentation } from '../document-layout-presentation';
import { DataStreamTreeNode } from './data-stream-tree-node';
+import { getHeadingSections } from './heading-sections';
interface ITableCache {
table: DataStreamTreeNode;
@@ -538,6 +542,9 @@ export class DocumentViewModel implements IDisposable {
private _plainTopLevelParagraphNodes: DataStreamTreeNode[] = [];
+ private _headingSections: IHeadingSection[] | null = null;
+ private _collapsedHeadingSections: IHeadingSection[] | null = null;
+
private _metadataCachesDirty = false;
private _textRunsOrderedAndDisjoint = true;
@@ -603,6 +610,8 @@ export class DocumentViewModel implements IDisposable {
this._treeNodes = [];
this._treeNodesByStartIndex = [];
this._plainTopLevelParagraphNodes = [];
+ this._headingSections = null;
+ this._collapsedHeadingSections = null;
this._lastTextRun = null;
// this._headerTreeMap.clear();
this._noteTreeMap.forEach((viewModel) => viewModel.dispose());
@@ -637,6 +646,53 @@ export class DocumentViewModel implements IDisposable {
return this._children;
}
+ getHeadingSections(): readonly IHeadingSection[] {
+ const snapshot = this.getSnapshot();
+ if (snapshot.documentStyle.documentFlavor !== DocumentFlavor.MODERN) {
+ return [];
+ }
+ this._headingSections ??= getHeadingSections(this._children, (index) => {
+ const paragraph = this.getParagraph(index);
+ if (!paragraph?.styleId || paragraph.paragraphStyle?.namedStyleType != null) {
+ return paragraph;
+ }
+ return {
+ ...paragraph,
+ paragraphStyle: resolveDocumentParagraphStyle(snapshot.documentStyle, paragraph.paragraphStyle, {
+ styles: snapshot.styles,
+ paragraphStyleId: paragraph.styleId,
+ }),
+ };
+ });
+ return this._headingSections;
+ }
+
+ getCollapsedHeadingAtOffset(offset: number): IHeadingSection | undefined {
+ if (!this._collapsedHeadingSections) {
+ this._collapsedHeadingSections = [];
+ for (const section of this.getHeadingSections()) {
+ const previous = this._collapsedHeadingSections[this._collapsedHeadingSections.length - 1];
+ if (section.collapsed && section.endOffset > section.startOffset &&
+ (!previous || section.startOffset >= previous.endOffset)) {
+ this._collapsedHeadingSections.push(section);
+ }
+ }
+ }
+ let low = 0;
+ let high = this._collapsedHeadingSections.length - 1;
+ while (low <= high) {
+ const middle = Math.floor((low + high) / 2);
+ const section = this._collapsedHeadingSections[middle];
+ if (offset < section.startOffset) {
+ high = middle - 1;
+ } else if (offset >= section.endOffset) {
+ low = middle + 1;
+ } else {
+ return section;
+ }
+ }
+ }
+
getBody(): IDocumentLayoutBody | undefined {
const presentation = getDocumentLayoutPresentation(this._documentDataModel);
return presentation
@@ -674,6 +730,8 @@ export class DocumentViewModel implements IDisposable {
}
reset(documentDataModel: DocumentDataModel) {
+ this._headingSections = null;
+ this._collapsedHeadingSections = null;
this._children.forEach((child) => child.dispose());
this._textRunsCache.clear();
this._paragraphCache.clear();
@@ -714,6 +772,8 @@ export class DocumentViewModel implements IDisposable {
}
this._documentDataModel = documentDataModel;
+ this._headingSections = null;
+ this._collapsedHeadingSections = null;
this._metadataCachesDirty = true;
this._lastTextRun = null;
if (!this._textRunsOrderedAndDisjoint) {
@@ -729,6 +789,8 @@ export class DocumentViewModel implements IDisposable {
}
this._documentDataModel = documentDataModel;
+ this._headingSections = null;
+ this._collapsedHeadingSections = null;
this._metadataCachesDirty = true;
this._lastTextRun = null;
diff --git a/packages/engine-render/src/components/docs/view-model/heading-sections.ts b/packages/engine-render/src/components/docs/view-model/heading-sections.ts
new file mode 100644
index 0000000000..904effa11f
--- /dev/null
+++ b/packages/engine-render/src/components/docs/view-model/heading-sections.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 { IParagraph } from '@univerjs/core';
+import { DataStreamTreeNodeType, NamedStyleType } from '@univerjs/core';
+import type { DataStreamTreeNode } from './data-stream-tree-node';
+
+export interface IHeadingSection {
+ paragraphId: string;
+ paragraphIndex: number;
+ startOffset: number;
+ endOffset: number;
+ collapsed: boolean;
+}
+
+/** Each table cell and modern column has its own heading hierarchy. */
+export function getHeadingSections(
+ sections: readonly DataStreamTreeNode[],
+ getParagraph: (index: number) => IParagraph | undefined
+): IHeadingSection[] {
+ const result: IHeadingSection[] = [];
+ function visitFlow(nodes: readonly DataStreamTreeNode[], endOffset: number): void {
+ const open: Array<{ level: number; section: IHeadingSection }> = [];
+ for (const node of nodes) {
+ const paragraph = node.nodeType === DataStreamTreeNodeType.PARAGRAPH && node.children.length === 0
+ ? getParagraph(node.endIndex)
+ : undefined;
+ const level = paragraph?.paragraphStyle?.namedStyleType;
+ if (paragraph && level != null && level >= NamedStyleType.HEADING_1 && level <= NamedStyleType.HEADING_5) {
+ while (open.length && open[open.length - 1].level >= level) {
+ open.pop()!.section.endOffset = node.startIndex;
+ }
+ const section: IHeadingSection = {
+ paragraphId: paragraph.paragraphId,
+ paragraphIndex: paragraph.startIndex,
+ startOffset: paragraph.startIndex + 1,
+ endOffset,
+ collapsed: paragraph.headingCollapsed === true,
+ };
+ result.push(section);
+ open.push({ level, section });
+ }
+ visitContainers(node);
+ }
+ }
+ function visitContainers(node: DataStreamTreeNode): void {
+ if (node.nodeType === DataStreamTreeNodeType.TABLE_CELL || node.nodeType === DataStreamTreeNodeType.COLUMN) {
+ const nodes = node.children.flatMap((child) => child.nodeType === DataStreamTreeNodeType.SECTION_BREAK
+ ? child.children
+ : [child]);
+ visitFlow(nodes, nodes.length ? nodes[nodes.length - 1].endIndex + 1 : node.endIndex);
+ return;
+ }
+ for (const child of node.children) {
+ visitContainers(child);
+ }
+ }
+ const nodes = sections.flatMap((section) => section.children);
+ visitFlow(nodes, nodes.length ? nodes[nodes.length - 1].endIndex + 1 : 0);
+ return result.sort((a, b) => a.paragraphIndex - b.paragraphIndex);
+}