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.

refactor(docs): refactor document element facade (#7156)

wpxp12345667da8f5e9a1f
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index f42ec5285c..a8808aac8e 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -75,7 +75,7 @@ export { DEFAULT_DOCUMENT_SUB_COMPONENT_ID } from './docs/data-model/subdocument
export { ActionIterator } from './docs/data-model/text-x/action-iterator';
export { TextXActionType } from './docs/data-model/text-x/action-types';
export type { IDeleteAction, IInsertAction, IRetainAction, TextXAction } from './docs/data-model/text-x/action-types';
-export { normalizeTextRuns } from './docs/data-model/text-x/apply-utils/common';
+export { normalizeTextRuns, RESTORE_INSERTED_PARAGRAPH_IDS } from './docs/data-model/text-x/apply-utils/common';
export { updateAttributeByDelete } from './docs/data-model/text-x/apply-utils/delete-apply';
export { updateAttributeByInsert } from './docs/data-model/text-x/apply-utils/insert-apply';
export { getPlainText } from './docs/data-model/text-x/build-utils/parse';
diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.ts
index 16f1eb2c99..db82b75489 100644
--- a/packages/core/src/types/interfaces/i-document-data.ts
+++ b/packages/core/src/types/interfaces/i-document-data.ts
@@ -151,6 +151,18 @@ export interface IDocumentBody {
payloads?: Record<string, string>;
}
+/**
+ * The top-level block types in a document body.
+ * These block types are used to represent the structure of the document and can be used to identify different sections or elements within the document.
+ */
+export enum DocumentBlockType {
+ PARAGRAPH = 'paragraph',
+ BLOCK_RANGE = 'blockRange',
+ TABLE = 'table',
+ CUSTOM_BLOCK = 'customBlock',
+ COLUMN_GROUP = 'columnGroup',
+}
+
export interface IDocStyle {
name: string;
basedOn: string;
diff --git a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
index d7684f4b19..223024760c 100644
--- a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
@@ -15,7 +15,7 @@
*/
import type { IMutiPageParagraphBound, ITableBound } from '../doc-event-manager.service';
-import { BlockType, DataStreamTreeTokenType, DOC_RANGE_TYPE, DocumentBlockRangeType, PresetListType } from '@univerjs/core';
+import { BlockType, DataStreamTreeTokenType, DOC_RANGE_TYPE, DocumentBlockRangeType, DocumentBlockType, PresetListType } from '@univerjs/core';
import { DocumentEditArea } from '@univerjs/engine-render';
import { BehaviorSubject, Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
@@ -61,8 +61,8 @@ describe('DocParagraphMenuService', () => {
expect(attachPopupToRect).toHaveBeenCalledTimes(1);
expect(service.activeTarget).toMatchObject({
- kind: 'paragraph',
- key: 'paragraph:2',
+ kind: DocumentBlockType.PARAGRAPH,
+ key: `${DocumentBlockType.PARAGRAPH}:2`,
emptyMode: true,
});
});
@@ -210,7 +210,7 @@ describe('DocParagraphMenuService', () => {
}));
expect(attachPopupToRect).toHaveBeenCalledTimes(1);
- expect(service.activeTarget?.kind).toBe('paragraph');
+ expect(service.activeTarget?.kind).toBe(DocumentBlockType.PARAGRAPH);
expect(service.activeTarget?.draggable).toBe(true);
expect(service.activeTarget?.cellRange).toEqual({ startOffset: 2, endOffset: 8 });
@@ -248,8 +248,8 @@ describe('DocParagraphMenuService', () => {
}));
service.showTableMenu(tableBound);
- expect(service.activeTarget?.kind).toBe('paragraph');
- expect(service.activeTarget?.key).toBe('paragraph:7');
+ expect(service.activeTarget?.kind).toBe(DocumentBlockType.PARAGRAPH);
+ expect(service.activeTarget?.key).toBe(`${DocumentBlockType.PARAGRAPH}:7`);
expect(disposeCellMenu).not.toHaveBeenCalled();
expect(attachPopupToRect).toHaveBeenCalledTimes(2);
});
@@ -411,7 +411,7 @@ describe('DocParagraphMenuService', () => {
}));
expect(attachPopupToRect).toHaveBeenCalledTimes(1);
- expect(service.activeTarget?.kind).toBe('paragraph');
+ expect(service.activeTarget?.kind).toBe(DocumentBlockType.PARAGRAPH);
});
it('hides an already visible paragraph menu when a table rect selection becomes active', () => {
@@ -469,7 +469,7 @@ describe('DocParagraphMenuService', () => {
});
expect(attachPopupToRect).toHaveBeenCalledTimes(1);
- expect(service.activeTarget?.kind).toBe('table');
+ expect(service.activeTarget?.kind).toBe(DocumentBlockType.TABLE);
});
it('keeps an already visible table menu when a table rect selection becomes active', () => {
@@ -504,7 +504,7 @@ describe('DocParagraphMenuService', () => {
});
expect(dispose).not.toHaveBeenCalled();
- expect(service.activeTarget?.kind).toBe('table');
+ expect(service.activeTarget?.kind).toBe(DocumentBlockType.TABLE);
});
it('uses list icons for list paragraph menus', () => {
@@ -549,7 +549,7 @@ describe('DocParagraphMenuService', () => {
}));
expect(service.activeTarget).toMatchObject({
- kind: 'paragraph',
+ kind: DocumentBlockType.PARAGRAPH,
icon: 'ReduceIcon',
emptyMode: false,
draggable: true,
@@ -576,8 +576,8 @@ describe('DocParagraphMenuService', () => {
}));
expect(service.activeTarget).toMatchObject({
- kind: 'customBlock',
- key: 'customBlock:custom-1',
+ kind: DocumentBlockType.CUSTOM_BLOCK,
+ key: `${DocumentBlockType.CUSTOM_BLOCK}:custom-1`,
icon: 'TextTypeIcon',
menuRange: {
startOffset: 0,
@@ -674,7 +674,7 @@ describe('DocParagraphMenuService', () => {
service.hideParagraphMenu(true);
expect(dispose).not.toHaveBeenCalled();
- expect(service.activeTarget?.kind).toBe('paragraph');
+ expect(service.activeTarget?.kind).toBe(DocumentBlockType.PARAGRAPH);
service.setBlockMenuDragging(false);
service.hideParagraphMenu(true);
@@ -738,7 +738,7 @@ describe('DocParagraphMenuService', () => {
expect(preventDefault).toHaveBeenCalledTimes(1);
expect(stopPropagation).toHaveBeenCalledTimes(1);
expect(dispose).not.toHaveBeenCalled();
- expect(service.activeTarget?.kind).toBe('paragraph');
+ expect(service.activeTarget?.kind).toBe(DocumentBlockType.PARAGRAPH);
expect(slashRequests).toHaveLength(1);
expect(slashRequests[0]).toMatchObject({
anchorRect: paragraph.firstLine,
@@ -773,7 +773,7 @@ describe('DocParagraphMenuService', () => {
});
expect(attachPopupToRect).toHaveBeenCalledTimes(1);
- expect(service.activeTarget?.kind).toBe('paragraph');
+ expect(service.activeTarget?.kind).toBe(DocumentBlockType.PARAGRAPH);
expect(slashRequests).toHaveLength(1);
});
@@ -805,7 +805,7 @@ describe('DocParagraphMenuService', () => {
});
expect(attachPopupToRect).toHaveBeenCalledTimes(1);
- expect(service.activeTarget?.kind).toBe('paragraph');
+ expect(service.activeTarget?.kind).toBe(DocumentBlockType.PARAGRAPH);
expect(service.activeTarget?.emptyMode).toBe(false);
expect(slashRequests).toHaveLength(1);
});
@@ -842,7 +842,7 @@ describe('DocParagraphMenuService', () => {
});
expect(attachPopupToRect).toHaveBeenCalledTimes(1);
- expect(service.activeTarget?.kind).toBe('paragraph');
+ expect(service.activeTarget?.kind).toBe(DocumentBlockType.PARAGRAPH);
expect(service.activeTarget?.icon).toBe('UnorderIcon');
expect(slashRequests).toHaveLength(1);
});
@@ -880,7 +880,7 @@ describe('DocParagraphMenuService', () => {
expect(preventDefault).toHaveBeenCalledTimes(1);
expect(stopPropagation).toHaveBeenCalledTimes(1);
expect(attachPopupToRect).toHaveBeenCalledTimes(1);
- expect(service.activeTarget?.kind).toBe('paragraph');
+ expect(service.activeTarget?.kind).toBe(DocumentBlockType.PARAGRAPH);
expect(slashRequests).toHaveLength(1);
});
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 a864970b59..7c17995a75 100644
--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
@@ -18,15 +18,7 @@ import type { DocumentDataModel, ICustomBlock, ICustomTable, IDocumentBlockRange
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,
- Inject,
- isInternalEditorID,
- PresetListType,
-} from '@univerjs/core';
+import { BlockType, DataStreamTreeTokenType, Disposable, DOC_RANGE_TYPE, DocumentBlockType, Inject, isInternalEditorID, PresetListType } from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
import { DocumentEditArea } from '@univerjs/engine-render';
import { BehaviorSubject, combineLatest, first, throttleTime } from 'rxjs';
@@ -45,10 +37,8 @@ import {
import { DocFloatMenuService } from './float-menu.service';
import { DocSelectionRenderService } from './selection/doc-selection-render.service';
-export type DocBlockMenuTargetKind = 'paragraph' | 'blockRange' | 'table' | 'customBlock';
-
export interface IDocBlockMenuTarget {
- kind: DocBlockMenuTargetKind;
+ kind: Exclude<DocumentBlockType, DocumentBlockType.COLUMN_GROUP>;
key: string;
paragraph?: IMutiPageParagraphBound;
blockRange?: IDocumentBlockRange;
@@ -268,7 +258,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
return;
}
- if (this._paragrahMenu?.target.kind === 'table') {
+ if (this._paragrahMenu?.target.kind === DocumentBlockType.TABLE) {
return;
}
@@ -319,7 +309,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
this.disposeWithMe(this._docSelectionManagerService.textSelection$.subscribe(({ textRanges, rectRanges }) => {
const selectionState = this._getExpandedSelectionState([...textRanges, ...rectRanges]);
- if (selectionState.hasExpandedTextRange || (selectionState.hasRectRange && this._paragrahMenu?.target.kind !== 'table')) {
+ if (selectionState.hasExpandedTextRange || (selectionState.hasRectRange && this._paragrahMenu?.target.kind !== DocumentBlockType.TABLE)) {
this.hideParagraphMenu(true);
}
}));
@@ -561,8 +551,8 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
}
const target: IDocBlockMenuTarget = {
- kind: 'table',
- key: `table:${table.tableId}`,
+ kind: DocumentBlockType.TABLE,
+ key: `${DocumentBlockType.TABLE}:${table.tableId}`,
table,
icon: 'GridIcon',
menuRange: {
@@ -623,7 +613,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
private _shouldKeepCurrentCellMenuForTable(table: ICustomTable): boolean {
const target = this._paragrahMenu?.target;
- if (!target || target.kind === 'table' || !target.cellRange) {
+ if (!target || target.kind === DocumentBlockType.TABLE || !target.cellRange) {
return false;
}
@@ -706,8 +696,8 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
blockRange,
} as IMutiPageParagraphBound;
return {
- kind: 'blockRange',
- key: `blockRange:${blockRange.blockId}`,
+ kind: DocumentBlockType.BLOCK_RANGE,
+ key: `${DocumentBlockType.BLOCK_RANGE}:${blockRange.blockId}`,
paragraph: targetParagraph,
blockRange,
icon: BLOCK_RANGE_ICON_MAP[blockRange.blockType],
@@ -734,8 +724,8 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
const isCustomBlockOnly = customBlock?.blockType === BlockType.CUSTOM && paragraphDataStream.replace(/[\b\r\n]/g, '') === '';
if (customBlock && customBlock.blockType === BlockType.CUSTOM && isCustomBlockOnly) {
return {
- kind: 'customBlock',
- key: `customBlock:${customBlock.blockId}`,
+ kind: DocumentBlockType.CUSTOM_BLOCK,
+ key: `${DocumentBlockType.CUSTOM_BLOCK}:${customBlock.blockId}`,
paragraph,
customBlock,
icon: 'TextTypeIcon',
@@ -756,8 +746,8 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
}
return {
- kind: 'paragraph',
- key: `paragraph:${paragraph.startIndex}`,
+ kind: DocumentBlockType.PARAGRAPH,
+ key: `${DocumentBlockType.PARAGRAPH}:${paragraph.startIndex}`,
paragraph,
icon: isHorizontalRuleParagraph ? 'ReduceIcon' : listIcon,
cellRange: cellRange ?? undefined,
@@ -790,8 +780,8 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
}
targets.push({
- kind: 'table',
- key: `table:${table.tableId}`,
+ kind: DocumentBlockType.TABLE,
+ key: `${DocumentBlockType.TABLE}:${table.tableId}`,
table,
icon: 'GridIcon',
menuRange: { startOffset: table.startIndex, endOffset: table.endIndex, collapsed: false },
@@ -810,8 +800,8 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
}
targets.push({
- kind: 'blockRange',
- key: `blockRange:${blockRange.blockId}`,
+ kind: DocumentBlockType.BLOCK_RANGE,
+ key: `${DocumentBlockType.BLOCK_RANGE}:${blockRange.blockId}`,
blockRange,
icon: BLOCK_RANGE_ICON_MAP[blockRange.blockType],
menuRange: { startOffset: blockRange.startIndex, endOffset: blockRange.endIndex + 1, collapsed: false },
@@ -868,8 +858,8 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
}
targets.push({
- kind: 'blockRange',
- key: `blockRange:${blockRange.blockId}`,
+ kind: DocumentBlockType.BLOCK_RANGE,
+ key: `${DocumentBlockType.BLOCK_RANGE}:${blockRange.blockId}`,
blockRange,
icon: BLOCK_RANGE_ICON_MAP[blockRange.blockType],
cellRange,
diff --git a/packages/docs-ui/src/views/ParagraphMenu.tsx b/packages/docs-ui/src/views/ParagraphMenu.tsx
index 948fac244a..d1ed9260f8 100644
--- a/packages/docs-ui/src/views/ParagraphMenu.tsx
+++ b/packages/docs-ui/src/views/ParagraphMenu.tsx
@@ -542,17 +542,17 @@ function deleteBodyText(body: IDocumentBody, startOffset: number, endOffset: num
body.blockRanges = shiftIndexRangesAfterDelete(body.blockRanges, startOffset, length);
}
-function stripBlockParagraphStyle(style: IParagraph['paragraphStyle'], blockType: string): IParagraph['paragraphStyle'] {
+function stripBlockParagraphStyle(style: IParagraph['paragraphStyle'], blockType: DocumentBlockRangeType): IParagraph['paragraphStyle'] {
const nextStyle = { ...style };
- if (blockType === 'quote') {
+ if (blockType === DocumentBlockRangeType.QUOTE) {
delete nextStyle.indentStart;
delete nextStyle.spaceAbove;
delete nextStyle.spaceBelow;
return nextStyle;
}
- if (blockType === 'code') {
+ if (blockType === DocumentBlockRangeType.CODE) {
delete nextStyle.indentStart;
delete nextStyle.indentEnd;
delete nextStyle.spaceAbove;
@@ -563,7 +563,7 @@ function stripBlockParagraphStyle(style: IParagraph['paragraphStyle'], blockType
return nextStyle;
}
- if (blockType === 'callout') {
+ if (blockType === DocumentBlockRangeType.CALLOUT) {
delete nextStyle.indentStart;
delete nextStyle.indentEnd;
delete nextStyle.spaceAbove;
@@ -574,7 +574,7 @@ function stripBlockParagraphStyle(style: IParagraph['paragraphStyle'], blockType
return nextStyle;
}
-function unwrapBlockRangeBody(documentBody: IDocumentBody, blockRange: IDocumentBlockRange) {
+export function unwrapBlockRangeBody(documentBody: IDocumentBody, blockRange: IDocumentBlockRange) {
const body = Tools.deepClone(documentBody);
const endTokenOffset = getEndTokenOffset(body, blockRange);
diff --git a/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts b/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
index c08a133c82..ec00ee8812 100644
--- a/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
+++ b/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import type { IDocumentBlockRange } from '@univerjs/core';
+import type { IDocumentBlockRange, IDocumentBody, IParagraphStyle } from '@univerjs/core';
import type { IDocBlockMoveValidationContext } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IMutiPageParagraphBound } from '../../services/doc-event-manager.service';
import type { IDocBlockMenuTarget } from '../../services/doc-paragraph-menu.service';
-import { DocumentBlockRangeType, NamedStyleType } from '@univerjs/core';
+import { DataStreamTreeTokenType, DocumentBlockRangeType, DocumentBlockType, NamedStyleType } from '@univerjs/core';
import { DocBlockMoveValidatorService } from '@univerjs/docs';
import { describe, expect, it } from 'vitest';
import { HorizontalLineCommand } from '../../commands/commands/doc-horizontal-line.command';
@@ -35,6 +35,7 @@ import {
isEmptyParagraphMenuTarget,
shouldExecuteParagraphMenuMove,
shouldUseInsertBelowRange,
+ unwrapBlockRangeBody,
} from '../ParagraphMenu';
function paragraphBound(): IMutiPageParagraphBound {
@@ -48,7 +49,7 @@ function paragraphBound(): IMutiPageParagraphBound {
function blockTarget(blockRange: IDocumentBlockRange): IDocBlockMenuTarget {
return {
- kind: 'blockRange',
+ kind: DocumentBlockType.BLOCK_RANGE,
key: 'block:quote-1',
blockRange,
menuRange: {
@@ -65,6 +66,25 @@ function blockTarget(blockRange: IDocumentBlockRange): IDocBlockMenuTarget {
};
}
+function blockRangeBody(blockType: DocumentBlockRangeType, paragraphStyle: IParagraphStyle): IDocumentBody {
+ const T = DataStreamTreeTokenType;
+
+ return {
+ dataStream: `${T.BLOCK_START}A${T.PARAGRAPH}${T.BLOCK_END}${T.PARAGRAPH}${T.SECTION_BREAK}`,
+ paragraphs: [{
+ startIndex: 2,
+ paragraphId: 'paragraph-1',
+ paragraphStyle,
+ }],
+ blockRanges: [{
+ blockId: 'block-1',
+ blockType,
+ startIndex: 0,
+ endIndex: 2,
+ }],
+ };
+}
+
describe('ParagraphMenu command behavior', () => {
it('applies a heading choice to the paragraph target as a named style change', () => {
const targetRange: ITextRangeWithStyle = {
@@ -153,6 +173,59 @@ describe('ParagraphMenu command behavior', () => {
expect(getParagraphMenuHiddenItemIds(DOC_PARAGRAPH_T_EDIT_MENU_ID, target)).not.toContain('docs-quote.command.insert');
});
+ it('strips block paragraph styles when unwrapping block ranges', () => {
+ const codeResult = unwrapBlockRangeBody(blockRangeBody(DocumentBlockRangeType.CODE, {
+ indentStart: { v: 12 },
+ indentEnd: { v: 8 },
+ spaceAbove: { v: 4 },
+ spaceBelow: { v: 6 },
+ textStyle: { ff: 'monospace', fs: 12 },
+ horizontalAlign: 1,
+ }), {
+ blockId: 'block-1',
+ blockType: DocumentBlockRangeType.CODE,
+ startIndex: 0,
+ endIndex: 2,
+ });
+
+ expect(codeResult.body.paragraphs?.[0].paragraphStyle).toEqual({
+ horizontalAlign: 1,
+ });
+
+ const calloutResult = unwrapBlockRangeBody(blockRangeBody(DocumentBlockRangeType.CALLOUT, {
+ indentStart: { v: 12 },
+ indentEnd: { v: 8 },
+ spaceAbove: { v: 4 },
+ spaceBelow: { v: 6 },
+ textStyle: { ff: 'Inter' },
+ }), {
+ blockId: 'block-1',
+ blockType: DocumentBlockRangeType.CALLOUT,
+ startIndex: 0,
+ endIndex: 2,
+ });
+
+ expect(calloutResult.body.paragraphs?.[0].paragraphStyle).toEqual({
+ textStyle: { ff: 'Inter' },
+ });
+
+ const quoteResult = unwrapBlockRangeBody(blockRangeBody(DocumentBlockRangeType.QUOTE, {
+ indentStart: { v: 12 },
+ indentEnd: { v: 8 },
+ spaceAbove: { v: 4 },
+ spaceBelow: { v: 6 },
+ }), {
+ blockId: 'block-1',
+ blockType: DocumentBlockRangeType.QUOTE,
+ startIndex: 0,
+ endIndex: 2,
+ });
+
+ expect(quoteResult.body.paragraphs?.[0].paragraphStyle).toEqual({
+ indentEnd: { v: 8 },
+ });
+ });
+
it('routes explicit and declared insert actions below the active block', () => {
expect(shouldUseInsertBelowRange('doc.command.insert-image', { id: 'image' })).toBe(true);
expect(shouldUseInsertBelowRange('docs.operation.insert-embed', { id: 'docs.operation.insert-embed.below' })).toBe(true);
diff --git a/packages/docs/src/facade/__tests__/f-doc-block-range.spec.ts b/packages/docs/src/facade/__tests__/f-document-block-range.spec.ts
similarity index 73%
rename from packages/docs/src/facade/__tests__/f-doc-block-range.spec.ts
rename to packages/docs/src/facade/__tests__/f-document-block-range.spec.ts
index 8aa763c8dd..c5b7b230b0 100644
--- a/packages/docs/src/facade/__tests__/f-doc-block-range.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document-block-range.spec.ts
@@ -16,11 +16,11 @@
import type { Univer } from '@univerjs/core';
import type { FDocument } from '../f-document';
-import { DocumentBlockRangeType } from '@univerjs/core';
+import { DocumentBlockRangeType, DocumentBlockType } from '@univerjs/core';
import { afterEach, describe, expect, it } from 'vitest';
import { createBlockRangeDocument, createTestBed } from './create-test-bed';
-describe('FDocBlockRange', () => {
+describe('FDocumentBlockRange', () => {
let univer: Univer | null = null;
let document: FDocument;
@@ -36,33 +36,32 @@ describe('FDocBlockRange', () => {
univer = null;
});
- it('should edit and remove block range content while preserving surrounding paragraphs', () => {
+ it('edits and removes block range content while preserving surrounding paragraphs', () => {
for (const blockType of [DocumentBlockRangeType.QUOTE, DocumentBlockRangeType.CALLOUT, DocumentBlockRangeType.CODE]) {
createDocumentFacade(blockType);
const body = document.getBody();
- const block = body.getChild(0).asBlockRange();
+ const block = body.getElement(0)!.asBlockRange();
- expect(block.getType()).toBe('blockRange');
+ expect(block.getType()).toBe(DocumentBlockType.BLOCK_RANGE);
expect(block.getKey()).toBe(`${blockType}-1`);
expect(block.getParent()).toBe(body);
expect(block.getBlockType()).toBe(blockType);
expect(block.getText()).toBe('Block');
- expect(body.getBlockRange(block.getKey()).blockType).toBe(blockType);
- expect(body.getBlockRangeText(block.getKey())).toBe('Block');
+ expect(block.getBlockRange().blockType).toBe(blockType);
expect(body.insertParagraph(0, 'Intro').getText()).toBe('Intro');
expect(block.getText()).toBe('Block');
expect(block.setText('Updated')).toBe(true);
- expect(body.getBlockRangeText(block.getKey())).toBe('Updated');
- expect(block.removeFromParent()).toBe(true);
+ expect(block.getText()).toBe('Updated');
+ expect(block.remove()).toBe(true);
expect(document.save().body?.dataStream).toBe('Intro\rAfter\r\n');
}
});
- it('should unwrap a block range from the body', () => {
+ it('unwraps a block range from the body', () => {
createDocumentFacade();
- expect(document.getBody().getChild(0).asBlockRange().unwrap()).toBe(true);
+ expect(document.getBody().getElement(0)!.asBlockRange().unwrap()).toBe(true);
expect(document.save().body?.dataStream).toBe('After\r\n');
});
});
diff --git a/packages/docs/src/facade/__tests__/f-doc-body.spec.ts b/packages/docs/src/facade/__tests__/f-document-body.spec.ts
similarity index 62%
rename from packages/docs/src/facade/__tests__/f-doc-body.spec.ts
rename to packages/docs/src/facade/__tests__/f-document-body.spec.ts
index ec4ecf4717..19d597764b 100644
--- a/packages/docs/src/facade/__tests__/f-doc-body.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document-body.spec.ts
@@ -16,11 +16,11 @@
import type { Univer } from '@univerjs/core';
import type { FDocument } from '../f-document';
+import { DocumentBlockType } from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { DocElementStaleError } from '../doc-element-registry';
import { createSimpleDocument, createTestBed } from './create-test-bed';
-describe('FDocBody', () => {
+describe('FDocumentBody', () => {
let univer: Univer;
let document: FDocument;
@@ -34,31 +34,31 @@ describe('FDocBody', () => {
univer.dispose();
});
- it('should read, insert, replace, style and remove paragraphs by stable paragraph ids', () => {
+ it('reads, inserts, replaces, styles and removes paragraphs by stable paragraph ids', () => {
const body = document.getBody();
- expect(body.getNumChildren()).toBe(3);
+ expect(body.getElements()).toHaveLength(3);
- const first = body.getChild(0);
- const second = body.getChild(1).asParagraph();
- expect(first.getType()).toBe('paragraph');
+ const first = body.getElement(0)!;
+ const second = body.getElement(1)!.asParagraph();
+ expect(first.getType()).toBe(DocumentBlockType.PARAGRAPH);
expect(first.getKey()).toBe('para_alpha');
- expect(first.asParagraph().getId()).toBe('para_alpha');
- expect(second.getId()).toBe('para_beta');
+ expect(first.asParagraph().getParagraphId()).toBe('para_alpha');
+ expect(second.getParagraphId()).toBe('para_beta');
expect(second.getKey()).toBe('para_beta');
expect(first.getParent()).toBe(body);
expect(first.getNextSibling()?.asParagraph().getText()).toBe('Beta');
- expect(body.getChild(1).getPreviousSibling()?.asParagraph().getText()).toBe('Alpha');
- expect(body.createSibling(first.getType(), first.getKey(), 1)?.asParagraph().getText()).toBe('Beta');
+ expect(body.getElement(1)!.getPreviousSibling()?.asParagraph().getText()).toBe('Alpha');
+ expect(first.getSibling(1)?.asParagraph().getText()).toBe('Beta');
- expect(body.getChildIndex(second)).toBe(1);
+ expect(body.getElementIndex(second)).toBe(1);
expect(body.insertText(0, 'Hello ')).toBe(true);
expect(document.save().body?.dataStream).toBe('Hello Alpha\rBeta\rGamma\r\n');
const title = body.insertParagraph(0, 'Title');
- expect(title.getId()).toMatch(/^para_/);
- expect(title.getKey()).toBe(title.getId());
+ expect(title.getParagraphId()).toMatch(/^para_/);
+ expect(title.getKey()).toBe(title.getParagraphId());
expect(title.getText()).toBe('Title');
- expect(document.save().body?.paragraphs?.[0].paragraphId).toBe(title.getId());
+ expect(document.save().body?.paragraphs?.[0].paragraphId).toBe(title.getParagraphId());
expect(document.save().body?.dataStream).toBe('Title\rHello Alpha\rBeta\rGamma\r\n');
const tail = body.appendParagraph('Tail');
@@ -78,33 +78,32 @@ describe('FDocBody', () => {
ts: { bl: 1 },
});
- const paragraph = body.getChild(0).asParagraph();
- expect(body.setParagraphStyle(paragraph, { horizontalAlign: 2 })).toBe(true);
+ const paragraph = body.getElement(0)!.asParagraph();
+ expect(paragraph.setStyle({ horizontalAlign: 2 })).toBe(true);
expect(document.save().body?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(2);
- expect(body.getParagraphText(paragraph.getKey())).toBe('Hi Alpha');
- expect(body.getParagraphRange(paragraph.getKey())).toMatchObject({ startOffset: 0, endOffset: 8 });
- expect(body.resolveParagraph(paragraph.getKey()).paragraphIndex).toBe(0);
- expect(body.resolveElement(paragraph.getType(), paragraph.getKey())).toMatchObject({ type: 'paragraph', position: 0 });
+ expect(paragraph.getText()).toBe('Hi Alpha');
+ expect(paragraph.getRange()).toMatchObject({ startOffset: 0, endOffset: 8 });
+ expect(paragraph.getResolvedParagraphInfo().paragraphIndex).toBe(0);
+ expect(body.resolveElement(paragraph)).toMatchObject({ type: DocumentBlockType.PARAGRAPH, position: 0 });
- expect(body.setParagraphText(paragraph.getKey(), 'Updated')).toBe(true);
+ expect(paragraph.setText('Updated')).toBe(true);
expect(paragraph.getText()).toBe('Updated');
- expect(body.appendParagraphText(paragraph.getKey(), ' suffix')).toBe(true);
+ expect(paragraph.appendText(' suffix')).toBe(true);
expect(paragraph.getText()).toBe('Updated suffix');
- expect(body.removeParagraph(paragraph.getKey())).toBe(true);
+ expect(body.removeParagraph(paragraph)).toBe(true);
expect(document.save().body?.dataStream).toBe('Beta\rGamma\rTail\r\n');
});
- it('should reject ambiguous or missing paragraph identities as stale elements', () => {
+ it('rejects ambiguous or missing paragraph identities as stale elements', () => {
const body = document.getBody();
document.getDocumentDataModel().getBody()!.paragraphs![1].paragraphId = 'para_alpha';
- expect(() => body.resolveParagraph('para_alpha')).toThrow(DocElementStaleError);
+ expect(() => body.getElement(0)!.asParagraph().getResolvedParagraphInfo()).toThrow('Multiple document paragraphs with id para_alpha found');
document.getDocumentDataModel().getBody()!.paragraphs![1].paragraphId = 'para_beta';
const invalidParagraph = document.getDocumentDataModel().getBody()!.paragraphs![0] as { paragraphId?: string };
delete invalidParagraph.paragraphId;
- expect(() => body.getChild(0)).toThrow(DocElementStaleError);
- expect(() => body.getChild(0)).toThrow('Paragraph at index 0 is missing paragraphId.');
+ expect(() => body.getElement(0)).toThrow('Paragraph at index 0 is missing paragraphId.');
});
});
diff --git a/packages/docs/src/facade/__tests__/f-doc-custom-block.spec.ts b/packages/docs/src/facade/__tests__/f-document-custom-block.spec.ts
similarity index 74%
rename from packages/docs/src/facade/__tests__/f-doc-custom-block.spec.ts
rename to packages/docs/src/facade/__tests__/f-document-custom-block.spec.ts
index e331668d47..fe6110229b 100644
--- a/packages/docs/src/facade/__tests__/f-doc-custom-block.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document-custom-block.spec.ts
@@ -16,10 +16,11 @@
import type { Univer } from '@univerjs/core';
import type { FDocument } from '../f-document';
+import { DocumentBlockType } from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { createCustomBlockDocument, createTestBed } from './create-test-bed';
-describe('FDocCustomBlock', () => {
+describe('FDocumentCustomBlock', () => {
let univer: Univer;
let document: FDocument;
@@ -38,20 +39,19 @@ describe('FDocCustomBlock', () => {
univer.dispose();
});
- it('should expose custom block identity and remove the block from document body', () => {
+ it('exposes custom block identity and removes the block from document body', () => {
const body = document.getBody();
- const customBlock = body.getChild(0).asCustomBlock();
+ const customBlock = body.getElement(0)!.asCustomBlock();
- expect(customBlock.getType()).toBe('customBlock');
+ expect(customBlock.getType()).toBe(DocumentBlockType.CUSTOM_BLOCK);
expect(customBlock.getKey()).toBe('custom-1');
expect(customBlock.getParent()).toBe(body);
- expect(customBlock.getBlockId()).toBe('custom-1');
- expect(body.getCustomBlock(customBlock.getBlockId()).blockId).toBe('custom-1');
- expect(customBlock.removeFromParent()).toBe(true);
+ expect(customBlock.getCustomBlock().blockId).toBe('custom-1');
+ expect(body.removeCustomBlock(customBlock)).toBe(true);
expect(document.save().body?.customBlocks).toEqual([]);
createDocumentFacade();
- expect(document.getBody().removeCustomBlock('custom-1')).toBe(true);
+ expect(document.getBody().getElement(0)!.asCustomBlock().remove()).toBe(true);
expect(document.save().body?.dataStream).toBe('\raa\r\n');
});
});
diff --git a/packages/docs/src/facade/__tests__/f-doc-element.spec.ts b/packages/docs/src/facade/__tests__/f-document-element.spec.ts
similarity index 58%
rename from packages/docs/src/facade/__tests__/f-doc-element.spec.ts
rename to packages/docs/src/facade/__tests__/f-document-element.spec.ts
index 4518ab9d33..de53b698bd 100644
--- a/packages/docs/src/facade/__tests__/f-doc-element.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document-element.spec.ts
@@ -16,7 +16,7 @@
import type { IDocumentData, Univer } from '@univerjs/core';
import type { FDocument } from '../f-document';
-import { DocumentBlockRangeType } from '@univerjs/core';
+import { DocumentBlockRangeType, DocumentBlockType } from '@univerjs/core';
import { afterEach, describe, expect, it } from 'vitest';
import {
createBlockRangeDocument,
@@ -26,7 +26,7 @@ import {
createTestBed,
} from './create-test-bed';
-describe('FDocElement', () => {
+describe('FDocumentElement', () => {
let univer: Univer | null = null;
let document: FDocument;
@@ -42,42 +42,45 @@ describe('FDocElement', () => {
univer = null;
});
- it('should cast body elements to their concrete facade types', () => {
+ it('casts body elements to their concrete facade types', () => {
createDocumentFacade(createSimpleDocument());
- expect(document.getBody().getChild(0).asParagraph().getText()).toBe('Alpha');
+ expect(document.getBody().getElement(0)!.asParagraph().getText()).toBe('Alpha');
createDocumentFacade(createBlockRangeDocument());
- expect(document.getBody().getChild(0).asBlockRange().getBlockType()).toBe(DocumentBlockRangeType.QUOTE);
+ expect(document.getBody().getElement(0)!.asBlockRange().getBlockType()).toBe(DocumentBlockRangeType.QUOTE);
createDocumentFacade(createTableDocument());
- expect(document.getBody().getChild(0).asTable().getTableId()).toBe('table-1');
+ expect(document.getBody().getElement(0)!.asTable().getTable().tableId).toBe('table-1');
createDocumentFacade(createCustomBlockDocument());
- expect(document.getBody().getChild(0).asCustomBlock().getBlockId()).toBe('custom-1');
+ expect(document.getBody().getElement(0)!.asCustomBlock().getCustomBlock().blockId).toBe('custom-1');
});
- it('should remove a generic element from its parent', () => {
+ it('removes a generic element from its parent', () => {
createDocumentFacade(createSimpleDocument());
- expect(document.getBody().getChild(0).removeFromParent()).toBe(true);
+ expect(document.getBody().getElement(0)!.remove()).toBe(true);
expect(document.save().body?.dataStream).toBe('Beta\rGamma\r\n');
});
- it('should navigate siblings and reject invalid casts', () => {
+ it('navigates siblings and rejects invalid casts without changing the element type', () => {
createDocumentFacade(createSimpleDocument());
const body = document.getBody();
- const first = body.getChild(0);
- const second = body.getChild(1);
+ const first = body.getElement(0)!;
+ const second = body.getElement(1)!;
expect(first.getPreviousSibling()).toBeNull();
expect(first.getNextSibling()?.getKey()).toBe(second.getKey());
expect(second.getPreviousSibling()?.getKey()).toBe(first.getKey());
- expect(() => first.asTable()).toThrow('Cannot cast paragraph to table.');
- expect(() => first.asBlockRange()).toThrow('Cannot cast paragraph to blockRange.');
- expect(() => first.asCustomBlock()).toThrow('Cannot cast paragraph to customBlock.');
+ expect(() => first.asTable()).toThrow('Element type is not a table: paragraph');
+ expect(() => first.asBlockRange()).toThrow('Element type is not a block range: paragraph');
+ expect(() => first.asCustomBlock()).toThrow('Element type is not a custom block: paragraph');
+ expect(first.getType()).toBe(DocumentBlockType.PARAGRAPH);
createDocumentFacade(createTableDocument());
- expect(() => document.getBody().getChild(0).asParagraph()).toThrow('Cannot cast table to paragraph.');
+ const table = document.getBody().getElement(0)!;
+ expect(() => table.asParagraph()).toThrow('Element type is not a paragraph: table');
+ expect(table.getType()).toBe(DocumentBlockType.TABLE);
});
});
diff --git a/packages/docs/src/facade/__tests__/f-doc-paragraph.spec.ts b/packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts
similarity index 65%
rename from packages/docs/src/facade/__tests__/f-doc-paragraph.spec.ts
rename to packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts
index d67c663326..1d6bd910ff 100644
--- a/packages/docs/src/facade/__tests__/f-doc-paragraph.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts
@@ -16,9 +16,8 @@
import type { IDocumentData, Univer } from '@univerjs/core';
import type { FDocument } from '../f-document';
-import { PresetListType } from '@univerjs/core';
+import { DocumentBlockType, PresetListType } from '@univerjs/core';
import { afterEach, describe, expect, it } from 'vitest';
-import { DocElementStaleError } from '../doc-element-registry';
import {
createBulletDocument,
createDuplicateDocument,
@@ -27,7 +26,7 @@ import {
createTestBed,
} from './create-test-bed';
-describe('FDocParagraph', () => {
+describe('FDocumentParagraph', () => {
let univer: Univer | null = null;
let document: FDocument;
@@ -43,50 +42,51 @@ describe('FDocParagraph', () => {
univer = null;
});
- it('should keep paragraph handles stable when text is duplicated or inserted before them', () => {
+ it('keeps paragraph handles stable when text is duplicated or inserted before them', () => {
createDocumentFacade(createDuplicateDocument());
const body = document.getBody();
- const secondSame = body.getChild(1).asParagraph();
+ const secondSame = body.getElement(1)!.asParagraph();
- expect(secondSame.getId()).toBe('para_same_2');
+ expect(secondSame.getParagraphId()).toBe('para_same_2');
expect(body.insertParagraph(0, 'X').getText()).toBe('X');
- expect(body.getChildIndex(secondSame)).toBe(2);
+ expect(body.getElementIndex(secondSame)).toBe(2);
expect(secondSame.setText('Picked')).toBe(true);
expect(document.save().body?.dataStream).toBe('X\rSame\rPicked\rTail\r\n');
- expect(secondSame.removeFromParent()).toBe(true);
+ expect(secondSame.remove()).toBe(true);
expect(document.save().body?.dataStream).toBe('X\rSame\rTail\r\n');
});
- it('should mark paragraph handles as stale after their backing paragraph is removed', () => {
+ it('marks paragraph handles as stale after their backing paragraph is removed', () => {
createDocumentFacade(createSimpleDocument());
- const paragraph = document.getBody().getChild(1).asParagraph();
- expect(paragraph.removeFromParent()).toBe(true);
- expect(() => paragraph.getText()).toThrow(DocElementStaleError);
- expect(() => paragraph.removeFromParent()).toThrow(DocElementStaleError);
+ const paragraph = document.getBody().getElement(1)!.asParagraph();
+ expect(paragraph.remove()).toBe(true);
+ expect(() => paragraph.getText()).toThrow('Document paragraph with id para_beta not found');
+ expect(() => paragraph.remove()).toThrow('Document paragraph with id para_beta not found');
});
- it('should update checklist paragraphs without changing non-task list items', () => {
+ it('updates checklist paragraphs without changing non-task list items', () => {
createDocumentFacade(createBulletDocument());
const bulletBody = document.getBody();
- const listItem = bulletBody.getChild(0).asParagraph();
- expect(listItem.getType()).toBe('paragraph');
+ const listItem = bulletBody.getElement(0)!.asParagraph();
+ expect(listItem.getType()).toBe(DocumentBlockType.PARAGRAPH);
expect(listItem.getKey()).toMatch(/^para_/);
- expect(listItem.getId()).toBe(listItem.getKey());
+ expect(listItem.getParagraphId()).toBe(listItem.getKey());
expect(listItem.getParent()).toBe(bulletBody);
expect(listItem.isListItem()).toBe(true);
expect(listItem.isTask()).toBe(false);
+ expect(listItem.setTaskChecked(true)).toBe(false);
createDocumentFacade(createTaskDocument());
- const task = document.getBody().getChild(0).asParagraph();
+ const task = document.getBody().getElement(0)!.asParagraph();
expect(task.isListItem()).toBe(true);
expect(task.isTask()).toBe(true);
expect(task.setTaskChecked(true)).toBe(true);
expect(document.save().body?.paragraphs?.[0].bullet?.listType).toBe(PresetListType.CHECK_LIST_CHECKED);
- expect(document.getBody().setTaskChecked(task.getKey(), false)).toBe(true);
+ expect(task.setTaskChecked(false)).toBe(true);
expect(document.save().body?.paragraphs?.[0].bullet?.listType).toBe(PresetListType.CHECK_LIST);
});
});
diff --git a/packages/docs/src/facade/__tests__/f-doc-table.spec.ts b/packages/docs/src/facade/__tests__/f-document-table.spec.ts
similarity index 76%
rename from packages/docs/src/facade/__tests__/f-doc-table.spec.ts
rename to packages/docs/src/facade/__tests__/f-document-table.spec.ts
index 146983002d..9922c84bc4 100644
--- a/packages/docs/src/facade/__tests__/f-doc-table.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document-table.spec.ts
@@ -16,10 +16,11 @@
import type { Univer } from '@univerjs/core';
import type { FDocument } from '../f-document';
+import { DocumentBlockType } from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { createTableDocument, createTestBed } from './create-test-bed';
-describe('FDocTable', () => {
+describe('FDocumentTable', () => {
let univer: Univer;
let document: FDocument;
@@ -38,20 +39,19 @@ describe('FDocTable', () => {
univer.dispose();
});
- it('should expose table identity and remove the table from document body', () => {
+ it('exposes table identity and removes the table from document body', () => {
const body = document.getBody();
- const table = body.getChild(0).asTable();
+ const table = body.getElement(0)!.asTable();
- expect(table.getType()).toBe('table');
+ expect(table.getType()).toBe(DocumentBlockType.TABLE);
expect(table.getKey()).toBe('table-1');
expect(table.getParent()).toBe(body);
- expect(table.getTableId()).toBe('table-1');
- expect(body.getTable(table.getTableId()).tableId).toBe('table-1');
- expect(table.removeFromParent()).toBe(true);
+ expect(table.getTable().tableId).toBe('table-1');
+ expect(body.removeTable(table)).toBe(true);
expect(document.save().body?.tables).toEqual([]);
createDocumentFacade();
- expect(document.getBody().removeTable('table-1')).toBe(true);
+ expect(document.getBody().getElement(0)!.asTable().remove()).toBe(true);
expect(document.save().body?.dataStream).toBe('aa\r\n');
});
});
diff --git a/packages/docs/src/facade/__tests__/f-document.spec.ts b/packages/docs/src/facade/__tests__/f-document.spec.ts
index 24e9af4213..aa0d83f5b8 100644
--- a/packages/docs/src/facade/__tests__/f-document.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document.spec.ts
@@ -42,7 +42,7 @@ describe('FDocument', () => {
univer.dispose();
});
- it('should edit document text through append, insert and paragraph operations', () => {
+ it('edits document text through append, insert and paragraph operations', () => {
expect(document.appendText('Univer')).toBe(true);
expect(document.save().body?.dataStream).toBe('Hello,Univer\r\n');
@@ -65,7 +65,7 @@ describe('FDocument', () => {
expect(document.save().body?.dataStream).toBe('Hello,Line 1\rLine 2\r\r\n');
});
- it('should include current document resources in saved snapshots', () => {
+ it('includes current document resources in saved snapshots', () => {
const resourceManagerService = get(IResourceManagerService);
resourceManagerService.registerPluginResource({
@@ -74,7 +74,7 @@ describe('FDocument', () => {
onLoad: () => undefined,
onUnLoad: () => undefined,
toJson: () => '{"value":1}',
- parseJson: (bytes) => JSON.parse(bytes),
+ parseJson: (bytes: string) => JSON.parse(bytes),
});
expect(document.save().resources).toEqual([
@@ -85,14 +85,14 @@ describe('FDocument', () => {
]);
});
- it('should expose document identity and snapshot data from the active model', () => {
+ it('exposes document identity and snapshot data from the active model', () => {
expect(document.getId()).toBe('test');
expect(document.getName()).toBe('');
expect(document.getDocumentDataModel().getUnitId()).toBe('test');
expect(document.save().body?.dataStream).toBe('Hello,\r\n');
});
- it('should run undo and redo against the active document', () => {
+ it('runs undo and redo against the active document', () => {
get(IUndoRedoService);
expect(document.appendText('One')).toBe(true);
@@ -105,21 +105,21 @@ describe('FDocument', () => {
expect(document.save().body?.dataStream).toBe('Hello,One\r\n');
});
- it('should preserve paragraph ids in saved snapshots and body wrappers', () => {
+ it('preserves paragraph ids in saved snapshots and body wrappers', () => {
univer.dispose();
createDocumentFacade(createSimpleDocument());
const savedParagraphs = document.save().body?.paragraphs;
const body = document.getBody();
- const paragraph = body.getChild(0).asParagraph();
+ const paragraph = body.getElement(0)!.asParagraph();
expect(savedParagraphs?.map((item) => item.paragraphId)).toEqual(['para_alpha', 'para_beta', 'para_gamma']);
expect(savedParagraphs?.map((item) => item.startIndex)).toEqual([5, 10, 16]);
- expect(paragraph.getId()).toBe('para_alpha');
+ expect(paragraph.getParagraphId()).toBe('para_alpha');
expect(paragraph.getText()).toBe('Alpha');
});
- it('should keep caller-provided paragraph ids when creating a body facade', () => {
+ it('keeps caller-provided paragraph ids when creating a body facade', () => {
univer.dispose();
createDocumentFacade(createDocumentData('doc-with-ids', {
dataStream: 'Legacy\r\n',
@@ -127,9 +127,9 @@ describe('FDocument', () => {
sectionBreaks: [{ startIndex: 7 }],
}));
- const paragraph = document.getBody().getChild(0).asParagraph();
+ const paragraph = document.getBody().getElement(0)!.asParagraph();
- expect(paragraph.getId()).toBe('para_fixture_26');
+ expect(paragraph.getParagraphId()).toBe('para_fixture_26');
expect(document.save().body?.paragraphs?.[0].paragraphId).toBe('para_fixture_26');
});
});
diff --git a/packages/docs/src/facade/doc-element-registry.ts b/packages/docs/src/facade/doc-element-registry.ts
deleted file mode 100644
index 5c51bae2eb..0000000000
--- a/packages/docs/src/facade/doc-element-registry.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IDocumentBody } from '@univerjs/core';
-
-/**
- * The top-level document body element types supported by the doc facade.
- */
-export type FDocElementType = 'paragraph' | 'table' | 'blockRange' | 'customBlock';
-
-const PARAGRAPH_REGISTRY_MIGRATION_ERROR = 'DocElementRegistry no longer tracks paragraph identity; use paragraphId.';
-
-/**
- * Error thrown when a facade element key can no longer be resolved uniquely.
- *
- * A stale paragraph usually means the paragraph was deleted, or the document no
- * longer contains exactly one paragraph with the requested `paragraphId`.
- *
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * paragraph.removeFromParent();
- *
- * try {
- * paragraph.getText();
- * } catch (error) {
- * if (error instanceof DocElementStaleError) {
- * console.log('The paragraph handle is stale.');
- * }
- * }
- * ```
- */
-export class DocElementStaleError extends Error {
- /**
- * Create a stale element error.
- * @param {string} message The error message.
- */
- constructor(message = 'Doc element is stale') {
- super(message);
- this.name = 'DocElementStaleError';
- }
-}
-
-/**
- * @deprecated Paragraph facade identity is now resolved directly from persisted
- * `paragraphId` values. This class remains as a compatibility shell for callers
- * that constructed document facade internals directly.
- *
- * @hideconstructor
- */
-export class DocElementRegistry {
- /**
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
- * @throws {Error} Always throws; use `paragraph.paragraphId` instead.
- */
- getParagraphKey(_segmentId: string, _body: IDocumentBody, _paragraphIndex: number): string {
- throw new Error(PARAGRAPH_REGISTRY_MIGRATION_ERROR);
- }
-
- /**
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
- * @throws {Error} Always throws; resolve paragraph handles by `paragraphId` instead.
- */
- resolveParagraphStartIndex(_segmentId: string, _key: string): number {
- throw new Error(PARAGRAPH_REGISTRY_MIGRATION_ERROR);
- }
-
- /**
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
- * @throws {Error} Always throws; resolve paragraph handles by `paragraphId` instead.
- */
- syncParagraph(_segmentId: string, _key: string, _body: IDocumentBody): number {
- throw new Error(PARAGRAPH_REGISTRY_MIGRATION_ERROR);
- }
-
- /**
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
- * @throws {Error} Always throws; stale state is detected from live `paragraphId` lookups.
- */
- markStale(_segmentId: string, _key: string): void {
- throw new Error(PARAGRAPH_REGISTRY_MIGRATION_ERROR);
- }
-
- /**
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
- * @throws {Error} Always throws; text edits no longer need registry offset tracking.
- */
- beforeTextEdit(_segmentId: string, _startOffset: number, _endOffset: number, _insertLength: number): void {
- throw new Error(PARAGRAPH_REGISTRY_MIGRATION_ERROR);
- }
-}
diff --git a/packages/docs/src/facade/f-doc-block-range.ts b/packages/docs/src/facade/f-doc-block-range.ts
deleted file mode 100644
index 157cf2b4bd..0000000000
--- a/packages/docs/src/facade/f-doc-block-range.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { DocumentBlockRangeType } from '@univerjs/core';
-import type { FDocBody } from './f-doc-body';
-
-/**
- * A facade wrapper for document block ranges, such as callout, quote, and code blocks.
- *
- * Block range identity is backed by the persisted `IDocumentBlockRange.blockId`,
- * so wrappers can be re-resolved after text is inserted before the block range.
- *
- * @hideconstructor
- */
-export class FDocBlockRange {
- constructor(
- protected readonly _body: FDocBody,
- protected readonly _key: string
- ) {}
-
- /**
- * Get the document element type.
- * @returns {'blockRange'} The literal block range element type.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
- * console.log(blockRange.getType());
- * ```
- */
- getType(): 'blockRange' {
- return 'blockRange';
- }
-
- /**
- * Get the block range key.
- * @returns {string} The persisted `blockId` for this block range.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
- * console.log(blockRange.getKey());
- * ```
- */
- getKey(): string {
- return this._key;
- }
-
- /**
- * Get the parent body facade that owns this block range.
- * @returns {FDocBody} The document body facade.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
- * console.log(blockRange.getParent().getChildIndex(blockRange));
- * ```
- */
- getParent(): FDocBody {
- return this._body;
- }
-
- /**
- * Remove this block range and its content from the parent body.
- * @returns {boolean} `true` if the block range content was removed.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
- * blockRange.removeFromParent();
- * ```
- */
- removeFromParent(): boolean {
- return this._body.removeBlockRange(this._key);
- }
-
- /**
- * Get the block range type.
- * @returns {DocumentBlockRangeType} The block type, such as callout, quote, or code.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
- * console.log(blockRange.getBlockType());
- * ```
- */
- getBlockType(): DocumentBlockRangeType {
- return this._body.getBlockRange(this._key).blockType;
- }
-
- /**
- * Get the plain text inside this block range.
- * @returns {string} The block range text.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
- * console.log(blockRange.getText());
- * ```
- */
- getText(): string {
- return this._body.getBlockRangeText(this._key);
- }
-
- /**
- * Replace the plain text inside this block range.
- * @param {string} text The replacement text.
- * @returns {boolean} `true` if the block range text was replaced.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
- * blockRange.setText('Updated block text');
- * ```
- */
- setText(text: string): boolean {
- return this._body.setBlockRangeText(this._key, text);
- }
-
- /**
- * Remove this block range wrapper from the body.
- *
- * This currently removes the block range and its content, matching
- * `removeFromParent()`.
- *
- * @returns {boolean} `true` if the block range content was removed.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
- * blockRange.unwrap();
- * ```
- */
- unwrap(): boolean {
- return this.removeFromParent();
- }
-}
diff --git a/packages/docs/src/facade/f-doc-body.ts b/packages/docs/src/facade/f-doc-body.ts
deleted file mode 100644
index 324a9158a9..0000000000
--- a/packages/docs/src/facade/f-doc-body.ts
+++ /dev/null
@@ -1,973 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { DocumentDataModel, ICommandService, ICustomBlock, ICustomTable, IDocumentBlockRange, IDocumentBody, IParagraph, IParagraphStyle, ITextStyle } from '@univerjs/core';
-import type { IRichTextEditingMutationParams } from '@univerjs/docs';
-import type { DocElementRegistry, FDocElementType } from './doc-element-registry';
-import { getRichTextEditPath, JSONX, PresetListType, TextX, TextXActionType, UpdateDocsAttributeType } from '@univerjs/core';
-import { RichTextEditingMutation } from '@univerjs/docs';
-import { DocElementStaleError } from './doc-element-registry';
-import { buildPlainTextInsertBody } from './utils';
-import { FDocElement } from './f-doc-element';
-import { FDocParagraph } from './f-doc-paragraph';
-
-/**
- * A text range in a document segment. Offsets are zero-based positions in the segment data stream.
- */
-export interface IFDocTextRange {
- /** The inclusive start offset of the range. */
- startOffset: number;
- /** The exclusive end offset of the range. */
- endOffset: number;
- /** The header/footer segment id. Omit or use an empty string for the main body. */
- segmentId?: string;
-}
-
-/**
- * Resolved paragraph metadata in the current document body.
- */
-export interface IFDocResolvedParagraph {
- /** The underlying paragraph snapshot object. */
- paragraph: IParagraph;
- /** The current paragraph index in the body paragraph list. */
- paragraphIndex: number;
- /** The inclusive start offset of the paragraph text. */
- startOffset: number;
- /** The exclusive end offset of the paragraph text, before the paragraph break. */
- endOffset: number;
-}
-
-/**
- * A stable facade element handle that can be resolved by type and key.
- */
-export interface IFDocElementHandle {
- /**
- * Get the element type.
- * @returns {FDocElementType} The element type used by the facade resolver.
- */
- getType(): FDocElementType;
- /**
- * Get the persisted key used by the facade to resolve the element.
- * @returns {string} The facade key.
- */
- getKey(): string;
-}
-
-/**
- * A rich-text-like object, such as `RichTextValue` or `RichTextBuilder`, that can provide document body data.
- */
-export interface IFDocRichTextLike {
- /**
- * Get rich text data that contains document body data.
- * @returns {{ body?: IDocumentBody }} The rich text data object.
- */
- getData(): { body?: IDocumentBody };
-}
-
-function isRichTextLike(value: unknown): value is IFDocRichTextLike {
- return typeof value === 'object' && value !== null && 'getData' in value && typeof (value as IFDocRichTextLike).getData === 'function';
-}
-
-interface IFDocChildInfo {
- type: FDocElementType;
- key: string;
- position: number;
- priority: number;
-}
-
-const FACADE_TRIGGER = 'doc-facade';
-const RESTORE_INSERTED_PARAGRAPH_IDS = '__textXRestoreParagraphIds';
-
-/**
- * A Facade API object bounded to a document body or header/footer segment.
- * It provides Google Docs-like element access and range editing methods.
- *
- * Paragraph elements use their persisted `paragraphId`. Tables, block ranges, and
- * custom blocks use their persisted ids.
- *
- * @hideconstructor
- */
-export class FDocBody {
- constructor(
- private readonly _documentDataModel: DocumentDataModel,
- private readonly _commandService: ICommandService,
- _registry: DocElementRegistry,
- private readonly _segmentId = ''
- ) {}
-
- /**
- * Get the number of top-level child elements in the body.
- * @returns {number} The number of child elements.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const body = doc.getBody();
- * console.log(body.getNumChildren());
- * ```
- */
- getNumChildren(): number {
- return this._getChildren().length;
- }
-
- /**
- * Get a top-level child element by child index.
- * @param {number} index The zero-based child index.
- * @returns {FDocElement} The child element wrapper.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const body = doc.getBody();
- * const firstChild = body.getChild(0);
- * console.log(firstChild.getType());
- * ```
- */
- getChild(index: number): FDocElement {
- const child = this._getChildren()[index];
- if (!child) {
- throw new RangeError(`Child index ${index} is out of range.`);
- }
-
- return this._createElement(child.type, child.key);
- }
-
- /**
- * Get the current child index of an element handle.
- * The index is resolved from the element key, so a paragraph handle keeps pointing
- * to the same paragraph after facade edits insert content before it.
- * @param {IFDocElementHandle} element The element handle to locate.
- * @returns {number} The current zero-based child index.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const body = doc.getBody();
- * const paragraph = body.getChild(1).asParagraph();
- * body.insertParagraph(0, 'Intro');
- * console.log(body.getChildIndex(paragraph));
- * ```
- */
- getChildIndex(element: IFDocElementHandle): number {
- const resolved = this.resolveElement(element.getType(), element.getKey());
- const index = this._getChildren().findIndex((child) => child.type === resolved.type && child.key === resolved.key);
-
- if (index < 0) {
- throw new Error('Doc element is stale');
- }
-
- return index;
- }
-
- /**
- * Insert plain text at a document body offset.
- * @param {number} index The zero-based insertion offset.
- * @param {string} text The plain text to insert.
- * @returns {boolean} `true` if the edit was applied.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const body = doc.getBody();
- * body.insertText(0, 'Hello ');
- * ```
- */
- insertText(index: number, text: string): boolean {
- return this._replaceBodyRange({ startOffset: index, endOffset: index }, buildPlainTextInsertBody(text));
- }
-
- /**
- * Insert a plain-text paragraph before the paragraph at the given paragraph index.
- * @param {number} index The zero-based paragraph insertion index.
- * @param {string} text The paragraph text. Defaults to an empty paragraph.
- * @returns {FDocParagraph} The inserted paragraph wrapper.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const body = doc.getBody();
- * const paragraph = body.insertParagraph(0, 'Document title');
- * paragraph.appendText(' suffix');
- * ```
- */
- insertParagraph(index: number, text = ''): FDocParagraph {
- const offset = this._getParagraphInsertOffset(index);
- const result = this._replaceBodyRange({ startOffset: offset, endOffset: offset }, buildPlainTextInsertBody(`${text}\r`));
- if (!result) {
- throw new Error('Failed to insert paragraph.');
- }
-
- const paragraphIndex = this._normalizeInsertedParagraphIndex(index);
- const paragraph = this._getBody().paragraphs?.[paragraphIndex];
- return new FDocParagraph(this, this._getParagraphId(paragraph, paragraphIndex));
- }
-
- /**
- * Append a plain-text paragraph at the end of the body.
- * @param {string} text The paragraph text. Defaults to an empty paragraph.
- * @returns {FDocParagraph} The appended paragraph wrapper.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const body = doc.getBody();
- * const paragraph = body.appendParagraph('Summary');
- * console.log(paragraph.getText());
- * ```
- */
- appendParagraph(text = ''): FDocParagraph {
- return this.insertParagraph(this._getBody().paragraphs?.length ?? 0, text);
- }
-
- /**
- * Delete a range from the body.
- * @param {IFDocTextRange} range The text range to delete.
- * @returns {boolean} `true` if the range was deleted.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const body = doc.getBody();
- * body.deleteRange({ startOffset: 0, endOffset: 5 });
- * ```
- */
- deleteRange(range: IFDocTextRange): boolean {
- return this._replaceBodyRange(range, { dataStream: '' });
- }
-
- /**
- * Replace a range with plain text or rich text body data.
- * @param {IFDocTextRange} range The text range to replace.
- * @param {string | IFDocRichTextLike | { body?: IDocumentBody }} value The replacement text or rich-text-like value.
- * @returns {boolean} `true` if the replacement was applied.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const body = doc.getBody();
- * body.replaceRange({ startOffset: 0, endOffset: 5 }, 'Hello');
- * ```
- */
- replaceRange(range: IFDocTextRange, value: string | IFDocRichTextLike | { body?: IDocumentBody }): boolean {
- let body: IDocumentBody;
-
- if (typeof value === 'string') {
- body = buildPlainTextInsertBody(value);
- } else if (isRichTextLike(value)) {
- body = value.getData().body ?? { dataStream: '' };
- } else {
- body = value.body ?? { dataStream: '' };
- }
-
- return this._replaceBodyRange(range, body);
- }
-
- /**
- * Apply text style to a body range.
- * @param {IFDocTextRange} range The range to style.
- * @param {ITextStyle} style The Univer text style patch.
- * @returns {boolean} `true` if the style was applied.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const body = doc.getBody();
- * body.setTextStyle({ startOffset: 0, endOffset: 5 }, { bl: 1 });
- * ```
- */
- setTextStyle(range: IFDocTextRange, style: ITextStyle): boolean {
- const len = range.endOffset - range.startOffset;
- const updateBody: IDocumentBody = {
- dataStream: '',
- textRuns: [{
- st: 0,
- ed: len,
- ts: style,
- }],
- };
-
- return this._retainBodyRange(range, updateBody, UpdateDocsAttributeType.COVER);
- }
-
- /**
- * Apply paragraph style to a paragraph handle or text range.
- * @param {FDocElement | FDocParagraph | IFDocTextRange} paragraph The paragraph handle or a range inside the paragraph.
- * @param {IParagraphStyle} style The Univer paragraph style patch.
- * @returns {boolean} `true` if the style was applied.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const body = doc.getBody();
- * const paragraph = body.getChild(0).asParagraph();
- * body.setParagraphStyle(paragraph, { horizontalAlign: 2 });
- * ```
- */
- setParagraphStyle(paragraph: FDocElement | FDocParagraph | IFDocTextRange, style: IParagraphStyle): boolean {
- const resolved = paragraph instanceof FDocElement || paragraph instanceof FDocParagraph
- ? this.resolveParagraph(paragraph.getKey())
- : this._findParagraphByRange(paragraph);
-
- const updateBody: IDocumentBody = {
- dataStream: '',
- paragraphs: [{
- ...resolved.paragraph,
- startIndex: 0,
- paragraphStyle: {
- ...resolved.paragraph.paragraphStyle,
- ...style,
- },
- }],
- };
- this._preserveExplicitParagraphIds(updateBody);
-
- return this._retainBodyRange(
- { startOffset: resolved.endOffset, endOffset: resolved.endOffset + 1 },
- updateBody,
- UpdateDocsAttributeType.REPLACE
- );
- }
-
- /**
- * Get the text content of a paragraph by paragraph id.
- * @param {string} key The paragraph id.
- * @returns {string} The paragraph text without the trailing paragraph break.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * console.log(doc.getBody().getParagraphText(paragraph.getKey()));
- * ```
- */
- getParagraphText(key: string): string {
- const resolved = this.resolveParagraph(key);
- return this._getBody().dataStream.slice(resolved.startOffset, resolved.endOffset);
- }
-
- /**
- * Replace the text content of a paragraph by paragraph id.
- * @param {string} key The paragraph id.
- * @param {string} text The replacement paragraph text.
- * @returns {boolean} `true` if the paragraph text was replaced.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * doc.getBody().setParagraphText(paragraph.getKey(), 'Updated text');
- * ```
- */
- setParagraphText(key: string, text: string): boolean {
- const resolved = this.resolveParagraph(key);
- return this.replaceRange({ startOffset: resolved.startOffset, endOffset: resolved.endOffset }, text);
- }
-
- /**
- * Append text to a paragraph by paragraph id.
- * @param {string} key The paragraph id.
- * @param {string} text The text to append before the paragraph break.
- * @returns {boolean} `true` if the text was appended.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * doc.getBody().appendParagraphText(paragraph.getKey(), ' suffix');
- * ```
- */
- appendParagraphText(key: string, text: string): boolean {
- const resolved = this.resolveParagraph(key);
- return this.insertText(resolved.endOffset, text);
- }
-
- /**
- * Remove a paragraph by paragraph id.
- * @param {string} key The paragraph id.
- * @returns {boolean} `true` if the paragraph was removed.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * doc.getBody().removeParagraph(paragraph.getKey());
- * ```
- */
- removeParagraph(key: string): boolean {
- const resolved = this.resolveParagraph(key);
- return this.deleteRange({ startOffset: resolved.startOffset, endOffset: resolved.endOffset + 1 });
- }
-
- /**
- * Get a paragraph text range by paragraph id.
- * @param {string} key The paragraph id.
- * @returns {IFDocTextRange} The paragraph range excluding the trailing paragraph break.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * const range = doc.getBody().getParagraphRange(paragraph.getKey());
- * console.log(range.startOffset, range.endOffset);
- * ```
- */
- getParagraphRange(key: string): IFDocTextRange {
- const resolved = this.resolveParagraph(key);
- return { startOffset: resolved.startOffset, endOffset: resolved.endOffset, segmentId: this._segmentId };
- }
-
- /**
- * Check whether a paragraph has list metadata.
- * @param {string} key The paragraph id.
- * @returns {boolean} `true` if the paragraph is a list item.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * console.log(doc.getBody().isListParagraph(paragraph.getKey()));
- * ```
- */
- isListParagraph(key: string): boolean {
- return Boolean(this.resolveParagraph(key).paragraph.bullet);
- }
-
- /**
- * Check whether a paragraph is a task/checklist item.
- * @param {string} key The paragraph id.
- * @returns {boolean} `true` if the paragraph is an unchecked or checked task item.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * console.log(doc.getBody().isTaskParagraph(paragraph.getKey()));
- * ```
- */
- isTaskParagraph(key: string): boolean {
- const listType = this.resolveParagraph(key).paragraph.bullet?.listType;
- return listType === PresetListType.CHECK_LIST || listType === PresetListType.CHECK_LIST_CHECKED;
- }
-
- /**
- * Set the checked state of a task/checklist paragraph.
- * @param {string} key The paragraph id.
- * @param {boolean} checked Whether the task should be checked.
- * @returns {boolean} `true` if the task state was updated, or `false` if the paragraph is not a task item.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * doc.getBody().setTaskChecked(paragraph.getKey(), true);
- * ```
- */
- setTaskChecked(key: string, checked: boolean): boolean {
- const resolved = this.resolveParagraph(key);
- const bullet = resolved.paragraph.bullet;
- if (!bullet || !this.isTaskParagraph(key)) {
- return false;
- }
-
- const updateBody: IDocumentBody = {
- dataStream: '',
- paragraphs: [{
- ...resolved.paragraph,
- startIndex: 0,
- bullet: {
- ...bullet,
- listType: checked ? PresetListType.CHECK_LIST_CHECKED : PresetListType.CHECK_LIST,
- },
- }],
- };
- this._preserveExplicitParagraphIds(updateBody);
-
- return this._retainBodyRange(
- { startOffset: resolved.endOffset, endOffset: resolved.endOffset + 1 },
- updateBody,
- UpdateDocsAttributeType.REPLACE
- );
- }
-
- /**
- * Resolve a paragraph id to its current paragraph metadata.
- * @param {string} key The paragraph id.
- * @returns {IFDocResolvedParagraph} The current paragraph metadata.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * const resolved = doc.getBody().resolveParagraph(paragraph.getKey());
- * console.log(resolved.paragraphIndex);
- * ```
- */
- resolveParagraph(key: string): IFDocResolvedParagraph {
- const body = this._getBody();
- const paragraphs = body.paragraphs ?? [];
- const matches = paragraphs
- .map((paragraph, paragraphIndex) => ({ paragraph, paragraphIndex }))
- .filter(({ paragraph }) => paragraph.paragraphId === key);
-
- if (matches.length !== 1) {
- throw new DocElementStaleError(matches.length > 1
- ? `Doc paragraph id "${key}" is duplicated.`
- : `Doc paragraph id "${key}" is stale.`);
- }
-
- const { paragraph, paragraphIndex } = matches[0];
- const startOffset = paragraphIndex > 0 ? body.paragraphs![paragraphIndex - 1].startIndex + 1 : 0;
-
- return {
- paragraph,
- paragraphIndex,
- startOffset,
- endOffset: paragraph.startIndex,
- };
- }
-
- /**
- * Resolve an element key to its current child metadata.
- * @param {FDocElementType} type The element type.
- * @param {string} key The persisted element key.
- * @returns {object} The current child metadata used by the facade.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const element = doc.getBody().getChild(0);
- * const resolved = doc.getBody().resolveElement(element.getType(), element.getKey());
- * console.log(resolved.position);
- * ```
- */
- resolveElement(type: FDocElementType, key: string): IFDocChildInfo {
- if (type === 'paragraph') {
- const paragraph = this.resolveParagraph(key);
- return { type, key, position: paragraph.startOffset, priority: 3 };
- }
-
- const child = this._getChildren().find((item) => item.type === type && item.key === key);
- if (!child) {
- throw new Error('Doc element is stale');
- }
-
- return child;
- }
-
- /**
- * Get a callout, quote, or code block range by block id.
- * @param {string} key The persisted block range id.
- * @returns {IDocumentBlockRange} The matching block range snapshot.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const block = doc.getBody().getChild(0).asBlockRange();
- * console.log(doc.getBody().getBlockRange(block.getKey()).blockType);
- * ```
- */
- getBlockRange(key: string): IDocumentBlockRange {
- const blockRange = this._getBody().blockRanges?.find((item) => item.blockId === key);
- if (!blockRange) {
- throw new Error('Doc element is stale');
- }
-
- return blockRange;
- }
-
- /**
- * Get the text inside a callout, quote, or code block range.
- * @param {string} key The persisted block range id.
- * @returns {string} The block range text.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const block = doc.getBody().getChild(0).asBlockRange();
- * console.log(doc.getBody().getBlockRangeText(block.getKey()));
- * ```
- */
- getBlockRangeText(key: string): string {
- const blockRange = this.getBlockRange(key);
- return this._getBody().dataStream.slice(blockRange.startIndex, blockRange.endIndex);
- }
-
- /**
- * Replace the text inside a callout, quote, or code block range.
- * @param {string} key The persisted block range id.
- * @param {string} text The replacement text.
- * @returns {boolean} `true` if the text was replaced.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const block = doc.getBody().getChild(0).asBlockRange();
- * doc.getBody().setBlockRangeText(block.getKey(), 'Updated block');
- * ```
- */
- setBlockRangeText(key: string, text: string): boolean {
- const blockRange = this.getBlockRange(key);
- const body = buildPlainTextInsertBody(`${text}\r`);
- body.blockRanges = [{
- ...blockRange,
- startIndex: 0,
- endIndex: text.length,
- }];
-
- return this.replaceRange({ startOffset: blockRange.startIndex, endOffset: blockRange.endIndex + 1 }, { body });
- }
-
- /**
- * Remove a callout, quote, or code block range and its content.
- * @param {string} key The persisted block range id.
- * @returns {boolean} `true` if the block range content was removed.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const block = doc.getBody().getChild(0).asBlockRange();
- * doc.getBody().removeBlockRange(block.getKey());
- * ```
- */
- removeBlockRange(key: string): boolean {
- const blockRange = this.getBlockRange(key);
- return this.deleteRange({ startOffset: blockRange.startIndex, endOffset: blockRange.endIndex + 1 });
- }
-
- /**
- * Get a table marker by table id.
- * @param {string} key The persisted table id.
- * @returns {ICustomTable} The matching table marker.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const table = doc.getBody().getChild(0).asTable();
- * console.log(doc.getBody().getTable(table.getTableId()));
- * ```
- */
- getTable(key: string): ICustomTable {
- const table = this._getBody().tables?.find((item) => item.tableId === key);
- if (!table) {
- throw new Error('Doc element is stale');
- }
-
- return table;
- }
-
- /**
- * Remove a table marker and its content range.
- * @param {string} key The persisted table id.
- * @returns {boolean} `true` if the table range was removed.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const table = doc.getBody().getChild(0).asTable();
- * doc.getBody().removeTable(table.getTableId());
- * ```
- */
- removeTable(key: string): boolean {
- const table = this.getTable(key);
- return this.deleteRange({ startOffset: table.startIndex, endOffset: table.endIndex + 1 });
- }
-
- /**
- * Get a custom block marker by block id.
- * @param {string} key The persisted custom block id.
- * @returns {ICustomBlock} The matching custom block marker.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
- * console.log(doc.getBody().getCustomBlock(customBlock.getBlockId()));
- * ```
- */
- getCustomBlock(key: string): ICustomBlock {
- const block = this._getBody().customBlocks?.find((item) => item.blockId === key);
- if (!block) {
- throw new Error('Doc element is stale');
- }
-
- return block;
- }
-
- /**
- * Remove a custom block marker and its placeholder character.
- * @param {string} key The persisted custom block id.
- * @returns {boolean} `true` if the custom block placeholder was removed.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
- * doc.getBody().removeCustomBlock(customBlock.getBlockId());
- * ```
- */
- removeCustomBlock(key: string): boolean {
- const block = this.getCustomBlock(key);
- return this.deleteRange({ startOffset: block.startIndex, endOffset: block.startIndex + 1 });
- }
-
- /**
- * Create a sibling element wrapper relative to the current element key.
- * @param {FDocElementType} type The current element type.
- * @param {string} key The current element key.
- * @param {-1 | 1} direction `-1` for previous sibling, `1` for next sibling.
- * @returns {FDocElement | null} The sibling wrapper, or `null` if none exists.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const element = doc.getBody().getChild(0);
- * const next = doc.getBody().createSibling(element.getType(), element.getKey(), 1);
- * console.log(next?.getType());
- * ```
- */
- createSibling(type: FDocElementType, key: string, direction: -1 | 1): FDocElement | null {
- const index = this.getChildIndex(this._createElement(type, key));
- const child = this._getChildren()[index + direction];
- return child ? this._createElement(child.type, child.key) : null;
- }
-
- private _getChildren(): IFDocChildInfo[] {
- const body = this._getBody();
- const children: IFDocChildInfo[] = [];
-
- for (let index = 0; index < (body.paragraphs?.length ?? 0); index++) {
- const paragraph = body.paragraphs![index];
- children.push({
- type: 'paragraph',
- key: this._getParagraphId(paragraph, index),
- position: index > 0 ? body.paragraphs![index - 1].startIndex + 1 : 0,
- priority: 3,
- });
- }
-
- body.blockRanges?.forEach((blockRange) => children.push({
- type: 'blockRange',
- key: blockRange.blockId,
- position: blockRange.startIndex,
- priority: 0,
- }));
-
- body.tables?.forEach((table) => children.push({
- type: 'table',
- key: table.tableId,
- position: table.startIndex,
- priority: 1,
- }));
-
- body.customBlocks?.forEach((customBlock) => children.push({
- type: 'customBlock',
- key: customBlock.blockId,
- position: customBlock.startIndex,
- priority: 2,
- }));
-
- return children.sort((a, b) => a.position - b.position || a.priority - b.priority);
- }
-
- private _createElement(type: FDocElementType, key: string): FDocElement {
- return new FDocElement(this, type, key);
- }
-
- private _getBody(): IDocumentBody {
- const body = this._documentDataModel.getSelfOrHeaderFooterModel(this._segmentId).getBody();
- if (!body) {
- throw new Error('The document body is empty');
- }
-
- return body;
- }
-
- private _getParagraphInsertOffset(index: number): number {
- const body = this._getBody();
- if (index <= 0) {
- return 0;
- }
-
- const paragraphs = body.paragraphs ?? [];
- if (paragraphs.length === 0) {
- return Math.max(0, body.dataStream.length - 1);
- }
-
- if (index >= paragraphs.length) {
- return paragraphs[paragraphs.length - 1].startIndex + 1;
- }
-
- return paragraphs[index - 1].startIndex + 1;
- }
-
- private _normalizeInsertedParagraphIndex(index: number): number {
- const paragraphs = this._getBody().paragraphs ?? [];
- return Math.max(0, Math.min(index, paragraphs.length - 1));
- }
-
- private _getParagraphId(paragraph: IParagraph | undefined, paragraphIndex: number): string {
- if (!paragraph) {
- throw new RangeError(`Paragraph index ${paragraphIndex} is out of range.`);
- }
-
- if (!paragraph.paragraphId) {
- throw new DocElementStaleError(`Paragraph at index ${paragraphIndex} is missing paragraphId.`);
- }
-
- return paragraph.paragraphId;
- }
-
- private _preserveExplicitParagraphIds(body: IDocumentBody): void {
- (body as IDocumentBody & Record<string, unknown>)[RESTORE_INSERTED_PARAGRAPH_IDS] = true;
- }
-
- private _findParagraphByRange(range: IFDocTextRange): IFDocResolvedParagraph {
- const paragraphs = this._getBody().paragraphs ?? [];
- const paragraphIndex = paragraphs.findIndex((paragraph, index) => {
- const startOffset = index > 0 ? paragraphs[index - 1].startIndex + 1 : 0;
- return startOffset <= range.startOffset && range.endOffset <= paragraph.startIndex;
- });
-
- if (paragraphIndex < 0) {
- throw new RangeError('Range does not resolve to a paragraph.');
- }
-
- const paragraph = paragraphs[paragraphIndex];
- return {
- paragraph,
- paragraphIndex,
- startOffset: paragraphIndex > 0 ? paragraphs[paragraphIndex - 1].startIndex + 1 : 0,
- endOffset: paragraph.startIndex,
- };
- }
-
- private _replaceBodyRange(range: IFDocTextRange, insertBody: IDocumentBody): boolean {
- const startOffset = range.startOffset;
- const endOffset = range.endOffset;
- const textX = new TextX();
-
- if (startOffset > 0) {
- textX.push({ t: TextXActionType.RETAIN, len: startOffset });
- }
-
- if (endOffset > startOffset) {
- textX.push({ t: TextXActionType.DELETE, len: endOffset - startOffset });
- }
-
- if (insertBody.dataStream.length > 0) {
- textX.push({
- t: TextXActionType.INSERT,
- body: insertBody,
- len: insertBody.dataStream.length,
- });
- }
-
- return this._executeTextX(textX);
- }
-
- private _retainBodyRange(range: IFDocTextRange, body: IDocumentBody, coverType: UpdateDocsAttributeType): boolean {
- if (body.textRuns?.length && this._getBody().textRuns == null) {
- this._ensureTextRuns();
- }
-
- const textX = new TextX();
- if (range.startOffset > 0) {
- textX.push({ t: TextXActionType.RETAIN, len: range.startOffset });
- }
-
- textX.push({
- t: TextXActionType.RETAIN,
- body,
- coverType,
- len: range.endOffset - range.startOffset,
- });
-
- return this._executeTextX(textX);
- }
-
- private _ensureTextRuns(): void {
- const currentBody = this._getBody();
- if (currentBody.textRuns != null) {
- return;
- }
-
- const jsonX = JSONX.getInstance();
- const actions = jsonX.replaceOp(
- [...getRichTextEditPath(this._documentDataModel, this._segmentId), 'textRuns'],
- undefined,
- []
- );
-
- this._commandService.syncExecuteCommand<IRichTextEditingMutationParams>(
- RichTextEditingMutation.id,
- {
- unitId: this._documentDataModel.getUnitId(),
- segmentId: this._segmentId,
- actions,
- textRanges: [],
- trigger: FACADE_TRIGGER,
- isEditing: false,
- }
- );
- }
-
- private _executeTextX(textX: TextX): boolean {
- const jsonX = JSONX.getInstance();
- const actions = jsonX.editOp(textX.serialize(), getRichTextEditPath(this._documentDataModel, this._segmentId));
- const result = this._commandService.syncExecuteCommand<IRichTextEditingMutationParams>(
- RichTextEditingMutation.id,
- {
- unitId: this._documentDataModel.getUnitId(),
- segmentId: this._segmentId,
- actions,
- textRanges: [],
- trigger: FACADE_TRIGGER,
- isEditing: false,
- }
- );
-
- return Boolean(result);
- }
-}
diff --git a/packages/docs/src/facade/f-doc-custom-block.ts b/packages/docs/src/facade/f-doc-custom-block.ts
deleted file mode 100644
index 5cec5bc8e8..0000000000
--- a/packages/docs/src/facade/f-doc-custom-block.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { FDocBody } from './f-doc-body';
-
-/**
- * A facade wrapper for a document custom block, such as an embedded drawing or widget.
- *
- * Custom block identity is backed by the persisted `ICustomBlock.blockId`, so the
- * wrapper can be re-resolved after text is inserted before the custom block.
- *
- * @hideconstructor
- */
-export class FDocCustomBlock {
- constructor(
- protected readonly _body: FDocBody,
- protected readonly _key: string
- ) {}
-
- /**
- * Get the document element type.
- * @returns {'customBlock'} The literal custom block element type.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
- * console.log(customBlock.getType());
- * ```
- */
- getType(): 'customBlock' {
- return 'customBlock';
- }
-
- /**
- * Get the custom block key.
- * @returns {string} The persisted `blockId` for this custom block.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
- * console.log(customBlock.getKey());
- * ```
- */
- getKey(): string {
- return this._key;
- }
-
- /**
- * Get the parent body facade that owns this custom block.
- * @returns {FDocBody} The document body facade.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
- * console.log(customBlock.getParent().getChildIndex(customBlock));
- * ```
- */
- getParent(): FDocBody {
- return this._body;
- }
-
- /**
- * Remove this custom block from the parent body.
- * @returns {boolean} `true` if the custom block placeholder was removed.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
- * customBlock.removeFromParent();
- * ```
- */
- removeFromParent(): boolean {
- return this._body.removeCustomBlock(this._key);
- }
-
- /**
- * Get the persisted custom block id.
- * @returns {string} The `ICustomBlock.blockId` value.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
- * console.log(customBlock.getBlockId());
- * ```
- */
- getBlockId(): string {
- return this._body.getCustomBlock(this._key).blockId;
- }
-}
diff --git a/packages/docs/src/facade/f-doc-element.ts b/packages/docs/src/facade/f-doc-element.ts
deleted file mode 100644
index c1643ae3fa..0000000000
--- a/packages/docs/src/facade/f-doc-element.ts
+++ /dev/null
@@ -1,231 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { FDocBody } from './f-doc-body';
-import type { FDocElementType } from './doc-element-registry';
-import { FDocBlockRange } from './f-doc-block-range';
-import { FDocCustomBlock } from './f-doc-custom-block';
-import { FDocParagraph } from './f-doc-paragraph';
-import { FDocTable } from './f-doc-table';
-
-/**
- * A generic top-level document body element.
- *
- * Use this wrapper when you need to inspect an element type first, navigate to
- * neighboring elements, or cast the element to a more specific facade wrapper.
- *
- * Paragraph keys are persisted `paragraphId` values. Tables, block ranges, and
- * custom blocks use their persisted ids.
- *
- * @hideconstructor
- */
-export class FDocElement {
- constructor(
- protected readonly _body: FDocBody,
- protected readonly _type: FDocElementType,
- protected readonly _key: string
- ) {}
-
- /**
- * Get the document element type.
- * @returns {FDocElementType} The element type, such as `paragraph`, `table`, `blockRange`, or `customBlock`.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const element = doc.getBody().getChild(0);
- * console.log(element.getType());
- * ```
- */
- getType(): FDocElementType {
- return this._type;
- }
-
- /**
- * Get the facade key used to resolve this element.
- * @returns {string} The paragraph `paragraphId` or persisted table/block/custom block id.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const body = doc.getBody();
- * const element = body.getChild(0);
- * console.log(element.getKey());
- * ```
- */
- getKey(): string {
- return this._key;
- }
-
- /**
- * Get the parent body facade that owns this element.
- * @returns {FDocBody} The document body facade.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const element = doc.getBody().getChild(0);
- * console.log(element.getParent().getNumChildren());
- * ```
- */
- getParent(): FDocBody {
- return this._body;
- }
-
- /**
- * Get the next sibling element in the current body order.
- * @returns {FDocElement | null} The next sibling wrapper, or `null` when this is the last child.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const first = doc.getBody().getChild(0);
- * const next = first.getNextSibling();
- * console.log(next?.getType());
- * ```
- */
- getNextSibling(): FDocElement | null {
- return this._body.createSibling(this._type, this._key, 1);
- }
-
- /**
- * Get the previous sibling element in the current body order.
- * @returns {FDocElement | null} The previous sibling wrapper, or `null` when this is the first child.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const second = doc.getBody().getChild(1);
- * const previous = second.getPreviousSibling();
- * console.log(previous?.getType());
- * ```
- */
- getPreviousSibling(): FDocElement | null {
- return this._body.createSibling(this._type, this._key, -1);
- }
-
- /**
- * Remove this element from its parent body.
- * @returns {boolean} `true` if the element content was removed.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const body = doc.getBody();
- * const element = body.getChild(0);
- * element.removeFromParent();
- * ```
- */
- removeFromParent(): boolean {
- if (this._type === 'paragraph') {
- return this._body.removeParagraph(this._key);
- }
-
- if (this._type === 'blockRange') {
- return this._body.removeBlockRange(this._key);
- }
-
- if (this._type === 'table') {
- return this._body.removeTable(this._key);
- }
-
- return this._body.removeCustomBlock(this._key);
- }
-
- /**
- * Cast this generic element to a paragraph facade.
- * @returns {FDocParagraph} The paragraph facade wrapper.
- * @throws {TypeError} If the element is not a paragraph.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * console.log(paragraph.getText());
- * ```
- */
- asParagraph(): FDocParagraph {
- this._assertType('paragraph');
- return new FDocParagraph(this._body, this._key);
- }
-
- /**
- * Cast this generic element to a table facade.
- * @returns {FDocTable} The table facade wrapper.
- * @throws {TypeError} If the element is not a table.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const table = doc.getBody().getChild(0).asTable();
- * console.log(table.getTableId());
- * ```
- */
- asTable(): FDocTable {
- this._assertType('table');
- return new FDocTable(this._body, this._key);
- }
-
- /**
- * Cast this generic element to a callout, quote, or code block range facade.
- * @returns {FDocBlockRange} The block range facade wrapper.
- * @throws {TypeError} If the element is not a block range.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
- * console.log(blockRange.getBlockType());
- * ```
- */
- asBlockRange(): FDocBlockRange {
- this._assertType('blockRange');
- return new FDocBlockRange(this._body, this._key);
- }
-
- /**
- * Cast this generic element to a custom block facade.
- * @returns {FDocCustomBlock} The custom block facade wrapper.
- * @throws {TypeError} If the element is not a custom block.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
- * console.log(customBlock.getBlockId());
- * ```
- */
- asCustomBlock(): FDocCustomBlock {
- this._assertType('customBlock');
- return new FDocCustomBlock(this._body, this._key);
- }
-
- private _assertType(type: FDocElementType): void {
- if (this._type !== type) {
- throw new TypeError(`Cannot cast ${this._type} to ${type}.`);
- }
- }
-}
diff --git a/packages/docs/src/facade/f-doc-paragraph.ts b/packages/docs/src/facade/f-doc-paragraph.ts
deleted file mode 100644
index a49be7f67d..0000000000
--- a/packages/docs/src/facade/f-doc-paragraph.ts
+++ /dev/null
@@ -1,233 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { FDocBody, IFDocTextRange } from './f-doc-body';
-
-/**
- * A paragraph facade wrapper.
- *
- * Paragraph identity is backed by the persisted `paragraphId`. The id is
- * re-resolved before each method call, so insertions before this paragraph do
- * not break the wrapper.
- *
- * @hideconstructor
- */
-export class FDocParagraph {
- constructor(
- protected readonly _body: FDocBody,
- protected readonly _key: string
- ) {}
-
- /**
- * Get the document element type.
- * @returns {'paragraph'} The literal paragraph element type.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * console.log(paragraph.getType());
- * ```
- */
- getType(): 'paragraph' {
- return 'paragraph';
- }
-
- /**
- * Get the persisted paragraph id.
- * @returns {string} The paragraph id.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * console.log(paragraph.getKey());
- * ```
- */
- getKey(): string {
- return this._key;
- }
-
- /**
- * Get the persisted paragraph id.
- * @returns {string} The paragraph id.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * console.log(paragraph.getId());
- * ```
- */
- getId(): string {
- return this._key;
- }
-
- /**
- * Get the parent body facade that owns this paragraph.
- * @returns {FDocBody} The document body facade.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * console.log(paragraph.getParent().getChildIndex(paragraph));
- * ```
- */
- getParent(): FDocBody {
- return this._body;
- }
-
- /**
- * Remove this paragraph from its parent body.
- * @returns {boolean} `true` if the paragraph was removed.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * paragraph.removeFromParent();
- * ```
- */
- removeFromParent(): boolean {
- return this._body.removeParagraph(this._key);
- }
-
- /**
- * Get this paragraph's plain text.
- * @returns {string} The paragraph text without the trailing paragraph break.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * console.log(paragraph.getText());
- * ```
- */
- getText(): string {
- return this._body.getParagraphText(this._key);
- }
-
- /**
- * Replace this paragraph's plain text.
- * @param {string} text The replacement text. Do not include the paragraph break.
- * @returns {boolean} `true` if the paragraph text was replaced.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * paragraph.setText('Updated title');
- * ```
- */
- setText(text: string): boolean {
- return this._body.setParagraphText(this._key, text);
- }
-
- /**
- * Append plain text before this paragraph's trailing paragraph break.
- * @param {string} text The plain text to append.
- * @returns {boolean} `true` if the text was appended.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * paragraph.appendText(' suffix');
- * ```
- */
- appendText(text: string): boolean {
- return this._body.appendParagraphText(this._key, text);
- }
-
- /**
- * Get the current text range occupied by this paragraph.
- * @returns {IFDocTextRange} The paragraph text range, excluding the trailing paragraph break.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * const range = paragraph.getRange();
- * doc.getBody().setTextStyle(range, { bl: 1 });
- * ```
- */
- getRange(): IFDocTextRange {
- return this._body.getParagraphRange(this._key);
- }
-
- /**
- * Check whether this paragraph is a bullet, ordered, or checklist item.
- * @returns {boolean} `true` if the paragraph has list metadata.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * console.log(paragraph.isListItem());
- * ```
- */
- isListItem(): boolean {
- return this._body.isListParagraph(this._key);
- }
-
- /**
- * Check whether this paragraph is a task/checklist item.
- * @returns {boolean} `true` if this paragraph is an unchecked or checked task item.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * if (paragraph.isTask()) {
- * paragraph.setTaskChecked(true);
- * }
- * ```
- */
- isTask(): boolean {
- return this._body.isTaskParagraph(this._key);
- }
-
- /**
- * Set the checked state of this task/checklist paragraph.
- * @param {boolean} checked Whether the task item should be checked.
- * @returns {boolean} `true` if the task state was updated, or `false` if this paragraph is not a task item.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const paragraph = doc.getBody().getChild(0).asParagraph();
- * if (paragraph.isTask()) {
- * paragraph.setTaskChecked(false);
- * }
- * ```
- */
- setTaskChecked(checked: boolean): boolean {
- return this._body.setTaskChecked(this._key, checked);
- }
-}
diff --git a/packages/docs/src/facade/f-doc-table.ts b/packages/docs/src/facade/f-doc-table.ts
deleted file mode 100644
index 2a5db79f3b..0000000000
--- a/packages/docs/src/facade/f-doc-table.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { FDocBody } from './f-doc-body';
-
-/**
- * A facade wrapper for a document table marker.
- *
- * Table identity is backed by the persisted `ICustomTable.tableId`, so the
- * wrapper can be re-resolved after text is inserted before the table.
- *
- * @hideconstructor
- */
-export class FDocTable {
- constructor(
- protected readonly _body: FDocBody,
- protected readonly _key: string
- ) {}
-
- /**
- * Get the document element type.
- * @returns {'table'} The literal table element type.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const table = doc.getBody().getChild(0).asTable();
- * console.log(table.getType());
- * ```
- */
- getType(): 'table' {
- return 'table';
- }
-
- /**
- * Get the table key.
- * @returns {string} The persisted `tableId` for this table.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const table = doc.getBody().getChild(0).asTable();
- * console.log(table.getKey());
- * ```
- */
- getKey(): string {
- return this._key;
- }
-
- /**
- * Get the parent body facade that owns this table.
- * @returns {FDocBody} The document body facade.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const table = doc.getBody().getChild(0).asTable();
- * console.log(table.getParent().getChildIndex(table));
- * ```
- */
- getParent(): FDocBody {
- return this._body;
- }
-
- /**
- * Remove this table from the parent body.
- * @returns {boolean} `true` if the table range was removed.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const table = doc.getBody().getChild(0).asTable();
- * table.removeFromParent();
- * ```
- */
- removeFromParent(): boolean {
- return this._body.removeTable(this._key);
- }
-
- /**
- * Get the persisted table id.
- * @returns {string} The `ICustomTable.tableId` value.
- * @example
- * ```ts
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
- *
- * const table = doc.getBody().getChild(0).asTable();
- * console.log(table.getTableId());
- * ```
- */
- getTableId(): string {
- return this._body.getTable(this._key).tableId;
- }
-}
diff --git a/packages/docs/src/facade/f-document-block-range.ts b/packages/docs/src/facade/f-document-block-range.ts
new file mode 100644
index 0000000000..fbb0939954
--- /dev/null
+++ b/packages/docs/src/facade/f-document-block-range.ts
@@ -0,0 +1,182 @@
+/**
+ * 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 { DocumentBlockRangeType, IDocumentBlockRange, Injector } from '@univerjs/core';
+import type { FDocumentBody } from './f-document-body';
+import type { IFDocumentElementInfo } from './f-document-element';
+import { DocumentBlockType } from '@univerjs/core';
+import { FDocumentElement } from './f-document-element';
+import { buildPlainTextInsertBody } from './utils';
+
+interface IFDocumentBlockRangeMixin {
+ asBlockRange(): FDocumentBlockRange;
+}
+
+/**
+ * A facade wrapper for document block ranges, such as callout, quote, and code blocks.
+ *
+ * Block range identity is backed by the persisted `IDocumentBlockRange.blockId`,
+ * so wrappers can be re-resolved after text is inserted before the block range.
+ *
+ * @hideconstructor
+ */
+export class FDocumentBlockRange extends FDocumentElement {
+ constructor(
+ protected readonly body: FDocumentBody,
+ protected readonly info: IFDocumentElementInfo,
+ protected readonly injector: Injector
+ ) {
+ super(body, info, injector);
+
+ if (this.getType() !== DocumentBlockType.BLOCK_RANGE) {
+ throw new Error(`Element type is not a block range: ${this.getType()}`);
+ }
+ }
+
+ /**
+ * Get the top-level block range data model.
+ * @returns {IDocumentBlockRange} The block range data model.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isBlockRange()) {
+ * const blockRange = element.asBlockRange();
+ * console.log(blockRange.getBlockRange());
+ * }
+ * ```
+ */
+ getBlockRange(): IDocumentBlockRange {
+ const { blockRanges = [] } = this._body.getBody();
+ const blockRange = blockRanges.find((blockRange) => blockRange.blockId === this.getKey());
+ if (!blockRange) {
+ throw new Error(`Block range not found: ${this.getKey()}`);
+ }
+ return blockRange;
+ }
+
+ /**
+ * Get the block range type.
+ * @returns {DocumentBlockRangeType} The block type, such as callout, quote, or code.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isBlockRange()) {
+ * const blockRange = element.asBlockRange();
+ * console.log(blockRange.getBlockType());
+ * }
+ * ```
+ */
+ getBlockType(): DocumentBlockRangeType {
+ const blockRange = this.getBlockRange();
+ return blockRange.blockType;
+ }
+
+ /**
+ * Get the plain text inside this block range.
+ * @returns {string} The block range text.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isBlockRange()) {
+ * const blockRange = element.asBlockRange();
+ * console.log(blockRange.getText());
+ * }
+ * ```
+ */
+ getText(): string {
+ const { dataStream } = this._body.getBody();
+ const { startIndex, endIndex } = this.getBlockRange();
+ return dataStream.slice(startIndex, endIndex);
+ }
+
+ /**
+ * Replace the plain text inside this block range.
+ * @param {string} text The replacement text.
+ * @returns {boolean} `true` if the block range text was replaced.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isBlockRange()) {
+ * const blockRange = element.asBlockRange();
+ * blockRange.setText('Updated block text');
+ * console.log(blockRange.getText());
+ * }
+ * ```
+ */
+ setText(text: string): boolean {
+ const blockRange = this.getBlockRange();
+ const { startIndex, endIndex } = blockRange;
+ const updateBody = buildPlainTextInsertBody(`${text}\r`);
+ updateBody.blockRanges = [{
+ ...blockRange,
+ startIndex: 0,
+ endIndex: text.length,
+ }];
+
+ return this._body.replaceRange({ startOffset: startIndex, endOffset: endIndex + 1 }, updateBody);
+ }
+
+ /**
+ * Remove this block range wrapper from the body.
+ *
+ * This currently removes the block range and its content, matching
+ * `remove()`.
+ *
+ * @returns {boolean} `true` if the block range content was removed.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isBlockRange()) {
+ * const blockRange = element.asBlockRange();
+ * const removed = blockRange.unwrap();
+ * console.log(removed ? 'Block range removed' : 'Failed to remove block range');
+ * }
+ * ```
+ */
+ unwrap(): boolean {
+ return this.remove();
+ }
+}
+
+export class FDocumentBlockRangeMixin extends FDocumentElement {
+ override asBlockRange(): FDocumentBlockRange {
+ if (this.getType() !== DocumentBlockType.BLOCK_RANGE) {
+ throw new Error(`Element type is not a block range: ${this.getType()}`);
+ }
+ return this._injector.createInstance(FDocumentBlockRange, this._body, this.getResolvedInfo(), this._injector);
+ }
+}
+
+FDocumentElement.extend(FDocumentBlockRangeMixin);
+declare module '@univerjs/docs/facade' {
+ // eslint-disable-next-line ts/naming-convention
+ interface FDocumentElement extends IFDocumentBlockRangeMixin { }
+}
diff --git a/packages/docs/src/facade/f-document-body.ts b/packages/docs/src/facade/f-document-body.ts
new file mode 100644
index 0000000000..a25440026f
--- /dev/null
+++ b/packages/docs/src/facade/f-document-body.ts
@@ -0,0 +1,587 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel, IDocumentBody, Injector, IParagraph, ITextStyle } from '@univerjs/core';
+import type { IRichTextEditingMutationParams } from '@univerjs/docs';
+import type { FDocumentBlockRange } from './f-document-block-range';
+import type { FDocumentCustomBlock } from './f-document-custom-block';
+import type { IFDocumentElementInfo } from './f-document-element';
+import type { FDocumentTable } from './f-document-table';
+import { DocumentBlockType, getRichTextEditPath, ICommandService, JSONX, TextX, TextXActionType, UpdateDocsAttributeType } from '@univerjs/core';
+import { RichTextEditingMutation } from '@univerjs/docs';
+import { FDocumentElement } from './f-document-element';
+import { FDocumentParagraph } from './f-document-paragraph';
+import { buildPlainTextInsertBody } from './utils';
+
+/**
+ * A text range in a document segment. Offsets are zero-based positions in the segment data stream.
+ */
+export interface IFDocumentTextRange {
+ /** The inclusive start offset of the range. */
+ startOffset: number;
+ /** The exclusive end offset of the range. */
+ endOffset: number;
+ /** The header/footer segment id. Omit or use an empty string for the main body. */
+ segmentId?: string;
+}
+
+/**
+ * A Facade API object bounded to a document body or header/footer segment.
+ * It provides Google Docs-like element access and range editing methods.
+ *
+ * Paragraph elements use their persisted `paragraphId`. Tables, block ranges, and
+ * custom blocks use their persisted ids.
+ *
+ * @hideconstructor
+ */
+export class FDocumentBody {
+ constructor(
+ private readonly _documentDataModel: DocumentDataModel,
+ private readonly _injector: Injector,
+ private readonly _segmentId = ''
+ ) {}
+
+ /**
+ * Get the segment id of this document body facade.
+ * The main body has an empty string segment id.
+ * The header and footer FDocumentBody instances have their respective segment ids.
+ * @returns {string} The segment id of this document body facade.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * console.log(fDocumentBody.getSegmentId());
+ * ```
+ */
+ getSegmentId(): string {
+ return this._segmentId;
+ }
+
+ /**
+ * Get the underlying document body snapshot.
+ * @returns {IDocumentBody} The document body snapshot.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * console.log(fDocumentBody.getBody());
+ * ```
+ */
+ getBody(): IDocumentBody {
+ const body = this._documentDataModel.getSelfOrHeaderFooterModel(this._segmentId).getBody();
+ if (!body) {
+ throw new Error('The document body is empty');
+ }
+
+ return body;
+ }
+
+ /**
+ * Get a list of top-level child elements in the body.
+ * @returns {FDocumentElement[]} The list of top-level document elements.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const elements = fDocumentBody.getElements();
+ * console.log(elements);
+ * ```
+ */
+ getElements(): FDocumentElement[] {
+ const children = this._getChildren();
+ return children.map((child) => {
+ return this._injector.createInstance(FDocumentElement, this, child, this._injector);
+ });
+ }
+
+ /**
+ * Get a top-level child element by child index.
+ * @param {number} index The zero-based child index.
+ * @returns {FDocumentElement} The top-level child element wrapper.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ * console.log(element);
+ * ```
+ */
+ getElement(index: number): FDocumentElement | null {
+ return this.getElements()[index] ?? null;
+ }
+
+ /**
+ * Get the current child index of an element handle.
+ * The index is resolved from the element key, so a paragraph handle keeps pointing
+ * to the same paragraph after facade edits insert content before it.
+ * @param {FDocumentElement} element The element handle to locate.
+ * @returns {number} The current zero-based child index.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ * console.log(fDocumentBody.getElementIndex(element));
+ * ```
+ */
+ getElementIndex(element: FDocumentElement): number {
+ const { type, key } = element.getResolvedInfo();
+ const index = this._getChildren().findIndex((child) => child.type === type && child.key === key);
+
+ if (index < 0) {
+ throw new Error('Doc element is stale');
+ }
+
+ return index;
+ }
+
+ /**
+ * Insert plain text at a document body offset.
+ * @param {number} index The zero-based insertion offset.
+ * @param {string} text The plain text to insert.
+ * @returns {boolean} `true` if the edit was applied.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * fDocumentBody.insertText(0, 'Hello ');
+ * ```
+ */
+ insertText(index: number, text: string): boolean {
+ return this._replaceBodyRange({ startOffset: index, endOffset: index }, buildPlainTextInsertBody(text));
+ }
+
+ /**
+ * Apply text style to a body range.
+ * @param {IFDocumentTextRange} range The range to style.
+ * @param {ITextStyle} style The Univer text style patch.
+ * @returns {boolean} `true` if the style was applied.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * fDocumentBody.setTextStyle({ startOffset: 0, endOffset: 5 }, { bl: 1 });
+ * ```
+ */
+ setTextStyle(range: IFDocumentTextRange, style: ITextStyle): boolean {
+ const len = range.endOffset - range.startOffset;
+ const updateBody: IDocumentBody = {
+ dataStream: '',
+ textRuns: [{
+ st: 0,
+ ed: len,
+ ts: style,
+ }],
+ };
+
+ return this._retainBodyRange(range, updateBody, UpdateDocsAttributeType.COVER);
+ }
+
+ /**
+ * Insert a plain-text paragraph before the paragraph at the given paragraph index.
+ * @param {number} index The zero-based paragraph insertion index.
+ * @param {string} text The paragraph text. Defaults to an empty paragraph.
+ * @returns {FDocumentParagraph} The inserted paragraph wrapper.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const paragraph = fDocumentBody.insertParagraph(0, 'Document title');
+ * paragraph.appendText(' suffix');
+ * ```
+ */
+ insertParagraph(index: number, text = ''): FDocumentParagraph {
+ const offset = this._getParagraphInsertOffset(index);
+ const result = this._replaceBodyRange({ startOffset: offset, endOffset: offset }, buildPlainTextInsertBody(`${text}\r`));
+ if (!result) {
+ throw new Error('Failed to insert paragraph.');
+ }
+
+ const { paragraphs = [] } = this.getBody();
+ const paragraph = paragraphs[index];
+ if (!paragraph) {
+ throw new Error('Failed to insert paragraph.');
+ }
+
+ const info = this._resolveParagraphInfo(paragraph, index, paragraphs[index - 1]?.startIndex);
+
+ return this._injector.createInstance(FDocumentParagraph, this, info, this._injector);
+ }
+
+ /**
+ * Append a plain-text paragraph at the end of the body.
+ * @param {string} text The paragraph text. Defaults to an empty paragraph.
+ * @returns {FDocumentParagraph} The appended paragraph wrapper.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const paragraph = fDocumentBody.appendParagraph('Summary');
+ * console.log(paragraph.getText());
+ * ```
+ */
+ appendParagraph(text = ''): FDocumentParagraph {
+ const { paragraphs = [] } = this.getBody();
+ return this.insertParagraph(paragraphs.length, text);
+ }
+
+ /**
+ * Delete a range from the body.
+ * @param {IFDocumentTextRange} range The text range to delete.
+ * @returns {boolean} `true` if the range was deleted.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * fDocumentBody.deleteRange({ startOffset: 0, endOffset: 5 });
+ * ```
+ */
+ deleteRange(range: IFDocumentTextRange): boolean {
+ return this._replaceBodyRange(range, { dataStream: '' });
+ }
+
+ /**
+ * Replace a range with plain text or rich text body data.
+ * @param {IFDocumentTextRange} range The text range to replace.
+ * @param {string | IDocumentBody | undefined} value The replacement text or rich text body data. If `undefined`, the range is deleted.
+ * @returns {boolean} `true` if the replacement was applied.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ *
+ * // Replace a range with plain text
+ * fDocumentBody.replaceRange({ startOffset: 0, endOffset: 5 }, 'Hello');
+ *
+ * // Replace a range with rich text body data
+ * const richText = univerAPI.newRichText().insertText(5, 'World', { ff: 'Arial', fs: 12 });
+ * fDocumentBody.replaceRange({ startOffset: 5, endOffset: 10 }, richText);
+ * ```
+ */
+ replaceRange(range: IFDocumentTextRange, value: string | IDocumentBody | undefined): boolean {
+ let body: IDocumentBody = { dataStream: '' };
+
+ if (typeof value === 'string') {
+ body = buildPlainTextInsertBody(value);
+ } else if (value) {
+ body = value;
+ }
+
+ return this._replaceBodyRange(range, body);
+ }
+
+ /**
+ * Retain a range with a new body and cover type.
+ * @param {IFDocumentTextRange} range The text range to retain.
+ * @param {IDocumentBody} body The new body data to retain.
+ * @param {UpdateDocsAttributeType} coverType The cover type for the retained range.
+ * @returns {boolean} `true` if the retention was applied.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ *
+ * // Retain a range with a new body and cover type
+ * const newBody = univerAPI.newRichText().insertText(0, 'Retained text', { bl: 1 });
+ * fDocumentBody.retainRange({ startOffset: 0, endOffset: 5 }, newBody, univerAPI.Enum.UpdateDocsAttributeType.COVER);
+ * ```
+ */
+ retainRange(range: IFDocumentTextRange, body: IDocumentBody, coverType: UpdateDocsAttributeType): boolean {
+ return this._retainBodyRange(range, body, coverType);
+ }
+
+ /**
+ * Remove a paragraph by paragraph id.
+ * @param {FDocumentParagraph} paragraph The paragraph handle to remove.
+ * @returns {boolean} `true` if the paragraph was removed.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isParagraph()) {
+ * const paragraph = element.asParagraph();
+ * const removed = fDocumentBody.removeParagraph(paragraph);
+ * console.log(removed ? 'Paragraph removed' : 'Failed to remove paragraph');
+ * }
+ * ```
+ */
+ removeParagraph(paragraph: FDocumentParagraph): boolean {
+ const { startOffset, endOffset } = paragraph.getResolvedParagraphInfo();
+ return this.deleteRange({ startOffset, endOffset: endOffset + 1 });
+ }
+
+ /**
+ * Remove a callout, quote, or code block range and its content.
+ * @param {FDocumentBlockRange} blockRange The block range handle to remove.
+ * @returns {boolean} `true` if the block range content was removed.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isBlockRange()) {
+ * const blockRange = element.asBlockRange();
+ * const removed = fDocumentBody.removeBlockRange(blockRange);
+ * console.log(removed ? 'Block range removed' : 'Failed to remove block range');
+ * }
+ * ```
+ */
+ removeBlockRange(blockRange: FDocumentBlockRange): boolean {
+ const { startIndex, endIndex } = blockRange.getBlockRange();
+ return this.deleteRange({ startOffset: startIndex, endOffset: endIndex + 1 });
+ }
+
+ /**
+ * Remove a table marker and its content range.
+ * @returns {boolean} `true` if the table range was removed.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isTable()) {
+ * const table = element.asTable();
+ * const removed = fDocumentBody.removeTable(table);
+ * console.log(removed ? 'Table removed' : 'Failed to remove table');
+ * }
+ * ```
+ */
+ removeTable(table: FDocumentTable): boolean {
+ const { startIndex, endIndex } = table.getTable();
+ return this.deleteRange({ startOffset: startIndex, endOffset: endIndex + 1 });
+ }
+
+ /**
+ * Remove a custom block marker and its placeholder character.
+ * @param {FDocumentCustomBlock} customBlock The custom block handle to remove.
+ * @returns {boolean} `true` if the custom block placeholder was removed.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isCustomBlock()) {
+ * const customBlock = element.asCustomBlock();
+ * const removed = fDocumentBody.removeCustomBlock(customBlock);
+ * console.log(removed ? 'Custom block removed' : 'Failed to remove custom block');
+ * }
+ * ```
+ */
+ removeCustomBlock(customBlock: FDocumentCustomBlock): boolean {
+ const { startIndex } = customBlock.getCustomBlock();
+ return this.deleteRange({ startOffset: startIndex, endOffset: startIndex + 1 });
+ }
+
+ /**
+ * Resolve an element key to its current child metadata.
+ * @param {FDocumentElement} element The element handle to resolve.
+ * @returns {IFDocumentElementInfo} The current child metadata used by the facade.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ * const resolved = fDocumentBody.resolveElement(element);
+ * console.log(resolved);
+ * ```
+ */
+ resolveElement(element: FDocumentElement): IFDocumentElementInfo {
+ const { type, key } = element.getResolvedInfo();
+ const child = this._getChildren().find((item) => item.type === type && item.key === key);
+ if (!child) {
+ throw new Error('Doc element is stale');
+ }
+ return child;
+ }
+
+ private _getChildren(): IFDocumentElementInfo[] {
+ const { paragraphs, blockRanges, tables, customBlocks } = this.getBody();
+ const children: IFDocumentElementInfo[] = [];
+
+ if (paragraphs) {
+ for (let i = 0; i < paragraphs.length; i++) {
+ const paragraph = paragraphs[i];
+ const info = this._resolveParagraphInfo(paragraph, i, paragraphs[i - 1]?.startIndex);
+ children.push(info);
+ }
+ }
+
+ if (blockRanges) {
+ for (let i = 0; i < blockRanges.length; i++) {
+ const blockRange = blockRanges[i];
+ children.push({
+ type: DocumentBlockType.BLOCK_RANGE,
+ key: blockRange.blockId,
+ position: blockRange.startIndex,
+ priority: 0,
+ });
+ }
+ }
+
+ if (tables) {
+ for (let i = 0; i < tables.length; i++) {
+ const table = tables[i];
+ children.push({
+ type: DocumentBlockType.TABLE,
+ key: table.tableId,
+ position: table.startIndex,
+ priority: 1,
+ });
+ }
+ }
+
+ if (customBlocks) {
+ for (let i = 0; i < customBlocks.length; i++) {
+ const customBlock = customBlocks[i];
+ children.push({
+ type: DocumentBlockType.CUSTOM_BLOCK,
+ key: customBlock.blockId,
+ position: customBlock.startIndex,
+ priority: 2,
+ });
+ }
+ }
+
+ return children.sort((a, b) => a.position - b.position || a.priority - b.priority);
+ }
+
+ private _resolveParagraphInfo(paragraph: IParagraph, paragraphIndex: number, previousParagraphStartIndex: number | undefined): IFDocumentElementInfo {
+ return {
+ type: DocumentBlockType.PARAGRAPH,
+ key: this._getParagraphId(paragraph, paragraphIndex),
+ position: paragraphIndex > 0 ? (previousParagraphStartIndex as number) + 1 : 0,
+ priority: 3,
+ };
+ }
+
+ private _getParagraphId(paragraph: IParagraph | undefined, paragraphIndex: number): string {
+ if (!paragraph) {
+ throw new Error(`Paragraph index ${paragraphIndex} is out of range.`);
+ }
+
+ if (!paragraph.paragraphId) {
+ throw new Error(`Paragraph at index ${paragraphIndex} is missing paragraphId.`);
+ }
+
+ return paragraph.paragraphId;
+ }
+
+ private _getParagraphInsertOffset(index: number): number {
+ if (index <= 0) {
+ return 0;
+ }
+
+ const { dataStream, paragraphs = [] } = this.getBody();
+
+ if (paragraphs.length === 0) {
+ return Math.max(0, dataStream.length - 1);
+ }
+
+ if (index >= paragraphs.length) {
+ return paragraphs[paragraphs.length - 1].startIndex + 1;
+ }
+
+ return paragraphs[index - 1].startIndex + 1;
+ }
+
+ private _replaceBodyRange(range: IFDocumentTextRange, insertBody: IDocumentBody): boolean {
+ const { startOffset, endOffset } = range;
+ const textX = new TextX();
+
+ if (startOffset > 0) {
+ textX.push({ t: TextXActionType.RETAIN, len: startOffset });
+ }
+
+ if (endOffset > startOffset) {
+ textX.push({ t: TextXActionType.DELETE, len: endOffset - startOffset });
+ }
+
+ if (insertBody.dataStream.length > 0) {
+ textX.push({
+ t: TextXActionType.INSERT,
+ body: insertBody,
+ len: insertBody.dataStream.length,
+ });
+ }
+
+ return this._executeTextX(textX);
+ }
+
+ private _retainBodyRange(range: IFDocumentTextRange, body: IDocumentBody, coverType: UpdateDocsAttributeType): boolean {
+ if (body.textRuns?.length && this.getBody().textRuns == null) {
+ this._ensureTextRuns();
+ }
+
+ const textX = new TextX();
+ if (range.startOffset > 0) {
+ textX.push({ t: TextXActionType.RETAIN, len: range.startOffset });
+ }
+
+ textX.push({
+ t: TextXActionType.RETAIN,
+ body,
+ coverType,
+ len: range.endOffset - range.startOffset,
+ });
+
+ return this._executeTextX(textX);
+ }
+
+ private _ensureTextRuns(): void {
+ const jsonX = JSONX.getInstance();
+ const actions = jsonX.replaceOp(
+ [...getRichTextEditPath(this._documentDataModel, this._segmentId), 'textRuns'],
+ undefined,
+ []
+ );
+
+ const commandService = this._injector.get(ICommandService);
+ commandService.syncExecuteCommand<IRichTextEditingMutationParams>(
+ RichTextEditingMutation.id,
+ {
+ unitId: this._documentDataModel.getUnitId(),
+ segmentId: this._segmentId,
+ actions,
+ textRanges: [],
+ isEditing: false,
+ }
+ );
+ }
+
+ private _executeTextX(textX: TextX): boolean {
+ const jsonX = JSONX.getInstance();
+ const actions = jsonX.editOp(textX.serialize(), getRichTextEditPath(this._documentDataModel, this._segmentId));
+
+ const commandService = this._injector.get(ICommandService);
+ const result = commandService.syncExecuteCommand<IRichTextEditingMutationParams, IRichTextEditingMutationParams | false>(
+ RichTextEditingMutation.id,
+ {
+ unitId: this._documentDataModel.getUnitId(),
+ segmentId: this._segmentId,
+ actions,
+ textRanges: [],
+ isEditing: false,
+ }
+ );
+
+ return result !== false;
+ }
+}
diff --git a/packages/docs/src/facade/f-document-custom-block.ts b/packages/docs/src/facade/f-document-custom-block.ts
new file mode 100644
index 0000000000..ce691f4516
--- /dev/null
+++ b/packages/docs/src/facade/f-document-custom-block.ts
@@ -0,0 +1,82 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICustomBlock, Injector } from '@univerjs/core';
+import type { FDocumentBody } from './f-document-body';
+import type { IFDocumentElementInfo } from './f-document-element';
+import { DocumentBlockType } from '@univerjs/core';
+import { FDocumentElement } from './f-document-element';
+
+interface IFDocumentCustomBlockMixin {
+ asCustomBlock(): FDocumentCustomBlock;
+}
+
+/**
+ * A facade wrapper for document top-level custom blocks.
+ * @hideconstructor
+ */
+export class FDocumentCustomBlock extends FDocumentElement {
+ constructor(
+ protected readonly body: FDocumentBody,
+ protected readonly info: IFDocumentElementInfo,
+ protected readonly injector: Injector
+ ) {
+ super(body, info, injector);
+
+ if (this.getType() !== DocumentBlockType.CUSTOM_BLOCK) {
+ throw new Error(`Element type is not a custom block: ${this.getType()}`);
+ }
+ }
+
+ /**
+ * Get the custom block marker.
+ * @returns {ICustomBlock} The custom block marker.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isCustomBlock()) {
+ * const customBlock = element.asCustomBlock();
+ * console.log(customBlock.getCustomBlock());
+ * }
+ * ```
+ */
+ getCustomBlock(): ICustomBlock {
+ const { customBlocks = [] } = this._body.getBody();
+ const block = customBlocks.find((item) => item.blockId === this.getKey());
+ if (!block) {
+ throw new Error('Doc custom block is stale');
+ }
+ return block;
+ }
+}
+
+export class FDocumentCustomBlockMixin extends FDocumentElement {
+ override asCustomBlock(): FDocumentCustomBlock {
+ if (this.getType() !== DocumentBlockType.CUSTOM_BLOCK) {
+ throw new Error(`Element type is not a custom block: ${this.getType()}`);
+ }
+ return this._injector.createInstance(FDocumentCustomBlock, this._body, this.getResolvedInfo(), this._injector);
+ }
+}
+
+FDocumentElement.extend(FDocumentCustomBlockMixin);
+declare module '@univerjs/docs/facade' {
+ // eslint-disable-next-line ts/naming-convention
+ interface FDocumentElement extends IFDocumentCustomBlockMixin { }
+}
diff --git a/packages/docs/src/facade/f-document-element.ts b/packages/docs/src/facade/f-document-element.ts
new file mode 100644
index 0000000000..212cf18e13
--- /dev/null
+++ b/packages/docs/src/facade/f-document-element.ts
@@ -0,0 +1,254 @@
+/**
+ * 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 { Injector } from '@univerjs/core';
+import type { FDocumentBody } from './f-document-body';
+import { DocumentBlockType } from '@univerjs/core';
+import { FBase } from '@univerjs/core/facade';
+
+export interface IFDocumentElementInfo {
+ type: DocumentBlockType;
+ key: string;
+ position: number;
+ priority: number;
+}
+
+/**
+ * A generic top-level document body element.
+ *
+ * Use this wrapper when you need to inspect an element type first, navigate to
+ * neighboring elements, or cast the element to a more specific facade wrapper.
+ *
+ * Paragraph keys are persisted `paragraphId` values. Tables, block ranges, and
+ * custom blocks use their persisted ids.
+ *
+ * @hideconstructor
+ */
+export class FDocumentElement extends FBase {
+ constructor(
+ protected readonly _body: FDocumentBody,
+ protected readonly _info: IFDocumentElementInfo,
+ protected readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ /**
+ * Get the document element type.
+ * @returns {DocumentBlockType} The element type, such as `paragraph`, `table`, `blockRange`, or `customBlock`.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ * console.log(element?.getType());
+ * ```
+ */
+ getType(): DocumentBlockType {
+ return this._info.type;
+ }
+
+ /**
+ * Whether this element is a paragraph.
+ * @returns {boolean} `true` if this element is a paragraph.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ * console.log(element?.isParagraph());
+ * ```
+ */
+ isParagraph(): boolean {
+ return this._info.type === DocumentBlockType.PARAGRAPH;
+ }
+
+ /**
+ * Whether this element is a table.
+ * @returns {boolean} `true` if this element is a table.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ * console.log(element?.isTable());
+ * ```
+ */
+ isTable(): boolean {
+ return this._info.type === DocumentBlockType.TABLE;
+ }
+
+ /**
+ * Whether this element is a block range, such as a callout, quote, or code block.
+ * @returns {boolean} `true` if this element is a block range.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ * console.log(element?.isBlockRange());
+ * ```
+ */
+ isBlockRange(): boolean {
+ return this._info.type === DocumentBlockType.BLOCK_RANGE;
+ }
+
+ /**
+ * Whether this element is a custom block.
+ * @returns {boolean} `true` if this element is a custom block.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ * console.log(element?.isCustomBlock());
+ * ```
+ */
+ isCustomBlock(): boolean {
+ return this._info.type === DocumentBlockType.CUSTOM_BLOCK;
+ }
+
+ /**
+ * Get the facade key used to resolve this element.
+ * @returns {string} The paragraph `paragraphId` or persisted table/block/custom block id.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ * console.log(element?.getKey());
+ * ```
+ */
+ getKey(): string {
+ return this._info.key;
+ }
+
+ /**
+ * Get the parent body facade that owns this element.
+ * @returns {FDocumentBody} The document body facade.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ * console.log(element?.getParent());
+ * ```
+ */
+ getParent(): FDocumentBody {
+ return this._body;
+ }
+
+ /**
+ * Get the resolved element info for this wrapper.
+ * @returns {IFDocumentElementInfo} The resolved element info, including type, key, position, and priority.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ * console.log(element?.getResolvedInfo());
+ * ```
+ */
+ getResolvedInfo(): IFDocumentElementInfo {
+ return this._info;
+ }
+
+ /**
+ * Get the next sibling element in the current body order.
+ * @returns {FDocumentElement | null} The next sibling wrapper, or `null` when this is the last child.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ * console.log(element?.getNextSibling());
+ * ```
+ */
+ getNextSibling(): FDocumentElement | null {
+ return this._createSibling(1);
+ }
+
+ /**
+ * Get the previous sibling element in the current body order.
+ * @returns {FDocumentElement | null} The previous sibling wrapper, or `null` when this is the first child.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(1);
+ * console.log(element?.getPreviousSibling());
+ * ```
+ */
+ getPreviousSibling(): FDocumentElement | null {
+ return this._createSibling(-1);
+ }
+
+ /**
+ * Get the sibling element at a relative offset from this element.
+ * @param {number} offset The relative offset from this element. Use `1` for the next sibling, `-1` for the previous sibling, and so on.
+ * @returns {FDocumentElement | null} The sibling wrapper at the specified offset, or `null` when the offset is out of range.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * // Get the third sibling after this element
+ * const nextThirdSibling = element?.getSibling(3);
+ * console.log(nextThirdSibling?.getType());
+ * ```
+ */
+ getSibling(offset: number): FDocumentElement | null {
+ return this._createSibling(offset);
+ }
+
+ /**
+ * Remove this element from its parent body.
+ * @returns {boolean} `true` if the element content was removed.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ * const removed = element?.remove();
+ * console.log(removed);
+ * ```
+ */
+ remove(): boolean {
+ if (this.isParagraph()) {
+ return this._body.removeParagraph(this.asParagraph());
+ }
+
+ if (this.isBlockRange()) {
+ return this._body.removeBlockRange(this.asBlockRange());
+ }
+
+ if (this.isTable()) {
+ return this._body.removeTable(this.asTable());
+ }
+
+ return this._body.removeCustomBlock(this.asCustomBlock());
+ }
+
+ private _createSibling(offset: number): FDocumentElement | null {
+ if (offset === 0) {
+ throw new Error('Offset cannot be zero.');
+ }
+
+ const index = this._body.getElementIndex(this);
+ return this._body.getElement(index + offset);
+ }
+}
diff --git a/packages/docs/src/facade/f-document-paragraph.ts b/packages/docs/src/facade/f-document-paragraph.ts
new file mode 100644
index 0000000000..2383ad0695
--- /dev/null
+++ b/packages/docs/src/facade/f-document-paragraph.ts
@@ -0,0 +1,356 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentBody, Injector, IParagraph, IParagraphStyle } from '@univerjs/core';
+import type { FDocumentBody, IFDocumentTextRange } from './f-document-body';
+import type { IFDocumentElementInfo } from './f-document-element';
+import { DocumentBlockType, PresetListType, RESTORE_INSERTED_PARAGRAPH_IDS, UpdateDocsAttributeType } from '@univerjs/core';
+import { FDocumentElement } from './f-document-element';
+
+interface IFDocumentParagraphMixin {
+ asParagraph(): FDocumentParagraph;
+}
+
+/**
+ * Resolved paragraph metadata in the the document body.
+ */
+export interface IFDocumentResolvedParagraph {
+ /** The underlying paragraph snapshot object. */
+ paragraph: IParagraph;
+ /** The current paragraph index in the body paragraph list. */
+ paragraphIndex: number;
+ /** The inclusive start offset of the paragraph text. */
+ startOffset: number;
+ /** The exclusive end offset of the paragraph text, before the paragraph break. */
+ endOffset: number;
+}
+
+/**
+ * A paragraph facade wrapper.
+ *
+ * Paragraph identity is backed by the persisted `paragraphId`. The id is
+ * re-resolved before each method call, so insertions before this paragraph do
+ * not break the wrapper.
+ *
+ * @hideconstructor
+ */
+export class FDocumentParagraph extends FDocumentElement {
+ constructor(
+ protected readonly body: FDocumentBody,
+ protected readonly info: IFDocumentElementInfo,
+ protected readonly injector: Injector
+ ) {
+ super(body, info, injector);
+
+ if (this.getType() !== DocumentBlockType.PARAGRAPH) {
+ throw new Error(`Element type is not a paragraph: ${this.getType()}`);
+ }
+ }
+
+ /**
+ * Get the persisted paragraph id.
+ * @returns {string} The paragraph id.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isParagraph()) {
+ * const paragraph = element.asParagraph();
+ * console.log(paragraph.getParagraphId());
+ * }
+ * ```
+ */
+ getParagraphId(): string {
+ return this.getKey();
+ }
+
+ /**
+ * Get the resolved paragraph info for this wrapper.
+ * @returns {IFDocumentResolvedParagraph} The resolved paragraph info, including the paragraph object, its index, and its text range.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isParagraph()) {
+ * const paragraph = element.asParagraph();
+ * console.log(paragraph.getResolvedParagraphInfo());
+ * }
+ * ```
+ */
+ getResolvedParagraphInfo(): IFDocumentResolvedParagraph {
+ const { paragraphs = [] } = this._body.getBody();
+ const matches = paragraphs
+ .map((paragraph, paragraphIndex) => ({ paragraph, paragraphIndex }))
+ .filter(({ paragraph }) => paragraph.paragraphId === this.getKey());
+
+ if (matches.length === 0) {
+ throw new Error(`Document paragraph with id ${this.getKey()} not found`);
+ }
+
+ if (matches.length > 1) {
+ throw new Error(`Multiple document paragraphs with id ${this.getKey()} found`);
+ }
+
+ const { paragraph, paragraphIndex } = matches[0];
+ const startOffset = paragraphIndex > 0 ? paragraphs[paragraphIndex - 1].startIndex + 1 : 0;
+
+ return {
+ paragraph,
+ paragraphIndex,
+ startOffset,
+ endOffset: paragraph.startIndex,
+ };
+ }
+
+ /**
+ * Get the current text range occupied by this paragraph.
+ * @returns {IFDocumentTextRange} The paragraph text range, excluding the trailing paragraph break.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isParagraph()) {
+ * const paragraph = element.asParagraph();
+ * const range = paragraph.getRange();
+ * fDocumentBody.setTextStyle(range, { bl: 1 });
+ * }
+ * ```
+ */
+ getRange(): IFDocumentTextRange {
+ const { startOffset, endOffset } = this.getResolvedParagraphInfo();
+ return { startOffset, endOffset, segmentId: this._body.getSegmentId() };
+ }
+
+ /**
+ * Get this paragraph's plain text.
+ * @returns {string} The paragraph text without the trailing paragraph break.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isParagraph()) {
+ * const paragraph = element.asParagraph();
+ * console.log(paragraph.getText());
+ * }
+ * ```
+ */
+ getText(): string {
+ const { dataStream } = this._body.getBody();
+ const { startOffset, endOffset } = this.getResolvedParagraphInfo();
+ return dataStream.slice(startOffset, endOffset);
+ }
+
+ /**
+ * Replace this paragraph's plain text.
+ * @param {string} text The replacement text. Do not include the paragraph break.
+ * @returns {boolean} `true` if the paragraph text was replaced.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isParagraph()) {
+ * const paragraph = element.asParagraph();
+ * const success = paragraph.setText('Updated title');
+ * console.log(success ? 'Text updated' : 'Failed to update text');
+ * }
+ * ```
+ */
+ setText(text: string): boolean {
+ const { startOffset, endOffset } = this.getResolvedParagraphInfo();
+ return this._body.replaceRange({ startOffset, endOffset }, text);
+ }
+
+ /**
+ * Append plain text before this paragraph's trailing paragraph break.
+ * @param {string} text The plain text to append.
+ * @returns {boolean} `true` if the text was appended.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isParagraph()) {
+ * const paragraph = element.asParagraph();
+ * const success = paragraph.appendText(' Appended text');
+ * console.log(success ? 'Text appended' : 'Failed to append text');
+ * }
+ * ```
+ */
+ appendText(text: string): boolean {
+ const { endOffset } = this.getResolvedParagraphInfo();
+ return this._body.insertText(endOffset, text);
+ }
+
+ /**
+ * Apply paragraph style to a paragraph handle or text range.
+ * @param {IParagraphStyle} style The Univer paragraph style patch.
+ * @returns {boolean} `true` if the style was applied.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isParagraph()) {
+ * const paragraph = element.asParagraph();
+ * paragraph.setStyle({ horizontalAlign: 2 });
+ * }
+ * ```
+ */
+ setStyle(style: IParagraphStyle): boolean {
+ const { paragraph, endOffset } = this.getResolvedParagraphInfo();
+
+ const updateBody: IDocumentBody = {
+ dataStream: '',
+ paragraphs: [{
+ ...paragraph,
+ startIndex: 0,
+ paragraphStyle: {
+ ...paragraph.paragraphStyle,
+ ...style,
+ },
+ }],
+ };
+
+ this._preserveExplicitParagraphIds(updateBody);
+
+ return this._body.retainRange(
+ { startOffset: endOffset, endOffset: endOffset + 1 },
+ updateBody,
+ UpdateDocsAttributeType.REPLACE
+ );
+ }
+
+ /**
+ * Check whether this paragraph is a bullet, ordered, or checklist item.
+ * @returns {boolean} `true` if the paragraph has list metadata.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isParagraph()) {
+ * const paragraph = element.asParagraph();
+ * console.log(paragraph.isListItem() ? 'This is a list item' : 'This is not a list item');
+ * }
+ * ```
+ */
+ isListItem(): boolean {
+ const { paragraph } = this.getResolvedParagraphInfo();
+ return Boolean(paragraph.bullet);
+ }
+
+ /**
+ * Check whether this paragraph is a task/checklist item.
+ * @returns {boolean} `true` if this paragraph is an unchecked or checked task item.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isParagraph()) {
+ * const paragraph = element.asParagraph();
+ * console.log(paragraph.isTask() ? 'This is a task item' : 'This is not a task item');
+ * }
+ * ```
+ */
+ isTask(): boolean {
+ const { paragraph } = this.getResolvedParagraphInfo();
+ const listType = paragraph.bullet?.listType;
+ return listType === PresetListType.CHECK_LIST || listType === PresetListType.CHECK_LIST_CHECKED;
+ }
+
+ /**
+ * Set the checked state of this task/checklist paragraph.
+ * @param {boolean} checked Whether the task item should be checked.
+ * @returns {boolean} `true` if the task state was updated, or `false` if this paragraph is not a task item.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isParagraph()) {
+ * const paragraph = element.asParagraph();
+ *
+ * if (paragraph.isTask()) {
+ * const success = paragraph.setTaskChecked(true);
+ * console.log(success ? 'Task checked' : 'Failed to check task');
+ * }
+ * }
+ * ```
+ */
+ setTaskChecked(checked: boolean): boolean {
+ if (!this.isTask()) {
+ return false;
+ }
+
+ const { paragraph, endOffset } = this.getResolvedParagraphInfo();
+ const bullet = paragraph.bullet!;
+
+ const updateBody: IDocumentBody = {
+ dataStream: '',
+ paragraphs: [{
+ ...paragraph,
+ startIndex: 0,
+ bullet: {
+ ...bullet,
+ listType: checked ? PresetListType.CHECK_LIST_CHECKED : PresetListType.CHECK_LIST,
+ },
+ }],
+ };
+
+ this._preserveExplicitParagraphIds(updateBody);
+
+ return this._body.retainRange(
+ { startOffset: endOffset, endOffset: endOffset + 1 },
+ updateBody,
+ UpdateDocsAttributeType.REPLACE
+ );
+ }
+
+ private _preserveExplicitParagraphIds(body: IDocumentBody): void {
+ (body as IDocumentBody & Record<string, unknown>)[RESTORE_INSERTED_PARAGRAPH_IDS] = true;
+ }
+}
+
+export class FDocumentParagraphMixin extends FDocumentElement {
+ override asParagraph(): FDocumentParagraph {
+ if (this.getType() !== DocumentBlockType.PARAGRAPH) {
+ throw new Error(`Element type is not a paragraph: ${this.getType()}`);
+ }
+ return this._injector.createInstance(FDocumentParagraph, this._body, this.getResolvedInfo(), this._injector);
+ }
+}
+
+FDocumentElement.extend(FDocumentParagraphMixin);
+declare module '@univerjs/docs/facade' {
+ // eslint-disable-next-line ts/naming-convention
+ interface FDocumentElement extends IFDocumentParagraphMixin { }
+}
diff --git a/packages/docs/src/facade/f-document-table.ts b/packages/docs/src/facade/f-document-table.ts
new file mode 100644
index 0000000000..02e2efd987
--- /dev/null
+++ b/packages/docs/src/facade/f-document-table.ts
@@ -0,0 +1,82 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICustomTable, Injector } from '@univerjs/core';
+import type { FDocumentBody } from './f-document-body';
+import type { IFDocumentElementInfo } from './f-document-element';
+import { DocumentBlockType } from '@univerjs/core';
+import { FDocumentElement } from './f-document-element';
+
+interface IFDocumentTableMixin {
+ asTable(): FDocumentTable;
+}
+
+/**
+ * A facade wrapper for document top-level tables.
+ * @hideconstructor
+ */
+export class FDocumentTable extends FDocumentElement {
+ constructor(
+ protected readonly body: FDocumentBody,
+ protected readonly info: IFDocumentElementInfo,
+ protected readonly injector: Injector
+ ) {
+ super(body, info, injector);
+
+ if (this.getType() !== DocumentBlockType.TABLE) {
+ throw new Error(`Element type is not a table: ${this.getType()}`);
+ }
+ }
+
+ /**
+ * Get the table marker.
+ * @returns {ICustomTable} The table marker.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * const element = fDocumentBody.getElement(0);
+ *
+ * if (element?.isTable()) {
+ * const table = element.asTable();
+ * console.log(table.getTable());
+ * }
+ * ```
+ */
+ getTable(): ICustomTable {
+ const { tables = [] } = this._body.getBody();
+ const table = tables.find((item) => item.tableId === this.getKey());
+ if (!table) {
+ throw new Error('Doc table is stale');
+ }
+ return table;
+ }
+}
+
+export class FDocumentTableMixin extends FDocumentElement {
+ override asTable(): FDocumentTable {
+ if (this.getType() !== DocumentBlockType.TABLE) {
+ throw new Error(`Element type is not a table: ${this.getType()}`);
+ }
+ return this._injector.createInstance(FDocumentTable, this._body, this.getResolvedInfo(), this._injector);
+ }
+}
+
+FDocumentElement.extend(FDocumentTableMixin);
+declare module '@univerjs/docs/facade' {
+ // eslint-disable-next-line ts/naming-convention
+ interface FDocumentElement extends IFDocumentTableMixin { }
+}
diff --git a/packages/docs/src/facade/f-document.ts b/packages/docs/src/facade/f-document.ts
index 82f0796108..2bb19fd910 100644
--- a/packages/docs/src/facade/f-document.ts
+++ b/packages/docs/src/facade/f-document.ts
@@ -27,8 +27,7 @@ import {
} from '@univerjs/core';
import { FBaseInitialable } from '@univerjs/core/facade';
import { InsertTextCommand } from '@univerjs/docs';
-import { DocElementRegistry } from './doc-element-registry';
-import { FDocBody } from './f-doc-body';
+import { FDocumentBody } from './f-document-body';
import {
buildPlainTextInsertBody,
getNormalizedPlainTextCursorOffset,
@@ -48,7 +47,6 @@ export interface IDocumentInsertTextFacadeOptions {
*/
export class FDocument extends FBaseInitialable {
readonly id: string;
- private readonly _docElementRegistry = new DocElementRegistry();
constructor(
private readonly _documentDataModel: DocumentDataModel,
@@ -84,23 +82,23 @@ export class FDocument extends FBaseInitialable {
* use their persisted `paragraphId` values. Persisted elements, such as tables
* and custom blocks, use their existing ids.
*
- * @returns {FDocBody} The document body API instance.
+ * @returns {FDocumentBody} The document body API instance.
* @example
* ```typescript
- * const doc = univerAPI.getActiveDocument();
- * if (!doc) throw new Error('No active document');
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ * console.log(fDocumentBody.getBody());
*
- * const body = doc.getBody();
- * const paragraph = body.getChild(0).asParagraph();
- * paragraph.appendText(' updated');
+ * const element = fDocumentBody.getElement(0);
+ * if (element.isParagraph()) {
+ * const paragraph = element.asParagraph();
+ * paragraph.appendText(' updated');
+ * console.log(paragraph.getText());
+ * }
* ```
*/
- getBody(): FDocBody {
- return new FDocBody(
- this._documentDataModel,
- this._commandService,
- this._docElementRegistry
- );
+ getBody(): FDocumentBody {
+ return this._injector.createInstance(FDocumentBody, this._documentDataModel, this._injector);
}
override dispose(): void {
diff --git a/packages/docs/src/facade/f-enum.ts b/packages/docs/src/facade/f-enum.ts
new file mode 100644
index 0000000000..48095f334d
--- /dev/null
+++ b/packages/docs/src/facade/f-enum.ts
@@ -0,0 +1,52 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { UpdateDocsAttributeType } from '@univerjs/core';
+import { FEnum } from '@univerjs/core/facade';
+
+/**
+ * @ignore
+ */
+export interface IFDocsEnumMixin {
+ /**
+ * Update document attribute types. These types define how document attributes are updated.
+ * - `COVER`: If the attribute is not present, it will be added. If it is present, it will be overwritten while retaining the original properties.
+ * - `REPLACE`: The original properties will be replaced entirely.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const fDocumentBody = fDocument.getBody();
+ *
+ * // Retain a range with a new body and cover type
+ * const newBody = univerAPI.newRichText().insertText(0, 'Retained text', { bl: 1 });
+ * fDocumentBody.retainRange({ startOffset: 0, endOffset: 5 }, newBody, univerAPI.Enum.UpdateDocsAttributeType.COVER);
+ * ```
+ */
+ UpdateDocsAttributeType: typeof UpdateDocsAttributeType;
+}
+
+export class FDocsEnumMixin extends FEnum implements IFDocsEnumMixin {
+ override get UpdateDocsAttributeType(): typeof UpdateDocsAttributeType {
+ return UpdateDocsAttributeType;
+ }
+}
+
+FEnum.extend(FDocsEnumMixin);
+declare module '@univerjs/core/facade' {
+ // eslint-disable-next-line ts/naming-convention
+ export interface FEnum extends IFDocsEnumMixin {
+ }
+}
diff --git a/packages/docs/src/facade/index.ts b/packages/docs/src/facade/index.ts
index a308636b6d..e0a3828280 100644
--- a/packages/docs/src/facade/index.ts
+++ b/packages/docs/src/facade/index.ts
@@ -15,14 +15,12 @@
*/
import './f-univer';
+import './f-enum';
-export { DocElementRegistry, DocElementStaleError, type FDocElementType } from './doc-element-registry';
-export { FDocBlockRange } from './f-doc-block-range';
-export { FDocBody, type IFDocElementHandle, type IFDocResolvedParagraph, type IFDocRichTextLike, type IFDocTextRange } from './f-doc-body';
-export { FDocCustomBlock } from './f-doc-custom-block';
-export { FDocElement } from './f-doc-element';
-export { FDocParagraph } from './f-doc-paragraph';
-export { FDocTable } from './f-doc-table';
export { FDocument } from './f-document';
-
-export type * from './f-univer';
+export { FDocumentBlockRange } from './f-document-block-range';
+export { FDocumentBody, type IFDocumentTextRange } from './f-document-body';
+export { FDocumentCustomBlock } from './f-document-custom-block';
+export { FDocumentElement } from './f-document-element';
+export { FDocumentParagraph } from './f-document-paragraph';
+export { FDocumentTable } from './f-document-table';
diff --git a/packages/docs/src/facade/utils.ts b/packages/docs/src/facade/utils.ts
index 262068710f..6cd68e4c1c 100644
--- a/packages/docs/src/facade/utils.ts
+++ b/packages/docs/src/facade/utils.ts
@@ -14,11 +14,9 @@
* limitations under the License.
*/
-import type { IDocumentBody } from '@univerjs/core';
+import type { IDocumentBody, IParagraphStyle } from '@univerjs/core';
import { createParagraphId } from '@univerjs/core';
-type IParagraphStyle = NonNullable<IDocumentBody['paragraphs']>[number]['paragraphStyle'];
-
export interface IBuildPlainTextInsertBodyOptions {
paragraphStyle?: IParagraphStyle;
removeLeadingParagraphBreak?: boolean;
@@ -58,7 +56,7 @@ export function getNormalizedPlainTextCursorOffset(
);
}
-export function getParagraphStyleAtOffset(body: IDocumentBody, offset: number): IParagraphStyle {
+export function getParagraphStyleAtOffset(body: IDocumentBody, offset: number): IParagraphStyle | undefined {
const paragraphs = body.paragraphs ?? [];
const paragraph = paragraphs.find((item) => item.startIndex >= offset) ?? paragraphs[paragraphs.length - 1];