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): keep only paragraph APIs in docs package facade (#7175)

wpxp123456fae37bbbd44a
diff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts
index 74bd9b8cd7..90a56238d2 100644
--- a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts
+++ b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts
@@ -242,7 +242,7 @@ test('diff set force string cell', async () => {
activeWorkbook.startEditing();
const activeDocument = window.univerAPI.getActiveDocument();
- activeDocument.getBody().getElement(0)?.asParagraph().appendText("'1");
+ activeDocument.getParagraphs()[0]?.appendText("'1");
await activeWorkbook.endEditingAsync(true);
activeSheet.getRange('I1').setValue({
diff --git a/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.ts b/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.ts
index da2d1b8025..4d9ca76547 100644
--- a/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.ts
+++ b/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.ts
@@ -173,11 +173,6 @@ describe('DocumentDataModel + RichTextBuilder integration', () => {
expect(model.zoomRatio).toBe(1.5);
expect(model.getDisabled()).toBe(true);
- const headerModel = model.getSelfOrHeaderFooterModel('header1');
- const footerModel = model.getSelfOrHeaderFooterModel('footer1');
- expect(headerModel.getUnitId()).toBe(model.getUnitId());
- expect(footerModel.getUnitId()).toBe(model.getUnitId());
-
const richText = RichTextBuilder.create(RichTextBuilder.newEmptyData());
richText
.insertText('Hello')
diff --git a/packages/core/src/docs/data-model/document-data-model.ts b/packages/core/src/docs/data-model/document-data-model.ts
index 1e1b3e2826..5aacc2ca09 100644
--- a/packages/core/src/docs/data-model/document-data-model.ts
+++ b/packages/core/src/docs/data-model/document-data-model.ts
@@ -336,18 +336,20 @@ export class DocumentDataModel extends DocumentDataModelSimple {
this.change$.next(this.change$.value + 1);
}
- getSelfOrHeaderFooterModel(segmentId?: string) {
- if (segmentId != null) {
- if (this.headerModelMap.has(segmentId)) {
- return this.headerModelMap.get(segmentId)!;
- }
+ getSelfOrHeaderFooterModel(segmentId?: string): DocumentDataModel | null {
+ if (segmentId === null || segmentId === undefined || segmentId === '') {
+ return this;
+ }
- if (this.footerModelMap.has(segmentId)) {
- return this.footerModelMap.get(segmentId)!;
- }
+ if (this.headerModelMap.has(segmentId)) {
+ return this.headerModelMap.get(segmentId)!;
+ }
+
+ if (this.footerModelMap.has(segmentId)) {
+ return this.footerModelMap.get(segmentId)!;
}
- return this as DocumentDataModel;
+ return null;
}
override getUnitId() {
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/paragraph.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/paragraph.spec.ts
index c1ac56781d..1e1b6f8e74 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/__tests__/paragraph.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/paragraph.spec.ts
@@ -165,6 +165,30 @@ describe('paragraph build utils', () => {
expect(body.paragraphs?.[2].bullet?.nestingLevel).toBe(1);
});
+ it('should set bullets with an explicit list id', () => {
+ const doc = createDocModel();
+ const body = doc.getBody()!;
+ const thirdParagraph = body.paragraphs![2] as IParagraph;
+
+ const textX = setParagraphBullet({
+ paragraphs: [thirdParagraph],
+ listType: PresetListType.ORDER_LIST,
+ listId: 'agent-list-id',
+ document: doc,
+ });
+
+ if (textX === false) {
+ throw new Error('Expected setParagraphBullet to return TextX actions');
+ }
+
+ TextX.apply(body, textX.serialize());
+
+ expect(body.paragraphs?.[2].bullet).toMatchObject({
+ listId: 'agent-list-id',
+ listType: PresetListType.ORDER_LIST,
+ });
+ });
+
it('should set paragraph styles across selected ranges and optionally add text runs', () => {
const doc = createDocModel();
const body = doc.getBody()!;
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/drawings.ts b/packages/core/src/docs/data-model/text-x/build-utils/drawings.ts
index 381cbc6a4a..130ca46363 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/drawings.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/drawings.ts
@@ -20,8 +20,8 @@ import type { DocumentDataModel } from '../../document-data-model';
import type { JSONXActions } from '../../json-x/json-x';
import { createParagraphId } from '../../../paragraph-id';
import { JSONX } from '../../json-x/json-x';
-import { TextXActionType } from '../action-types';
import { DataStreamTreeTokenType } from '../../types';
+import { TextXActionType } from '../action-types';
import { TextX } from '../text-x';
import { getRichTextEditPath } from '../utils';
import { deleteSelectionTextX } from './text-x-utils';
@@ -62,7 +62,7 @@ export const addDrawing = (param: IAddDrawingParam) => {
const textX = new TextX();
const jsonX = JSONX.getInstance();
const rawActions: JSONXActions = [];
- const body = documentDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const body = documentDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (!body) {
return false;
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/paragraph.ts b/packages/core/src/docs/data-model/text-x/build-utils/paragraph.ts
index 6dad0364c6..e594ae1cfb 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/paragraph.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/paragraph.ts
@@ -35,7 +35,7 @@ export interface ISwitchParagraphBulletParams {
export const switchParagraphBullet = (params: ISwitchParagraphBulletParams) => {
const { paragraphs: currentParagraphs, segmentId, document: docDataModel } = params;
let listType = params.listType;
- const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs ?? [];
+ const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.paragraphs ?? [];
const isAlreadyList = currentParagraphs.every((paragraph) => paragraph.bullet?.listType.indexOf(listType) === 0);
const ID_LENGTH = 6;
@@ -120,7 +120,7 @@ export interface IToggleChecklistParagraphParams {
export const toggleChecklistParagraph = (params: IToggleChecklistParagraphParams) => {
const { paragraphIndex, segmentId, document: docDataModel } = params;
- const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs;
+ const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.paragraphs;
if (paragraphs == null) {
return false;
}
@@ -174,20 +174,21 @@ export const toggleChecklistParagraph = (params: IToggleChecklistParagraphParams
export interface ISetParagraphBulletParams {
paragraphs: IParagraph[];
listType: string;
+ listId?: string;
segmentId?: string;
document: DocumentDataModel;
}
export const setParagraphBullet = (params: ISetParagraphBulletParams) => {
- const { paragraphs: currentParagraphs, listType, segmentId, document: docDataModel } = params;
- const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs;
+ const { paragraphs: currentParagraphs, listType, listId: explicitListId, segmentId, document: docDataModel } = params;
+ const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.paragraphs;
if (paragraphs == null) {
return false;
}
const ID_LENGTH = 6;
- const listId = generateRandomId(ID_LENGTH);
+ const listId = explicitListId ?? generateRandomId(ID_LENGTH);
const memoryCursor = new MemoryCursor();
@@ -337,8 +338,8 @@ export const setParagraphStyle = (params: ISetParagraphStyleParams) => {
textX: _textX,
} = params;
const segment = docDataModel.getSelfOrHeaderFooterModel(segmentId);
- const paragraphs = segment.getBody()?.paragraphs ?? [];
- const dataStream = segment.getBody()?.dataStream ?? '';
+ const paragraphs = segment?.getBody()?.paragraphs ?? [];
+ const dataStream = segment?.getBody()?.dataStream ?? '';
const currentParagraphs = getParagraphsInRanges(textRanges, paragraphs, dataStream);
const memoryCursor = new MemoryCursor();
if (cursor) {
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts b/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
index 5604a84003..eddc28f66d 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/text-x-utils.ts
@@ -37,7 +37,7 @@ export interface IDeleteCustomRangeParam {
export function deleteCustomRangeTextX(params: IDeleteCustomRangeParam) {
const { rangeId, segmentId, documentDataModel, insert } = params;
- const range = documentDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.customRanges?.find((r) => r.rangeId === rangeId);
+ const range = documentDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.customRanges?.find((r) => r.rangeId === rangeId);
if (!range) {
return false;
}
diff --git a/packages/core/src/services/instance/__tests__/instance.service.spec.ts b/packages/core/src/services/instance/__tests__/instance.service.spec.ts
index 2778506ce6..21896c7ec9 100644
--- a/packages/core/src/services/instance/__tests__/instance.service.spec.ts
+++ b/packages/core/src/services/instance/__tests__/instance.service.spec.ts
@@ -168,11 +168,11 @@ describe('UniverInstanceService', () => {
const replacement = new DocumentDataModel(createDocData('doc-unit'));
service.changeDoc(doc.getUnitId(), replacement);
- expect(service.getUniverDocInstance('doc-unit')).toBe(replacement);
+ expect(service.getUnit('doc-unit')).toBe(replacement);
expect(service.disposeUnit('doc-unit')).toBe(true);
expect(disposed).toEqual(['doc-unit']);
- expect(service.getCurrentUniverDocInstance()).toBeNull();
+ expect(service.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)).toBeNull();
expect(service.getFocusedUnit()).toBeUndefined();
expect(service.disposeUnit('missing')).toBe(false);
});
diff --git a/packages/core/src/services/instance/instance.service.ts b/packages/core/src/services/instance/instance.service.ts
index e2829124d5..ec83340c12 100644
--- a/packages/core/src/services/instance/instance.service.ts
+++ b/packages/core/src/services/instance/instance.service.ts
@@ -98,10 +98,6 @@ export interface IUniverInstanceService {
/** @deprecated */
getUniverSheetInstance(unitId: string): Nullable<Workbook>;
- /** @deprecated */
- getUniverDocInstance(unitId: string): Nullable<DocumentDataModel>;
- /** @deprecated */
- getCurrentUniverDocInstance(): Nullable<DocumentDataModel>;
}
export const IUniverInstanceService = createIdentifier<IUniverInstanceService>('univer.current');
@@ -225,14 +221,6 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
return unit;
}
- getCurrentUniverDocInstance(): Nullable<DocumentDataModel> {
- return this.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC) as Nullable<DocumentDataModel>;
- }
-
- getUniverDocInstance(unitId: string): Nullable<DocumentDataModel> {
- return this.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- }
-
getUniverSheetInstance(unitId: string): Nullable<Workbook> {
return this.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
}
diff --git a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts
index 3fe7d80122..89c9c2b59d 100644
--- a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts
+++ b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts
@@ -884,8 +884,8 @@ describe('docs drawing commands integration', () => {
expect(doc.getBody()?.dataStream).toBe('AB\r\n');
expect(doc.getBody()?.customBlocks).toEqual([]);
- expect(header.getBody()?.dataStream).toBe('He\bader\r\n');
- expect(header.getBody()?.customBlocks).toEqual([{ startIndex: 2, blockId: 'shape-1' }]);
+ expect(header?.getBody()?.dataStream).toBe('He\bader\r\n');
+ expect(header?.getBody()?.customBlocks).toEqual([{ startIndex: 2, blockId: 'shape-1' }]);
expect(testBed.refreshControls).toHaveBeenCalled();
testBed.univer.dispose();
diff --git a/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts
index 4aa70d36aa..bc6b595f71 100644
--- a/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts
+++ b/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IAccessor, ICommand, IMutationInfo, ITextRangeParam, JSONXActions } from '@univerjs/core';
+import type { DocumentDataModel, IAccessor, ICommand, IMutationInfo, ITextRangeParam, JSONXActions } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { IInsertDrawingCommandParams } from './interfaces';
import {
@@ -26,6 +26,7 @@ import {
JSONX,
TextX,
TextXActionType,
+ UniverInstanceType,
} from '@univerjs/core';
import { DocContentInsertService, DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { getCustomBlockIdsInSelections } from '@univerjs/docs-ui';
@@ -48,7 +49,7 @@ export const InsertDocDrawingCommand: ICommand = {
const univerInstanceService = accessor.get(IUniverInstanceService);
const activeTextRange = docSelectionManagerService.getActiveTextRange();
- const documentDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const documentDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (documentDataModel == null) {
return false;
}
@@ -71,7 +72,7 @@ export const InsertDocDrawingCommand: ICommand = {
const { drawings } = params;
const { collapsed, startOffset, segmentId = '' } = targetTextRange;
- const body = documentDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const body = documentDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (body == null) {
return false;
diff --git a/packages/docs-drawing-ui/src/commands/commands/move-drawings.command.ts b/packages/docs-drawing-ui/src/commands/commands/move-drawings.command.ts
index 30a5bb85e8..994d981b4b 100644
--- a/packages/docs-drawing-ui/src/commands/commands/move-drawings.command.ts
+++ b/packages/docs-drawing-ui/src/commands/commands/move-drawings.command.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IAccessor, ICommand } from '@univerjs/core';
+import type { DocumentDataModel, IAccessor, ICommand } from '@univerjs/core';
import type { IDocDrawing } from '@univerjs/docs-drawing';
import type { IDrawingDocTransform, IUpdateDrawingDocTransformParams } from './update-doc-drawing.command';
import {
@@ -23,6 +23,7 @@ import {
ICommandService,
IUniverInstanceService,
PositionedObjectLayoutType,
+ UniverInstanceType,
} from '@univerjs/core';
import { IDocDrawingService } from '@univerjs/docs-drawing';
import { IRenderManagerService } from '@univerjs/engine-render';
@@ -60,7 +61,7 @@ export const MoveDocDrawingsCommand: ICommand = {
}
const transformer = scene.getTransformerByCreate();
- const documentDataModel = univerInstanceService.getUniverDocInstance(unitId);
+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
const newDrawings = drawings.map((drawing) => {
const { drawingId } = drawing as IDocDrawing;
diff --git a/packages/docs-drawing-ui/src/commands/commands/remove-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/remove-doc-drawing.command.ts
index 5ce7e34bf0..97e01aed39 100644
--- a/packages/docs-drawing-ui/src/commands/commands/remove-doc-drawing.command.ts
+++ b/packages/docs-drawing-ui/src/commands/commands/remove-doc-drawing.command.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IAccessor, ICommand, IMutationInfo, JSONXActions } from '@univerjs/core';
+import type { DocumentDataModel, IAccessor, ICommand, IMutationInfo, JSONXActions } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IDeleteDrawingCommandParams } from './interfaces';
@@ -27,6 +27,7 @@ import {
MemoryCursor,
TextX,
TextXActionType,
+ UniverInstanceType,
} from '@univerjs/core';
import { RichTextEditingMutation } from '@univerjs/docs';
import { DocSelectionRenderService } from '@univerjs/docs-ui';
@@ -43,7 +44,7 @@ export const RemoveDocDrawingCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const renderManagerService = accessor.get(IRenderManagerService);
- const documentDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const documentDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (params == null || documentDataModel == null) {
return false;
@@ -57,7 +58,7 @@ export const RemoveDocDrawingCommand: ICommand = {
const textX = new TextX();
const jsonX = JSONX.getInstance();
- const customBlocks = documentDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.customBlocks ?? [];
+ const customBlocks = documentDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.customBlocks ?? [];
const removeCustomBlocks = removeDrawings
.map((drawing) => customBlocks.find((customBlock) => customBlock.blockId === drawing.drawingId))
.filter((block) => !!block)
diff --git a/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.ts
index 33d8731ecb..7d513147ab 100644
--- a/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.ts
+++ b/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.ts
@@ -31,6 +31,7 @@ import {
TextX,
TextXActionType,
Tools,
+ UniverInstanceType,
} from '@univerjs/core';
import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { DocSelectionRenderService } from '@univerjs/docs-ui';
@@ -102,8 +103,8 @@ function getDeleteAndInsertCustomBlockActions(
const jsonX = JSONX.getInstance();
const rawActions: JSONXActions = [];
- const oldBody = documentDataModel.getSelfOrHeaderFooterModel(oldSegmentId).getBody();
- const body = documentDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const oldBody = documentDataModel.getSelfOrHeaderFooterModel(oldSegmentId)?.getBody();
+ const body = documentDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (oldBody == null || body == null) {
return;
@@ -270,7 +271,7 @@ export const UpdateDocDrawingWrappingStyleCommand: ICommand = {
.getSkeletonData();
const viewModel = renderObject?.with(DocSkeletonManagerService).getViewModel();
const scene = renderObject?.scene;
- const documentDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const documentDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (documentDataModel == null || skeletonData == null || scene == null || viewModel == null) {
return false;
@@ -452,13 +453,12 @@ export const UpdateDocDrawingDistanceCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const documentDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const { drawings, dist, unitId } = params;
+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
if (documentDataModel == null) {
return false;
}
- const { drawings, dist, unitId } = params;
-
const jsonX = JSONX.getInstance();
const rawActions: JSONXActions = [];
@@ -523,13 +523,12 @@ export const UpdateDocDrawingWrapTextCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const documentDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const { drawings, wrapText, unitId } = params;
+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
if (documentDataModel == null) {
return false;
}
- const { drawings, wrapText, unitId } = params;
-
const jsonX = JSONX.getInstance();
const rawActions: JSONXActions = [];
@@ -599,20 +598,20 @@ export const UpdateDrawingDocTransformCommand: ICommand = {
const univerInstanceService = accessor.get(IUniverInstanceService);
const renderManagerService = accessor.get(IRenderManagerService);
- const renderObject = renderManagerService.getRenderById(params.unitId);
+ const { drawings, unitId } = params;
+ const renderObject = renderManagerService.getRenderUnitById(unitId);
const scene = renderObject?.scene;
if (scene == null) {
return false;
}
+
const transformer = scene.getTransformerByCreate();
- const documentDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
if (documentDataModel == null) {
return false;
}
- const { drawings, unitId } = params;
-
const jsonX = JSONX.getInstance();
const rawActions: JSONXActions = [];
@@ -679,28 +678,29 @@ export const IMoveInlineDrawingCommand: ICommand = {
return false;
}
+ const { drawing, unitId, offset, segmentId: newSegmentId, segmentPage, needRefreshDrawings } = params;
+
const renderManagerService = accessor.get(IRenderManagerService);
- const docSelectionRenderService = renderManagerService.getRenderById(params.unitId)?.with(DocSelectionRenderService);
+ const docSelectionRenderService = renderManagerService.getRenderUnitById(unitId)?.with(DocSelectionRenderService);
const docRefreshDrawingsService = accessor.get(DocRefreshDrawingsService);
- const renderObject = renderManagerService.getRenderById(params.unitId);
+ const renderObject = renderManagerService.getRenderUnitById(unitId);
const scene = renderObject?.scene;
const skeleton = renderObject?.with(DocSkeletonManagerService).getSkeleton();
if (scene == null || docSelectionRenderService == null) {
return false;
}
+
const transformer = scene.getTransformerByCreate();
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const documentDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
if (documentDataModel == null) {
return false;
}
- const { drawing, unitId, offset, segmentId: newSegmentId, segmentPage, needRefreshDrawings } = params;
-
// Need to refresh drawings if not find the anchor position.
if (needRefreshDrawings) {
docRefreshDrawingsService.refreshDrawings(skeleton);
@@ -779,26 +779,27 @@ export const ITransformNonInlineDrawingCommand: ICommand = {
return false;
}
- const renderManagerService = accessor.get(IRenderManagerService);
+ const { drawing, unitId, offset, docTransform, segmentId: newSegmentId, segmentPage } = params;
- const docSelectionRenderService = renderManagerService.getRenderById(params.unitId)?.with(DocSelectionRenderService);
+ const renderManagerService = accessor.get(IRenderManagerService);
+ const docSelectionRenderService = renderManagerService.getRenderUnitById(unitId)?.with(DocSelectionRenderService);
- const renderObject = renderManagerService.getRenderById(params.unitId);
+ const renderObject = renderManagerService.getRenderUnitById(unitId);
const scene = renderObject?.scene;
if (scene == null || docSelectionRenderService == null) {
return false;
}
+
const transformer = scene.getTransformerByCreate();
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const documentDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
if (documentDataModel == null) {
return false;
}
- const { drawing, unitId, offset, docTransform, segmentId: newSegmentId, segmentPage } = params;
const rawActions: JSONXActions = [];
const { drawingId } = drawing;
diff --git a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-notification.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-notification.controller.spec.ts
index 21df1ccb22..cf2b5ea7c6 100644
--- a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-notification.controller.spec.ts
+++ b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-notification.controller.spec.ts
@@ -42,8 +42,8 @@ function createController() {
};
const controller = new DocDrawingAddRemoveController(
{
- getCurrentUniverDocInstance: vi.fn(() => ({ getUnitId: () => 'doc-1' })),
- getUniverDocInstance: vi.fn(() => ({
+ getCurrentUnitOfType: vi.fn(() => ({ getUnitId: () => 'doc-1' })),
+ getUnit: vi.fn(() => ({
getSnapshot: () => ({
drawings: {
'drawing-1': {
@@ -71,7 +71,10 @@ function createController() {
} as never,
drawingManagerService as never,
docDrawingService as never,
- { getRenderById: vi.fn(() => ({ scene: { getTransformerByCreate: () => ({ refreshControls }) } })) } as never
+ {
+ getRenderById: vi.fn(() => ({ scene: { getTransformerByCreate: () => ({ refreshControls }) } })),
+ getRenderUnitById: vi.fn(() => ({ scene: { getTransformerByCreate: () => ({ refreshControls }) } })),
+ } as never
);
return { controller, beforeHandlers, executedHandlers, drawingManagerService, docDrawingService, refreshControls };
diff --git a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-transformer-update.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-transformer-update.controller.spec.ts
index b030ca8748..35629a73df 100644
--- a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-transformer-update.controller.spec.ts
+++ b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-transformer-update.controller.spec.ts
@@ -409,7 +409,7 @@ describe('DocDrawingTransformerController business methods', () => {
drawingId: 'drawing-inline',
}));
controller._univerInstanceService = {
- getUniverDocInstance: vi.fn(() => ({
+ getUnit: vi.fn(() => ({
getSnapshot: () => ({
drawings: {
'drawing-inline': inlineDrawing,
diff --git a/packages/docs-drawing-ui/src/controllers/doc-drawing-notification.controller.ts b/packages/docs-drawing-ui/src/controllers/doc-drawing-notification.controller.ts
index c0da87642f..ed256e078e 100644
--- a/packages/docs-drawing-ui/src/controllers/doc-drawing-notification.controller.ts
+++ b/packages/docs-drawing-ui/src/controllers/doc-drawing-notification.controller.ts
@@ -16,7 +16,7 @@
/* eslint-disable ts/no-explicit-any */
-import type { ICommandInfo, IDrawingSearch, JSONXActions, Nullable } from '@univerjs/core';
+import type { DocumentDataModel, ICommandInfo, IDrawingSearch, JSONXActions, Nullable } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { IDocDrawing } from '@univerjs/docs-drawing';
import type { IDrawingJsonUndo1, IDrawingOrderMapParam } from '@univerjs/drawing';
@@ -27,6 +27,7 @@ import {
JSONX,
RedoCommand,
UndoCommand,
+ UniverInstanceType,
} from '@univerjs/core';
import { RichTextEditingMutation } from '@univerjs/docs';
import { getDocDrawingRenderOrder, IDocDrawingService } from '@univerjs/docs-drawing';
@@ -182,14 +183,14 @@ export class DocDrawingAddRemoveController extends Disposable {
return;
}
- const unitId = this._univerInstanceService.getCurrentUniverDocInstance()?.getUnitId();
+ const unitId = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)?.getUnitId();
const focusedDrawings = this._drawingManagerService.getFocusDrawings();
if (unitId == null || focusedDrawings.length === 0) {
return;
}
- const renderObject = this._renderManagerService.getRenderById(unitId);
+ const renderObject = this._renderManagerService.getRenderUnitById(unitId);
const scene = renderObject?.scene;
if (scene == null) {
return false;
@@ -238,7 +239,7 @@ export class DocDrawingAddRemoveController extends Disposable {
}
private _updateDrawingsOrder(unitId: string) {
- const documentDataModel = this._univerInstanceService.getUniverDocInstance(unitId);
+ const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
if (documentDataModel == null) {
return;
diff --git a/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.ts b/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.ts
index 685d99afa4..dd0f375daa 100644
--- a/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.ts
+++ b/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IDocDrawingBase, IDocDrawingPosition, Nullable } from '@univerjs/core';
+import type { DocumentDataModel, IDocDrawingBase, IDocDrawingPosition, Nullable } from '@univerjs/core';
import type { BaseObject, Documents, IDocumentSkeletonGlyph, IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonTable, Image, IPoint, Viewport } from '@univerjs/engine-render';
import type { IDrawingDocTransform } from '../commands/commands/update-doc-drawing.command';
import {
@@ -30,6 +30,7 @@ import {
throttle,
toDisposable,
Tools,
+ UniverInstanceType,
} from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
import { DocSelectionRenderService, getAnchorBounding, getDocObject, getOneTextSelectionRange, NodePositionConvertToCursor, TEXT_RANGE_LAYER_INDEX } from '@univerjs/docs-ui';
@@ -151,7 +152,7 @@ export class DocDrawingTransformerController extends Disposable {
continue;
}
- const documentDataModel = this._univerInstanceService.getUniverDocInstance(drawing.unitId);
+ const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(drawing.unitId, UniverInstanceType.UNIVER_DOC);
const drawingData = documentDataModel?.getSnapshot().drawings?.[drawing.drawingId];
if (drawingData?.layoutType === PositionedObjectLayoutType.INLINE) {
diff --git a/packages/docs-drawing-ui/src/menu/image.menu.ts b/packages/docs-drawing-ui/src/menu/image.menu.ts
index 90c00eda5c..9bee1c54c3 100644
--- a/packages/docs-drawing-ui/src/menu/image.menu.ts
+++ b/packages/docs-drawing-ui/src/menu/image.menu.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IAccessor } from '@univerjs/core';
+import type { DocumentDataModel, IAccessor } from '@univerjs/core';
import type { IMenuItem } from '@univerjs/ui';
import type { LocaleKey } from '../locale/types';
import { IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
@@ -37,8 +37,8 @@ const getDisableWhenSelectionInTableObservable = (accessor: IAccessor) => {
if (activeRange) {
const { segmentId, startOffset, endOffset } = activeRange;
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
- const tables = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody()?.tables;
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const tables = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.tables;
if (tables && tables.length) {
if (tables.some((table) => {
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPosition.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPosition.tsx
index 46daaa77b7..d62776f163 100644
--- a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPosition.tsx
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPosition.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICommandInfo, IDrawingParam, IObjectPositionH, IObjectPositionV, Nullable } from '@univerjs/core';
+import type { DocumentDataModel, ICommandInfo, IDrawingParam, IObjectPositionH, IObjectPositionV, Nullable } from '@univerjs/core';
import type { IDocDrawing } from '@univerjs/docs-drawing';
import type { IDocumentSkeletonDrawing } from '@univerjs/engine-render';
import type { LocaleKey } from '../../locale/types';
@@ -26,6 +26,7 @@ import {
ObjectRelativeFromH,
ObjectRelativeFromV,
PositionedObjectLayoutType,
+ UniverInstanceType,
} from '@univerjs/core';
import { Checkbox, clsx, InputNumber, Select } from '@univerjs/design';
import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
@@ -60,7 +61,7 @@ export const DocDrawingPosition = (props: IDocDrawingPositionProps) => {
const { unitId } = drawingParam;
- const documentDataModel = univerInstanceService.getUniverDocInstance(unitId);
+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
const documentFlavor = documentDataModel?.getSnapshot().documentStyle.documentFlavor;
@@ -251,17 +252,17 @@ export const DocDrawingPosition = (props: IDocDrawingPositionProps) => {
}
const { drawingId, unitId } = focusDrawings[0];
- const documentDataModel = univerInstanceService.getUniverDocInstance(unitId);
- const skeleton = renderManagerService.getRenderById(unitId)
+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
+ const skeleton = renderManagerService.getRenderUnitById(unitId)
?.with(DocSkeletonManagerService)
.getSkeleton();
- const docSelectionRenderService = renderManagerService.getRenderById(unitId)?.with(DocSelectionRenderService);
+ const docSelectionRenderService = renderManagerService.getRenderUnitById(unitId)?.with(DocSelectionRenderService);
const segmentId = docSelectionRenderService?.getSegment();
const segmentPage = docSelectionRenderService?.getSegmentPage();
- const drawing = documentDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody()?.customBlocks?.find((c) => c.blockId === drawingId);
+ const drawing = documentDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.customBlocks?.find((c) => c.blockId === drawingId);
if (drawing == null || skeleton == null || docSelectionRenderService == null) {
return;
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingTextWrap.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingTextWrap.tsx
index 3d218bb8aa..6968b19fde 100644
--- a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingTextWrap.tsx
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingTextWrap.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICommandInfo, IDrawingParam, Nullable } from '@univerjs/core';
+import type { DocumentDataModel, ICommandInfo, IDrawingParam, Nullable } from '@univerjs/core';
import type { IDocDrawing } from '@univerjs/docs-drawing';
import type { LocaleKey } from '../../locale/types';
import {
@@ -23,6 +23,7 @@ import {
IUniverInstanceService,
LocaleService,
PositionedObjectLayoutType,
+ UniverInstanceType,
WrapTextType,
} from '@univerjs/core';
import { clsx, InputNumber, Radio, RadioGroup } from '@univerjs/design';
@@ -69,9 +70,9 @@ export const DocDrawingTextWrap = (props: IDocDrawingTextWrapProps) => {
const { unitId } = drawingParam;
- const documentDataModel = univerInstanceService.getUniverDocInstance(unitId);
+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- const renderObject = renderManagerService.getRenderById(unitId);
+ const renderObject = renderManagerService.getRenderUnitById(unitId);
const scene = renderObject?.scene;
if (scene == null) {
return null;
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx
index f18625a234..8a0fc8cd92 100644
--- a/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx
@@ -114,6 +114,7 @@ class TestDocSkeletonManagerService {
getViewModel() {
return {
getEditArea: () => DocumentEditArea.BODY,
+ reset: () => undefined,
};
}
}
@@ -150,11 +151,11 @@ class TestRenderManagerService {
this._render = render;
}
- getRenderUnitById(_unitId: string) {
- return this._render;
- }
+ private _getRender() {
+ if (this._render == null) {
+ return null;
+ }
- getRenderById(_unitId: string) {
return {
...(this._render as object),
scene: this._scene,
@@ -171,6 +172,14 @@ class TestRenderManagerService {
},
};
}
+
+ getRenderUnitById(_unitId: string) {
+ return this._getRender();
+ }
+
+ getRenderById(_unitId: string) {
+ return this._getRender();
+ }
}
function createDocData(): IDocumentData {
diff --git a/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts b/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts
index 4af795f13e..37b8520863 100644
--- a/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts
+++ b/packages/docs-hyper-link-ui/src/commands/commands/update-link.command.ts
@@ -43,8 +43,12 @@ export const UpdateDocHyperLinkCommand: ICommand<IUpdateDocHyperLinkCommandParam
return false;
}
- const oldBody = getBodySlice(doc.getSelfOrHeaderFooterModel(segmentId).getBody()!, currentSelection.startOffset!, currentSelection.endOffset!);
- const textRun = oldBody.textRuns?.[0];
+ const oldBody = doc.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+ if (!oldBody) {
+ return false;
+ }
+
+ const textRun = getBodySlice(oldBody, currentSelection.startOffset!, currentSelection.endOffset!).textRuns?.[0];
if (textRun) {
textRun.ed = params.label.length + 1;
}
diff --git a/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts b/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts
index 74fde1542f..87df8a1ea1 100644
--- a/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts
+++ b/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts
@@ -101,7 +101,7 @@ export const ClickDocHyperLinkOperation: ICommand<{ unitId: string; linkId: stri
const { unitId, linkId, segmentId } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
const doc = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- const body = doc?.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const body = doc?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
const link = body?.customRanges?.find((range) => range.rangeId === linkId && range.rangeType === CustomRangeType.HYPERLINK)?.properties?.url;
if (!isSafeUrl(link)) {
diff --git a/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx b/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
index ffbad3a712..23d0b51115 100644
--- a/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
+++ b/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
@@ -43,7 +43,7 @@ export const DocLinkPopup = () => {
const { unitId, linkId, segmentId, startIndex, endIndex } = currentPopup;
const doc = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- const body = doc?.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const body = doc?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
const link = body?.customRanges?.find((range) => range.rangeId === linkId && range.rangeType === CustomRangeType.HYPERLINK && range.startIndex === startIndex && range.endIndex === endIndex);
if (!link) {
diff --git a/packages/docs-mention-ui/src/__tests__/docs-mention-ui.integration.spec.ts b/packages/docs-mention-ui/src/__tests__/docs-mention-ui.integration.spec.ts
index 0dd41c95f7..40af3c420b 100644
--- a/packages/docs-mention-ui/src/__tests__/docs-mention-ui.integration.spec.ts
+++ b/packages/docs-mention-ui/src/__tests__/docs-mention-ui.integration.spec.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import type { ICommand, IDisposable, IDocumentData, Univer } from '@univerjs/core';
+import type { DocumentDataModel, ICommand, IDisposable, IDocumentData, Univer } from '@univerjs/core';
import type { IInsertTextCommandParams } from '@univerjs/docs';
-import { awaitTime, CustomRangeType, Direction, ICommandService, IUniverInstanceService } from '@univerjs/core';
+import { awaitTime, CustomRangeType, Direction, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import {
DocSelectionManagerService,
InsertTextCommand,
@@ -241,7 +241,7 @@ describe('docs-mention-ui integration', () => {
await awaitTime(0);
const documentBody = testBed.get(IUniverInstanceService)
- .getCurrentUniverDocInstance()
+ .getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
?.getBody();
expect(documentBody?.dataStream).toBe('Hello @Alice\r\n');
@@ -293,7 +293,7 @@ describe('docs-mention-ui integration', () => {
await awaitTime(0);
const docBody = testBed.get(IUniverInstanceService)
- .getCurrentUniverDocInstance()
+ .getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
?.getBody();
expect(docBody?.dataStream).toBe('Hello @Alice\r\n');
expect(docBody?.customRanges).toEqual([]);
diff --git a/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts
index 59f063b0da..c003ab51ed 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts
@@ -15,7 +15,7 @@
*/
import type { ICommand, IDocumentData, Univer } from '@univerjs/core';
-import { awaitTime, DataStreamTreeTokenType, ICommandService } from '@univerjs/core';
+import { awaitTime, DataStreamTreeTokenType, DocumentBlockRangeType, ICommandService } from '@univerjs/core';
import {
DocContentInsertService,
DocSelectionManagerService,
@@ -25,6 +25,7 @@ import {
import { afterEach, describe, expect, it } from 'vitest';
import {
buildDocTableInsertBody,
+ canInsertTableAtOffset,
CreateDocTableCommand,
normalizeTableInsertOffset,
shouldCreateParagraphBeforeTable,
@@ -627,6 +628,89 @@ describe('doc table create command helpers', () => {
expect(snapshot.tableSource?.[tableId].tableColumns.map((column) => column.size.width.v)).toEqual([180, 180]);
});
+ it('does not create a table inside a block range', async () => {
+ const documentData = createParagraphDocument(`${DataStreamTreeTokenType.BLOCK_START}Callout\r${DataStreamTreeTokenType.BLOCK_END}\r\n`);
+ const testBed = createTableCreationBed({
+ ...documentData,
+ body: {
+ ...documentData.body!,
+ paragraphs: [{ paragraphId: 'para_block_range', startIndex: 8 }],
+ sectionBreaks: [{ startIndex: 11 }],
+ blockRanges: [{ blockId: 'callout-1', blockType: DocumentBlockRangeType.CALLOUT, startIndex: 0, endIndex: 9 }],
+ },
+ });
+ const commandService = testBed.get(ICommandService);
+ setActiveTableRange(testBed, 2);
+ setCommandSkeletonPage(testBed, 2, {
+ pageWidth: 540,
+ marginLeft: 90,
+ marginRight: 90,
+ });
+
+ await expect(commandService.executeCommand(CreateDocTableCommand.id, {
+ rowCount: 1,
+ colCount: 1,
+ })).resolves.toBe(false);
+
+ expect(testBed.doc.getSnapshot().body?.tables).toBeUndefined();
+ expect(testBed.doc.getSnapshot().tableSource).toEqual({});
+ });
+
+ it('does not create a table inside an existing table range', async () => {
+ const fixture = createTableFixture(1, 1);
+ const testBed = createTableCreationBed(fixture.documentData);
+ const commandService = testBed.get(ICommandService);
+ const insertOffset = fixture.cellRanges[0].startIndex + 1;
+ setActiveTableRange(testBed, insertOffset);
+ setCommandSkeletonPage(testBed, insertOffset, {
+ pageWidth: 540,
+ marginLeft: 90,
+ marginRight: 90,
+ });
+
+ await expect(commandService.executeCommand(CreateDocTableCommand.id, {
+ rowCount: 1,
+ colCount: 1,
+ })).resolves.toBe(false);
+
+ expect(testBedSnapshotTableIds(testBed)).toEqual([TABLE_ID]);
+ });
+
+ it('allows insertion immediately after an existing table range', () => {
+ const fixture = createTableFixture(1, 1);
+ const tableEndOffset = fixture.documentData.body!.tables![0].endIndex;
+
+ expect(canInsertTableAtOffset(fixture.documentData.body!, tableEndOffset)).toBe(true);
+ });
+
+ it('does not create a table on a custom block', async () => {
+ const testBed = createTableCreationBed({
+ ...createParagraphDocument('A\b\r\n'),
+ body: {
+ dataStream: 'A\b\r\n',
+ textRuns: [{ st: 0, ed: 2, ts: {} }],
+ paragraphs: [{ paragraphId: 'para_custom_block', startIndex: 2 }],
+ sectionBreaks: [{ startIndex: 3 }],
+ customBlocks: [{ startIndex: 1, blockId: 'custom-block-1' }],
+ },
+ });
+ const commandService = testBed.get(ICommandService);
+ setActiveTableRange(testBed, 1);
+ setCommandSkeletonPage(testBed, 1, {
+ pageWidth: 540,
+ marginLeft: 90,
+ marginRight: 90,
+ });
+
+ await expect(commandService.executeCommand(CreateDocTableCommand.id, {
+ rowCount: 1,
+ colCount: 1,
+ })).resolves.toBe(false);
+
+ expect(testBed.doc.getSnapshot().body?.tables).toBeUndefined();
+ expect(testBed.doc.getSnapshot().tableSource).toEqual({});
+ });
+
it('does not create a table without a render skeleton for the cursor', async () => {
const testBed = createTableCreationBed(createParagraphDocument('Hello\r\n'));
const commandService = testBed.get(ICommandService);
diff --git a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts
index 830a4f0874..6e814cf2f2 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts
@@ -978,17 +978,15 @@ describe('misc document commands', () => {
it('deletes the current paragraph through rich text editing', async () => {
({ univer, get } = createCommandTestBed(createMultiParagraphDoc()));
commandService = get(ICommandService);
- commandService.registerCommand(DeleteCurrentParagraphCommand);
+ expect(DeleteCurrentParagraphCommand).toMatchObject({
+ multi: true,
+ name: DeleteCurrentParagraphCommand.id,
+ });
+ commandService.registerMultipleCommand(DeleteCurrentParagraphCommand);
commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
setCollapsedSelection(2);
- expect(await commandService.executeCommand(DeleteCurrentParagraphCommand.id)).toEqual(expect.objectContaining({
- unitId: 'test-doc',
- textRanges: [expect.objectContaining({
- startOffset: 2,
- endOffset: 2,
- })],
- }));
+ expect(await commandService.executeCommand(DeleteCurrentParagraphCommand.id)).toBe(true);
await awaitTime(0);
expect(getBody()?.dataStream).toBe('Body\r\n');
diff --git a/packages/docs-ui/src/commands/commands/break-line.command.ts b/packages/docs-ui/src/commands/commands/break-line.command.ts
index d728029caa..099ca80ff7 100644
--- a/packages/docs-ui/src/commands/commands/break-line.command.ts
+++ b/packages/docs-ui/src/commands/commands/break-line.command.ts
@@ -107,7 +107,7 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {
const { horizontalLine } = params ?? {};
const { segmentId } = activeTextRange;
const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
- const originBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId ?? '').getBody();
+ const originBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId ?? '')?.getBody();
if (docDataModel == null || originBody == null) {
return false;
diff --git a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
index 7806d5e78e..0f03549f22 100644
--- a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
+++ b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts
@@ -40,6 +40,7 @@ import {
TextX,
TextXActionType,
Tools,
+ UniverInstanceType,
} from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { getCustomDecorationAtPosition, getCustomRangeAtPosition } from '../../basics/paragraph';
@@ -102,8 +103,8 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
return false;
}
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
- const originBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const originBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (docDataModel == null || originBody == null) {
return false;
}
@@ -261,7 +262,7 @@ function getCutActionsFromTextRanges(
docDataModel: DocumentDataModel,
segmentId: string
) {
- const originBody = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const originBody = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
const textX = new TextX();
const jsonX = JSONX.getInstance();
@@ -339,7 +340,7 @@ function getCutActionsFromRectRanges(
segmentId: string
): JSONXActions {
const rawActions: JSONXActions = [];
- const segmentBody = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const segmentBody = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (segmentBody == null) {
return rawActions;
@@ -498,16 +499,12 @@ export const CutContentCommand: ICommand<IInnerCutCommandParams> = {
return false;
}
- const unitId = univerInstanceService.getCurrentUniverDocInstance()?.getUnitId();
- if (!unitId) {
- return false;
- }
-
- const docDataModel = univerInstanceService.getUniverDocInstance(unitId);
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (docDataModel == null) {
return false;
}
+ const unitId = docDataModel.getUnitId();
const docSkeletonManagerService = getCommandSkeleton(accessor, unitId);
if (docSkeletonManagerService == null) {
diff --git a/packages/docs-ui/src/commands/commands/doc-block-move.command.ts b/packages/docs-ui/src/commands/commands/doc-block-move.command.ts
index a66c34545a..9644768c2d 100644
--- a/packages/docs-ui/src/commands/commands/doc-block-move.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-block-move.command.ts
@@ -47,9 +47,11 @@ export const MoveDocBlockCommand: ICommand<IMoveDocBlockCommandParams> = {
const univerInstanceService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
- const doc = (params.unitId
- ? univerInstanceService.getUnit(params.unitId, UniverInstanceType.UNIVER_DOC)
- : univerInstanceService.getCurrentUniverDocInstance()) as DocumentDataModel | undefined;
+
+ const { unitId, sourceRange, targetOffset } = params;
+ const doc = unitId
+ ? univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC)
+ : univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (!doc) {
return false;
@@ -58,13 +60,13 @@ export const MoveDocBlockCommand: ICommand<IMoveDocBlockCommandParams> = {
const previousDocumentData = doc.getSnapshot();
const moveResult = buildMoveDocBlockActions({
documentData: previousDocumentData,
- sourceRange: params.sourceRange,
- targetOffset: params.targetOffset,
+ sourceRange,
+ targetOffset,
});
const { nextDocumentData, movedRange } = accessor.get(DocBlockMoveValidatorService).transformMoveResult({
unitId: doc.getUnitId(),
- sourceRange: params.sourceRange,
- targetOffset: params.targetOffset,
+ sourceRange,
+ targetOffset,
previousDocumentData,
result: moveResult,
});
diff --git a/packages/docs-ui/src/commands/commands/doc-delete.command.ts b/packages/docs-ui/src/commands/commands/doc-delete.command.ts
index f6ac29c33d..4a1607f209 100644
--- a/packages/docs-ui/src/commands/commands/doc-delete.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-delete.command.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ICommand, IDocumentBlockRange, IDocumentBody, IMutationInfo, IParagraph, ITextRange, JSONXActions, Nullable } from '@univerjs/core';
+import type { DocumentDataModel, IAccessor, ICommand, IDocumentBlockRange, IDocumentBody, IMultiCommand, IMutationInfo, IParagraph, ITextRange, JSONXActions, Nullable } from '@univerjs/core';
import type { IDeleteTextCommandParams, IRichTextEditingMutationParams, IUpdateTextCommandParams } from '@univerjs/docs';
import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';
import {
@@ -64,15 +64,14 @@ export const DeleteCustomBlockCommand: ICommand<IDeleteCustomBlockParams> = {
const univerInstanceService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
+ const { direction, range, unitId, drawingId } = params;
const activeRange = docSelectionManagerService.getActiveTextRange();
- const documentDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
if (activeRange == null || documentDataModel == null) {
return false;
}
- const { direction, range, unitId, drawingId } = params;
-
const { startOffset, segmentId, style } = activeRange;
const cursor = direction === DeleteDirection.LEFT ? startOffset - 1 : startOffset;
@@ -161,7 +160,7 @@ export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {
}
const { segmentId, style } = activeRange;
const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
- const originBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const originBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (docDataModel == null || originBody == null) {
return false;
}
@@ -281,7 +280,7 @@ export const RemoveHorizontalLineCommand: ICommand = {
}
const { segmentId, style } = activeRange;
const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
- const originBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const originBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (docDataModel == null || originBody == null) {
return false;
}
@@ -436,7 +435,7 @@ export const DeleteLeftCommand: ICommand = {
let result = true;
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (docDataModel == null) {
return false;
}
@@ -478,7 +477,7 @@ export const DeleteLeftCommand: ICommand = {
const { segmentId, style, segmentPage } = activeRange;
- const body = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const body = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (body == null) {
return false;
@@ -663,7 +662,7 @@ export const DeleteRightCommand: ICommand = {
handler: async (accessor) => {
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (!docDataModel) {
return false;
}
@@ -702,7 +701,7 @@ export const DeleteRightCommand: ICommand = {
const { segmentId, style, segmentPage } = activeRange;
- const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (!docDataModel || !body) {
return false;
}
@@ -795,7 +794,7 @@ export const DeleteRightCommand: ICommand = {
},
};
-async function executeDeleteAutoFormat(accessor: Parameters<ICommand['handler']>[0], commandId: string): Promise<boolean | null> {
+async function executeDeleteAutoFormat(accessor: IAccessor, commandId: string): Promise<boolean | null> {
if (!accessor.has(DocAutoFormatService)) {
return null;
}
@@ -887,8 +886,16 @@ function resetEmptyCenteredParagraphAlignment(
});
}
-export const DeleteCurrentParagraphCommand: ICommand = {
+export interface IDeleteCurrentParagraphCommandParams {
+ unitId?: string;
+ blockRange?: IDocumentBlockRange;
+}
+
+export const DeleteCurrentParagraphCommand: IMultiCommand<IDeleteCurrentParagraphCommandParams> = {
id: 'doc.command.delete-current-paragraph',
+ name: 'doc.command.delete-current-paragraph',
+ multi: true,
+ priority: 0,
type: CommandType.COMMAND,
handler: async (accessor) => {
const univerInstanceService = accessor.get(IUniverInstanceService);
diff --git a/packages/docs-ui/src/commands/commands/doc-header-footer.command.ts b/packages/docs-ui/src/commands/commands/doc-header-footer.command.ts
index 3de872fa9c..5e2f855f63 100644
--- a/packages/docs-ui/src/commands/commands/doc-header-footer.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-header-footer.command.ts
@@ -25,6 +25,7 @@ import {
ICommandService,
IUniverInstanceService,
JSONX,
+ UniverInstanceType,
} from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';
@@ -157,8 +158,8 @@ export const CoreHeaderFooterCommand: ICommand<ICoreHeaderFooterParams> = {
const univerInstanceService = accessor.get(IUniverInstanceService);
const renderManagerService = accessor.get(IRenderManagerService);
const { unitId, segmentId, createType, headerFooterProps } = params;
- const docSkeletonManagerService = renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService);
- const docDataModel = univerInstanceService.getUniverDocInstance(unitId);
+ const docSkeletonManagerService = renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService);
+ const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
const docViewModel = docSkeletonManagerService?.getViewModel();
if (docDataModel == null || docViewModel == null) {
diff --git a/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.ts b/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.ts
index 80a5679f23..ff1fda1d6b 100644
--- a/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.ts
@@ -44,8 +44,8 @@ export const DocParagraphSettingCommand: ICommand<IDocParagraphSettingCommandPar
const unitId = docDataModel.getUnitId();
const segment = docDataModel.getSelfOrHeaderFooterModel(segmentId);
- const allParagraphs = segment.getBody()?.paragraphs ?? [];
- const dataStream = segment.getBody()?.dataStream ?? '';
+ const allParagraphs = segment?.getBody()?.paragraphs ?? [];
+ const dataStream = segment?.getBody()?.dataStream ?? '';
const paragraphs = BuildTextUtils.range.getParagraphsInRanges(docRanges, allParagraphs, dataStream) ?? [];
const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
diff --git a/packages/docs-ui/src/commands/commands/doc-select-all.command.ts b/packages/docs-ui/src/commands/commands/doc-select-all.command.ts
index 82e57ce7ab..82f69a60e0 100644
--- a/packages/docs-ui/src/commands/commands/doc-select-all.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-select-all.command.ts
@@ -36,7 +36,7 @@ export const DocSelectAllCommand: ICommand<ISelectAllCommandParams> = {
const { segmentId } = activeRange;
const unitId = docDataModel.getUnitId();
- const body = docDataModel.getSelfOrHeaderFooterModel(segmentId).getSnapshot().body;
+ const body = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (body == null) {
return false;
}
diff --git a/packages/docs-ui/src/commands/commands/ime-input.command.ts b/packages/docs-ui/src/commands/commands/ime-input.command.ts
index 3421efa380..d4e5271441 100644
--- a/packages/docs-ui/src/commands/commands/ime-input.command.ts
+++ b/packages/docs-ui/src/commands/commands/ime-input.command.ts
@@ -58,7 +58,7 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
}
const { style, segmentId } = previousActiveRange;
- const body = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const body = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (body == null) {
return false;
diff --git a/packages/docs-ui/src/commands/commands/inline-format.command.ts b/packages/docs-ui/src/commands/commands/inline-format.command.ts
index 45b3e6e647..711f7303e9 100644
--- a/packages/docs-ui/src/commands/commands/inline-format.command.ts
+++ b/packages/docs-ui/src/commands/commands/inline-format.command.ts
@@ -301,7 +301,7 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
return false;
}
- const body = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const body = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (body == null) {
return false;
diff --git a/packages/docs-ui/src/commands/commands/insert-below/insert-bullet-below.command.ts b/packages/docs-ui/src/commands/commands/insert-below/insert-bullet-below.command.ts
index b04c8c2e2c..3f79c70f27 100644
--- a/packages/docs-ui/src/commands/commands/insert-below/insert-bullet-below.command.ts
+++ b/packages/docs-ui/src/commands/commands/insert-below/insert-bullet-below.command.ts
@@ -45,8 +45,8 @@ export const InsertBulletBelowCommand: ICommand<IInsertBulletBelowCommandParams>
return false;
}
const segment = docDataModel.getSelfOrHeaderFooterModel(textRanges[0].segmentId);
- const paragraphs = segment.getBody()?.paragraphs ?? [];
- const dataStream = segment.getBody()?.dataStream ?? '';
+ const paragraphs = segment?.getBody()?.paragraphs ?? [];
+ const dataStream = segment?.getBody()?.dataStream ?? '';
const currentParagraph = BuildTextUtils.range.getParagraphsInRange(textRanges[0], paragraphs, dataStream)[0];
if (!currentParagraph) {
return false;
diff --git a/packages/docs-ui/src/commands/commands/list.command.ts b/packages/docs-ui/src/commands/commands/list.command.ts
index f140f9e720..e5423c07c3 100644
--- a/packages/docs-ui/src/commands/commands/list.command.ts
+++ b/packages/docs-ui/src/commands/commands/list.command.ts
@@ -63,8 +63,8 @@ export const ListOperationCommand: ICommand<IListOperationCommandParams> = {
const segmentId = docRanges[0].segmentId;
const segment = docDataModel.getSelfOrHeaderFooterModel(segmentId);
- const paragraphs = segment.getBody()?.paragraphs ?? [];
- const dataStream = segment.getBody()?.dataStream ?? '';
+ const paragraphs = segment?.getBody()?.paragraphs ?? [];
+ const dataStream = segment?.getBody()?.dataStream ?? '';
if (!paragraphs.length) {
return false;
@@ -127,8 +127,8 @@ export const ChangeListTypeCommand: ICommand<IChangeListTypeCommandParams> = {
const { segmentId } = activeRanges[0];
const segment = docDataModel.getSelfOrHeaderFooterModel(segmentId);
- const paragraphs = segment.getBody()?.paragraphs ?? [];
- const dataStream = segment.getBody()?.dataStream ?? '';
+ const paragraphs = segment?.getBody()?.paragraphs ?? [];
+ const dataStream = segment?.getBody()?.dataStream ?? '';
if (!paragraphs.length) {
return false;
@@ -199,8 +199,8 @@ export const ChangeListNestingLevelCommand: ICommand<IChangeListNestingLevelComm
const { segmentId } = activeRange;
const selections = docSelectionManagerService.getDocRanges() ?? [];
const segment = docDataModel.getSelfOrHeaderFooterModel(segmentId);
- const paragraphs = segment.getBody()?.paragraphs ?? [];
- const dataStream = segment.getBody()?.dataStream ?? '';
+ const paragraphs = segment?.getBody()?.paragraphs ?? [];
+ const dataStream = segment?.getBody()?.dataStream ?? '';
if (!paragraphs.length) {
return false;
@@ -307,7 +307,7 @@ export const ToggleCheckListCommand: ICommand<IToggleCheckListCommandParams> = {
return false;
}
- const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs;
+ const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.paragraphs;
if (paragraphs == null) {
return false;
}
diff --git a/packages/docs-ui/src/commands/commands/paragraph-align.command.ts b/packages/docs-ui/src/commands/commands/paragraph-align.command.ts
index 89ac6a5dc6..210e7aad86 100644
--- a/packages/docs-ui/src/commands/commands/paragraph-align.command.ts
+++ b/packages/docs-ui/src/commands/commands/paragraph-align.command.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICommand, IMutationInfo, IParagraphStyle } from '@univerjs/core';
+import type { DocumentDataModel, ICommand, IMutationInfo, IParagraphStyle } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import {
BuildTextUtils,
@@ -27,6 +27,7 @@ import {
MemoryCursor,
TextX,
TextXActionType,
+ UniverInstanceType,
UpdateDocsAttributeType,
} from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
@@ -48,7 +49,7 @@ export const AlignOperationCommand: ICommand<IAlignOperationCommandParams> = {
const { alignType } = params;
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (docDataModel == null) {
return false;
}
@@ -60,8 +61,8 @@ export const AlignOperationCommand: ICommand<IAlignOperationCommandParams> = {
const segmentId = allRanges[0].segmentId;
const segment = docDataModel.getSelfOrHeaderFooterModel(segmentId);
- const paragraphs = segment.getBody()?.paragraphs ?? [];
- const dataStream = segment.getBody()?.dataStream ?? '';
+ const paragraphs = segment?.getBody()?.paragraphs ?? [];
+ const dataStream = segment?.getBody()?.dataStream ?? '';
if (paragraphs == null) {
return false;
diff --git a/packages/docs-ui/src/commands/commands/replace-content.command.ts b/packages/docs-ui/src/commands/commands/replace-content.command.ts
index a29ba05975..e7842e2d89 100644
--- a/packages/docs-ui/src/commands/commands/replace-content.command.ts
+++ b/packages/docs-ui/src/commands/commands/replace-content.command.ts
@@ -59,7 +59,7 @@ export const ReplaceSnapshotCommand: ICommand<IReplaceSnapshotCommandParams> = {
const commandService = accessor.get(ICommandService);
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- const prevSnapshot = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getSnapshot();
+ const prevSnapshot = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getSnapshot();
if (docDataModel == null || prevSnapshot == null) {
return false;
@@ -202,7 +202,7 @@ export const ReplaceContentCommand: ICommand<IReplaceContentCommandParams> = {
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- const prevBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getSnapshot().body;
+ const prevBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (docDataModel == null || prevBody == null) {
return false;
@@ -253,7 +253,7 @@ export const CoverContentCommand: ICommand<ICoverContentCommandParams> = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
- const docDatModel = univerInstanceService.getUniverDocInstance(unitId);
+ const docDatModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
const prevBody = docDatModel?.getSnapshot().body;
@@ -381,7 +381,7 @@ export const ReplaceTextRunsCommand: ICommand<IReplaceContentCommandParams> = {
// const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- const prevBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getSnapshot().body;
+ const prevBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (docDataModel == null || prevBody == null) {
return false;
diff --git a/packages/docs-ui/src/commands/commands/set-doc-zoom-ratio.command.ts b/packages/docs-ui/src/commands/commands/set-doc-zoom-ratio.command.ts
index eaa46c8b7d..32116bfac1 100644
--- a/packages/docs-ui/src/commands/commands/set-doc-zoom-ratio.command.ts
+++ b/packages/docs-ui/src/commands/commands/set-doc-zoom-ratio.command.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import type { IAccessor, ICommand } from '@univerjs/core';
+import type { DocumentDataModel, IAccessor, ICommand } from '@univerjs/core';
import type { ISetDocZoomRatioOperationParams } from '../operations/set-doc-zoom-ratio.operation';
-import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
+import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import {
SetDocZoomRatioOperation,
SetDocZoomRatioUndoMutationFactory,
@@ -36,30 +36,26 @@ export const SetDocZoomRatioCommand: ICommand = {
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- let documentId = univerInstanceService.getCurrentUniverDocInstance()?.getUnitId();
- if (!documentId) return false;
+ const { zoomRatio = 1, documentId } = params || {};
- let zoomRatio = 1;
+ const docDatModel = documentId
+ ? univerInstanceService.getUnit<DocumentDataModel>(documentId, UniverInstanceType.UNIVER_DOC)
+ : univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ if (!docDatModel) return false;
- if (params) {
- documentId = params.documentId ?? documentId;
- zoomRatio = params.zoomRatio ?? zoomRatio;
- }
-
- const workbook = univerInstanceService.getUniverDocInstance(documentId);
- if (!workbook) return false;
+ const unitId = docDatModel.getUnitId();
const setZoomRatioMutationParams: ISetDocZoomRatioOperationParams = {
zoomRatio,
- unitId: documentId,
+ unitId,
};
const undoMutationParams = SetDocZoomRatioUndoMutationFactory(accessor, setZoomRatioMutationParams);
- const result = commandService.syncExecuteCommand(SetDocZoomRatioOperation.id, setZoomRatioMutationParams);
+ const result = commandService.syncExecuteCommand<ISetDocZoomRatioOperationParams>(SetDocZoomRatioOperation.id, setZoomRatioMutationParams);
if (result) {
undoRedoService.pushUndoRedo({
- unitID: documentId,
+ unitID: unitId,
undoMutations: [{ id: SetDocZoomRatioOperation.id, params: undoMutationParams }],
redoMutations: [{ id: SetDocZoomRatioOperation.id, params: setZoomRatioMutationParams }],
});
diff --git a/packages/docs-ui/src/commands/commands/set-heading.command.ts b/packages/docs-ui/src/commands/commands/set-heading.command.ts
index 3e2f4e5334..b2b5e212bc 100644
--- a/packages/docs-ui/src/commands/commands/set-heading.command.ts
+++ b/packages/docs-ui/src/commands/commands/set-heading.command.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ICommand, IMutationInfo, ITextRangeParam } from '@univerjs/core';
+import type { DocumentDataModel, IAccessor, ICommand, IMutationInfo, ITextRangeParam } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import {
@@ -62,9 +62,15 @@ export const SetParagraphNamedStyleCommand: ICommand<ISetParagraphNamedStyleComm
if (!selections?.length) {
return false;
}
+
const segmentId = selections[0].segmentId;
+ const documentDataModel = doc.getSelfOrHeaderFooterModel(segmentId);
+ if (!documentDataModel) {
+ return false;
+ }
+
const textX = BuildTextUtils.paragraph.style.set({
- document: doc.getSelfOrHeaderFooterModel(segmentId),
+ document: documentDataModel,
textRanges: selections,
style: {
namedStyleType: params.value,
@@ -96,7 +102,7 @@ export const SetParagraphNamedStyleCommand: ICommand<ISetParagraphNamedStyleComm
},
};
-function consumeContentInsertRange(accessor: Parameters<ICommand['handler']>[0], unitId: string) {
+function consumeContentInsertRange(accessor: IAccessor, unitId: string) {
try {
return accessor.get(DocContentInsertService).consumeInsertRange(unitId);
} catch {
@@ -105,7 +111,7 @@ function consumeContentInsertRange(accessor: Parameters<ICommand['handler']>[0],
}
function insertNamedStyleParagraph(
- accessor: Parameters<ICommand['handler']>[0],
+ accessor: IAccessor,
doc: DocumentDataModel,
namedStyleType: NamedStyleType,
startOffset: number,
@@ -169,8 +175,8 @@ export const QuickHeadingCommand: ICommand<ISetParagraphNamedStyleCommandParams>
const { segmentId, startOffset } = activeRange;
const segment = docDataModel.getSelfOrHeaderFooterModel(segmentId);
- const paragraphs = segment.getBody()?.paragraphs ?? [];
- const dataStream = segment.getBody()?.dataStream ?? '';
+ const paragraphs = segment?.getBody()?.paragraphs ?? [];
+ const dataStream = segment?.getBody()?.dataStream ?? '';
const paragraph = BuildTextUtils.paragraph.util.getParagraphsInRange(activeRange, paragraphs, dataStream)[0];
if (!paragraph) {
return false;
diff --git a/packages/docs-ui/src/commands/commands/switch-doc-mode.command.ts b/packages/docs-ui/src/commands/commands/switch-doc-mode.command.ts
index c7ca7eaa45..72e4bebd77 100644
--- a/packages/docs-ui/src/commands/commands/switch-doc-mode.command.ts
+++ b/packages/docs-ui/src/commands/commands/switch-doc-mode.command.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICommand, ICommandInfo, JSONXActions } from '@univerjs/core';
+import type { DocumentDataModel, ICommand, ICommandInfo, JSONXActions } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import {
CommandType,
@@ -23,6 +23,7 @@ import {
IUniverInstanceService,
JSONX,
ObjectRelativeFromV,
+ UniverInstanceType,
} from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { IRenderManagerService } from '@univerjs/engine-render';
@@ -42,7 +43,7 @@ export const SwitchDocModeCommand: ICommand<ISwitchDocModeCommandParams> = {
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (docDataModel == null) {
return false;
diff --git a/packages/docs-ui/src/commands/commands/table/doc-table-create.command.ts b/packages/docs-ui/src/commands/commands/table/doc-table-create.command.ts
index ccc597eb68..fc4720e0d4 100644
--- a/packages/docs-ui/src/commands/commands/table/doc-table-create.command.ts
+++ b/packages/docs-ui/src/commands/commands/table/doc-table-create.command.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import type { ICommand, IMutationInfo, IParagraph, ISectionBreak, ITextRun, JSONXActions } from '@univerjs/core';
+import type { DocumentDataModel, ICommand, IDocumentBody, IMutationInfo, IParagraph, ISectionBreak, ITextRun, JSONXActions } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
-import { CommandType, createParagraphId, DataStreamTreeTokenType, getRichTextEditPath, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';
+import { CommandType, createParagraphId, DataStreamTreeTokenType, getRichTextEditPath, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';
import { DocContentInsertService, DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { getTextRunAtPosition } from '../../../basics/paragraph';
import { DocMenuStyleService } from '../../../services/doc-menu-style.service';
@@ -78,6 +78,26 @@ export function normalizeTableInsertOffset(body: { dataStream: string }, startOf
return startOffset === 0 && body.dataStream[0] === DataStreamTreeTokenType.PARAGRAPH ? 1 : startOffset;
}
+export function canInsertTableAtOffset(body: Pick<IDocumentBody, 'tables' | 'blockRanges' | 'customBlocks'>, offset: number): boolean {
+ return !(
+ isOffsetInTableRange(body.tables, offset) ||
+ isOffsetInIndexRange(body.blockRanges, offset) ||
+ isOffsetOnPointRange(body.customBlocks, offset)
+ );
+}
+
+function isOffsetInTableRange(ranges: Array<{ startIndex: number; endIndex: number }> | undefined, offset: number): boolean {
+ return Boolean(ranges?.some((range) => range.startIndex <= offset && offset < range.endIndex));
+}
+
+function isOffsetInIndexRange(ranges: Array<{ startIndex: number; endIndex: number }> | undefined, offset: number): boolean {
+ return Boolean(ranges?.some((range) => range.startIndex <= offset && offset <= range.endIndex));
+}
+
+function isOffsetOnPointRange(ranges: Array<{ startIndex: number }> | undefined, offset: number): boolean {
+ return Boolean(ranges?.some((range) => range.startIndex === offset));
+}
+
/**
* The command to create a table at cursor point.
*/
@@ -93,7 +113,7 @@ export const CreateDocTableCommand: ICommand<ICreateDocTableCommandParams> = {
const commandService = accessor.get(ICommandService);
const docMenuStyleService = accessor.get(DocMenuStyleService);
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (docDataModel == null) {
return false;
}
@@ -110,7 +130,7 @@ export const CreateDocTableCommand: ICommand<ICreateDocTableCommandParams> = {
}
const segmentId = contentInsertRange?.segmentId ?? activeRange?.segmentId ?? '';
const segmentPage = activeRange?.segmentPage;
- const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (body == null) {
return false;
}
@@ -123,6 +143,9 @@ export const CreateDocTableCommand: ICommand<ICreateDocTableCommandParams> = {
return false;
}
const startOffset = normalizeTableInsertOffset(body, contentInsertRange?.startOffset ?? activeRange!.startOffset);
+ if (!canInsertTableAtOffset(body, startOffset)) {
+ return false;
+ }
const paragraphs = body.paragraphs ?? [];
const prevParagraph = paragraphs.find((p) => p.startIndex >= startOffset);
diff --git a/packages/docs-ui/src/commands/commands/table/doc-table-delete.command.ts b/packages/docs-ui/src/commands/commands/table/doc-table-delete.command.ts
index 6598f2f4e0..d2a10ee2bf 100644
--- a/packages/docs-ui/src/commands/commands/table/doc-table-delete.command.ts
+++ b/packages/docs-ui/src/commands/commands/table/doc-table-delete.command.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import type { ICommand, IMutationInfo, JSONXActions } from '@univerjs/core';
+import type { DocumentDataModel, ICommand, IMutationInfo, JSONXActions } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
-import { CommandType, getRichTextEditPath, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';
+import { CommandType, getRichTextEditPath, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { getCommandSkeleton } from '../../util';
import { getDeleteColumnsActionParams, getDeleteRowsActionsParams, getDeleteTableActionParams, getRangeInfoFromRanges } from './table';
@@ -44,8 +44,8 @@ export const DocTableDeleteRowsCommand: ICommand<IDocTableDeleteRowsCommandParam
const { segmentId } = rangeInfo;
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
- const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (docDataModel == null || body == null) {
return false;
@@ -147,8 +147,8 @@ export const DocTableDeleteColumnsCommand: ICommand<IDocTableDeleteColumnsComman
const { segmentId } = rangeInfo;
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
- const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (docDataModel == null || body == null) {
return false;
@@ -261,8 +261,8 @@ export const DocTableDeleteTableCommand: ICommand<IDocTableDeleteTableCommandPar
const { segmentId } = rangeInfo;
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
- const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (docDataModel == null || body == null) {
return false;
diff --git a/packages/docs-ui/src/commands/commands/table/doc-table-insert.command.ts b/packages/docs-ui/src/commands/commands/table/doc-table-insert.command.ts
index a1935a7bb4..f868c277c4 100644
--- a/packages/docs-ui/src/commands/commands/table/doc-table-insert.command.ts
+++ b/packages/docs-ui/src/commands/commands/table/doc-table-insert.command.ts
@@ -134,7 +134,7 @@ export const DocTableInsertRowCommand: ICommand<IDocTableInsertRowCommandParams>
const { segmentId } = rangeInfo;
const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
- const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (docDataModel == null || body == null) {
return false;
@@ -241,8 +241,8 @@ export const DocTableInsertColumnCommand: ICommand<IDocTableInsertColumnCommandP
const { segmentId } = rangeInfo;
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
- const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (docDataModel == null || body == null) {
return false;
diff --git a/packages/docs-ui/src/commands/commands/table/doc-table-tab.command.ts b/packages/docs-ui/src/commands/commands/table/doc-table-tab.command.ts
index 1749d2c206..d7a56782b9 100644
--- a/packages/docs-ui/src/commands/commands/table/doc-table-tab.command.ts
+++ b/packages/docs-ui/src/commands/commands/table/doc-table-tab.command.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import type { ICommand, Nullable } from '@univerjs/core';
+import type { DocumentDataModel, ICommand, Nullable } from '@univerjs/core';
import type { IOffsets } from './table';
-import { CommandType, ICommandService, IUniverInstanceService } from '@univerjs/core';
+import { CommandType, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import { getCommandSkeleton } from '../../util';
import { DocTableInsertRowCommand } from './doc-table-insert.command';
@@ -39,7 +39,7 @@ export const DocTableTabCommand: ICommand<IDocTableTabCommandParams> = {
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (!docDataModel) {
return false;
}
diff --git a/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.spec.ts
index 938a268ec3..acb4b92ed9 100644
--- a/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.spec.ts
+++ b/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.spec.ts
@@ -89,10 +89,11 @@ function createController(options: {
} as never,
{
getCurrentTypeOfUnit$: vi.fn(() => new BehaviorSubject({ getUnitId: () => 'doc-1' })),
- getUniverDocInstance: vi.fn(() => unit),
+ getUnit: vi.fn(() => unit),
} as never,
{
getRenderById: vi.fn(() => ({ mainComponent: document })),
+ getRenderUnitById: vi.fn(() => ({ mainComponent: document })),
} as never,
{
getViewModel: vi.fn(() => viewModel),
diff --git a/packages/docs-ui/src/controllers/doc-header-footer.controller.ts b/packages/docs-ui/src/controllers/doc-header-footer.controller.ts
index e8e4d84df4..a912f29c1f 100644
--- a/packages/docs-ui/src/controllers/doc-header-footer.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-header-footer.controller.ts
@@ -314,8 +314,8 @@ export class DocHeaderFooterController extends Disposable implements IRenderModu
}
const unitId = unit.getUnitId();
- const currentRender = this._renderManagerService.getRenderById(unitId);
- if (this._editorService.isEditor(unitId) || this._instanceSrv.getUniverDocInstance(unitId) == null) {
+ const currentRender = this._renderManagerService.getRenderUnitById(unitId);
+ if (this._editorService.isEditor(unitId) || this._instanceSrv.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC) == null) {
return;
}
diff --git a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
index 02d157fca0..b87d47aaeb 100644
--- a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICommandInfo, Nullable } from '@univerjs/core';
+import type { DocumentDataModel, ICommandInfo, Nullable } from '@univerjs/core';
import type {
DocumentSkeleton,
IDocumentSkeletonCached,
@@ -38,6 +38,7 @@ import {
Inject,
IUniverInstanceService,
RANGE_DIRECTION,
+ UniverInstanceType,
} from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
import { DocumentSkeletonPageType, IRenderManagerService, LineType } from '@univerjs/engine-render';
@@ -117,7 +118,7 @@ export class DocMoveCursorController extends Disposable {
private _handleShiftMoveSelection(direction: Direction, granularity: DocCursorMoveGranularity = 'character') {
const activeRange = this._textSelectionManagerService.getActiveTextRange();
const allRanges = this._textSelectionManagerService.getTextRanges()!;
- const docDataModel = this._univerInstanceService.getCurrentUniverDocInstance();
+ const docDataModel = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (docDataModel == null) {
return;
}
@@ -176,7 +177,7 @@ export class DocMoveCursorController extends Disposable {
: rangeDirection === RANGE_DIRECTION.FORWARD
? endOffset
: startOffset;
- const body = docDataModel.getSelfOrHeaderFooterModel(normalizedSegmentId).getBody();
+ const body = docDataModel.getSelfOrHeaderFooterModel(normalizedSegmentId)?.getBody();
if (body == null) {
return;
@@ -315,7 +316,7 @@ export class DocMoveCursorController extends Disposable {
private _handleMoveCursor(direction: Direction, granularity: DocCursorMoveGranularity = 'character') {
const activeRange = this._textSelectionManagerService.getActiveTextRange();
const allRanges = this._textSelectionManagerService.getTextRanges();
- const docDataModel = this._univerInstanceService.getCurrentUniverDocInstance();
+ const docDataModel = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (docDataModel == null) {
return false;
}
@@ -331,7 +332,7 @@ export class DocMoveCursorController extends Disposable {
const { startOffset, endOffset, style, collapsed, segmentId, startNodePosition, endNodePosition, segmentPage } = activeRange;
const normalizedSegmentId = segmentId ?? '';
const normalizedSegmentPage = segmentPage ?? -1;
- const body = docDataModel.getSelfOrHeaderFooterModel(normalizedSegmentId).getBody();
+ const body = docDataModel.getSelfOrHeaderFooterModel(normalizedSegmentId)?.getBody();
if (body == null) {
return;
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-editor-bridge.controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-editor-bridge.controller.spec.ts
index 5d8d7fd21e..4b4027b980 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-editor-bridge.controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-editor-bridge.controller.spec.ts
@@ -49,7 +49,7 @@ function createController(options: { cancelResize?: boolean; sheetEditor?: boole
const controller = new DocEditorBridgeController(
{ unitId: 'editor-1' } as never,
{
- getUniverDocInstance: vi.fn(() => ({
+ getUnit: vi.fn(() => ({
getSnapshot: () => ({
documentStyle: {
marginTop: 10,
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-editor-bridge.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-editor-bridge.controller.ts
index 23305063c1..513a998496 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc-editor-bridge.controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-editor-bridge.controller.ts
@@ -81,7 +81,7 @@ export class DocEditorBridgeController extends Disposable implements IRenderModu
return;
}
- const editorDataModel = this._univerInstanceService.getUniverDocInstance(unitId);
+ const editorDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
if (!editorDataModel) {
return;
}
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts
index 9eeac274bc..e34fe1d09b 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts
@@ -74,7 +74,10 @@ export class DocInputController extends Disposable implements IRenderModule {
const { segmentId } = activeRange;
const docDataModel = this._context.unit;
- const originBody = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()!;
+ const originBody = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+ if (!originBody) {
+ return;
+ }
// Insert content's style should follow the text style of the current position.
const defaultTextStyle = this._docMenuStyleService.getDefaultStyle();
diff --git a/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts
index 707a030c39..73d022d085 100644
--- a/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts
@@ -99,12 +99,12 @@ export class DocZoomRenderController extends Disposable implements IRenderModule
return;
}
- const documentModel = this._univerInstanceService.getCurrentUniverDocInstance();
+ const documentModel = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (!documentModel) return;
this._updateTimer = window.setTimeout(() => {
const currentSheet = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- const sheetRenderer = currentSheet && this._renderManagerService.getRenderById(currentSheet.getUnitId());
+ const sheetRenderer = currentSheet && this._renderManagerService.getRenderUnitById(currentSheet.getUnitId());
const zoomRatio = !this._isSheetEditor ? getDocEffectiveZoomRatio(documentModel) : sheetRenderer?.scene.scaleX || 1;
this.updateViewZoom(zoomRatio, false);
@@ -163,7 +163,7 @@ export class DocZoomRenderController extends Disposable implements IRenderModule
this.disposeWithMe(
// hold ctrl & mousewheel ---> zoom
scene.onMouseWheel$.subscribeEvent((e: IWheelEvent) => {
- const documentModel = this._univerInstanceService.getCurrentUniverDocInstance();
+ const documentModel = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (!documentModel) {
return;
}
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index a0eb4b8620..acd9c909b6 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -38,12 +38,13 @@ export { getCustomBlockIdsInSelections, getCutActionsFromDocRanges } from './com
export { buildMoveDocBlockActions, MoveDocBlockCommand } from './commands/commands/doc-block-move.command';
export type { IMoveDocBlockCommandParams } from './commands/commands/doc-block-move.command';
export {
+ DeleteCurrentParagraphCommand,
DeleteCustomBlockCommand,
DeleteLeftCommand,
DeleteRightCommand,
MergeTwoParagraphCommand,
} from './commands/commands/doc-delete.command';
-export type { IDeleteCustomBlockParams } from './commands/commands/doc-delete.command';
+export type { IDeleteCurrentParagraphCommandParams, IDeleteCustomBlockParams } from './commands/commands/doc-delete.command';
export { getCursorWhenDelete } from './commands/commands/doc-delete.command';
export { HorizontalLineCommand } from './commands/commands/doc-horizontal-line.command';
export { DocSelectAllCommand } from './commands/commands/doc-select-all.command';
diff --git a/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts b/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts
index cfdd64a9f0..9ad0c98bee 100644
--- a/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts
+++ b/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts
@@ -85,7 +85,7 @@ function createTableMenuHarness(options: {
textSelection$: selection$,
};
const univerInstanceService = {
- getCurrentUniverDocInstance: () => ({
+ getCurrentUnitOfType: () => ({
getSelfOrHeaderFooterModel: () => ({
getBody: () => ({
tables: [{ endIndex: 30, startIndex: 10, tableId: 'table-1' }],
diff --git a/packages/docs-ui/src/menu/context-menu.ts b/packages/docs-ui/src/menu/context-menu.ts
index c23a8a3da5..e64daae205 100644
--- a/packages/docs-ui/src/menu/context-menu.ts
+++ b/packages/docs-ui/src/menu/context-menu.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IAccessor } from '@univerjs/core';
+import type { DocumentDataModel, IAccessor } from '@univerjs/core';
import type { IRectRangeWithStyle } from '@univerjs/engine-render';
import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';
import type { Subscriber } from 'rxjs';
@@ -81,8 +81,8 @@ function notInTableSubscriber(subscriber: Subscriber<boolean>, docSelectionManag
return;
}
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
- const tables = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody()?.tables;
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const tables = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.tables;
if (tables && tables.length) {
if (tables.some((table) => {
diff --git a/packages/docs-ui/src/menu/menu.ts b/packages/docs-ui/src/menu/menu.ts
index 0827f08abb..d3cb537b1c 100644
--- a/packages/docs-ui/src/menu/menu.ts
+++ b/packages/docs-ui/src/menu/menu.ts
@@ -148,13 +148,13 @@ function getHeaderFooterMenuHiddenObservable(
if (unitId == null) {
return subscriber.next(true);
}
- const docDataModel = univerInstanceService.getUniverDocInstance(unitId);
+ const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
const documentFlavor = docDataModel?.getSnapshot().documentStyle.documentFlavor;
subscriber.next(documentFlavor !== DocumentFlavor.TRADITIONAL);
});
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (docDataModel == null) {
return subscriber.next(true);
@@ -196,7 +196,7 @@ function getTableDisabledObservable(accessor: IAccessor): Observable<boolean> {
return;
}
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (docDataModel == null) {
subscriber.next(true);
@@ -1126,7 +1126,7 @@ const listValueFactory$ = (accessor: IAccessor) => {
return;
}
- const docDataModel = univerInstanceService.getUniverDocInstance(unitId);
+ const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
if (docDataModel == null) {
return;
}
@@ -1137,7 +1137,7 @@ const listValueFactory$ = (accessor: IAccessor) => {
if (range) {
const doc = docDataModel.getSelfOrHeaderFooterModel(range?.segmentId);
- const paragraphs = BuildTextUtils.range.getParagraphsInRange(range, doc.getBody()?.paragraphs ?? [], doc.getBody()?.dataStream ?? '');
+ const paragraphs = BuildTextUtils.range.getParagraphsInRange(range, doc?.getBody()?.paragraphs ?? [], doc?.getBody()?.dataStream ?? '');
let listType: string | undefined;
if (paragraphs.every((p) => {
if (!listType) {
@@ -1347,7 +1347,7 @@ function getFontStyleAtCursor(accessor: IAccessor) {
}
const { segmentId } = activeRange;
- const body = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const body = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (body == null) {
return {
@@ -1375,7 +1375,7 @@ export function getParagraphStyleAtCursor(accessor: IAccessor) {
const univerInstanceService = accessor.get(IUniverInstanceService);
const textSelectionService = accessor.get(DocSelectionManagerService);
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
const docRanges = textSelectionService.getDocRanges();
const activeRange = docRanges.find((r) => r.isActive) ?? docRanges[0];
@@ -1386,7 +1386,7 @@ export function getParagraphStyleAtCursor(accessor: IAccessor) {
const { startOffset, segmentId } = activeRange;
- const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs;
+ const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.paragraphs;
if (paragraphs == null) {
return;
diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.ts
index 698684041d..d36a6e6af7 100644
--- a/packages/docs-ui/src/plugin.ts
+++ b/packages/docs-ui/src/plugin.ts
@@ -30,7 +30,7 @@ import {
touchDependencies,
UniverInstanceType,
} from '@univerjs/core';
-import { DocInterceptorService, DocSkeletonManagerService, IDocStateChangeInterceptorService } from '@univerjs/docs';
+import { DocInterceptorService, DocSkeletonManagerService, IDocStateChangeInterceptorService, UniverDocsPlugin } from '@univerjs/docs';
import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
import { IShortcutService } from '@univerjs/ui';
import pkg from '../package.json';
@@ -163,7 +163,7 @@ import {
import { ShiftTabShortCut } from './shortcuts/format.shortcut';
import { H1HeadingShortcut, H2HeadingShortcut, H3HeadingShortcut, H4HeadingShortcut, H5HeadingShortcut, NormalTextHeadingShortcut } from './shortcuts/heading.shortcut';
-@DependentOn(UniverRenderEnginePlugin)
+@DependentOn(UniverRenderEnginePlugin, UniverDocsPlugin)
export class UniverDocsUIPlugin extends Plugin {
static override pluginName = 'DOC_UI_PLUGIN';
static override packageName = pkg.name;
@@ -293,7 +293,6 @@ export class UniverDocsUIPlugin extends Plugin {
InsertCustomRangeCommand,
SetParagraphNamedStyleCommand,
QuickHeadingCommand,
- DeleteCurrentParagraphCommand,
DocCopyCurrentParagraphCommand,
DocCutCurrentParagraphCommand,
H1HeadingCommand,
@@ -314,7 +313,7 @@ export class UniverDocsUIPlugin extends Plugin {
this.disposeWithMe(this._commandService.registerCommand(e));
});
- [DocCopyCommand, DocCutCommand, DocPasteCommand].forEach((command) => this.disposeWithMe(this._commandService.registerMultipleCommand(command)));
+ [DocCopyCommand, DocCutCommand, DocPasteCommand, DeleteCurrentParagraphCommand].forEach((command) => this.disposeWithMe(this._commandService.registerMultipleCommand(command)));
}
private _initializeShortcut(): void {
diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
index ca980fb37f..5f81806f63 100644
--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IDisposable, IDocumentBody, IDocumentData } from '@univerjs/core';
+import type { DocumentDataModel, IDisposable, IDocumentBody, IDocumentData } from '@univerjs/core';
import type { IDocImage } from '@univerjs/docs-drawing';
import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';
import {
@@ -416,7 +416,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
}
private _getDocumentBodyInRanges(sliceType: SliceBodyType, ranges?: ITextRangeWithStyle[]) {
- const docDataModel = this._univerInstanceService.getCurrentUniverDocInstance();
+ const docDataModel = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
const allRanges = ranges ?? this._docSelectionManagerService.getDocRanges();
const results: IDocumentData['body'][] = [];
@@ -455,7 +455,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
const deleteRange = { startOffset, endOffset, collapsed };
- const docBody = docDataModel.getSelfOrHeaderFooterModel(segmentId).sliceBody(deleteRange.startOffset, deleteRange.endOffset, sliceType);
+ const docBody = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.sliceBody(deleteRange.startOffset, deleteRange.endOffset, sliceType);
if (docBody == null) {
continue;
}
diff --git a/packages/docs-ui/src/services/doc-auto-format.service.ts b/packages/docs-ui/src/services/doc-auto-format.service.ts
index b850f5eaea..c7374ec2d1 100644
--- a/packages/docs-ui/src/services/doc-auto-format.service.ts
+++ b/packages/docs-ui/src/services/doc-auto-format.service.ts
@@ -83,15 +83,15 @@ export class DocAutoFormatService extends Disposable {
const unit = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
const docRanges = this._textSelectionManagerService.getDocRanges();
const selection = docRanges.find((range) => range.isActive) ?? docRanges[0];
+ const documentDataModel = unit?.getSelfOrHeaderFooterModel(selection?.segmentId ?? '');
- if (unit && selection) {
- const doc = unit.getSelfOrHeaderFooterModel(selection.segmentId);
+ if (unit && selection && documentDataModel) {
const context: IAutoFormatContext = {
- unit: doc,
+ unit: documentDataModel,
selection,
isBody: !selection.segmentId,
- paragraphs: BuildTextUtils.range.getParagraphsInRange(selection, doc.getBody()?.paragraphs ?? [], doc.getBody()?.dataStream ?? ''),
- customRanges: BuildTextUtils.customRange.getCustomRangesInterestsWithSelection(selection, doc.getBody()?.customRanges ?? []),
+ paragraphs: BuildTextUtils.range.getParagraphsInRange(selection, documentDataModel.getBody()?.paragraphs ?? [], documentDataModel.getBody()?.dataStream ?? ''),
+ customRanges: BuildTextUtils.customRange.getCustomRangesInterestsWithSelection(selection, documentDataModel.getBody()?.customRanges ?? []),
commandId: id,
commandParams: params,
};
diff --git a/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts b/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts
index 48bef97237..79fe4d27bf 100644
--- a/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts
+++ b/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts
@@ -35,6 +35,7 @@ import {
LocalUndoRedoService,
ThemeService,
UniverInstanceService,
+ UniverInstanceType,
} from '@univerjs/core';
import {
DocSelectionManagerService,
@@ -264,7 +265,7 @@ describe('EditorService', () => {
service.focus('editor-1');
expect(service.getFocusId()).toBe('editor-1');
- expect(univerInstanceService.getCurrentUniverDocInstance()?.getUnitId()).toBe('editor-1');
+ expect(univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)?.getUnitId()).toBe('editor-1');
expect(editorFocused).toBe(1);
expect(focusRanges).toEqual([{ startOffset: 3, endOffset: 3 }]);
expect(service.getEditor()).toBe(service.getEditor('editor-1'));
diff --git a/packages/docs-ui/src/services/editor/editor-manager.service.ts b/packages/docs-ui/src/services/editor/editor-manager.service.ts
index 5f3375ce5d..8fdf1647f9 100644
--- a/packages/docs-ui/src/services/editor/editor-manager.service.ts
+++ b/packages/docs-ui/src/services/editor/editor-manager.service.ts
@@ -309,7 +309,7 @@ export class EditorService extends Disposable implements IEditorService, IDispos
}
private _getCurrentEditorUnitId() {
- const current = this._univerInstanceService.getCurrentUniverDocInstance()!;
+ const current = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)!;
return current.getUnitId();
}
diff --git a/packages/docs-ui/src/services/selection/text-range.ts b/packages/docs-ui/src/services/selection/text-range.ts
index 197a9681b9..e831f7c0b6 100644
--- a/packages/docs-ui/src/services/selection/text-range.ts
+++ b/packages/docs-ui/src/services/selection/text-range.ts
@@ -165,7 +165,7 @@ export class TextRange implements IDocRange {
.getViewModel()
.getDataModel()
.getSelfOrHeaderFooterModel(this._segmentId)
- .getBody();
+ ?.getBody();
if (startOffset == null || body == null) {
return startOffset;
@@ -183,7 +183,7 @@ export class TextRange implements IDocRange {
.getViewModel()
.getDataModel()
.getSelfOrHeaderFooterModel(this._segmentId)
- .getBody();
+ ?.getBody();
if (endOffset == null || body == null) {
return endOffset;
diff --git a/packages/docs-ui/src/views/ParagraphMenu.tsx b/packages/docs-ui/src/views/ParagraphMenu.tsx
index d1ed9260f8..704e9e6577 100644
--- a/packages/docs-ui/src/views/ParagraphMenu.tsx
+++ b/packages/docs-ui/src/views/ParagraphMenu.tsx
@@ -384,6 +384,23 @@ export function getParagraphMenuResolvedCommand(option: IValueOption, targetRang
}, targetRange);
}
+export function getParagraphMenuCommandParams(
+ commandId: string | undefined,
+ commandParams: Record<string, unknown> | undefined,
+ target: IDocBlockMenuTarget | null | undefined,
+ unitId: string
+): Record<string, unknown> | undefined {
+ if (commandId !== DeleteCurrentParagraphCommand.id || target?.kind !== 'blockRange' || !target.blockRange) {
+ return commandParams;
+ }
+
+ return {
+ ...(commandParams ?? {}),
+ unitId,
+ blockRange: target.blockRange,
+ };
+}
+
function getParagraphMenuType(target: IDocBlockMenuTarget | null | undefined, emptyMode: boolean): string {
if (target?.kind === 'table') {
return DOC_TABLE_BLOCK_MENU_ID;
@@ -1021,7 +1038,12 @@ function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; t
await executeResolvedCommand({
...option,
commandId,
- params: commandParams as Record<string, unknown> | undefined,
+ params: getParagraphMenuCommandParams(
+ commandId,
+ commandParams as Record<string, unknown> | undefined,
+ latestTarget,
+ popup.unitId
+ ),
}, getParagraphMenuCommandTargetRange(commandId, targetRange, formattingRange));
} finally {
restoreTextRanges(previousTextRanges);
diff --git a/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts b/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
index ec00ee8812..381f448674 100644
--- a/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
+++ b/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts
@@ -22,6 +22,7 @@ import type { IDocBlockMenuTarget } from '../../services/doc-paragraph-menu.serv
import { DataStreamTreeTokenType, DocumentBlockRangeType, DocumentBlockType, NamedStyleType } from '@univerjs/core';
import { DocBlockMoveValidatorService } from '@univerjs/docs';
import { describe, expect, it } from 'vitest';
+import { DeleteCurrentParagraphCommand } from '../../commands/commands/doc-delete.command';
import { HorizontalLineCommand } from '../../commands/commands/doc-horizontal-line.command';
import { BulletListCommand } from '../../commands/commands/list.command';
import { AlignCenterCommand } from '../../commands/commands/paragraph-align.command';
@@ -29,6 +30,7 @@ import { H2HeadingCommand, SetParagraphNamedStyleCommand } from '../../commands/
import { DOC_PARAGRAPH_T_EDIT_MENU_ID, INSERT_BELLOW_MENU_ID } from '../../menu/paragraph-menu';
import {
getParagraphFormattingRange,
+ getParagraphMenuCommandParams,
getParagraphMenuCommandTargetRange,
getParagraphMenuHiddenItemIds,
getParagraphMenuResolvedCommand,
@@ -173,6 +175,26 @@ describe('ParagraphMenu command behavior', () => {
expect(getParagraphMenuHiddenItemIds(DOC_PARAGRAPH_T_EDIT_MENU_ID, target)).not.toContain('docs-quote.command.insert');
});
+ it('adds block range context to current paragraph delete commands', () => {
+ const blockRange = {
+ blockId: 'code-1',
+ blockType: DocumentBlockRangeType.CODE,
+ startIndex: 20,
+ endIndex: 45,
+ };
+
+ expect(getParagraphMenuCommandParams(
+ DeleteCurrentParagraphCommand.id,
+ { source: 'menu' },
+ blockTarget(blockRange),
+ 'doc-1'
+ )).toEqual({
+ source: 'menu',
+ unitId: 'doc-1',
+ blockRange,
+ });
+ });
+
it('strips block paragraph styles when unwrapping block ranges', () => {
const codeResult = unwrapBlockRangeBody(blockRangeBody(DocumentBlockRangeType.CODE, {
indentStart: { v: 12 },
diff --git a/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx b/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx
index c406e35085..f50af9c821 100644
--- a/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx
+++ b/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IDocumentStyle } from '@univerjs/core';
+import type { DocumentDataModel, IDocumentStyle } from '@univerjs/core';
import type { IHeaderFooterProps } from '../../../commands/commands/doc-header-footer.command';
import type { LocaleKey } from '../../../locale/types';
import {
@@ -23,6 +23,7 @@ import {
ICommandService,
IUniverInstanceService,
LocaleService,
+ UniverInstanceType,
} from '@univerjs/core';
import { Button, Checkbox, InputNumber } from '@univerjs/design';
import { DocSkeletonManagerService } from '@univerjs/docs';
@@ -94,7 +95,7 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
[type]: val ? BooleanNumber.TRUE : BooleanNumber.FALSE,
}));
- const docDataModel = univerInstanceService.getUniverDocInstance(unitId);
+ const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
const documentStyle = docDataModel?.getSnapshot().documentStyle;
const docSkeletonManagerService = renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService);
const viewModel = docSkeletonManagerService?.getViewModel();
@@ -200,7 +201,7 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
};
useEffect(() => {
- const docDataModel = univerInstanceService.getUniverDocInstance(unitId);
+ const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
const documentStyle = docDataModel?.getSnapshot().documentStyle;
if (documentStyle) {
diff --git a/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterPanel.tsx b/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterPanel.tsx
index 23e14f8be8..79926b56e5 100644
--- a/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterPanel.tsx
+++ b/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterPanel.tsx
@@ -14,8 +14,9 @@
* limitations under the License.
*/
+import type { DocumentDataModel } from '@univerjs/core';
import type { LocaleKey } from '../../../locale/types';
-import { IUniverInstanceService, LocaleService } from '@univerjs/core';
+import { IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';
import { useDependency } from '@univerjs/ui';
@@ -26,9 +27,9 @@ export const DocHeaderFooterPanel = () => {
const localeService = useDependency(LocaleService);
const renderManagerService = useDependency(IRenderManagerService);
const univerInstanceService = useDependency(IUniverInstanceService);
- const documentDataModel = univerInstanceService.getCurrentUniverDocInstance()!;
+ const documentDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)!;
const unitId = documentDataModel.getUnitId()!;
- const docSkeletonManagerService = renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService);
+ const docSkeletonManagerService = renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService);
const viewModel = docSkeletonManagerService!.getViewModel();
const [isEditHeaderFooter, setIsEditHeaderFooter] = useState(true);
diff --git a/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts b/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts
index d10a7affa2..7ed5dfa5d0 100644
--- a/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts
+++ b/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts
@@ -74,8 +74,8 @@ export const useCurrentParagraph = () => {
const segmentId = docRanges[0].segmentId;
const segment = docDataModel.getSelfOrHeaderFooterModel(segmentId);
- const paragraphs = segment.getBody()?.paragraphs ?? [];
- const dataStream = segment.getBody()?.dataStream ?? '';
+ const paragraphs = segment?.getBody()?.paragraphs ?? [];
+ const dataStream = segment?.getBody()?.dataStream ?? '';
const currentParagraphs = BuildTextUtils.range.getParagraphsInRanges(docRanges, paragraphs, dataStream) ?? [];
return currentParagraphs;
@@ -92,7 +92,7 @@ export const useCurrentSections = (currentParagraphs: IParagraph[]) => {
const segmentId = docRanges[0].segmentId;
- const sectionBreaks = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.sectionBreaks ?? [];
+ const sectionBreaks = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.sectionBreaks ?? [];
const currentSectionBreaks = currentParagraphs
.map((item) => findNearestSectionBreak(item.startIndex, sectionBreaks))
.reduce((a, b, index, list) => {
diff --git a/packages/docs/src/commands/commands/core-editing.command.ts b/packages/docs/src/commands/commands/core-editing.command.ts
index 57e027b3f4..001fb41962 100644
--- a/packages/docs/src/commands/commands/core-editing.command.ts
+++ b/packages/docs/src/commands/commands/core-editing.command.ts
@@ -67,7 +67,7 @@ export const InsertTextCommand: ICommand<IInsertTextCommandParams> = {
}
const activeRange = docSelectionManagerService.getActiveTextRange();
- const originBody = docDataModel.getSelfOrHeaderFooterModel(activeRange?.segmentId ?? '').getBody();
+ const originBody = docDataModel.getSelfOrHeaderFooterModel(activeRange?.segmentId ?? '')?.getBody();
if (originBody == null) {
return false;
@@ -153,7 +153,7 @@ export const DeleteTextCommand: ICommand<IDeleteTextCommandParams> = {
const univerInstanceService = accessor.get(IUniverInstanceService);
const { range, segmentId, unitId, direction, len = 1 } = params;
const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (docDataModel == null || body == null) {
return false;
}
@@ -230,7 +230,7 @@ export const UpdateTextCommand: ICommand<IUpdateTextCommandParams> = {
const { range, segmentId, updateBody, coverType, unitId, textRanges } = params;
const commandService = accessor.get(ICommandService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (docDataModel == null) {
return false;
diff --git a/packages/docs/src/facade/__tests__/f-document-block-range.spec.ts b/packages/docs/src/facade/__tests__/f-document-block-range.spec.ts
deleted file mode 100644
index c5b7b230b0..0000000000
--- a/packages/docs/src/facade/__tests__/f-document-block-range.spec.ts
+++ /dev/null
@@ -1,67 +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 { Univer } from '@univerjs/core';
-import type { FDocument } from '../f-document';
-import { DocumentBlockRangeType, DocumentBlockType } from '@univerjs/core';
-import { afterEach, describe, expect, it } from 'vitest';
-import { createBlockRangeDocument, createTestBed } from './create-test-bed';
-
-describe('FDocumentBlockRange', () => {
- let univer: Univer | null = null;
- let document: FDocument;
-
- function createDocumentFacade(blockType = DocumentBlockRangeType.QUOTE) {
- univer?.dispose();
- const testBed = createTestBed(createBlockRangeDocument(blockType));
- univer = testBed.univer;
- document = testBed.univerAPI.getActiveDocument()!;
- }
-
- afterEach(() => {
- univer?.dispose();
- univer = null;
- });
-
- 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.getElement(0)!.asBlockRange();
-
- 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(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(block.getText()).toBe('Updated');
- expect(block.remove()).toBe(true);
- expect(document.save().body?.dataStream).toBe('Intro\rAfter\r\n');
- }
- });
-
- it('unwraps a block range from the body', () => {
- createDocumentFacade();
-
- 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-document-body.spec.ts b/packages/docs/src/facade/__tests__/f-document-body.spec.ts
deleted file mode 100644
index ebf1849482..0000000000
--- a/packages/docs/src/facade/__tests__/f-document-body.spec.ts
+++ /dev/null
@@ -1,109 +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 { Univer } from '@univerjs/core';
-import type { FDocument } from '../f-document';
-import { DocumentBlockType } from '@univerjs/core';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { createSimpleDocument, createTestBed } from './create-test-bed';
-
-describe('FDocumentBody', () => {
- let univer: Univer;
- let document: FDocument;
-
- beforeEach(() => {
- const testBed = createTestBed(createSimpleDocument());
- univer = testBed.univer;
- document = testBed.univerAPI.getActiveDocument()!;
- });
-
- afterEach(() => {
- univer.dispose();
- });
-
- it('reads, inserts, replaces, styles and removes paragraphs by stable paragraph ids', () => {
- const body = document.getBody();
- expect(body.getElements()).toHaveLength(3);
-
- 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().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.getElement(1)!.getPreviousSibling()?.asParagraph().getText()).toBe('Alpha');
- expect(first.getSibling(1)?.asParagraph().getText()).toBe('Beta');
-
- 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.getParagraphId()).toMatch(/^para_/);
- expect(title.getKey()).toBe(title.getParagraphId());
- expect(title.getText()).toBe('Title');
- 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');
- expect(tail.getText()).toBe('Tail');
- 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.getElement(0)!.asParagraph().setText('Hi Alpha')).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.getElement(0)!.asParagraph();
- expect(paragraph.setStyle({ horizontalAlign: 2 })).toBe(true);
- expect(document.save().body?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(2);
-
- 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(paragraph.setText('Updated')).toBe(true);
- expect(paragraph.getText()).toBe('Updated');
- expect(paragraph.appendText(' suffix')).toBe(true);
- expect(paragraph.getText()).toBe('Updated suffix');
- expect(body.removeParagraph(paragraph)).toBe(true);
- expect(document.save().body?.dataStream).toBe('Beta\rGamma\rTail\r\n');
- });
-
- it('rejects ambiguous or missing paragraph identities as stale elements', () => {
- const body = document.getBody();
- document.getDocumentDataModel().getBody()!.paragraphs![1].paragraphId = 'para_alpha';
- 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.getElement(0)).toThrow('Paragraph at index 0 is missing paragraphId.');
- });
-});
diff --git a/packages/docs/src/facade/__tests__/f-document-custom-block.spec.ts b/packages/docs/src/facade/__tests__/f-document-custom-block.spec.ts
deleted file mode 100644
index fe6110229b..0000000000
--- a/packages/docs/src/facade/__tests__/f-document-custom-block.spec.ts
+++ /dev/null
@@ -1,57 +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 { 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('FDocumentCustomBlock', () => {
- let univer: Univer;
- let document: FDocument;
-
- function createDocumentFacade() {
- univer?.dispose();
- const testBed = createTestBed(createCustomBlockDocument());
- univer = testBed.univer;
- document = testBed.univerAPI.getActiveDocument()!;
- }
-
- beforeEach(() => {
- createDocumentFacade();
- });
-
- afterEach(() => {
- univer.dispose();
- });
-
- it('exposes custom block identity and removes the block from document body', () => {
- const body = document.getBody();
- const customBlock = body.getElement(0)!.asCustomBlock();
-
- expect(customBlock.getType()).toBe(DocumentBlockType.CUSTOM_BLOCK);
- expect(customBlock.getKey()).toBe('custom-1');
- expect(customBlock.getParent()).toBe(body);
- expect(customBlock.getCustomBlock().blockId).toBe('custom-1');
- expect(body.removeCustomBlock(customBlock)).toBe(true);
- expect(document.save().body?.customBlocks).toEqual([]);
-
- createDocumentFacade();
- 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-document-element.spec.ts b/packages/docs/src/facade/__tests__/f-document-element.spec.ts
deleted file mode 100644
index de53b698bd..0000000000
--- a/packages/docs/src/facade/__tests__/f-document-element.spec.ts
+++ /dev/null
@@ -1,86 +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 { IDocumentData, Univer } from '@univerjs/core';
-import type { FDocument } from '../f-document';
-import { DocumentBlockRangeType, DocumentBlockType } from '@univerjs/core';
-import { afterEach, describe, expect, it } from 'vitest';
-import {
- createBlockRangeDocument,
- createCustomBlockDocument,
- createSimpleDocument,
- createTableDocument,
- createTestBed,
-} from './create-test-bed';
-
-describe('FDocumentElement', () => {
- let univer: Univer | null = null;
- let document: FDocument;
-
- function createDocumentFacade(docData: IDocumentData) {
- univer?.dispose();
- const testBed = createTestBed(docData);
- univer = testBed.univer;
- document = testBed.univerAPI.getActiveDocument()!;
- }
-
- afterEach(() => {
- univer?.dispose();
- univer = null;
- });
-
- it('casts body elements to their concrete facade types', () => {
- createDocumentFacade(createSimpleDocument());
- expect(document.getBody().getElement(0)!.asParagraph().getText()).toBe('Alpha');
-
- createDocumentFacade(createBlockRangeDocument());
- expect(document.getBody().getElement(0)!.asBlockRange().getBlockType()).toBe(DocumentBlockRangeType.QUOTE);
-
- createDocumentFacade(createTableDocument());
- expect(document.getBody().getElement(0)!.asTable().getTable().tableId).toBe('table-1');
-
- createDocumentFacade(createCustomBlockDocument());
- expect(document.getBody().getElement(0)!.asCustomBlock().getCustomBlock().blockId).toBe('custom-1');
- });
-
- it('removes a generic element from its parent', () => {
- createDocumentFacade(createSimpleDocument());
-
- expect(document.getBody().getElement(0)!.remove()).toBe(true);
- expect(document.save().body?.dataStream).toBe('Beta\rGamma\r\n');
- });
-
- it('navigates siblings and rejects invalid casts without changing the element type', () => {
- createDocumentFacade(createSimpleDocument());
-
- const body = document.getBody();
- 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('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());
- 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-document-paragraph.spec.ts b/packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts
index 1d6bd910ff..758f936669 100644
--- a/packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document-paragraph.spec.ts
@@ -16,10 +16,11 @@
import type { IDocumentData, Univer } from '@univerjs/core';
import type { FDocument } from '../f-document';
-import { DocumentBlockType, PresetListType } from '@univerjs/core';
+import { PresetListType } from '@univerjs/core';
import { afterEach, describe, expect, it } from 'vitest';
import {
createBulletDocument,
+ createDocumentData,
createDuplicateDocument,
createSimpleDocument,
createTaskDocument,
@@ -45,12 +46,11 @@ describe('FDocumentParagraph', () => {
it('keeps paragraph handles stable when text is duplicated or inserted before them', () => {
createDocumentFacade(createDuplicateDocument());
- const body = document.getBody();
- const secondSame = body.getElement(1)!.asParagraph();
+ const secondSame = document.getParagraphs()[1];
- expect(secondSame.getParagraphId()).toBe('para_same_2');
- expect(body.insertParagraph(0, 'X').getText()).toBe('X');
- expect(body.getElementIndex(secondSame)).toBe(2);
+ expect(secondSame.getId()).toBe('para_same_2');
+ expect(document.insertParagraph(0, 'X').getText()).toBe('X');
+ expect(secondSame.getInfo().paragraphIndex).toBe(2);
expect(secondSame.setText('Picked')).toBe(true);
expect(document.save().body?.dataStream).toBe('X\rSame\rPicked\rTail\r\n');
expect(secondSame.remove()).toBe(true);
@@ -60,7 +60,7 @@ describe('FDocumentParagraph', () => {
it('marks paragraph handles as stale after their backing paragraph is removed', () => {
createDocumentFacade(createSimpleDocument());
- const paragraph = document.getBody().getElement(1)!.asParagraph();
+ const paragraph = document.getParagraphs()[1];
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');
@@ -69,19 +69,15 @@ describe('FDocumentParagraph', () => {
it('updates checklist paragraphs without changing non-task list items', () => {
createDocumentFacade(createBulletDocument());
- const bulletBody = document.getBody();
- const listItem = bulletBody.getElement(0)!.asParagraph();
- expect(listItem.getType()).toBe(DocumentBlockType.PARAGRAPH);
- expect(listItem.getKey()).toMatch(/^para_/);
- expect(listItem.getParagraphId()).toBe(listItem.getKey());
- expect(listItem.getParent()).toBe(bulletBody);
+ const listItem = document.getParagraphs()[0];
+ expect(listItem.getId()).toMatch(/^para_/);
expect(listItem.isListItem()).toBe(true);
expect(listItem.isTask()).toBe(false);
expect(listItem.setTaskChecked(true)).toBe(false);
createDocumentFacade(createTaskDocument());
- const task = document.getBody().getElement(0)!.asParagraph();
+ const task = document.getParagraphs()[0];
expect(task.isListItem()).toBe(true);
expect(task.isTask()).toBe(true);
expect(task.setTaskChecked(true)).toBe(true);
@@ -89,4 +85,73 @@ describe('FDocumentParagraph', () => {
expect(task.setTaskChecked(false)).toBe(true);
expect(document.save().body?.paragraphs?.[0].bullet?.listType).toBe(PresetListType.CHECK_LIST);
});
+
+ it('applies paragraph text style to the paragraph text range', () => {
+ createDocumentFacade(createSimpleDocument());
+
+ const paragraph = document.getParagraphs()[0];
+
+ expect(paragraph.setStyle({
+ textStyle: {
+ cl: {
+ rgb: '#FF0000',
+ },
+ fs: 14,
+ },
+ horizontalAlign: 2,
+ })).toBe(true);
+
+ expect(document.save().body?.paragraphs?.[0].paragraphStyle).toMatchObject({
+ horizontalAlign: 2,
+ textStyle: {
+ cl: {
+ rgb: '#FF0000',
+ },
+ fs: 14,
+ },
+ });
+ expect(document.save().body?.textRuns).toEqual([
+ {
+ st: 0,
+ ed: 5,
+ ts: {
+ cl: {
+ rgb: '#FF0000',
+ },
+ fs: 14,
+ },
+ },
+ ]);
+ });
+
+ it('keeps paragraph edits scoped to their header segment', () => {
+ const headerId = 'header-1';
+ createDocumentFacade({
+ ...createDocumentData('doc-with-header', {
+ dataStream: 'Body\r\n',
+ paragraphs: [{ startIndex: 4, paragraphId: 'para_body' }],
+ sectionBreaks: [{ startIndex: 5 }],
+ }),
+ headers: {
+ [headerId]: {
+ headerId,
+ body: {
+ dataStream: 'Head\r\n',
+ paragraphs: [{ startIndex: 4, paragraphId: 'para_header' }],
+ sectionBreaks: [{ startIndex: 5 }],
+ },
+ },
+ },
+ });
+
+ const headerParagraph = document.getParagraphs(headerId)[0];
+
+ expect(headerParagraph.getSegmentId()).toBe(headerId);
+ expect(headerParagraph.appendText('er')).toBe(true);
+ expect(document.appendParagraph('Tail', headerId).getText()).toBe('Tail');
+
+ expect(document.getBody().dataStream).toBe('Body\r\n');
+ expect(document.getBody(headerId).dataStream).toBe('Header\rTail\r\n');
+ expect(document.getBody(headerId).paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([6, 11]);
+ });
});
diff --git a/packages/docs/src/facade/__tests__/f-document-table.spec.ts b/packages/docs/src/facade/__tests__/f-document-table.spec.ts
deleted file mode 100644
index 9922c84bc4..0000000000
--- a/packages/docs/src/facade/__tests__/f-document-table.spec.ts
+++ /dev/null
@@ -1,57 +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 { 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('FDocumentTable', () => {
- let univer: Univer;
- let document: FDocument;
-
- function createDocumentFacade() {
- univer?.dispose();
- const testBed = createTestBed(createTableDocument());
- univer = testBed.univer;
- document = testBed.univerAPI.getActiveDocument()!;
- }
-
- beforeEach(() => {
- createDocumentFacade();
- });
-
- afterEach(() => {
- univer.dispose();
- });
-
- it('exposes table identity and removes the table from document body', () => {
- const body = document.getBody();
- const table = body.getElement(0)!.asTable();
-
- expect(table.getType()).toBe(DocumentBlockType.TABLE);
- expect(table.getKey()).toBe('table-1');
- expect(table.getParent()).toBe(body);
- expect(table.getTable().tableId).toBe('table-1');
- expect(body.removeTable(table)).toBe(true);
- expect(document.save().body?.tables).toEqual([]);
-
- createDocumentFacade();
- 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 71041251d7..946733fc34 100644
--- a/packages/docs/src/facade/__tests__/f-document.spec.ts
+++ b/packages/docs/src/facade/__tests__/f-document.spec.ts
@@ -44,18 +44,18 @@ describe('FDocument', () => {
});
it('edits document text through body and paragraph operations', () => {
- expect(document.getBody().insertText(6, 'Univer')).toBe(true);
+ expect(document.insertText(6, 'Univer')).toBe(true);
expect(document.save().body?.dataStream).toBe('Hello,Univer\r\n');
univer.dispose();
createDocumentFacade();
- expect(document.getBody().getElement(0)!.asParagraph().setText('HeDocso,')).toBe(true);
+ expect(document.getParagraphs()[0].setText('HeDocso,')).toBe(true);
expect(document.save().body?.dataStream).toBe('HeDocso,\r\n');
univer.dispose();
createDocumentFacade();
- expect(document.getBody().appendParagraph('Line 1').getText()).toBe('Line 1');
- expect(document.getBody().appendParagraph('Line 2').getText()).toBe('Line 2');
+ expect(document.appendParagraph('Line 1').getText()).toBe('Line 1');
+ expect(document.appendParagraph('Line 2').getText()).toBe('Line 2');
expect(document.save().body?.dataStream).toBe('Hello,\rLine 1\rLine 2\r\n');
});
@@ -104,21 +104,20 @@ describe('FDocument', () => {
expect(document.save().body?.dataStream).toBe('Hello,One\r\n');
});
- it('preserves paragraph ids in saved snapshots and body wrappers', () => {
+ it('preserves paragraph ids in saved snapshots and paragraph facades', () => {
univer.dispose();
createDocumentFacade(createSimpleDocument());
const savedParagraphs = document.save().body?.paragraphs;
- const body = document.getBody();
- const paragraph = body.getElement(0)!.asParagraph();
+ const paragraph = document.getParagraphs()[0];
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.getParagraphId()).toBe('para_alpha');
+ expect(paragraph.getId()).toBe('para_alpha');
expect(paragraph.getText()).toBe('Alpha');
});
- it('keeps caller-provided paragraph ids when creating a body facade', () => {
+ it('keeps caller-provided paragraph ids when creating paragraph facades', () => {
univer.dispose();
createDocumentFacade(createDocumentData('doc-with-ids', {
dataStream: 'Legacy\r\n',
@@ -126,9 +125,26 @@ describe('FDocument', () => {
sectionBreaks: [{ startIndex: 7 }],
}));
- const paragraph = document.getBody().getElement(0)!.asParagraph();
+ const paragraph = document.getParagraphs()[0];
- expect(paragraph.getParagraphId()).toBe('para_fixture_26');
+ expect(paragraph.getId()).toBe('para_fixture_26');
expect(document.save().body?.paragraphs?.[0].paragraphId).toBe('para_fixture_26');
});
+
+ it('preserves an editable empty paragraph when deleting past the end of an empty document', () => {
+ univer.dispose();
+ createDocumentFacade(createDocumentData('empty-doc', {
+ dataStream: '\r\n',
+ paragraphs: [{ startIndex: 0, paragraphId: 'para_empty' }],
+ sectionBreaks: [{ startIndex: 1 }],
+ }));
+
+ document.deleteRange({ startOffset: 0, endOffset: 5 });
+ const paragraph = document.insertParagraph(0, 'Document title');
+ expect(paragraph.appendText(' suffix')).toBe(true);
+
+ expect(document.save().body?.dataStream).toBe('Document title suffix\r\r\n');
+ expect(document.save().body?.paragraphs?.map((item) => item.startIndex)).toEqual([21, 22]);
+ expect(document.getParagraphs()[0].getText()).toBe('Document title suffix');
+ });
});
diff --git a/packages/docs/src/facade/f-document-block-range.ts b/packages/docs/src/facade/f-document-block-range.ts
deleted file mode 100644
index 315c22b3d5..0000000000
--- a/packages/docs/src/facade/f-document-block-range.ts
+++ /dev/null
@@ -1,183 +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, IDocumentBlockRange, Injector } from '@univerjs/core';
-import type { FDocumentBody, IFDocumentBodyEdit } 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 bodyEdit: IFDocumentBodyEdit,
- protected readonly info: IFDocumentElementInfo,
- protected readonly injector: Injector
- ) {
- super(body, bodyEdit, 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._bodyEdit.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._bodyEdit, 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
deleted file mode 100644
index 6ed21f08fd..0000000000
--- a/packages/docs/src/facade/f-document-body.ts
+++ /dev/null
@@ -1,561 +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, 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;
-}
-
-export interface IFDocumentBodyEdit {
- replaceRange: (range: IFDocumentTextRange, body: IDocumentBody) => boolean;
- retainRange: (range: IFDocumentTextRange, body: IDocumentBody, coverType: UpdateDocsAttributeType) => boolean;
-}
-
-/**
- * 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 {
- private readonly _bodyEdit: IFDocumentBodyEdit;
-
- constructor(
- private readonly _documentDataModel: DocumentDataModel,
- private readonly _injector: Injector,
- private readonly _segmentId = ''
- ) {
- this._bodyEdit = {
- replaceRange: this._replaceBodyRange.bind(this),
- retainRange: this._retainBodyRange.bind(this),
- };
- }
-
- /**
- * 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,
- this._bodyEdit,
- 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,
- this._bodyEdit,
- 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: '' });
- }
-
- /**
- * 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
deleted file mode 100644
index 58ff06e18f..0000000000
--- a/packages/docs/src/facade/f-document-custom-block.ts
+++ /dev/null
@@ -1,83 +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 { ICustomBlock, Injector } from '@univerjs/core';
-import type { FDocumentBody, IFDocumentBodyEdit } 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 bodyEdit: IFDocumentBodyEdit,
- protected readonly info: IFDocumentElementInfo,
- protected readonly injector: Injector
- ) {
- super(body, bodyEdit, 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._bodyEdit, 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
deleted file mode 100644
index 8fbe0db145..0000000000
--- a/packages/docs/src/facade/f-document-element.ts
+++ /dev/null
@@ -1,255 +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 { Injector } from '@univerjs/core';
-import type { FDocumentBody, IFDocumentBodyEdit } 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 _bodyEdit: IFDocumentBodyEdit,
- 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
index d4dd800ff5..89ae22b012 100644
--- a/packages/docs/src/facade/f-document-paragraph.ts
+++ b/packages/docs/src/facade/f-document-paragraph.ts
@@ -15,20 +15,15 @@
*/
import type { IDocumentBody, Injector, IParagraph, IParagraphStyle } from '@univerjs/core';
-import type { FDocumentBody, IFDocumentBodyEdit, 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';
-import { buildPlainTextInsertBody } from './utils';
-
-interface IFDocumentParagraphMixin {
- asParagraph(): FDocumentParagraph;
-}
+import type { FDocument } from './f-document';
+import type { IFDocumentTextRange } from './utils';
+import { PresetListType, RESTORE_INSERTED_PARAGRAPH_IDS, UpdateDocsAttributeType } from '@univerjs/core';
+import { buildPlainTextInsertBody, replaceBodyRange, retainBodyRange } from './utils';
/**
* Resolved paragraph metadata in the the document body.
*/
-export interface IFDocumentResolvedParagraph {
+export interface IFDocumentParagraphInfo {
/** The underlying paragraph snapshot object. */
paragraph: IParagraph;
/** The current paragraph index in the body paragraph list. */
@@ -48,19 +43,13 @@ export interface IFDocumentResolvedParagraph {
*
* @hideconstructor
*/
-export class FDocumentParagraph extends FDocumentElement {
+export class FDocumentParagraph {
constructor(
- protected readonly body: FDocumentBody,
- protected readonly bodyEdit: IFDocumentBodyEdit,
- protected readonly info: IFDocumentElementInfo,
- protected readonly injector: Injector
- ) {
- super(body, bodyEdit, info, injector);
-
- if (this.getType() !== DocumentBlockType.PARAGRAPH) {
- throw new Error(`Element type is not a paragraph: ${this.getType()}`);
- }
- }
+ private readonly _document: FDocument,
+ private readonly _paragraphId: string,
+ private readonly _segmentId = '',
+ private readonly _injector: Injector
+ ) {}
/**
* Get the persisted paragraph id.
@@ -68,46 +57,52 @@ export class FDocumentParagraph extends FDocumentElement {
* @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());
- * }
+ * const paragraph = fDocument.getParagraphs()[0];
+ * console.log(paragraph?.getId());
* ```
*/
- getParagraphId(): string {
- return this.getKey();
+ getId(): string {
+ return this._paragraphId;
}
/**
- * Get the resolved paragraph info for this wrapper.
- * @returns {IFDocumentResolvedParagraph} The resolved paragraph info, including the paragraph object, its index, and its text range.
+ * Get the segment id of this paragraph.
+ * The main body paragraphs have an empty string segment id.
+ * The header and footer paragraphs have a non-empty string segment id.
+ * @returns {string} The segment 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.getResolvedParagraphInfo());
- * }
+ * const paragraph = fDocument.getParagraphs()[0];
+ * console.log(paragraph?.getSegmentId());
* ```
*/
- getResolvedParagraphInfo(): IFDocumentResolvedParagraph {
- const { paragraphs = [] } = this._body.getBody();
+ getSegmentId(): string {
+ return this._segmentId;
+ }
+
+ /**
+ * Get this paragraph's metadata.
+ * @returns {IFDocumentParagraphInfo} The paragraph info.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const paragraph = fDocument.getParagraphs()[0];
+ * console.log(paragraph?.getInfo());
+ * ```
+ */
+ getInfo(): IFDocumentParagraphInfo {
+ const { paragraphs = [] } = this._document.getBody(this._segmentId);
const matches = paragraphs
.map((paragraph, paragraphIndex) => ({ paragraph, paragraphIndex }))
- .filter(({ paragraph }) => paragraph.paragraphId === this.getKey());
+ .filter(({ paragraph }) => paragraph.paragraphId === this._paragraphId);
if (matches.length === 0) {
- throw new Error(`Document paragraph with id ${this.getKey()} not found`);
+ throw new Error(`Document paragraph with id ${this._paragraphId} not found`);
}
if (matches.length > 1) {
- throw new Error(`Multiple document paragraphs with id ${this.getKey()} found`);
+ throw new Error(`Multiple document paragraphs with id ${this._paragraphId} found`);
}
const { paragraph, paragraphIndex } = matches[0];
@@ -127,19 +122,13 @@ export class FDocumentParagraph extends FDocumentElement {
* @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 });
- * }
+ * const paragraph = fDocument.getParagraphs()[0];
+ * console.log(paragraph?.getRange());
* ```
*/
getRange(): IFDocumentTextRange {
- const { startOffset, endOffset } = this.getResolvedParagraphInfo();
- return { startOffset, endOffset, segmentId: this._body.getSegmentId() };
+ const { startOffset, endOffset } = this.getInfo();
+ return { startOffset, endOffset, segmentId: this._segmentId };
}
/**
@@ -148,18 +137,13 @@ export class FDocumentParagraph extends FDocumentElement {
* @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());
- * }
+ * const paragraph = fDocument.getParagraphs()[0];
+ * console.log(paragraph?.getText());
* ```
*/
getText(): string {
- const { dataStream } = this._body.getBody();
- const { startOffset, endOffset } = this.getResolvedParagraphInfo();
+ const { dataStream } = this._document.getBody(this._segmentId);
+ const { startOffset, endOffset } = this.getInfo();
return dataStream.slice(startOffset, endOffset);
}
@@ -170,19 +154,23 @@ export class FDocumentParagraph extends FDocumentElement {
* @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');
- * }
+ * const paragraph = fDocument.getParagraphs()[0];
+ * paragraph?.setText('New text');
+ * console.log(paragraph?.getText());
* ```
*/
setText(text: string): boolean {
- const { startOffset, endOffset } = this.getResolvedParagraphInfo();
- return this._bodyEdit.replaceRange({ startOffset, endOffset }, buildPlainTextInsertBody(text));
+ const { startOffset, endOffset } = this.getInfo();
+ return replaceBodyRange(
+ {
+ startOffset,
+ endOffset,
+ segmentId: this._segmentId,
+ },
+ buildPlainTextInsertBody(text),
+ this._document.getDocumentDataModel(),
+ this._injector
+ );
}
/**
@@ -192,19 +180,14 @@ export class FDocumentParagraph extends FDocumentElement {
* @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');
- * }
+ * const paragraph = fDocument.getParagraphs()[0];
+ * paragraph?.appendText(' Appended text');
+ * console.log(paragraph?.getText());
* ```
*/
appendText(text: string): boolean {
- const { endOffset } = this.getResolvedParagraphInfo();
- return this._body.insertText(endOffset, text);
+ const { endOffset } = this.getInfo();
+ return this._document.insertText(endOffset, text, this._segmentId);
}
/**
@@ -214,17 +197,44 @@ export class FDocumentParagraph extends FDocumentElement {
* @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 });
- * }
+ * const paragraph = fDocument.getParagraphs()[0];
+ * paragraph?.setText('Styled text');
+ * paragraph?.setStyle({
+ * textStyle: {
+ * cl: {
+ * rgb: '#FF0000',
+ * },
+ * fs: 14,
+ * },
+ * horizontalAlign: 2,
+ * });
+ * console.log(paragraph?.getInfo().paragraph.paragraphStyle);
* ```
*/
setStyle(style: IParagraphStyle): boolean {
- const { paragraph, endOffset } = this.getResolvedParagraphInfo();
+ const { paragraph, startOffset, endOffset } = this.getInfo();
+ let result = true;
+
+ if (style.textStyle && startOffset < endOffset) {
+ result = retainBodyRange(
+ {
+ startOffset,
+ endOffset,
+ segmentId: this._segmentId,
+ },
+ {
+ dataStream: '',
+ textRuns: [{
+ st: 0,
+ ed: endOffset - startOffset,
+ ts: style.textStyle,
+ }],
+ },
+ UpdateDocsAttributeType.COVER,
+ this._document.getDocumentDataModel(),
+ this._injector
+ );
+ }
const updateBody: IDocumentBody = {
dataStream: '',
@@ -240,11 +250,17 @@ export class FDocumentParagraph extends FDocumentElement {
this._preserveExplicitParagraphIds(updateBody);
- return this._bodyEdit.retainRange(
- { startOffset: endOffset, endOffset: endOffset + 1 },
+ return retainBodyRange(
+ {
+ startOffset: endOffset,
+ endOffset: endOffset + 1,
+ segmentId: this._segmentId,
+ },
updateBody,
- UpdateDocsAttributeType.REPLACE
- );
+ UpdateDocsAttributeType.REPLACE,
+ this._document.getDocumentDataModel(),
+ this._injector
+ ) && result;
}
/**
@@ -253,17 +269,12 @@ export class FDocumentParagraph extends FDocumentElement {
* @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');
- * }
+ * const paragraph = fDocument.getParagraphs()[0];
+ * console.log(paragraph?.isListItem());
* ```
*/
isListItem(): boolean {
- const { paragraph } = this.getResolvedParagraphInfo();
+ const { paragraph } = this.getInfo();
return Boolean(paragraph.bullet);
}
@@ -273,17 +284,12 @@ export class FDocumentParagraph extends FDocumentElement {
* @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');
- * }
+ * const paragraph = fDocument.getParagraphs()[0];
+ * console.log(paragraph?.isTask());
* ```
*/
isTask(): boolean {
- const { paragraph } = this.getResolvedParagraphInfo();
+ const { paragraph } = this.getInfo();
const listType = paragraph.bullet?.listType;
return listType === PresetListType.CHECK_LIST || listType === PresetListType.CHECK_LIST_CHECKED;
}
@@ -295,16 +301,11 @@ export class FDocumentParagraph extends FDocumentElement {
* @example
* ```ts
* const fDocument = univerAPI.getActiveDocument();
- * const fDocumentBody = fDocument.getBody();
- * const element = fDocumentBody.getElement(0);
+ * const paragraph = fDocument.getParagraphs()[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');
- * }
+ * if (paragraph.isTask()) {
+ * const success = paragraph.setTaskChecked(true);
+ * console.log(success ? 'Task checked' : 'Failed to check task');
* }
* ```
*/
@@ -313,7 +314,7 @@ export class FDocumentParagraph extends FDocumentElement {
return false;
}
- const { paragraph, endOffset } = this.getResolvedParagraphInfo();
+ const { paragraph, endOffset } = this.getInfo();
const bullet = paragraph.bullet!;
const updateBody: IDocumentBody = {
@@ -330,29 +331,51 @@ export class FDocumentParagraph extends FDocumentElement {
this._preserveExplicitParagraphIds(updateBody);
- return this._bodyEdit.retainRange(
- { startOffset: endOffset, endOffset: endOffset + 1 },
+ return retainBodyRange(
+ {
+ startOffset: endOffset,
+ endOffset: endOffset + 1,
+ segmentId: this._segmentId,
+ },
updateBody,
- UpdateDocsAttributeType.REPLACE
+ UpdateDocsAttributeType.REPLACE,
+ this._document.getDocumentDataModel(),
+ this._injector
);
}
+ /**
+ * Remove this paragraph.
+ * @returns {boolean} `true` if the paragraph was removed.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const paragraph = fDocument.getParagraphs()[0];
+ * const success = paragraph?.remove();
+ * console.log(success ? 'Paragraph removed' : 'Failed to remove paragraph');
+ * ```
+ */
+ remove(): boolean {
+ const { startOffset, endOffset } = this.getInfo();
+ return this._document.deleteRange({
+ startOffset,
+ endOffset: endOffset + 1,
+ segmentId: this._segmentId,
+ });
+ }
+
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._bodyEdit, this.getResolvedInfo(), this._injector);
+export function isParagraphFacade(value: unknown): value is FDocumentParagraph {
+ if (typeof value !== 'object' || value === null) {
+ return false;
}
-}
-FDocumentElement.extend(FDocumentParagraphMixin);
-declare module '@univerjs/docs/facade' {
- // eslint-disable-next-line ts/naming-convention
- interface FDocumentElement extends IFDocumentParagraphMixin { }
+ return typeof (value as FDocumentParagraph).getId === 'function' &&
+ typeof (value as FDocumentParagraph).getSegmentId === 'function' &&
+ typeof (value as FDocumentParagraph).getInfo === 'function' &&
+ typeof (value as FDocumentParagraph).getRange === 'function';
}
diff --git a/packages/docs/src/facade/f-document-table.ts b/packages/docs/src/facade/f-document-table.ts
deleted file mode 100644
index 1c7091be4c..0000000000
--- a/packages/docs/src/facade/f-document-table.ts
+++ /dev/null
@@ -1,83 +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 { ICustomTable, Injector } from '@univerjs/core';
-import type { FDocumentBody, IFDocumentBodyEdit } 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 bodyEdit: IFDocumentBodyEdit,
- protected readonly info: IFDocumentElementInfo,
- protected readonly injector: Injector
- ) {
- super(body, bodyEdit, 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._bodyEdit, 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 a9df543ebb..415647b0a4 100644
--- a/packages/docs/src/facade/f-document.ts
+++ b/packages/docs/src/facade/f-document.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
+import type { DocumentDataModel, IDocumentBody, IDocumentData } from '@univerjs/core';
+import type { IFDocumentTextRange } from './utils';
import {
ICommandService,
Inject,
@@ -25,7 +26,14 @@ import {
UndoCommand,
} from '@univerjs/core';
import { FBaseInitialable } from '@univerjs/core/facade';
-import { FDocumentBody } from './f-document-body';
+import { FDocumentParagraph } from './f-document-paragraph';
+import { buildPlainTextInsertBody, replaceBodyRange } from './utils';
+
+export interface IFDocumentParagraphQuery {
+ text?: string;
+ paragraphId?: string;
+ segmentId?: string;
+}
/**
* Facade API object bounded to a document. It provides a set of methods to interact with the document.
@@ -48,43 +56,44 @@ export class FDocument extends FBaseInitialable {
/**
* Get the document data model of the document.
+ * @param {string} segmentId The segment id used to get the header/footer data model. Defaults to an empty string for the document data model of the document.
* @returns {DocumentDataModel} The document data model.
* @example
* ```typescript
* const fDocument = univerAPI.getActiveDocument();
- * const documentDataModel = fDocument.getDocumentDataModel();
- * console.log(documentDataModel);
+ * console.log(fDocument.getDocumentDataModel());
+ * console.log(fDocument.getDocumentDataModel('header-01')); // Get the header data model
+ * console.log(fDocument.getDocumentDataModel('footer-01')); // Get the footer data model
* ```
*/
- getDocumentDataModel(): DocumentDataModel {
- return this._documentDataModel;
+ getDocumentDataModel(segmentId: string = ''): DocumentDataModel {
+ const documentDataModel = this._documentDataModel.getSelfOrHeaderFooterModel(segmentId);
+ if (!documentDataModel) {
+ throw new Error(segmentId === '' ? 'Document data model is not found.' : `Document data model is not found in the segment: ${segmentId}`);
+ }
+ return 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
- * use their persisted `paragraphId` values. Persisted elements, such as tables
- * and custom blocks, use their existing ids.
- *
- * @returns {FDocumentBody} The document body API instance.
+ * Get the document body or header/footer body by the segment id.
+ * The main body has an empty segment id.
+ * The header and footer body have their respective segment ids.
+ * @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
+ * @returns {IDocumentBody} The document body.
* @example
* ```typescript
* const fDocument = univerAPI.getActiveDocument();
- * const fDocumentBody = fDocument.getBody();
- * console.log(fDocumentBody.getBody());
- *
- * const element = fDocumentBody.getElement(0);
- * if (element.isParagraph()) {
- * const paragraph = element.asParagraph();
- * paragraph.appendText(' updated');
- * console.log(paragraph.getText());
- * }
+ * console.log(fDocument.getBody()); // Get the main body
+ * console.log(fDocument.getBody('header-01')); // Get the header body
+ * console.log(fDocument.getBody('footer-01')); // Get the footer body
* ```
*/
- getBody(): FDocumentBody {
- return this._injector.createInstance(FDocumentBody, this._documentDataModel, this._injector);
+ getBody(segmentId: string = ''): IDocumentBody {
+ const body = this._documentDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+ if (!body) {
+ throw new Error(segmentId === '' ? 'Body is not found in the document.' : `Body is not found in the segment: ${segmentId}`);
+ }
+ return body;
}
override dispose(): void {
@@ -97,8 +106,7 @@ export class FDocument extends FBaseInitialable {
* @example
* ```typescript
* const fDocument = univerAPI.getActiveDocument();
- * const unitId = fDocument.getId();
- * console.log(unitId);
+ * console.log(fDocument.getId());
* ```
*/
getId(): string {
@@ -111,8 +119,7 @@ export class FDocument extends FBaseInitialable {
* @example
* ```typescript
* const fDocument = univerAPI.getActiveDocument();
- * const name = fDocument.getName();
- * console.log(name);
+ * console.log(fDocument.getName());
* ```
*/
getName(): string {
@@ -162,4 +169,235 @@ export class FDocument extends FBaseInitialable {
this._univerInstanceService.focusUnit(this.id);
return this._commandService.syncExecuteCommand(RedoCommand.id);
}
+
+ /**
+ * Insert plain text at a document body offset.
+ * @param {number} index The zero-based insertion offset.
+ * @param {string} text The plain text to insert.
+ * @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
+ * @returns {boolean} `true` if the edit was applied.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * fDocument.insertText(0, 'Hello ');
+ * ```
+ */
+ insertText(index: number, text: string, segmentId: string = ''): boolean {
+ return replaceBodyRange(
+ {
+ startOffset: index,
+ endOffset: index,
+ segmentId,
+ },
+ buildPlainTextInsertBody(text),
+ this._documentDataModel,
+ this._injector
+ );
+ }
+
+ /**
+ * Get all paragraphs in the document body or header/footer body by the segment id.
+ * @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
+ * @returns {FDocumentParagraph[]} An array of paragraph facade instances.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const paragraphs = fDocument.getParagraphs();
+ * console.log(paragraphs);
+ * ```
+ */
+ getParagraphs(segmentId: string = ''): FDocumentParagraph[] {
+ const { paragraphs = [] } = this.getBody(segmentId);
+ return paragraphs.map((paragraph) => this._createFDocumentParagraph(paragraph.paragraphId, segmentId));
+ }
+
+ /**
+ * Get a paragraph by its paragraph id and segment id.
+ * @param {string} paragraphId The paragraph id.
+ * @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
+ * @returns {FDocumentParagraph | null} The paragraph facade instance, or `null` if the paragraph is not found.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const paragraph = fDocument.getParagraph('paragraph-01');
+ * console.log(paragraph);
+ * ```
+ */
+ getParagraph(paragraphId: string, segmentId: string = ''): FDocumentParagraph | null {
+ const { paragraphs = [] } = this.getBody(segmentId);
+ const paragraph = paragraphs.find((paragraph) => paragraph.paragraphId === paragraphId);
+ if (!paragraph) {
+ return null;
+ }
+ return this._createFDocumentParagraph(paragraphId, segmentId);
+ }
+
+ /**
+ * Find a paragraph by its text content and segment id.
+ * @param {string} text The text content to search for.
+ * @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
+ * @returns {FDocumentParagraph | null} The paragraph facade instance, or `null` if the paragraph is not found.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const paragraph = fDocument.findParagraphByText('Hello');
+ * console.log(paragraph);
+ * ```
+ */
+ findParagraphByText(text: string, segmentId: string = ''): FDocumentParagraph | null {
+ return this.findParagraphs({ text, segmentId })[0] || null;
+ }
+
+ /**
+ * Find paragraphs by a query object, which can include text content, paragraph id, and segment id.
+ * @param {string | IFDocumentParagraphQuery} query The query object or text content to search for.
+ * @returns {FDocumentParagraph[]} An array of paragraph facade instances that match the query.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const paragraphsWithText = fDocument.findParagraphs('Hello');
+ * const paragraphsWithId = fDocument.findParagraphs({ paragraphId: 'paragraph-01' });
+ * const paragraphsWithSegment = fDocument.findParagraphs({ segmentId: 'header-01' });
+ * console.log(paragraphsWithText, paragraphsWithId, paragraphsWithSegment);
+ * ```
+ */
+ findParagraphs(query: string | IFDocumentParagraphQuery): FDocumentParagraph[] {
+ const normalized = typeof query === 'string' ? { text: query } : query;
+ const { text, paragraphId, segmentId = '' } = normalized;
+
+ return this.getParagraphs(segmentId).filter((paragraph) => {
+ if (paragraphId && paragraph.getId() !== paragraphId) {
+ return false;
+ }
+
+ if (text && !paragraph.getText().includes(text)) {
+ return false;
+ }
+
+ return true;
+ });
+ }
+
+ /**
+ * 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.
+ * @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
+ * @returns {FDocumentParagraph} The inserted paragraph facade instance.
+ * @example
+ * ```ts
+ * const fDocument = univerAPI.getActiveDocument();
+ * const paragraph = fDocument.insertParagraph(0, 'Document title');
+ * paragraph.appendText(' suffix');
+ * ```
+ */
+ insertParagraph(index: number, text: string = '', segmentId: string = ''): FDocumentParagraph {
+ const offset = this._getParagraphInsertOffset(index, segmentId);
+ const result = replaceBodyRange(
+ {
+ startOffset: offset,
+ endOffset: offset,
+ segmentId,
+ },
+ buildPlainTextInsertBody(`${text}\r`),
+ this._documentDataModel,
+ this._injector
+ );
+
+ if (!result) {
+ throw new Error('Failed to insert paragraph.');
+ }
+
+ const { paragraphs = [] } = this.getBody(segmentId);
+ const paragraph = paragraphs[index];
+ if (!paragraph) {
+ throw new Error('Failed to insert paragraph.');
+ }
+
+ return this._createFDocumentParagraph(paragraph.paragraphId, segmentId);
+ }
+
+ /**
+ * 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 paragraph = fDocument.appendParagraph('Summary');
+ * console.log(paragraph.getText());
+ * ```
+ */
+ appendParagraph(text: string = '', segmentId: string = ''): FDocumentParagraph {
+ const { paragraphs = [] } = this.getBody(segmentId);
+ return this.insertParagraph(paragraphs.length, text, segmentId);
+ }
+
+ /**
+ * 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();
+ * fDocument.deleteRange({ startOffset: 0, endOffset: 5 });
+ * ```
+ */
+ deleteRange(range: IFDocumentTextRange): boolean {
+ const normalizedRange = this._normalizeDeleteRange(range);
+ if (normalizedRange.startOffset >= normalizedRange.endOffset) {
+ return false;
+ }
+
+ return replaceBodyRange(
+ normalizedRange,
+ {
+ dataStream: '',
+ },
+ this._documentDataModel,
+ this._injector
+ );
+ }
+
+ private _createFDocumentParagraph(paragraphId: string, segmentId: string = ''): FDocumentParagraph {
+ return this._injector.createInstance(
+ FDocumentParagraph,
+ this,
+ paragraphId,
+ segmentId,
+ this._injector
+ );
+ }
+
+ private _normalizeDeleteRange(range: IFDocumentTextRange): IFDocumentTextRange {
+ const body = this.getBody(range.segmentId);
+ const protectedEndOffset = body.dataStream.endsWith('\r\n')
+ ? Math.max(0, body.dataStream.length - 2)
+ : body.dataStream.length;
+ const endOffset = Math.min(Math.max(range.endOffset, 0), protectedEndOffset);
+
+ return {
+ ...range,
+ startOffset: Math.min(Math.max(range.startOffset, 0), endOffset),
+ endOffset,
+ };
+ }
+
+ private _getParagraphInsertOffset(index: number, segmentId: string = ''): number {
+ if (index <= 0) {
+ return 0;
+ }
+
+ const { dataStream, paragraphs = [] } = this.getBody(segmentId);
+
+ 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;
+ }
}
diff --git a/packages/docs/src/facade/index.ts b/packages/docs/src/facade/index.ts
index 7b48e4f27f..53d540a081 100644
--- a/packages/docs/src/facade/index.ts
+++ b/packages/docs/src/facade/index.ts
@@ -17,9 +17,7 @@
import './f-univer';
export { FDocument } from './f-document';
-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';
+export { FDocumentParagraph, isParagraphFacade } from './f-document-paragraph';
+export type { IFDocumentParagraphInfo } from './f-document-paragraph';
+export type { IFDocumentTextRange } from './utils';
+export { stripBlockTokens } from './utils';
diff --git a/packages/docs/src/facade/utils.ts b/packages/docs/src/facade/utils.ts
index 6cd68e4c1c..4ce73a3243 100644
--- a/packages/docs/src/facade/utils.ts
+++ b/packages/docs/src/facade/utils.ts
@@ -14,14 +14,28 @@
* limitations under the License.
*/
-import type { IDocumentBody, IParagraphStyle } from '@univerjs/core';
-import { createParagraphId } from '@univerjs/core';
+import type { DocumentDataModel, IDocumentBody, Injector, IParagraphStyle, UpdateDocsAttributeType } from '@univerjs/core';
+import type { IRichTextEditingMutationParams } from '@univerjs/docs';
+import { createParagraphId, DataStreamTreeTokenType, getRichTextEditPath, ICommandService, JSONX, TextX, TextXActionType } from '@univerjs/core';
+import { RichTextEditingMutation } from '@univerjs/docs';
export interface IBuildPlainTextInsertBodyOptions {
paragraphStyle?: IParagraphStyle;
removeLeadingParagraphBreak?: boolean;
}
+/**
+ * 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;
+}
+
function cloneParagraphStyle(paragraphStyle: IParagraphStyle): IParagraphStyle {
return paragraphStyle == null ? paragraphStyle : JSON.parse(JSON.stringify(paragraphStyle));
}
@@ -95,3 +109,119 @@ export function buildPlainTextInsertBody(
return body;
}
+
+export function replaceBodyRange(
+ range: IFDocumentTextRange,
+ insertBody: IDocumentBody,
+ docDataModel: DocumentDataModel,
+ injector: Injector
+): boolean {
+ const { startOffset, endOffset, segmentId } = 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,
+ });
+ }
+
+ const jsonX = JSONX.getInstance();
+ const actions = jsonX.editOp(textX.serialize(), getRichTextEditPath(docDataModel, segmentId));
+
+ const commandService = injector.get(ICommandService);
+ const result = commandService.syncExecuteCommand<IRichTextEditingMutationParams, IRichTextEditingMutationParams>(
+ RichTextEditingMutation.id,
+ {
+ unitId: docDataModel.getUnitId(),
+ segmentId,
+ actions,
+ textRanges: [],
+ isEditing: false,
+ }
+ );
+
+ return Boolean(result?.actions && result.actions.length > 0);
+}
+
+export function retainBodyRange(
+ range: IFDocumentTextRange,
+ updateBody: IDocumentBody,
+ coverType: UpdateDocsAttributeType,
+ docDataModel: DocumentDataModel,
+ injector: Injector
+): boolean {
+ const { startOffset, endOffset, segmentId } = range;
+ const commandService = injector.get(ICommandService);
+
+ if (updateBody.textRuns?.length && docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.textRuns == null) {
+ const jsonX = JSONX.getInstance();
+ const actions = jsonX.replaceOp(
+ [...getRichTextEditPath(docDataModel, segmentId), 'textRuns'],
+ undefined,
+ []
+ );
+
+ commandService.syncExecuteCommand<IRichTextEditingMutationParams, IRichTextEditingMutationParams>(
+ RichTextEditingMutation.id,
+ {
+ unitId: docDataModel.getUnitId(),
+ segmentId,
+ actions,
+ textRanges: [],
+ isEditing: false,
+ }
+ );
+ }
+
+ const textX = new TextX();
+
+ if (startOffset > 0) {
+ textX.push({ t: TextXActionType.RETAIN, len: startOffset });
+ }
+
+ textX.push({
+ t: TextXActionType.RETAIN,
+ body: updateBody,
+ coverType,
+ len: endOffset - startOffset,
+ });
+
+ const jsonX = JSONX.getInstance();
+ const actions = jsonX.editOp(textX.serialize(), getRichTextEditPath(docDataModel, segmentId));
+
+ const result = commandService.syncExecuteCommand<IRichTextEditingMutationParams, IRichTextEditingMutationParams>(
+ RichTextEditingMutation.id,
+ {
+ unitId: docDataModel.getUnitId(),
+ segmentId,
+ actions,
+ textRanges: [],
+ isEditing: false,
+ }
+ );
+
+ return Boolean(result?.actions && result.actions.length > 0);
+}
+
+export function stripBlockTokens(text: string): string {
+ return Array.from(text)
+ .map((char) => char === DataStreamTreeTokenType.PARAGRAPH ? '\n' : char)
+ .filter(
+ (char) =>
+ char !== DataStreamTreeTokenType.BLOCK_START &&
+ char !== DataStreamTreeTokenType.BLOCK_END &&
+ char !== DataStreamTreeTokenType.SECTION_BREAK
+ )
+ .join('')
+ .replace(/\n$/, '');
+}
diff --git a/packages/docs/src/services/doc-state-change-manager.service.ts b/packages/docs/src/services/doc-state-change-manager.service.ts
index 6ef45b9303..99944985ce 100644
--- a/packages/docs/src/services/doc-state-change-manager.service.ts
+++ b/packages/docs/src/services/doc-state-change-manager.service.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import type { JSONXActions, Nullable } from '@univerjs/core';
+import type { DocumentDataModel, JSONXActions, Nullable } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';
import type { IDocStateChangeInfo, IDocStateChangeParams } from './doc-state-emit.service';
-import { createIdentifier, ICommandService, Inject, IUndoRedoService, IUniverInstanceService, JSONX, Optional, RedoCommandId, RxDisposable, UndoCommandId } from '@univerjs/core';
+import { createIdentifier, ICommandService, Inject, IUndoRedoService, IUniverInstanceService, JSONX, Optional, RedoCommandId, RxDisposable, UndoCommandId, UniverInstanceType } from '@univerjs/core';
import { BehaviorSubject, takeUntil } from 'rxjs';
import { DocStateEmitService } from './doc-state-emit.service';
@@ -83,7 +83,7 @@ export class DocStateChangeManagerService extends RxDisposable {
this.disposeWithMe(
this._commandService.beforeCommandExecuted((command) => {
if (command.id === UndoCommandId || command.id === RedoCommandId) {
- const univerDoc = this._univerInstanceService.getCurrentUniverDocInstance();
+ const univerDoc = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (univerDoc == null) {
return;
}
diff --git a/packages/docs/src/services/doc-view-model-manager.service.ts b/packages/docs/src/services/doc-view-model-manager.service.ts
index 5dc8d72f6e..25c10febef 100644
--- a/packages/docs/src/services/doc-view-model-manager.service.ts
+++ b/packages/docs/src/services/doc-view-model-manager.service.ts
@@ -93,7 +93,7 @@ export class DocViewModelManagerService extends RxDisposable implements IRenderM
}
private _setCurrent(unitId: string) {
- const documentDataModel = this._univerInstanceService.getUniverDocInstance(unitId);
+ const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
if (documentDataModel == null) {
throw new Error(`Document data model with id ${unitId} not found when build view model.`);
}
diff --git a/packages/docs/src/utils/custom-range-factory.ts b/packages/docs/src/utils/custom-range-factory.ts
index 48f535cebb..b0fa808174 100644
--- a/packages/docs/src/utils/custom-range-factory.ts
+++ b/packages/docs/src/utils/custom-range-factory.ts
@@ -74,7 +74,7 @@ export function addCustomRangeBySelectionFactory(accessor: IAccessor, param: IAd
if (!documentDataModel) {
return false;
}
- const body = documentDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();
+ const body = documentDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
if (!body) {
return false;
}
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-selection.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-selection.ts
index f595a16fa7..e0c79b082c 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-selection.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-selection.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IAccessor, IUnitRangeName, Workbook } from '@univerjs/core';
+import type { DocumentDataModel, IAccessor, IUnitRangeName, Workbook } from '@univerjs/core';
import type { ISequenceNode } from '@univerjs/engine-formula';
import { Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
@@ -29,7 +29,7 @@ import { useStateRef } from './use-state-ref';
function getCurrentBodyDataStreamAndOffset(accssor: IAccessor) {
const univerInstanceService = accssor.get(IUniverInstanceService);
- const documentModel = univerInstanceService.getCurrentUniverDocInstance();
+ const documentModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (!documentModel?.getBody()) {
return;
diff --git a/packages/sheets-formula-ui/src/views/more-functions/__tests__/MoreFunctions.spec.tsx b/packages/sheets-formula-ui/src/views/more-functions/__tests__/MoreFunctions.spec.tsx
index f710f98809..3223345e13 100644
--- a/packages/sheets-formula-ui/src/views/more-functions/__tests__/MoreFunctions.spec.tsx
+++ b/packages/sheets-formula-ui/src/views/more-functions/__tests__/MoreFunctions.spec.tsx
@@ -281,14 +281,6 @@ class TestUniverInstanceService {
getUniverSheetInstance() {
return this._workbook;
}
-
- getUniverDocInstance() {
- return null;
- }
-
- getCurrentUniverDocInstance() {
- return null;
- }
}
class SelectionState {
diff --git a/packages/sheets-hyper-link-ui/src/utils/index.ts b/packages/sheets-hyper-link-ui/src/utils/index.ts
index 6e472362cd..e8113c2e76 100644
--- a/packages/sheets-hyper-link-ui/src/utils/index.ts
+++ b/packages/sheets-hyper-link-ui/src/utils/index.ts
@@ -82,7 +82,7 @@ export const shouldDisableAddLink = (accessor: IAccessor) => {
return true;
}
- const body = doc.getSelfOrHeaderFooterModel(textRanges[0].segmentId).getBody();
+ const body = doc.getSelfOrHeaderFooterModel(textRanges[0].segmentId)?.getBody();
if (!body) {
return true;
}
diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/formula-editor.controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/formula-editor.controller.spec.ts
index 2b048fd37e..25ef625c5d 100644
--- a/packages/sheets-ui/src/controllers/editor/__tests__/formula-editor.controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/editor/__tests__/formula-editor.controller.spec.ts
@@ -69,7 +69,7 @@ function createController() {
};
controller._univerInstanceService = {
setCurrentUnitForType: vi.fn(),
- getUniverDocInstance: vi.fn(() => formulaDoc),
+ getUnit: vi.fn(() => formulaDoc),
};
controller._editorBridgeService = { isVisible: vi.fn(() => ({ visible: false })) };
controller._commandService = { syncExecuteCommand: vi.fn() };
diff --git a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
index 51431e079a..01dcd91e3c 100644
--- a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { Nullable } from '@univerjs/core';
+import type { DocumentDataModel, Nullable } from '@univerjs/core';
import type {
IRichTextEditingMutationParams,
} from '@univerjs/docs';
@@ -32,6 +32,7 @@ import {
IUndoRedoService,
IUniverInstanceService,
RxDisposable,
+ UniverInstanceType,
} from '@univerjs/core';
import {
DocSelectionManagerService,
@@ -129,8 +130,9 @@ export class FormulaEditorController extends RxDisposable {
if (isFocusButHidden) {
this._univerInstanceService.setCurrentUnitForType(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
- const formulaEditorDataModel = this._univerInstanceService.getUniverDocInstance(
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
+ const formulaEditorDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ UniverInstanceType.UNIVER_DOC
);
const visibleState = this._editorBridgeService.isVisible();
@@ -194,8 +196,9 @@ export class FormulaEditorController extends RxDisposable {
this.disposeWithMe(combineLatest([this._formulaEditorManagerService.position$, addFormulaBar$]).subscribe(([position]) => {
if (!position) return this._clearScheduledCallback();
const editorObject = getEditorObject(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, this._renderManagerService);
- const formulaEditorDataModel = this._univerInstanceService.getUniverDocInstance(
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
+ const formulaEditorDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ UniverInstanceType.UNIVER_DOC
);
if (editorObject == null || formulaEditorDataModel == null) return this._clearScheduledCallback();
@@ -222,8 +225,9 @@ export class FormulaEditorController extends RxDisposable {
const skeleton = this._renderManagerService.getRenderById(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)?.with(DocSkeletonManagerService).getSkeleton();
const editorObject = this._renderManagerService.getRenderById(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
- const formulaEditorDataModel = this._univerInstanceService.getUniverDocInstance(
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
+ const formulaEditorDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ UniverInstanceType.UNIVER_DOC
);
if (skeleton == null || position == null || editorObject == null || formulaEditorDataModel == null) {
diff --git a/packages/ui/src/common/__tests__/menu-hidden-observable.spec.ts b/packages/ui/src/common/__tests__/menu-hidden-observable.spec.ts
index 654fb57554..ad4e353b06 100644
--- a/packages/ui/src/common/__tests__/menu-hidden-observable.spec.ts
+++ b/packages/ui/src/common/__tests__/menu-hidden-observable.spec.ts
@@ -14,15 +14,12 @@
* limitations under the License.
*/
-import type { IAccessor, UniverInstanceType } from '@univerjs/core';
-import { DocumentFlavor } from '@univerjs/core';
+import type { IAccessor } from '@univerjs/core';
+import { DocumentFlavor, UniverInstanceType } from '@univerjs/core';
import { Subject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getHeaderFooterMenuHiddenObservable, getMenuHiddenObservable } from '../menu-hidden-observable';
-const TARGET_TYPE = 'sheet' as unknown as UniverInstanceType;
-const OTHER_TYPE = 'doc' as unknown as UniverInstanceType;
-
function createDocModel(flavor: DocumentFlavor) {
return {
getSnapshot: () => ({
@@ -40,7 +37,7 @@ function createMenuAccessor(options?: {
currentDocFlavor?: DocumentFlavor | null;
}) {
const focused$ = new Subject<string | null>();
- const unitType = options?.unitType ?? TARGET_TYPE;
+ const unitType = options?.unitType ?? UniverInstanceType.UNIVER_SHEET;
const hasFocusedUnitId = options != null && Object.prototype.hasOwnProperty.call(options, 'focusedUnitId');
const focusedUnitId = hasFocusedUnitId ? options.focusedUnitId! : 'unit-1';
const docFlavorByUnitId = options?.docFlavorByUnitId ?? {};
@@ -51,25 +48,22 @@ function createMenuAccessor(options?: {
focused$,
getUnitType: vi.fn(() => unitType),
getFocusedUnit: vi.fn(() => (focusedUnitId == null ? null : { getUnitId: () => focusedUnitId })),
- getUniverDocInstance: vi.fn((unitId: string) => {
+ getUnit: vi.fn((unitId: string) => {
const flavor = docFlavorByUnitId[unitId];
return flavor == null ? null : createDocModel(flavor);
}),
getCurrentUnitOfType: vi.fn((type: UniverInstanceType) => {
- if (type !== TARGET_TYPE) {
- return null;
+ if (type === UniverInstanceType.UNIVER_DOC) {
+ if (currentDocFlavor == null) {
+ return null;
+ }
+ return createDocModel(currentDocFlavor);
}
if (focusedUnitId == null) {
return null;
}
return { getUnitId: () => focusedUnitId };
}),
- getCurrentUniverDocInstance: vi.fn(() => {
- if (currentDocFlavor == null) {
- return null;
- }
- return createDocModel(currentDocFlavor);
- }),
};
const accessor = {
@@ -87,25 +81,25 @@ describe('getMenuHiddenObservable', () => {
it('should emit true when there is no focused unit initially', () => {
const { accessor } = createMenuAccessor({ focusedUnitId: null });
const hiddenValues: boolean[] = [];
- const sub = getMenuHiddenObservable(accessor, TARGET_TYPE).subscribe((hidden) => hiddenValues.push(hidden));
+ const sub = getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET).subscribe((hidden) => hiddenValues.push(hidden));
expect(hiddenValues).toEqual([true]);
sub.unsubscribe();
});
it('should emit false when focused unit type matches target type', () => {
- const { accessor } = createMenuAccessor({ unitType: TARGET_TYPE });
+ const { accessor } = createMenuAccessor({ unitType: UniverInstanceType.UNIVER_SHEET });
const hiddenValues: boolean[] = [];
- const sub = getMenuHiddenObservable(accessor, TARGET_TYPE).subscribe((hidden) => hiddenValues.push(hidden));
+ const sub = getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET).subscribe((hidden) => hiddenValues.push(hidden));
expect(hiddenValues).toEqual([false]);
sub.unsubscribe();
});
it('should emit true when focused unit type does not match target type', () => {
- const { accessor } = createMenuAccessor({ unitType: OTHER_TYPE });
+ const { accessor } = createMenuAccessor({ unitType: UniverInstanceType.UNIVER_DOC });
const hiddenValues: boolean[] = [];
- const sub = getMenuHiddenObservable(accessor, TARGET_TYPE).subscribe((hidden) => hiddenValues.push(hidden));
+ const sub = getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET).subscribe((hidden) => hiddenValues.push(hidden));
expect(hiddenValues).toEqual([true]);
sub.unsubscribe();
@@ -114,7 +108,7 @@ describe('getMenuHiddenObservable', () => {
it('should hide when focused unit does not match matchUnitId', () => {
const { accessor, service } = createMenuAccessor({ focusedUnitId: 'expected-unit' });
const hiddenValues: boolean[] = [];
- const sub = getMenuHiddenObservable(accessor, TARGET_TYPE, 'expected-unit').subscribe((hidden) => hiddenValues.push(hidden));
+ const sub = getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET, 'expected-unit').subscribe((hidden) => hiddenValues.push(hidden));
service.focused$.next('other-unit');
@@ -127,10 +121,10 @@ describe('getMenuHiddenObservable', () => {
const hiddenWithString: boolean[] = [];
const hiddenWithArray: boolean[] = [];
- const sub1 = getMenuHiddenObservable(accessor, TARGET_TYPE, undefined, 'blocked-unit').subscribe((hidden) =>
+ const sub1 = getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET, undefined, 'blocked-unit').subscribe((hidden) =>
hiddenWithString.push(hidden)
);
- const sub2 = getMenuHiddenObservable(accessor, TARGET_TYPE, undefined, ['blocked-unit']).subscribe((hidden) =>
+ const sub2 = getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET, undefined, ['blocked-unit']).subscribe((hidden) =>
hiddenWithArray.push(hidden)
);
@@ -146,7 +140,7 @@ describe('getMenuHiddenObservable', () => {
it('should hide when focused$ emits null unit id', () => {
const { accessor, service } = createMenuAccessor({ focusedUnitId: 'unit-1' });
const hiddenValues: boolean[] = [];
- const sub = getMenuHiddenObservable(accessor, TARGET_TYPE).subscribe((hidden) => hiddenValues.push(hidden));
+ const sub = getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET).subscribe((hidden) => hiddenValues.push(hidden));
service.focused$.next(null);
diff --git a/packages/ui/src/common/menu-hidden-observable.ts b/packages/ui/src/common/menu-hidden-observable.ts
index 382fe172da..bbdceb0d8a 100644
--- a/packages/ui/src/common/menu-hidden-observable.ts
+++ b/packages/ui/src/common/menu-hidden-observable.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { IAccessor, UniverInstanceType } from '@univerjs/core';
-import { DocumentFlavor, IUniverInstanceService } from '@univerjs/core';
+import type { DocumentDataModel, IAccessor } from '@univerjs/core';
+import { DocumentFlavor, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { Observable } from 'rxjs';
export function getMenuHiddenObservable(
@@ -67,13 +67,13 @@ export function getHeaderFooterMenuHiddenObservable(
if (unitId == null) {
return subscriber.next(true);
}
- const docDataModel = univerInstanceService.getUniverDocInstance(unitId);
+ const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
const documentFlavor = docDataModel?.getSnapshot().documentStyle.documentFlavor;
subscriber.next(documentFlavor !== DocumentFlavor.TRADITIONAL);
});
- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (docDataModel == null) {
subscriber.next(true);