Skip to content

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

feat(docs): add element facade APIs (#7064)

Univer01116c1a8681
diff --git a/examples/src/node/sdk/facade.ts b/examples/src/node/sdk/facade.ts
index 5e6baacad0..b10a4868d3 100644
--- a/examples/src/node/sdk/facade.ts
+++ b/examples/src/node/sdk/facade.ts
@@ -18,6 +18,7 @@
// However some plugins are implemented incorrectly, so they are not included here.
import '@univerjs/sheets/facade';
+import '@univerjs/docs/facade';
import '@univerjs/sheets-data-validation/facade';
import '@univerjs/engine-formula/facade';
import '@univerjs/sheets-filter/facade';
diff --git a/packages/docs-ui/src/facade/__tests__/create-test-bed.ts b/packages/docs-ui/src/facade/__tests__/create-test-bed.ts
deleted file mode 100644
index 67103c49e4..0000000000
--- a/packages/docs-ui/src/facade/__tests__/create-test-bed.ts
+++ /dev/null
@@ -1,117 +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 { Dependency, DocumentDataModel, IDocumentData } from '@univerjs/core';
-import {
- ILogService,
- Inject,
- Injector,
- IUniverInstanceService,
- LocaleService,
- LogLevel,
- Plugin,
- Univer,
- UniverInstanceType,
-} from '@univerjs/core';
-import { FUniver } from '@univerjs/core/facade';
-import { DocSelectionManagerService, DocSkeletonManagerService, DocStateChangeManagerService, DocStateEmitService } from '@univerjs/docs';
-import { DocIMEInputManagerService, DocsRenderService } from '@univerjs/docs-ui';
-import enUS from '@univerjs/docs-ui/locale/en-US';
-import zhCN from '@univerjs/docs-ui/locale/zh-CN';
-import { DumbCanvasColorService, ICanvasColorService, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-
-function getTestDocumentDataDemo(): IDocumentData {
- return {
- id: 'test',
- body: {
- dataStream: 'Hello,\r\n',
- },
- documentStyle: {
- pageSize: {
- width: 594.3,
- height: 840.51,
- },
- marginTop: 72,
- marginBottom: 72,
- marginRight: 90,
- marginLeft: 90,
- },
- };
-}
-
-export interface ITestBed {
- univer: Univer;
- get: Injector['get'];
- doc: DocumentDataModel;
- univerAPI: FUniver;
-}
-
-export function createTestBed(documentConfig?: IDocumentData, dependencies?: Dependency[]): ITestBed {
- const univer = new Univer();
- const injector = univer.__getInjector();
-
- class TestPlugin extends Plugin {
- static override pluginName = 'test-plugin';
-
- constructor(
- _config: undefined,
- @Inject(Injector) override readonly _injector: Injector
- ) {
- super();
- }
-
- override onStarting(): void {
- const injector = this._injector;
- injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
- injector.add([DocSelectionManagerService]);
- injector.add([DocStateEmitService]);
- injector.add([DocStateChangeManagerService]);
- injector.add([DocsRenderService]);
- injector.add([ICanvasColorService, { useClass: DumbCanvasColorService }]);
-
- dependencies?.forEach((d) => injector.add(d));
-
- const renderManagerService = injector.get(IRenderManagerService);
- renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_DOC, [DocSkeletonManagerService] as Dependency);
- renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_DOC, [DocIMEInputManagerService] as Dependency);
- }
-
- override onReady(): void {
- this._injector.get(DocStateChangeManagerService);
- this._injector.get(DocsRenderService);
- }
- }
-
- injector.get(LocaleService).load({ zhCN, enUS });
-
- univer.registerPlugin(TestPlugin);
- const doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, documentConfig ?? getTestDocumentDataDemo());
-
- const univerInstanceService = injector.get(IUniverInstanceService);
- univerInstanceService.focusUnit('test');
- const logService = injector.get(ILogService);
-
- logService.setLogLevel(LogLevel.SILENT);
-
- const univerAPI = FUniver.newAPI(injector);
-
- return {
- univer,
- get: injector.get.bind(injector),
- doc,
- univerAPI,
- };
-}
diff --git a/packages/docs-ui/src/facade/__tests__/f-document.spec.ts b/packages/docs-ui/src/facade/__tests__/f-document.spec.ts
deleted file mode 100644
index 1a267b611b..0000000000
--- a/packages/docs-ui/src/facade/__tests__/f-document.spec.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 { DocumentDataModel, ICommand, IDocumentData, Injector, Univer } from '@univerjs/core';
-import { ICommandService, IResourceManagerService, UniverInstanceType } from '@univerjs/core';
-import { InsertTextCommand, RichTextEditingMutation } from '@univerjs/docs';
-import { FDocument } from '@univerjs/docs/facade';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { createTestBed } from './create-test-bed';
-
-describe('Test FDocument', () => {
- let univer: Univer;
- let get: Injector['get'];
- let documentDataModel: DocumentDataModel;
- let document: FDocument;
-
- function createDocumentFacade(docData?: IDocumentData) {
- const testBed = createTestBed(docData);
- univer = testBed.univer;
- get = testBed.get;
- documentDataModel = testBed.doc;
-
- const commandService = get(ICommandService);
- commandService.registerCommand(InsertTextCommand);
- commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
-
- document = univer.__getInjector().createInstance(FDocument, documentDataModel);
- }
-
- beforeEach(() => {
- createDocumentFacade();
- });
-
- afterEach(() => {
- univer.dispose();
- });
-
- it('appends text at the tail of the body', async () => {
- await expect(document.appendText('Univer')).resolves.toBe(true);
-
- expect(document.save().body?.dataStream).toBe('Hello,Univer\r\n');
- });
-
- it('inserts text at an explicit document range', async () => {
- await expect(document.insertText('Docs', {
- endOffset: 4,
- segmentId: '',
- startOffset: 2,
- })).resolves.toBe(true);
-
- expect(document.save().body?.dataStream).toBe('HeDocso,\r\n');
- });
-
- it('inserts paragraphs at an explicit document range', async () => {
- await expect(document.insertParagraph('Line 1\nLine 2', {
- endOffset: 6,
- segmentId: '',
- startOffset: 6,
- })).resolves.toBe(true);
-
- expect(document.save().body?.dataStream).toBe('Hello,Line 1\rLine 2\r\r\n');
- });
-
- it('throws when appending text to a document without a body', () => {
- univer.dispose();
- createDocumentFacade({
- id: 'test',
- title: 'Test Document',
- documentStyle: {},
- });
-
- expect(() => document.appendText('Univer')).toThrowError('The document body is empty');
- });
-
- it('includes current document resources in snapshots', () => {
- const resourceManagerService = get(IResourceManagerService);
-
- resourceManagerService.registerPluginResource({
- pluginName: 'DOC_TEST_RESOURCE_PLUGIN',
- businesses: [UniverInstanceType.UNIVER_DOC],
- onLoad: () => undefined,
- onUnLoad: () => undefined,
- toJson: () => '{"value":1}',
- parseJson: (bytes) => JSON.parse(bytes),
- });
-
- expect(document.save().resources).toEqual([
- {
- name: 'DOC_TEST_RESOURCE_PLUGIN',
- data: '{"value":1}',
- },
- ]);
- });
-});
diff --git a/packages/docs/src/facade/__tests__/create-test-bed.ts b/packages/docs/src/facade/__tests__/create-test-bed.ts
new file mode 100644
index 0000000000..29fa720c84
--- /dev/null
+++ b/packages/docs/src/facade/__tests__/create-test-bed.ts
@@ -0,0 +1,92 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel, IDocumentData, Injector } from '@univerjs/core';
+import type { FUniver } from '@univerjs/core/facade';
+import { DisposableCollection, ILogService, IUniverInstanceService, LogLevel, Univer, UniverInstanceType } from '@univerjs/core';
+import { FUniver as FUniverCtor } from '@univerjs/core/facade';
+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
+import { BehaviorSubject } from 'rxjs';
+import { UniverDocsPlugin } from '../../plugin';
+import '../index';
+
+function getTestDocumentDataDemo(): IDocumentData {
+ return {
+ id: 'test',
+ body: {
+ dataStream: 'Hello,\r\n',
+ paragraphs: [{ startIndex: 6 }],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+export interface ITestBed {
+ univer: Univer;
+ get: Injector['get'];
+ doc: DocumentDataModel;
+ univerAPI: FUniver;
+}
+
+export function createTestBed(documentConfig?: IDocumentData): ITestBed {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+
+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+
+ univer.registerPlugin(UniverDocsPlugin);
+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ documentConfig ?? getTestDocumentDataDemo()
+ );
+
+ injector.get(IUniverInstanceService).focusUnit(doc.getUnitId());
+ injector.get(IRenderManagerService).addRender(doc.getUnitId(), {
+ unitId: doc.getUnitId(),
+ type: UniverInstanceType.UNIVER_DOC,
+ engine: new DisposableCollection() as never,
+ scene: new DisposableCollection() as never,
+ mainComponent: null,
+ components: new Map(),
+ isMainScene: true,
+ activated$: new BehaviorSubject(true),
+ with: <T>() => ({
+ getViewModel: () => ({
+ reset: () => undefined,
+ }),
+ }) as T,
+ activate: () => undefined,
+ deactivate: () => undefined,
+ isDisposed: () => false,
+ });
+
+ return {
+ univer,
+ get: injector.get.bind(injector),
+ doc,
+ univerAPI: FUniverCtor.newAPI(injector),
+ };
+}
diff --git a/packages/docs/src/facade/__tests__/f-document-node.spec.ts b/packages/docs/src/facade/__tests__/f-document-node.spec.ts
new file mode 100644
index 0000000000..84ff1e2df2
--- /dev/null
+++ b/packages/docs/src/facade/__tests__/f-document-node.spec.ts
@@ -0,0 +1,402 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentData, Univer } from '@univerjs/core';
+import type { FDocument } from '../f-document';
+import { DocumentBlockRangeType, IResourceManagerService, PresetListType, UniverInstanceType } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { DocElementStaleError } from '../doc-element-registry';
+import { createTestBed } from './create-test-bed';
+
+const DOCUMENT_STYLE: IDocumentData['documentStyle'] = {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+};
+
+function createDocumentData(id: string, body: NonNullable<IDocumentData['body']>): IDocumentData {
+ return {
+ id,
+ body: {
+ customBlocks: [],
+ ...body,
+ },
+ documentStyle: DOCUMENT_STYLE,
+ };
+}
+
+function createSimpleDocument(id = 'test'): IDocumentData {
+ return createDocumentData(id, {
+ dataStream: 'Alpha\rBeta\rGamma\r\n',
+ paragraphs: [{ startIndex: 5 }, { startIndex: 10 }, { startIndex: 16 }],
+ sectionBreaks: [{ startIndex: 17 }],
+ });
+}
+
+function createDuplicateDocument(id = 'test'): IDocumentData {
+ return createDocumentData(id, {
+ dataStream: 'Same\rSame\rTail\r\n',
+ paragraphs: [{ startIndex: 4 }, { startIndex: 9 }, { startIndex: 14 }],
+ sectionBreaks: [{ startIndex: 15 }],
+ });
+}
+
+function createTaskDocument(id = 'test'): IDocumentData {
+ return createDocumentData(id, {
+ dataStream: 'Todo\rDone\r\n',
+ paragraphs: [
+ {
+ startIndex: 4,
+ bullet: {
+ listId: 'task-list',
+ listType: PresetListType.CHECK_LIST,
+ nestingLevel: 0,
+ },
+ },
+ { startIndex: 9 },
+ ],
+ sectionBreaks: [{ startIndex: 10 }],
+ });
+}
+
+function createBulletDocument(id = 'test'): IDocumentData {
+ return createDocumentData(id, {
+ dataStream: 'Bullet\rTail\r\n',
+ paragraphs: [
+ {
+ startIndex: 6,
+ bullet: {
+ listId: 'bullet-list',
+ listType: PresetListType.BULLET_LIST,
+ nestingLevel: 0,
+ },
+ },
+ { startIndex: 11 },
+ ],
+ sectionBreaks: [{ startIndex: 12 }],
+ });
+}
+
+function createBlockRangeDocument(blockType = DocumentBlockRangeType.QUOTE, id = 'test'): IDocumentData {
+ return createDocumentData(id, {
+ dataStream: 'Block\rAfter\r\n',
+ paragraphs: [{ startIndex: 5 }, { startIndex: 11 }],
+ blockRanges: [{
+ blockId: `${blockType}-1`,
+ blockType,
+ startIndex: 0,
+ endIndex: 5,
+ }],
+ sectionBreaks: [{ startIndex: 12 }],
+ });
+}
+
+function createTableDocument(id = 'test'): IDocumentData {
+ return createDocumentData(id, {
+ dataStream: 'TT\raa\r\n',
+ paragraphs: [{ startIndex: 2 }, { startIndex: 5 }],
+ tables: [{ tableId: 'table-1', startIndex: 0, endIndex: 2 }],
+ sectionBreaks: [{ startIndex: 6 }],
+ });
+}
+
+function createCustomBlockDocument(id = 'test'): IDocumentData {
+ return createDocumentData(id, {
+ dataStream: '\b\raa\r\n',
+ paragraphs: [{ startIndex: 1 }, { startIndex: 4 }],
+ customBlocks: [{ blockId: 'custom-1', blockType: 'custom' as never, startIndex: 0 }],
+ sectionBreaks: [{ startIndex: 5 }],
+ });
+}
+
+describe('FDocument facade in Node', () => {
+ let univer: Univer;
+ let document: FDocument;
+ let get: ReturnType<typeof createTestBed>['get'];
+
+ function createDocumentFacade(docData?: IDocumentData) {
+ const testBed = createTestBed(docData);
+ univer = testBed.univer;
+ get = testBed.get;
+ document = testBed.univerAPI.getActiveDocument()!;
+ }
+
+ beforeEach(() => {
+ createDocumentFacade();
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('keeps existing FDocument methods in the docs package', async () => {
+ await expect(document.appendText('Univer')).resolves.toBe(true);
+ expect(document.save().body?.dataStream).toBe('Hello,Univer\r\n');
+
+ univer.dispose();
+ createDocumentFacade();
+ await expect(document.insertText('Docs', {
+ endOffset: 4,
+ segmentId: '',
+ startOffset: 2,
+ })).resolves.toBe(true);
+ expect(document.save().body?.dataStream).toBe('HeDocso,\r\n');
+
+ univer.dispose();
+ createDocumentFacade();
+ await expect(document.insertParagraph('Line 1\nLine 2', {
+ endOffset: 6,
+ segmentId: '',
+ startOffset: 6,
+ })).resolves.toBe(true);
+ expect(document.save().body?.dataStream).toBe('Hello,Line 1\rLine 2\r\r\n');
+ });
+
+ it('throws when appending text to a document without a body', () => {
+ univer.dispose();
+ createDocumentFacade({
+ id: 'test',
+ title: 'Test Document',
+ documentStyle: {},
+ });
+
+ expect(() => document.appendText('Univer')).toThrowError('The document body is empty');
+ });
+
+ it('includes current document resources in snapshots', () => {
+ const resourceManagerService = get(IResourceManagerService);
+
+ resourceManagerService.registerPluginResource({
+ pluginName: 'DOC_TEST_RESOURCE_PLUGIN',
+ businesses: [UniverInstanceType.UNIVER_DOC],
+ onLoad: () => undefined,
+ onUnLoad: () => undefined,
+ toJson: () => '{"value":1}',
+ parseJson: (bytes) => JSON.parse(bytes),
+ });
+
+ expect(document.save().resources).toEqual([
+ {
+ name: 'DOC_TEST_RESOURCE_PLUGIN',
+ data: '{"value":1}',
+ },
+ ]);
+ });
+
+ it('runs FDocBody paragraph and range APIs in Node', () => {
+ univer.dispose();
+ createDocumentFacade(createSimpleDocument());
+
+ const body = document.getBody();
+ expect(body.getNumChildren()).toBe(3);
+
+ const first = body.getChild(0);
+ const second = body.getChild(1).asParagraph();
+ expect(first.getType()).toBe('paragraph');
+ expect(first.getKey()).toMatch(/^paragraph-/);
+ 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.getChildIndex(second)).toBe(1);
+ expect(body.insertText(0, 'Hello ')).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Hello Alpha\rBeta\rGamma\r\n');
+
+ expect(body.insertParagraph(0, 'Title')).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Title\rHello Alpha\rBeta\rGamma\r\n');
+
+ expect(body.appendParagraph('Tail')).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Title\rHello Alpha\rBeta\rGamma\rTail\r\n');
+
+ expect(body.deleteRange({ startOffset: 0, endOffset: 6 })).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Hello Alpha\rBeta\rGamma\rTail\r\n');
+
+ expect(body.replaceRange({ startOffset: 0, endOffset: 5 }, 'Hi')).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Hi Alpha\rBeta\rGamma\rTail\r\n');
+
+ expect(body.setTextStyle({ startOffset: 0, endOffset: 2 }, { bl: 1 })).toBe(true);
+ expect(document.save().body?.textRuns).toContainEqual({
+ st: 0,
+ ed: 2,
+ ts: { bl: 1 },
+ });
+
+ const paragraph = body.getChild(0).asParagraph();
+ expect(body.setParagraphStyle(paragraph, { 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(body.setParagraphText(paragraph.getKey(), 'Updated')).toBe(true);
+ expect(paragraph.getText()).toBe('Updated');
+ expect(body.appendParagraphText(paragraph.getKey(), ' suffix')).toBe(true);
+ expect(paragraph.getText()).toBe('Updated suffix');
+ expect(body.removeParagraph(paragraph.getKey())).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Beta\rGamma\rTail\r\n');
+ });
+
+ it('keeps paragraph wrappers stable for insert-before and duplicate text', () => {
+ univer.dispose();
+ createDocumentFacade(createDuplicateDocument());
+
+ const body = document.getBody();
+ const secondSame = body.getChild(1).asParagraph();
+
+ expect(body.insertParagraph(0, 'X')).toBe(true);
+ expect(body.getChildIndex(secondSame)).toBe(2);
+ expect(secondSame.setText('Picked')).toBe(true);
+ expect(document.save().body?.dataStream).toBe('X\rSame\rPicked\rTail\r\n');
+ });
+
+ it('marks deleted paragraph wrappers as stale', () => {
+ univer.dispose();
+ createDocumentFacade(createSimpleDocument());
+
+ const paragraph = document.getBody().getChild(1).asParagraph();
+ expect(paragraph.removeFromParent()).toBe(true);
+ expect(() => paragraph.getText()).toThrow(DocElementStaleError);
+ });
+
+ it('runs FDocParagraph list and task APIs in Node', () => {
+ univer.dispose();
+ createDocumentFacade(createBulletDocument());
+
+ const bulletBody = document.getBody();
+ const listItem = bulletBody.getChild(0).asParagraph();
+ expect(listItem.getType()).toBe('paragraph');
+ expect(listItem.getKey()).toMatch(/^paragraph-/);
+ expect(listItem.getParent()).toBe(bulletBody);
+ expect(listItem.isListItem()).toBe(true);
+ expect(listItem.isTask()).toBe(false);
+
+ univer.dispose();
+ createDocumentFacade(createTaskDocument());
+
+ const task = document.getBody().getChild(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(document.save().body?.paragraphs?.[0].bullet?.listType).toBe(PresetListType.CHECK_LIST);
+ });
+
+ it('runs FDocElement cast APIs in Node', () => {
+ univer.dispose();
+ createDocumentFacade(createSimpleDocument());
+ expect(document.getBody().getChild(0).asParagraph().getText()).toBe('Alpha');
+
+ univer.dispose();
+ createDocumentFacade(createBlockRangeDocument());
+ expect(document.getBody().getChild(0).asBlockRange().getBlockType()).toBe(DocumentBlockRangeType.QUOTE);
+
+ univer.dispose();
+ createDocumentFacade(createTableDocument());
+ expect(document.getBody().getChild(0).asTable().getTableId()).toBe('table-1');
+
+ univer.dispose();
+ createDocumentFacade(createCustomBlockDocument());
+ expect(document.getBody().getChild(0).asCustomBlock().getBlockId()).toBe('custom-1');
+ });
+
+ it('runs FDocBlockRange APIs in Node', () => {
+ for (const blockType of [DocumentBlockRangeType.QUOTE, DocumentBlockRangeType.CALLOUT, DocumentBlockRangeType.CODE]) {
+ univer.dispose();
+ createDocumentFacade(createBlockRangeDocument(blockType));
+
+ const body = document.getBody();
+ const block = body.getChild(0).asBlockRange();
+
+ expect(block.getType()).toBe('blockRange');
+ 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(body.insertParagraph(0, 'Intro')).toBe(true);
+ expect(block.getText()).toBe('Block');
+ expect(block.setText('Updated')).toBe(true);
+ expect(body.getBlockRangeText(block.getKey())).toBe('Updated');
+ expect(block.removeFromParent()).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Intro\rAfter\r\n');
+ }
+
+ univer.dispose();
+ createDocumentFacade(createBlockRangeDocument());
+ expect(document.getBody().getChild(0).asBlockRange().unwrap()).toBe(true);
+ expect(document.save().body?.dataStream).toBe('After\r\n');
+ });
+
+ it('runs FDocTable APIs in Node', () => {
+ univer.dispose();
+ createDocumentFacade(createTableDocument());
+
+ const body = document.getBody();
+ const table = body.getChild(0).asTable();
+
+ expect(table.getType()).toBe('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(document.save().body?.tables).toEqual([]);
+
+ univer.dispose();
+ createDocumentFacade(createTableDocument());
+ expect(document.getBody().removeTable('table-1')).toBe(true);
+ expect(document.save().body?.dataStream).toBe('aa\r\n');
+ });
+
+ it('runs FDocCustomBlock APIs in Node', () => {
+ univer.dispose();
+ createDocumentFacade(createCustomBlockDocument());
+
+ const body = document.getBody();
+ const customBlock = body.getChild(0).asCustomBlock();
+
+ expect(customBlock.getType()).toBe('customBlock');
+ 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(document.save().body?.customBlocks).toEqual([]);
+
+ univer.dispose();
+ createDocumentFacade(createCustomBlockDocument());
+ expect(document.getBody().removeCustomBlock('custom-1')).toBe(true);
+ expect(document.save().body?.dataStream).toBe('\raa\r\n');
+ });
+
+ it('removes a generic element from its parent in Node', () => {
+ univer.dispose();
+ createDocumentFacade(createSimpleDocument());
+
+ expect(document.getBody().getChild(0).removeFromParent()).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Beta\rGamma\r\n');
+ });
+});
diff --git a/packages/docs/src/facade/doc-element-registry.ts b/packages/docs/src/facade/doc-element-registry.ts
new file mode 100644
index 0000000000..2ce7928641
--- /dev/null
+++ b/packages/docs/src/facade/doc-element-registry.ts
@@ -0,0 +1,197 @@
+/**
+ * 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';
+import { generateRandomId } from '@univerjs/core';
+
+/**
+ * The top-level document body element types supported by the doc facade.
+ */
+export type FDocElementType = 'paragraph' | 'table' | 'blockRange' | 'customBlock';
+
+interface IParagraphRegistryEntry {
+ key: string;
+ segmentId: string;
+ startIndex: number;
+ stale: boolean;
+}
+
+/**
+ * Error thrown when a facade element key can no longer be resolved uniquely.
+ *
+ * A stale paragraph usually means the paragraph was deleted, or an external edit
+ * changed the document in a way that the runtime temporary key cannot follow.
+ *
+ * @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';
+ }
+}
+
+/**
+ * Runtime registry for temporary paragraph keys.
+ *
+ * The registry is owned by an `FDocument` instance. It never writes keys into the
+ * document snapshot. Facade edits notify the registry before text changes so
+ * paragraph keys can move with their source paragraph or become stale when the
+ * source paragraph is removed.
+ *
+ * @hideconstructor
+ */
+export class DocElementRegistry {
+ private readonly _paragraphsBySegment = new Map<string, IParagraphRegistryEntry[]>();
+
+ /**
+ * Get or create the runtime key for a paragraph in a segment.
+ * @param {string} segmentId The header/footer segment id, or an empty string for the main body.
+ * @param {IDocumentBody} body The current document body snapshot.
+ * @param {number} paragraphIndex The zero-based paragraph index.
+ * @returns {string} The runtime key for the paragraph.
+ */
+ getParagraphKey(segmentId: string, body: IDocumentBody, paragraphIndex: number): string {
+ const paragraph = body.paragraphs?.[paragraphIndex];
+ if (!paragraph) {
+ throw new RangeError(`Paragraph index ${paragraphIndex} is out of range.`);
+ }
+
+ const entries = this._getSegmentEntries(segmentId);
+ const activeEntry = entries.find((entry) => !entry.stale && entry.startIndex === paragraph.startIndex);
+ if (activeEntry) {
+ return activeEntry.key;
+ }
+
+ const key = `paragraph-${generateRandomId(10)}`;
+ entries.push({
+ key,
+ segmentId,
+ startIndex: paragraph.startIndex,
+ stale: false,
+ });
+
+ return key;
+ }
+
+ /**
+ * Resolve a paragraph runtime key to its tracked paragraph break offset.
+ * @param {string} segmentId The header/footer segment id, or an empty string for the main body.
+ * @param {string} key The runtime paragraph key.
+ * @returns {number} The tracked paragraph `startIndex`.
+ * @throws {DocElementStaleError} If the key is missing or stale.
+ */
+ resolveParagraphStartIndex(segmentId: string, key: string): number {
+ const entry = this._getSegmentEntries(segmentId).find((item) => item.key === key);
+ if (!entry || entry.stale) {
+ throw new DocElementStaleError();
+ }
+
+ return entry.startIndex;
+ }
+
+ /**
+ * Resolve a paragraph runtime key against the current body.
+ * @param {string} segmentId The header/footer segment id, or an empty string for the main body.
+ * @param {string} key The runtime paragraph key.
+ * @param {IDocumentBody} body The current document body snapshot.
+ * @returns {number} The current paragraph index in `body.paragraphs`.
+ * @throws {DocElementStaleError} If the tracked paragraph no longer exists.
+ */
+ syncParagraph(segmentId: string, key: string, body: IDocumentBody): number {
+ const startIndex = this.resolveParagraphStartIndex(segmentId, key);
+ const paragraphIndex = body.paragraphs?.findIndex((paragraph) => paragraph.startIndex === startIndex) ?? -1;
+
+ if (paragraphIndex < 0) {
+ this.markStale(segmentId, key);
+ throw new DocElementStaleError();
+ }
+
+ return paragraphIndex;
+ }
+
+ /**
+ * Mark a paragraph runtime key as stale.
+ * @param {string} segmentId The header/footer segment id, or an empty string for the main body.
+ * @param {string} key The runtime paragraph key.
+ * @returns {void}
+ */
+ markStale(segmentId: string, key: string): void {
+ const entry = this._getSegmentEntries(segmentId).find((item) => item.key === key);
+ if (entry) {
+ entry.stale = true;
+ }
+ }
+
+ /**
+ * Update tracked paragraph offsets before a facade text edit is applied.
+ *
+ * Paragraphs inside the deleted range are marked stale. Paragraphs after the
+ * edited range move by the inserted length minus deleted length.
+ *
+ * @param {string} segmentId The header/footer segment id, or an empty string for the main body.
+ * @param {number} startOffset The inclusive start offset of the edit.
+ * @param {number} endOffset The exclusive end offset of the replaced range.
+ * @param {number} insertLength The data stream length inserted by the edit.
+ * @returns {void}
+ */
+ beforeTextEdit(segmentId: string, startOffset: number, endOffset: number, insertLength: number): void {
+ const deleteLength = Math.max(0, endOffset - startOffset);
+ const delta = insertLength - deleteLength;
+
+ for (const entry of this._getSegmentEntries(segmentId)) {
+ if (entry.stale) {
+ continue;
+ }
+
+ if (entry.startIndex >= startOffset && entry.startIndex < endOffset) {
+ entry.stale = true;
+ } else if (entry.startIndex >= endOffset) {
+ entry.startIndex += delta;
+ }
+ }
+ }
+
+ private _getSegmentEntries(segmentId: string): IParagraphRegistryEntry[] {
+ const key = segmentId || '';
+ let entries = this._paragraphsBySegment.get(key);
+ if (!entries) {
+ entries = [];
+ this._paragraphsBySegment.set(key, entries);
+ }
+
+ return entries;
+ }
+}
diff --git a/packages/docs/src/facade/f-doc-block-range.ts b/packages/docs/src/facade/f-doc-block-range.ts
new file mode 100644
index 0000000000..157cf2b4bd
--- /dev/null
+++ b/packages/docs/src/facade/f-doc-block-range.ts
@@ -0,0 +1,166 @@
+/**
+ * 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
new file mode 100644
index 0000000000..2b98a96a5b
--- /dev/null
+++ b/packages/docs/src/facade/f-doc-body.ts
@@ -0,0 +1,933 @@
+/**
+ * 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 { 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 runtime or 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';
+
+/**
+ * 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 runtime temporary keys that remain stable for this `FDocument`
+ * facade instance. Tables, block ranges, and custom blocks use their persisted ids.
+ *
+ * @hideconstructor
+ */
+export class FDocBody {
+ constructor(
+ private readonly _documentDataModel: DocumentDataModel,
+ private readonly _commandService: ICommandService,
+ private readonly _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 {boolean} `true` if the paragraph was inserted.
+ * @example
+ * ```ts
+ * const doc = univerAPI.getActiveDocument();
+ * if (!doc) throw new Error('No active document');
+ *
+ * const body = doc.getBody();
+ * body.insertParagraph(0, 'Document title');
+ * ```
+ */
+ insertParagraph(index: number, text = ''): boolean {
+ const offset = this._getParagraphInsertOffset(index);
+ return this._replaceBodyRange({ startOffset: offset, endOffset: offset }, buildPlainTextInsertBody(`${text}\r`));
+ }
+
+ /**
+ * Append a plain-text paragraph at the end of the body.
+ * @param {string} text The paragraph text. Defaults to an empty paragraph.
+ * @returns {boolean} `true` if the paragraph was appended.
+ * @example
+ * ```ts
+ * const doc = univerAPI.getActiveDocument();
+ * if (!doc) throw new Error('No active document');
+ *
+ * const body = doc.getBody();
+ * body.appendParagraph('Summary');
+ * ```
+ */
+ appendParagraph(text = ''): boolean {
+ 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,
+ },
+ }],
+ };
+
+ return this._retainBodyRange(
+ { startOffset: resolved.endOffset, endOffset: resolved.endOffset + 1 },
+ updateBody,
+ UpdateDocsAttributeType.REPLACE
+ );
+ }
+
+ /**
+ * Get the text content of a paragraph by runtime key.
+ * @param {string} key The paragraph runtime key.
+ * @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 runtime key.
+ * @param {string} key The paragraph runtime key.
+ * @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 runtime key.
+ * @param {string} key The paragraph runtime key.
+ * @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 runtime key.
+ * @param {string} key The paragraph runtime key.
+ * @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 runtime key.
+ * @param {string} key The paragraph runtime key.
+ * @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 runtime key.
+ * @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 runtime key.
+ * @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 runtime key.
+ * @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,
+ },
+ }],
+ };
+
+ return this._retainBodyRange(
+ { startOffset: resolved.endOffset, endOffset: resolved.endOffset + 1 },
+ updateBody,
+ UpdateDocsAttributeType.REPLACE
+ );
+ }
+
+ /**
+ * Resolve a paragraph runtime key to its current paragraph metadata.
+ * @param {string} key The paragraph runtime key.
+ * @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 paragraphIndex = this._registry.syncParagraph(this._segmentId, key, body);
+ const paragraph = body.paragraphs![paragraphIndex];
+ 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 runtime or 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._registry.getParagraphKey(this._segmentId, body, 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 _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(range, textX, insertBody.dataStream.length);
+ }
+
+ 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(range, textX, range.endOffset - range.startOffset, false);
+ }
+
+ 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(range: IFDocTextRange, textX: TextX, insertLength: number, trackTextEdit = true): boolean {
+ if (trackTextEdit) {
+ this._registry.beforeTextEdit(this._segmentId, range.startOffset, range.endOffset, insertLength);
+ }
+
+ 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
new file mode 100644
index 0000000000..5cec5bc8e8
--- /dev/null
+++ b/packages/docs/src/facade/f-doc-custom-block.ts
@@ -0,0 +1,112 @@
+/**
+ * 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
new file mode 100644
index 0000000000..940babbbf4
--- /dev/null
+++ b/packages/docs/src/facade/f-doc-element.ts
@@ -0,0 +1,231 @@
+/**
+ * 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 runtime temporary keys for the current `FDocument` facade
+ * lifecycle. 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 runtime paragraph key or persisted table/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
new file mode 100644
index 0000000000..a60a1f1488
--- /dev/null
+++ b/packages/docs/src/facade/f-doc-paragraph.ts
@@ -0,0 +1,218 @@
+/**
+ * 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 a runtime temporary key. The key is stable for
+ * the current `FDocument` facade lifecycle and is re-resolved before each method
+ * call, so insertions before this paragraph made through the facade 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 runtime key used to resolve this paragraph.
+ * @returns {string} The paragraph runtime key for the current `FDocument` facade lifecycle.
+ * @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 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
new file mode 100644
index 0000000000..2a5db79f3b
--- /dev/null
+++ b/packages/docs/src/facade/f-doc-table.ts
@@ -0,0 +1,112 @@
+/**
+ * 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.ts b/packages/docs/src/facade/f-document.ts
index 268acd0266..b044248f02 100644
--- a/packages/docs/src/facade/f-document.ts
+++ b/packages/docs/src/facade/f-document.ts
@@ -27,6 +27,8 @@ 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 {
buildPlainTextInsertBody,
getNormalizedPlainTextCursorOffset,
@@ -46,6 +48,7 @@ export interface IDocumentInsertTextFacadeOptions {
*/
export class FDocument extends FBaseInitialable {
readonly id: string;
+ private readonly _docElementRegistry = new DocElementRegistry();
constructor(
private readonly _documentDataModel: DocumentDataModel,
@@ -73,6 +76,34 @@ export class FDocument extends FBaseInitialable {
return this._documentDataModel;
}
+ /**
+ * Get the document body facade.
+ *
+ * The returned body facade provides synchronous Google Docs-like element APIs
+ * for reading and editing top-level document body elements. Paragraph elements
+ * receive runtime temporary keys that remain stable for this `FDocument`
+ * facade lifecycle. Persisted elements, such as tables and custom blocks, use
+ * their existing ids.
+ *
+ * @returns {FDocBody} The document body API instance.
+ * @example
+ * ```typescript
+ * const doc = univerAPI.getActiveDocument();
+ * if (!doc) throw new Error('No active document');
+ *
+ * const body = doc.getBody();
+ * const paragraph = body.getChild(0).asParagraph();
+ * paragraph.appendText(' updated');
+ * ```
+ */
+ getBody(): FDocBody {
+ return new FDocBody(
+ this._documentDataModel,
+ this._commandService,
+ this._docElementRegistry
+ );
+ }
+
override dispose(): void {
super.dispose();
}
diff --git a/packages/docs/src/facade/index.ts b/packages/docs/src/facade/index.ts
index 35cde4a7b3..a308636b6d 100644
--- a/packages/docs/src/facade/index.ts
+++ b/packages/docs/src/facade/index.ts
@@ -16,6 +16,13 @@
import './f-univer';
+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';