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: separate the doc model layer into a data model layer and a view model layer (#554)

Ran Luo5e2364f11a5e
diff --git a/packages/base-docs/src/basics/component-tools.ts b/packages/base-docs/src/basics/component-tools.ts
index c5ecba329a..1ba68a8561 100644
--- a/packages/base-docs/src/basics/component-tools.ts
+++ b/packages/base-docs/src/basics/component-tools.ts
@@ -21,7 +21,7 @@ export function getDocObject(
return;
}
- const { components, mainComponent, scene, engine } = currentRender;
+ const { mainComponent, scene, engine } = currentRender;
const document = mainComponent as Documents;
diff --git a/packages/base-docs/src/basics/retain-delete-params.ts b/packages/base-docs/src/basics/retain-delete-params.ts
index cb17973efa..0868728473 100644
--- a/packages/base-docs/src/basics/retain-delete-params.ts
+++ b/packages/base-docs/src/basics/retain-delete-params.ts
@@ -1,6 +1,4 @@
-import { ITextRange } from '@univerjs/core';
-
-import { IDeleteMutationParams, IRetainMutationParams } from '../commands/mutations/core-editing.mutation';
+import { IDeleteMutationParams, IRetainMutationParams, ITextRange } from '@univerjs/core';
export function getRetainAndDeleteFromReplace(
range: ITextRange,
diff --git a/packages/base-docs/src/commands/commands/clipboard.inner.command.ts b/packages/base-docs/src/commands/commands/clipboard.inner.command.ts
index 07991eb5d5..6f48b34504 100644
--- a/packages/base-docs/src/commands/commands/clipboard.inner.command.ts
+++ b/packages/base-docs/src/commands/commands/clipboard.inner.command.ts
@@ -4,22 +4,19 @@ import {
getDocsUpdateBody,
ICommand,
ICommandService,
+ IDeleteMutationParams,
IDocumentBody,
IMutationInfo,
+ IRetainMutationParams,
ITextRange,
IUndoRedoService,
IUniverInstanceService,
+ MemoryCursor,
} from '@univerjs/core';
-import { MemoryCursor } from '../../basics/memory-cursor';
import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';
import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
-import {
- IDeleteMutationParams,
- IRetainMutationParams,
- IRichTextEditingMutationParams,
- RichTextEditingMutation,
-} from '../mutations/core-editing.mutation';
+import { IRichTextEditingMutationParams, RichTextEditingMutation } from '../mutations/core-editing.mutation';
export interface IInnerPasteCommandParams {
segmentId: string;
diff --git a/packages/base-docs/src/commands/commands/core-editing.command.ts b/packages/base-docs/src/commands/commands/core-editing.command.ts
index 30112318c5..61e2918451 100644
--- a/packages/base-docs/src/commands/commands/core-editing.command.ts
+++ b/packages/base-docs/src/commands/commands/core-editing.command.ts
@@ -1,7 +1,7 @@
import { ITextRangeWithStyle } from '@univerjs/base-render';
import {
CommandType,
- createEmptyDocSnapshot,
+ DEFAULT_EMPTY_DOCUMENT_VALUE,
ICommand,
ICommandService,
IDocumentBody,
@@ -323,3 +323,11 @@ export const CoverCommand: ICommand<ICoverCommandParams> = {
return true;
},
};
+
+function createEmptyDocSnapshot(): Partial<IDocumentData> {
+ return {
+ body: {
+ dataStream: DEFAULT_EMPTY_DOCUMENT_VALUE,
+ },
+ };
+}
diff --git a/packages/base-docs/src/commands/commands/inline-format.command.ts b/packages/base-docs/src/commands/commands/inline-format.command.ts
index 916d227208..7603005ed6 100644
--- a/packages/base-docs/src/commands/commands/inline-format.command.ts
+++ b/packages/base-docs/src/commands/commands/inline-format.command.ts
@@ -11,9 +11,9 @@ import {
ITextRun,
IUndoRedoService,
IUniverInstanceService,
+ MemoryCursor,
} from '@univerjs/core';
-import { MemoryCursor } from '../../basics/memory-cursor';
import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
import { IRichTextEditingMutationParams, RichTextEditingMutation } from '../mutations/core-editing.mutation';
diff --git a/packages/base-docs/src/commands/mutations/core-editing.mutation.ts b/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
index 032d734787..0698cb4f32 100644
--- a/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
+++ b/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
@@ -1,52 +1,8 @@
-import {
- CommandType,
- IDocumentBody,
- IMutation,
- IUniverInstanceService,
- Tools,
- UpdateDocsAttributeType,
-} from '@univerjs/core';
-
-import { MemoryCursor } from '../../basics/memory-cursor';
-import { DeleteApply } from './functions/delete-apply';
-import { InsertApply } from './functions/insert-apply';
-import { UpdateAttributeApply } from './functions/update-apply';
-
-/**
- * Retain mutation is used to move the cursor or to update properties of the text in the given range.
- */
-export interface IRetainMutationParams {
- t: 'r';
- len: number;
- segmentId?: string;
- body?: IDocumentBody;
- coverType?: UpdateDocsAttributeType;
-}
-
-/**
- * Insert mutation is used to insert text (maybe with rich text properties) at the given position.
- */
-export interface IInsertMutationParams {
- t: 'i';
- body: IDocumentBody;
- len: number;
- line: number;
- segmentId?: string;
-}
-
-/**
- * Delete mutation is used to delete text at the given position.
- */
-export interface IDeleteMutationParams {
- t: 'd';
- line: number;
- len: number;
- segmentId?: string;
-}
+import { CommandType, type DocMutationParams, IMutation, IUniverInstanceService } from '@univerjs/core';
export interface IRichTextEditingMutationParams {
unitId: string;
- mutations: Array<IRetainMutationParams | IInsertMutationParams | IDeleteMutationParams>;
+ mutations: DocMutationParams[];
}
/**
@@ -62,72 +18,10 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
const documentModel = univerInstanceService.getUniverDocInstance(unitId);
if (!documentModel) {
- throw new Error(`DocumentModel not found for unitId: ${unitId}`);
+ throw new Error(`DocumentDataModel not found for unitId: ${unitId}`);
}
- const undoMutations: Array<IRetainMutationParams | IInsertMutationParams | IDeleteMutationParams> = [];
-
- const memoryCursor = new MemoryCursor();
-
- memoryCursor.reset();
-
- mutations.forEach((mutation) => {
- // FIXME: @jocs Since UpdateAttributeApply modifies the mutation(used in undo/redo),
- // so make a deep copy here, does UpdateAttributeApply need to
- // be modified to have no side effects in the future?
- mutation = Tools.deepClone(mutation);
-
- if (mutation.t === 'r') {
- const { coverType, body, len, segmentId } = mutation;
-
- if (body != null) {
- const documentBody = UpdateAttributeApply(
- documentModel,
- body,
- len,
- memoryCursor.cursor,
- coverType,
- segmentId
- );
-
- undoMutations.push({
- ...mutation,
- t: 'r',
- coverType: UpdateDocsAttributeType.REPLACE,
- body: documentBody,
- });
- } else {
- undoMutations.push({
- ...mutation,
- t: 'r',
- });
- }
-
- memoryCursor.moveCursor(len);
- } else if (mutation.t === 'i') {
- const { body, len, segmentId, line } = mutation;
-
- InsertApply(documentModel, body!, len, memoryCursor.cursor, segmentId);
- memoryCursor.moveCursor(len);
- undoMutations.push({
- t: 'd',
- len,
- line,
- segmentId,
- });
- } else if (mutation.t === 'd') {
- const { len, segmentId } = mutation;
- const documentBody = DeleteApply(documentModel, len, memoryCursor.cursor, segmentId);
-
- undoMutations.push({
- ...mutation,
- t: 'i',
- body: documentBody,
- });
- } else {
- throw new Error(`Unknown mutation type for mutation: ${mutation}.`);
- }
- });
+ const undoMutations = documentModel.apply(mutations);
return {
unitId,
diff --git a/packages/base-docs/src/commands/mutations/functions/insert-apply.ts b/packages/base-docs/src/commands/mutations/functions/insert-apply.ts
deleted file mode 100644
index 748188ba49..0000000000
--- a/packages/base-docs/src/commands/mutations/functions/insert-apply.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { DocumentModel, getDocsUpdateBody, IDocumentBody, insertTextToContent } from '@univerjs/core';
-
-import {
- insertCustomBlocks,
- insertCustomRanges,
- insertParagraphs,
- insertSectionBreaks,
- insertTables,
- insertTextRuns,
-} from './common';
-
-export function InsertApply(
- document: DocumentModel,
- insertBody: IDocumentBody,
- textLength: number,
- currentIndex: number,
- segmentId?: string
-) {
- const doc = document.snapshot;
-
- const bodyModel = document.getBodyModel(segmentId);
-
- const body = getDocsUpdateBody(doc, segmentId);
-
- if (textLength === 0) {
- return;
- }
-
- if (body == null) {
- throw new Error('no body has changed');
- }
-
- updateAttributeByInsert(body, insertBody, textLength, currentIndex);
-
- if (insertBody.dataStream.length > 1 && /\r/.test(insertBody.dataStream)) {
- // TODO: @JOCS, The DocumentModel needs to be rewritten to better support the
- // large area of updates that are brought about by the paste, abstract the
- // methods associated with the DocumentModel insertion, and support atomic operations
- bodyModel.reset(body);
- } else {
- bodyModel.insert(insertBody, currentIndex);
- }
-
- // console.log('插入的model打印', bodyModel, textLength, currentIndex);
-}
-
-function updateAttributeByInsert(
- body: IDocumentBody,
- insertBody: IDocumentBody,
- textLength: number,
- currentIndex: number
-) {
- body.dataStream = insertTextToContent(body.dataStream, currentIndex, insertBody.dataStream);
-
- insertTextRuns(body, insertBody, textLength, currentIndex);
-
- insertParagraphs(body, insertBody, textLength, currentIndex);
-
- insertSectionBreaks(body, insertBody, textLength, currentIndex);
-
- insertCustomBlocks(body, insertBody, textLength, currentIndex);
-
- insertTables(body, insertBody, textLength, currentIndex);
-
- insertCustomRanges(body, insertBody, textLength, currentIndex);
-}
diff --git a/packages/base-docs/src/controllers/clipboard.controller.ts b/packages/base-docs/src/controllers/clipboard.controller.ts
index 4caea81088..2def938c14 100644
--- a/packages/base-docs/src/controllers/clipboard.controller.ts
+++ b/packages/base-docs/src/controllers/clipboard.controller.ts
@@ -128,14 +128,9 @@ export class DocClipboardController extends Disposable {
private _getDocumentBodyInRanges(): IDocumentBody[] {
const ranges = this._textSelectionRenderManager.getAllTextRanges();
- const skeletonObject = this._docSkeletonManagerService.getCurrent();
+ const docDataModel = this._currentUniverService.getCurrentUniverDocInstance();
- if (skeletonObject == null) {
- return [];
- }
-
- const { skeleton } = skeletonObject;
- const { dataStream, textRuns = [], paragraphs = [] } = skeleton.getModel().getBodyModel().getBody();
+ const { dataStream, textRuns = [], paragraphs = [] } = docDataModel.getBody()!;
const results: IDocumentBody[] = [];
diff --git a/packages/base-docs/src/controllers/move-cursor.controller.ts b/packages/base-docs/src/controllers/move-cursor.controller.ts
index 16098369a2..69b7974a84 100644
--- a/packages/base-docs/src/controllers/move-cursor.controller.ts
+++ b/packages/base-docs/src/controllers/move-cursor.controller.ts
@@ -87,6 +87,7 @@ export class MoveCursorController extends Disposable {
private _handleShiftMoveSelection(direction: Direction) {
const activeRange = this._textSelectionRenderManager.getActiveRange();
const allRanges = this._textSelectionRenderManager.getAllTextRanges();
+ const docDataModel = this._currentUniverService.getCurrentUniverDocInstance();
const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
@@ -126,7 +127,7 @@ export class MoveCursorController extends Disposable {
: endOffset;
let focusOffset = collapsed ? endOffset : rangeDirection === RANGE_DIRECTION.FORWARD ? endOffset : startOffset;
- const dataStreamLength = skeleton.getModel().getBodyModel().getBody().dataStream.length ?? Infinity;
+ const dataStreamLength = docDataModel.getBody()!.dataStream.length ?? Infinity;
if (direction === Direction.LEFT || direction === Direction.RIGHT) {
focusOffset = direction === Direction.RIGHT ? ++focusOffset : --focusOffset;
@@ -187,6 +188,7 @@ export class MoveCursorController extends Disposable {
private _handleMoveCursor(direction: Direction) {
const activeRange = this._textSelectionRenderManager.getActiveRange();
const allRanges = this._textSelectionRenderManager.getAllTextRanges();
+ const docDataModel = this._currentUniverService.getCurrentUniverDocInstance();
const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
@@ -197,7 +199,7 @@ export class MoveCursorController extends Disposable {
}
const { startOffset, endOffset, style, collapsed } = activeRange;
- const dataStreamLength = skeleton.getModel().getBodyModel().getBody().dataStream.length ?? Infinity;
+ const dataStreamLength = docDataModel.getBody()!.dataStream.length ?? Infinity;
if (direction === Direction.LEFT || direction === Direction.RIGHT) {
let cursor;
diff --git a/packages/base-docs/src/controllers/zoom.controller.ts b/packages/base-docs/src/controllers/zoom.controller.ts
index d2c5471d00..2882e717d6 100644
--- a/packages/base-docs/src/controllers/zoom.controller.ts
+++ b/packages/base-docs/src/controllers/zoom.controller.ts
@@ -1,3 +1,4 @@
+/* eslint-disable no-magic-numbers */
import { IRenderManagerService, IWheelEvent } from '@univerjs/base-render';
import {
Disposable,
@@ -72,11 +73,11 @@ export class ZoomController extends Disposable {
this._initializedRender.add(unitId);
- const { mainComponent, components, scene } = currentRender;
+ const { scene } = currentRender;
this.disposeWithMe(
toDisposable(
- scene.onMouseWheelObserver.add((e: IWheelEvent, state) => {
+ scene.onMouseWheelObserver.add((e: IWheelEvent) => {
if (!e.ctrlKey) {
return;
}
diff --git a/packages/base-docs/src/index.ts b/packages/base-docs/src/index.ts
index 5f94ba82bf..49d5d9bffc 100644
--- a/packages/base-docs/src/index.ts
+++ b/packages/base-docs/src/index.ts
@@ -1,6 +1,5 @@
export { getDocObject } from './basics/component-tools';
export * from './basics/docs-view-key';
-export { MemoryCursor } from './basics/memory-cursor';
export { DocCopyCommand, DocCutCommand, DocPasteCommand } from './commands/commands/clipboard.command';
export {
CoverCommand,
diff --git a/packages/base-docs/src/services/doc-skeleton-manager.service.ts b/packages/base-docs/src/services/doc-skeleton-manager.service.ts
index a67638f8a1..de1b6577f7 100644
--- a/packages/base-docs/src/services/doc-skeleton-manager.service.ts
+++ b/packages/base-docs/src/services/doc-skeleton-manager.service.ts
@@ -1,5 +1,5 @@
import { DocumentSkeleton } from '@univerjs/base-render';
-import { DocumentModel, IUniverInstanceService, LocaleService, Nullable } from '@univerjs/core';
+import { DocumentDataModel, IUniverInstanceService, LocaleService, Nullable } from '@univerjs/core';
import { IDisposable, Inject } from '@wendellhu/redi';
import { BehaviorSubject } from 'rxjs';
@@ -84,15 +84,15 @@ export class DocSkeletonManagerService implements IDisposable {
}
setCurrent(searchParm: IDocSkeletonManagerSearch): Nullable<IDocSkeletonManagerParam> {
- const param = this._getCurrentBySearch(searchParm);
+ const curSkeleton = this._getCurrentBySearch(searchParm);
- if (param != null) {
- if (param.dirty) {
- param.skeleton.makeDirty(true);
- param.dirty = false;
+ if (curSkeleton != null) {
+ if (curSkeleton.dirty) {
+ curSkeleton.skeleton.makeDirty(true);
+ curSkeleton.dirty = false;
}
- param.skeleton.calculate();
+ curSkeleton.skeleton.calculate();
} else {
const { unitId } = searchParm;
@@ -138,7 +138,7 @@ export class DocSkeletonManagerService implements IDisposable {
return this._docSkeletonParam.find((param) => param.unitId === searchParm.unitId);
}
- private _buildSkeleton(documentModel: DocumentModel) {
+ private _buildSkeleton(documentModel: DocumentDataModel) {
return DocumentSkeleton.create(documentModel, this._localeService);
}
}
diff --git a/packages/base-docs/src/views/doc-canvas-view.ts b/packages/base-docs/src/views/doc-canvas-view.ts
index 6bd71bd3d7..c7ab4a0667 100644
--- a/packages/base-docs/src/views/doc-canvas-view.ts
+++ b/packages/base-docs/src/views/doc-canvas-view.ts
@@ -1,3 +1,4 @@
+/* eslint-disable no-magic-numbers */
import {
Documents,
EVENT_TYPE,
@@ -11,7 +12,7 @@ import {
Viewport,
} from '@univerjs/base-render';
import {
- DocumentModel,
+ DocumentDataModel,
EventState,
IConfigService,
IUniverInstanceService,
@@ -19,7 +20,7 @@ import {
Nullable,
OnLifecycle,
} from '@univerjs/core';
-import { Inject, Injector } from '@wendellhu/redi';
+import { Inject } from '@wendellhu/redi';
import {
DOCS_COMPONENT_DEFAULT_Z_INDEX,
@@ -34,7 +35,7 @@ import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.serv
export class DocCanvasView {
private _scene!: Scene;
- private _currentDocumentModel!: DocumentModel;
+ private _currentDocumentModel!: DocumentDataModel;
private _loadedMap = new Set();
@@ -42,8 +43,7 @@ export class DocCanvasView {
@IRenderManagerService private readonly _renderManagerService: RenderManagerService,
@IConfigService private readonly _configService: IConfigService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
- @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
- @Inject(Injector) private readonly _injector: Injector
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService
) {
this._currentUniverService.currentDoc$.subscribe((documentModel) => {
if (documentModel == null) {
@@ -117,7 +117,7 @@ export class DocCanvasView {
} else if (scene.scaleX + scrollNum < 0.1) {
scene.scale(0.1, 0.1);
} else {
- const value = e.deltaY > 0 ? 0.1 : -0.1;
+ // const value = e.deltaY > 0 ? 0.1 : -0.1;
// scene.scaleBy(scrollNum, scrollNum);
e.preventDefault();
}
diff --git a/packages/base-docs/tsconfig.json b/packages/base-docs/tsconfig.json
index 62dd043e50..064da5bfe8 100644
--- a/packages/base-docs/tsconfig.json
+++ b/packages/base-docs/tsconfig.json
@@ -7,8 +7,5 @@
"esModuleInterop": true,
"strictPropertyInitialization": false
},
- "include": [
- "src/**/*",
- "test/**/*.test.(ts|tsx|js)"
- ]
+ "include": ["src/**/*", "test/**/*.test.(ts|tsx|js)"]
}
diff --git a/packages/base-render/src/components/docs/block/paragraph/bullet.-ruler.ts b/packages/base-render/src/components/docs/block/paragraph/bullet-ruler.ts
similarity index 100%
rename from packages/base-render/src/components/docs/block/paragraph/bullet.-ruler.ts
rename to packages/base-render/src/components/docs/block/paragraph/bullet-ruler.ts
diff --git a/packages/base-render/src/components/docs/block/paragraph/bullet.ts b/packages/base-render/src/components/docs/block/paragraph/bullet.ts
index e58b697c4e..11e71ff196 100644
--- a/packages/base-render/src/components/docs/block/paragraph/bullet.ts
+++ b/packages/base-render/src/components/docs/block/paragraph/bullet.ts
@@ -3,7 +3,7 @@ import { IBullet, ILists, INestingLevel, ITextStyle, LocaleService, Nullable } f
import { FontCache } from '../../../../basics/font-cache';
import { IDocumentSkeletonBullet } from '../../../../basics/i-document-skeleton-cached';
import { getFontStyleString } from '../../../../basics/tools';
-import { getBulletOrderedSymbol } from './bullet.-ruler';
+import { getBulletOrderedSymbol } from './bullet-ruler';
export function dealWidthBullet(
bullet?: IBullet,
diff --git a/packages/base-render/src/components/docs/block/paragraph/index.ts b/packages/base-render/src/components/docs/block/paragraph/index.ts
index f11ae1a14b..0f6ff8b460 100644
--- a/packages/base-render/src/components/docs/block/paragraph/index.ts
+++ b/packages/base-render/src/components/docs/block/paragraph/index.ts
@@ -1,6 +1,6 @@
export * from './bullet';
-export * from './bullet.-ruler';
+export * from './bullet-ruler';
export * from './inline-drawing';
-export * from './language.-ruler';
-export * from './layout.-ruler';
+export * from './language-ruler';
+export * from './layout-ruler';
export * from './paragraph';
diff --git a/packages/base-render/src/components/docs/block/paragraph/language.-ruler.ts b/packages/base-render/src/components/docs/block/paragraph/language-ruler.ts
similarity index 100%
rename from packages/base-render/src/components/docs/block/paragraph/language.-ruler.ts
rename to packages/base-render/src/components/docs/block/paragraph/language-ruler.ts
diff --git a/packages/base-render/src/components/docs/block/paragraph/layout.-ruler.ts b/packages/base-render/src/components/docs/block/paragraph/layout-ruler.ts
similarity index 100%
rename from packages/base-render/src/components/docs/block/paragraph/layout.-ruler.ts
rename to packages/base-render/src/components/docs/block/paragraph/layout-ruler.ts
diff --git a/packages/base-render/src/components/docs/block/paragraph/paragraph.ts b/packages/base-render/src/components/docs/block/paragraph/paragraph.ts
index 75e7106415..491cda3082 100644
--- a/packages/base-render/src/components/docs/block/paragraph/paragraph.ts
+++ b/packages/base-render/src/components/docs/block/paragraph/paragraph.ts
@@ -36,8 +36,8 @@ import {
} from '../../common/tools';
import { dealWidthBullet } from './bullet';
import { dealWidthInlineDrawing } from './inline-drawing';
-import { composeCharForLanguage } from './language.-ruler';
-import { calculateParagraphLayout } from './layout.-ruler';
+import { composeCharForLanguage } from './language-ruler';
+import { calculateParagraphLayout } from './layout-ruler';
// eslint-disable-next-line max-lines-per-function
export function dealWidthParagraph(
diff --git a/packages/base-render/src/components/docs/doc-skeleton.ts b/packages/base-render/src/components/docs/doc-skeleton.ts
index bc7352c273..a6b4f36bd1 100644
--- a/packages/base-render/src/components/docs/doc-skeleton.ts
+++ b/packages/base-render/src/components/docs/doc-skeleton.ts
@@ -638,7 +638,7 @@ export class DocumentSkeleton extends Skeleton {
// TODO
}
- const { pages, renderedBlockIdMap } = blockInfo;
+ const { pages } = blockInfo;
// renderedBlockIdMap.forEach((value, blockId) => {
// this._renderedBlockIdMap.set(blockId, value);
diff --git a/packages/base-render/src/components/sheets/sheet-skeleton.ts b/packages/base-render/src/components/sheets/sheet-skeleton.ts
index 2183c2408e..79aa0ab9f3 100644
--- a/packages/base-render/src/components/sheets/sheet-skeleton.ts
+++ b/packages/base-render/src/components/sheets/sheet-skeleton.ts
@@ -1,9 +1,9 @@
import {
BooleanNumber,
DEFAULT_EMPTY_DOCUMENT_VALUE,
- DocumentModel,
+ DocumentDataModel,
+ DocumentDataModelSimple,
DocumentModelOrSimple,
- DocumentModelSimple,
getColorStyle,
HorizontalAlign,
IBorderStyleData,
@@ -1031,7 +1031,7 @@ export class SpreadsheetSkeleton extends Skeleton {
return;
}
- let documentModel: Nullable<DocumentModelSimple>;
+ let documentModel: Nullable<DocumentDataModelSimple>;
let fontString = 'document';
const cellOtherConfig = this._getOtherStyle(style) as ICellOtherConfig;
@@ -1554,9 +1554,10 @@ export class SpreadsheetSkeleton extends Skeleton {
}
if (isFull === false) {
- return new DocumentModelSimple(documentData);
+ return new DocumentDataModelSimple(documentData);
}
- return new DocumentModel(documentData);
+
+ return new DocumentDataModel(documentData);
}
private _getDocumentDataByStyle(
@@ -1628,9 +1629,10 @@ export class SpreadsheetSkeleton extends Skeleton {
};
if (isFull === false) {
- return new DocumentModelSimple(documentData);
+ return new DocumentDataModelSimple(documentData);
}
- return new DocumentModel(documentData);
+
+ return new DocumentDataModel(documentData);
}
private _setBorderProps(r: number, c: number, type: BORDER_TYPE, style: IStyleData, cache: IStylesCache) {
diff --git a/packages/base-render/src/shape/rich-text.ts b/packages/base-render/src/shape/rich-text.ts
index b3ef00855d..47c792365a 100644
--- a/packages/base-render/src/shape/rich-text.ts
+++ b/packages/base-render/src/shape/rich-text.ts
@@ -3,7 +3,7 @@
import {
BooleanNumber,
DEFAULT_EMPTY_DOCUMENT_VALUE,
- DocumentModelSimple,
+ DocumentDataModelSimple,
IBorderData,
IColorStyle,
IDocumentData,
@@ -94,7 +94,7 @@ export class RichText extends BaseObject {
this._bd = props.bd;
this._cl = props.cl;
- this._documentData = this.convertToDocumentData(props.text || '');
+ this._documentData = this._convertToDocumentData(props.text || '');
}
if (this._allowCache) {
@@ -104,7 +104,7 @@ export class RichText extends BaseObject {
});
}
- const docModel = new DocumentModelSimple(this._documentData);
+ const docModel = new DocumentDataModelSimple(this._documentData);
this._documentSkeleton = DocumentSkeleton.create(docModel, this._localeService);
@@ -228,7 +228,7 @@ export class RichText extends BaseObject {
this._documents.render(ctx);
}
- private convertToDocumentData(text: string) {
+ private _convertToDocumentData(text: string) {
const contentLength = text.length;
const documentData: IDocumentData = {
id: 'd',
diff --git a/packages/base-slides/src/views/render/adaptors/docs-adaptor.ts b/packages/base-slides/src/views/render/adaptors/docs-adaptor.ts
index d267efb9a8..f5d7286115 100644
--- a/packages/base-slides/src/views/render/adaptors/docs-adaptor.ts
+++ b/packages/base-slides/src/views/render/adaptors/docs-adaptor.ts
@@ -1,3 +1,4 @@
+/* eslint-disable no-magic-numbers */
import {
BaseObject,
Documents,
@@ -14,7 +15,7 @@ import {
ScrollBar,
Viewport,
} from '@univerjs/base-render';
-import { DocumentModel, EventState, IPageElement, LocaleService, PageElementType } from '@univerjs/core';
+import { DocumentDataModel, EventState, IPageElement, LocaleService, PageElementType } from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
import { CanvasObjectProviderRegistry, ObjectAdaptor } from '../adaptor';
@@ -68,7 +69,7 @@ export class DocsAdaptor extends ObjectAdaptor {
return;
}
- const documentSkeleton = DocumentSkeleton.create(new DocumentModel(documentData), this._localeService);
+ const documentSkeleton = DocumentSkeleton.create(new DocumentDataModel(documentData), this._localeService);
const documents = new Documents(DOCS_VIEW_KEY.MAIN, documentSkeleton);
diff --git a/packages/core/src/basics/univer-doc.ts b/packages/core/src/basics/univer-doc.ts
index e90a847e8d..3b334a9fb2 100644
--- a/packages/core/src/basics/univer-doc.ts
+++ b/packages/core/src/basics/univer-doc.ts
@@ -1,6 +1,6 @@
import { Ctor, Inject, Injector } from '@wendellhu/redi';
-import { DocumentModel } from '../docs/domain/document-model';
+import { DocumentDataModel } from '../docs/data-model/document-data-model';
import { Plugin, PluginCtor, PluginStore } from '../plugin/plugin';
import { LifecycleStages } from '../services/lifecycle/lifecycle';
import { LifecycleInitializerService, LifecycleService } from '../services/lifecycle/lifecycle.service';
@@ -53,8 +53,8 @@ export class UniverDoc extends Disposable {
);
}
- createDoc(docData: Partial<IDocumentData>): DocumentModel {
- return this._injector.createInstance(DocumentModel, docData);
+ createDoc(docData: Partial<IDocumentData>): DocumentDataModel {
+ return this._injector.createInstance(DocumentDataModel, docData);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
diff --git a/packages/core/src/basics/univer.ts b/packages/core/src/basics/univer.ts
index 4e0c16aa51..c0adddc229 100644
--- a/packages/core/src/basics/univer.ts
+++ b/packages/core/src/basics/univer.ts
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Ctor, Injector } from '@wendellhu/redi';
-import { DocumentModel } from '../docs/domain/document-model';
+import { DocumentDataModel } from '../docs/data-model/document-data-model';
import { Plugin, PluginCtor, PluginRegistry, PluginStore, PluginType } from '../plugin/plugin';
import { CommandService, ICommandService } from '../services/command/command.service';
import { ConfigService, IConfigService } from '../services/config/config.service';
@@ -111,8 +111,8 @@ export class Univer {
return workbook!;
}
- createUniverDoc(config: Partial<IDocumentData>): DocumentModel {
- let doc: DocumentModel;
+ createUniverDoc(config: Partial<IDocumentData>): DocumentDataModel {
+ let doc: DocumentDataModel;
const addDoc = () => {
doc = this._univerDoc!.createDoc(config);
this._univerInstanceService.addDoc(doc);
diff --git a/packages/core/src/common/const.ts b/packages/core/src/common/const.ts
index 93c98a128d..8ae5c887c8 100644
--- a/packages/core/src/common/const.ts
+++ b/packages/core/src/common/const.ts
@@ -1,3 +1,5 @@
export const DOCS_NORMAL_EDITOR_UNIT_ID_KEY = '__defaultDocumentNormalEditorSpecialUnitId_20231006__';
export const DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY = '__defaultDocumentFormulaBarEditorSpecialUnitId_20231012__';
+
+export const DEFAULT_EMPTY_DOCUMENT_VALUE = '\r\n';
diff --git a/packages/base-docs/src/basics/memory-cursor.ts b/packages/core/src/common/memory-cursor.ts
similarity index 100%
rename from packages/base-docs/src/basics/memory-cursor.ts
rename to packages/core/src/common/memory-cursor.ts
diff --git a/packages/base-docs/src/commands/mutations/__tests__/apply-utils.spec.ts b/packages/core/src/docs/data-model/__tests__/apply-utils.spec.ts
similarity index 97%
rename from packages/base-docs/src/commands/mutations/__tests__/apply-utils.spec.ts
rename to packages/core/src/docs/data-model/__tests__/apply-utils.spec.ts
index 8379401fbe..60127db975 100644
--- a/packages/base-docs/src/commands/mutations/__tests__/apply-utils.spec.ts
+++ b/packages/core/src/docs/data-model/__tests__/apply-utils.spec.ts
@@ -1,9 +1,11 @@
/* eslint-disable no-magic-numbers */
-import { BooleanNumber, IDocumentBody, ITextRun, Nullable, UpdateDocsAttributeType } from '@univerjs/core';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, Nullable } from 'vitest';
-import { deleteParagraphs, deleteTextRuns, insertTextRuns } from '../functions/common';
-import { coverTextRuns } from '../functions/update-apply';
+import { UpdateDocsAttributeType } from '../../../shared';
+import { BooleanNumber } from '../../../types/enum';
+import { IDocumentBody, ITextRun } from '../../../types/interfaces';
+import { deleteParagraphs, deleteTextRuns, insertTextRuns } from '../apply-utils/common';
+import { coverTextRuns } from '../apply-utils/update-apply';
describe('test case in apply utils', () => {
let body: Nullable<IDocumentBody> = null;
diff --git a/packages/base-docs/src/commands/mutations/functions/common.ts b/packages/core/src/docs/data-model/apply-utils/common.ts
similarity index 98%
rename from packages/base-docs/src/commands/mutations/functions/common.ts
rename to packages/core/src/docs/data-model/apply-utils/common.ts
index ab1b6f36ac..11326b9560 100644
--- a/packages/base-docs/src/commands/mutations/functions/common.ts
+++ b/packages/core/src/docs/data-model/apply-utils/common.ts
@@ -1,18 +1,15 @@
+import { horizontalLineSegmentsSubtraction, Nullable, sortRulesFactory, Tools } from '../../../shared';
+import { isSameStyleTextRun } from '../../../shared/compare';
import {
- DataStreamTreeTokenType,
- horizontalLineSegmentsSubtraction,
ICustomBlock,
ICustomRange,
IDocumentBody,
IParagraph,
ISectionBreak,
- isSameStyleTextRun,
ITable,
ITextRun,
- Nullable,
- sortRulesFactory,
- Tools,
-} from '@univerjs/core';
+} from '../../../types/interfaces';
+import { DataStreamTreeTokenType } from '../types';
export function normalizeTextRuns(textRuns: ITextRun[]) {
const results: ITextRun[] = [];
diff --git a/packages/base-docs/src/commands/mutations/functions/delete-apply.ts b/packages/core/src/docs/data-model/apply-utils/delete-apply.ts
similarity index 59%
rename from packages/base-docs/src/commands/mutations/functions/delete-apply.ts
rename to packages/core/src/docs/data-model/apply-utils/delete-apply.ts
index 21567b5b9c..0ad41979bb 100644
--- a/packages/base-docs/src/commands/mutations/functions/delete-apply.ts
+++ b/packages/core/src/docs/data-model/apply-utils/delete-apply.ts
@@ -1,14 +1,7 @@
-import {
- DEFAULT_EMPTY_DOCUMENT_VALUE,
- deleteContent,
- DocumentBodyModel,
- DocumentModel,
- getDocsUpdateBody,
- IDocumentBody,
- IParagraph,
- Tools,
-} from '@univerjs/core';
-
+import { DEFAULT_EMPTY_DOCUMENT_VALUE } from '../../../common/const';
+import { deleteContent, Tools } from '../../../shared';
+import { IDocumentBody, IParagraph } from '../../../types/interfaces';
+import { DocumentBodyModel } from '../document-body-model';
import {
deleteCustomBlocks,
deleteCustomRanges,
@@ -18,38 +11,7 @@ import {
deleteTextRuns,
} from './common';
-export function DeleteApply(
- document: DocumentModel,
- textLength: number,
- currentIndex: number,
- segmentId?: string
-): IDocumentBody {
- const doc = document.snapshot;
-
- const bodyModel = document.getBodyModel(segmentId);
-
- const body = getDocsUpdateBody(doc, segmentId);
-
- if (body == null) {
- throw new Error('no body has changed');
- }
-
- if (textLength <= 0) {
- return { dataStream: '' };
- }
-
- bodyModel.delete(currentIndex, textLength);
-
- const deleBody = updateAttributeByDelete(body, textLength, currentIndex);
-
- recoveryBody(bodyModel, body, deleBody); // If the last paragraph in the document is deleted, restore an initial blank document.
-
- // console.log('删除的model打印', bodyModel, body, deleBody);
-
- return deleBody;
-}
-
-function updateAttributeByDelete(body: IDocumentBody, textLength: number, currentIndex: number): IDocumentBody {
+export function updateAttributeByDelete(body: IDocumentBody, textLength: number, currentIndex: number): IDocumentBody {
const { dataStream } = body;
const startIndex = currentIndex;
@@ -86,7 +48,7 @@ function updateAttributeByDelete(body: IDocumentBody, textLength: number, curren
};
}
-function recoveryBody(bodyModel: DocumentBodyModel, body: IDocumentBody, deleBody: IDocumentBody) {
+export function recoveryBody(bodyModel: DocumentBodyModel, body: IDocumentBody, deleBody: IDocumentBody) {
if (bodyModel.children[0].children.length === 0) {
bodyModel.reset({
dataStream: DEFAULT_EMPTY_DOCUMENT_VALUE,
diff --git a/packages/core/src/docs/data-model/apply-utils/insert-apply.ts b/packages/core/src/docs/data-model/apply-utils/insert-apply.ts
new file mode 100644
index 0000000000..83ed98d2cf
--- /dev/null
+++ b/packages/core/src/docs/data-model/apply-utils/insert-apply.ts
@@ -0,0 +1,31 @@
+import { insertTextToContent } from '../../../shared';
+import { IDocumentBody } from '../../../types/interfaces';
+import {
+ insertCustomBlocks,
+ insertCustomRanges,
+ insertParagraphs,
+ insertSectionBreaks,
+ insertTables,
+ insertTextRuns,
+} from './common';
+
+export function updateAttributeByInsert(
+ body: IDocumentBody,
+ insertBody: IDocumentBody,
+ textLength: number,
+ currentIndex: number
+) {
+ body.dataStream = insertTextToContent(body.dataStream, currentIndex, insertBody.dataStream);
+
+ insertTextRuns(body, insertBody, textLength, currentIndex);
+
+ insertParagraphs(body, insertBody, textLength, currentIndex);
+
+ insertSectionBreaks(body, insertBody, textLength, currentIndex);
+
+ insertCustomBlocks(body, insertBody, textLength, currentIndex);
+
+ insertTables(body, insertBody, textLength, currentIndex);
+
+ insertCustomRanges(body, insertBody, textLength, currentIndex);
+}
diff --git a/packages/base-docs/src/commands/mutations/functions/update-apply.ts b/packages/core/src/docs/data-model/apply-utils/update-apply.ts
similarity index 95%
rename from packages/base-docs/src/commands/mutations/functions/update-apply.ts
rename to packages/core/src/docs/data-model/apply-utils/update-apply.ts
index 6edf39d78c..3fdc2ee288 100644
--- a/packages/base-docs/src/commands/mutations/functions/update-apply.ts
+++ b/packages/core/src/docs/data-model/apply-utils/update-apply.ts
@@ -1,6 +1,5 @@
+import { Nullable, Tools, UpdateDocsAttributeType } from '../../../shared';
import {
- DocumentModel,
- getDocsUpdateBody,
ICustomBlock,
ICustomRange,
IDocumentBody,
@@ -8,11 +7,7 @@ import {
ISectionBreak,
ITable,
ITextRun,
- Nullable,
- Tools,
- UpdateDocsAttributeType,
-} from '@univerjs/core';
-
+} from '../../../types/interfaces';
import {
deleteCustomBlocks,
deleteCustomRanges,
@@ -27,30 +22,7 @@ import {
normalizeTextRuns,
} from './common';
-export function UpdateAttributeApply(
- document: DocumentModel,
- updateBody: Nullable<IDocumentBody>,
- textLength: number,
- currentIndex: number,
- coverType = UpdateDocsAttributeType.COVER,
- segmentId?: string
-): IDocumentBody {
- if (updateBody == null) {
- throw new Error('updateBody is none');
- }
-
- const doc = document.snapshot;
-
- const body = getDocsUpdateBody(doc, segmentId);
-
- if (body == null) {
- throw new Error('no body has changed');
- }
-
- return updateAttribute(body, updateBody, textLength, currentIndex, coverType);
-}
-
-function updateAttribute(
+export function updateAttribute(
body: IDocumentBody,
updateBody: IDocumentBody,
textLength: number,
diff --git a/packages/core/src/docs/domain/data-stream-tree-node.ts b/packages/core/src/docs/data-model/data-stream-tree-node.ts
similarity index 95%
rename from packages/core/src/docs/domain/data-stream-tree-node.ts
rename to packages/core/src/docs/data-model/data-stream-tree-node.ts
index e797229e4b..2d1c46c6a8 100644
--- a/packages/core/src/docs/domain/data-stream-tree-node.ts
+++ b/packages/core/src/docs/data-model/data-stream-tree-node.ts
@@ -70,7 +70,7 @@ export class DataStreamTreeNode {
this.startIndex += len;
this.endIndex += len;
- this.addIndexForBlock(len);
+ this._addIndexForBlock(len);
}
selfPlus(len: number, index?: number) {
@@ -80,7 +80,7 @@ export class DataStreamTreeNode {
index = this.startIndex;
}
- this.addIndexForBlock(len, index);
+ this._addIndexForBlock(len, index);
}
split(index: number) {
@@ -137,9 +137,9 @@ export class DataStreamTreeNode {
lastNode.children = lastChildNodes;
- firstNode.resetBlocks();
+ firstNode._resetBlocks();
- lastNode.resetBlocks();
+ lastNode._resetBlocks();
return {
firstNode,
@@ -196,7 +196,7 @@ export class DataStreamTreeNode {
node.remove();
}
- private addIndexForBlock(addLen: number, index: number = -Infinity) {
+ private _addIndexForBlock(addLen: number, index: number = -Infinity) {
for (let i = 0, len = this.blocks.length; i < len; i++) {
const block = this.blocks[i];
@@ -206,7 +206,7 @@ export class DataStreamTreeNode {
}
}
- private resetBlocks() {
+ private _resetBlocks() {
if (this.nodeType !== DataStreamTreeNodeType.PARAGRAPH) {
return;
}
diff --git a/packages/core/src/docs/domain/document-body-model.ts b/packages/core/src/docs/data-model/document-body-model.ts
similarity index 88%
rename from packages/core/src/docs/domain/document-body-model.ts
rename to packages/core/src/docs/data-model/document-body-model.ts
index b4a52b5936..94a12fefcf 100644
--- a/packages/core/src/docs/domain/document-body-model.ts
+++ b/packages/core/src/docs/data-model/document-body-model.ts
@@ -5,7 +5,7 @@ import { IDocumentBody, ITextRun } from '../../types/interfaces/i-document-data'
import { DataStreamTreeNode } from './data-stream-tree-node';
import { DataStreamTreeNodeType, DataStreamTreeTokenType } from './types';
-export type DocumentBodyModelOrSimple = DocumentBodyModelSimple | DocumentBodyModel;
+type DocumentBodyModelOrSimple = DocumentBodyModelSimple | DocumentBodyModel;
export class DocumentBodyModelSimple implements IDisposable {
children: DataStreamTreeNode[] = [];
@@ -211,17 +211,17 @@ export class DocumentBodyModelSimple implements IDisposable {
}
export class DocumentBodyModel extends DocumentBodyModelSimple {
- private sectionBreakCurrentIndex = 0;
+ private _sectionBreakCurrentIndex = 0;
- private paragraphCurrentIndex = 0;
+ private _paragraphCurrentIndex = 0;
- private textRunCurrentIndex = 0;
+ private _textRunCurrentIndex = 0;
- private customBlockCurrentIndex = 0;
+ private _customBlockCurrentIndex = 0;
- private tableBlockCurrentIndex = 0;
+ private _tableBlockCurrentIndex = 0;
- private customRangeCurrentIndex = 0;
+ private _customRangeCurrentIndex = 0;
/**
* @deprecated use constructor directly
@@ -240,7 +240,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
insert(insertBody: IDocumentBody, insertIndex = 0) {
const dataStream = insertBody.dataStream;
let dataStreamLen = dataStream.length;
- const insertedNode = this.getParagraphByIndex(this.children, insertIndex);
+ const insertedNode = this._getParagraphByIndex(this.children, insertIndex);
if (insertedNode == null) {
return;
@@ -253,7 +253,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
const insertNodes = insertBodyModel.children;
for (const node of insertNodes) {
- this.forEachDown(node, (newNode) => {
+ this._forEachDown(node, (newNode) => {
newNode.plus(insertIndex);
});
}
@@ -274,7 +274,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
insertedLastNode
);
- this.forEachTop(insertedNode.parent, (currentNode) => {
+ this._forEachTop(insertedNode.parent, (currentNode) => {
// currentNode.endIndex += dataStreamLen;
currentNode.selfPlus(dataStreamLen, currentNode.getPositionInParent());
const children = currentNode.children;
@@ -289,7 +289,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
continue;
}
- this.forEachDown(node, (newNode) => {
+ this._forEachDown(node, (newNode) => {
newNode.plus(dataStreamLen);
});
}
@@ -302,7 +302,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
// insertedNode.endIndex += dataStreamLen;
insertedNode.selfPlus(dataStreamLen, insertIndex);
- this.forEachTop(insertedNode.parent, (currentNode) => {
+ this._forEachTop(insertedNode.parent, (currentNode) => {
// currentNode.endIndex += dataStreamLen;
currentNode.selfPlus(dataStreamLen, currentNode.getPositionInParent());
const children = currentNode.children;
@@ -316,7 +316,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
continue;
}
- this.forEachDown(node, (newNode) => {
+ this._forEachDown(node, (newNode) => {
newNode.plus(dataStreamLen);
});
}
@@ -326,10 +326,29 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
delete(currentIndex: number, textLength: number) {
const nodes = this.children;
- this.deleteTree(nodes, currentIndex, textLength);
+ this._deleteTree(nodes, currentIndex, textLength);
}
- private getParagraphByIndex(nodes: DataStreamTreeNode[], insertIndex: number): Nullable<DataStreamTreeNode> {
+ /** Get pure text content in the given range. */
+ getText(): string {
+ // Basically this is a DFS traversal of the tree to get the `content` and append it to the result.
+ // TODO: implement
+ const pieces: string[] = [];
+
+ function traverseTreeNode(node: DataStreamTreeNode) {
+ if (node.content) {
+ pieces.push(node.content);
+ }
+
+ node.children.forEach(traverseTreeNode);
+ }
+
+ this.children.forEach((n) => traverseTreeNode(n));
+
+ return pieces.join('');
+ }
+
+ private _getParagraphByIndex(nodes: DataStreamTreeNode[], insertIndex: number): Nullable<DataStreamTreeNode> {
for (const node of nodes) {
const { children } = node;
@@ -341,13 +360,13 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
return node;
}
- return this.getParagraphByIndex(children, insertIndex);
+ return this._getParagraphByIndex(children, insertIndex);
}
return null;
}
- private forEachTop(
+ private _forEachTop(
node: Nullable<DataStreamTreeNode>,
func: (node: DataStreamTreeNode | DocumentBodyModelOrSimple) => void
) {
@@ -361,23 +380,23 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
func(this);
}
- private forEachDown(node: DataStreamTreeNode, func: (node: DataStreamTreeNode) => void) {
+ private _forEachDown(node: DataStreamTreeNode, func: (node: DataStreamTreeNode) => void) {
func(node);
const children = node.children;
for (node of children) {
- this.forEachDown(node, func);
+ this._forEachDown(node, func);
}
}
override resetCache() {
- this.sectionBreakCurrentIndex = 0;
- this.paragraphCurrentIndex = 0;
- this.textRunCurrentIndex = 0;
- this.customBlockCurrentIndex = 0;
- this.tableBlockCurrentIndex = 0;
- this.customRangeCurrentIndex = 0;
+ this._sectionBreakCurrentIndex = 0;
+ this._paragraphCurrentIndex = 0;
+ this._textRunCurrentIndex = 0;
+ this._customBlockCurrentIndex = 0;
+ this._tableBlockCurrentIndex = 0;
+ this._customRangeCurrentIndex = 0;
}
override getSectionBreak(index: number) {
@@ -389,10 +408,10 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
return;
}
- for (let i = this.sectionBreakCurrentIndex; i < sectionBreaks.length; i++) {
+ for (let i = this._sectionBreakCurrentIndex; i < sectionBreaks.length; i++) {
const sectionBreak = sectionBreaks[i];
if (sectionBreak.startIndex === index) {
- this.sectionBreakCurrentIndex = i;
+ this._sectionBreakCurrentIndex = i;
return sectionBreak;
}
}
@@ -404,10 +423,10 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
return;
}
- for (let i = this.paragraphCurrentIndex; i < paragraphs.length; i++) {
+ for (let i = this._paragraphCurrentIndex; i < paragraphs.length; i++) {
const paragraph = paragraphs[i];
if (paragraph.startIndex === index) {
- this.paragraphCurrentIndex = i;
+ this._paragraphCurrentIndex = i;
return paragraph;
}
}
@@ -426,13 +445,13 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
const trRange: ITextRun[] = [];
- for (let i = this.textRunCurrentIndex, textRunsLen = textRuns.length; i < textRunsLen; i++) {
+ for (let i = this._textRunCurrentIndex, textRunsLen = textRuns.length; i < textRunsLen; i++) {
const textRun = textRuns[i];
if (textRun.st > endIndex) {
- this.textRunCurrentIndex = i;
+ this._textRunCurrentIndex = i;
break;
} else if (textRun.ed < startIndex) {
- this.textRunCurrentIndex = i;
+ this._textRunCurrentIndex = i;
continue;
} else {
trRange.push({
@@ -441,7 +460,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
sId: textRun.sId,
ts: textRun.ts,
});
- this.textRunCurrentIndex = i;
+ this._textRunCurrentIndex = i;
}
}
@@ -473,7 +492,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
return;
}
- const curTextRun = textRuns[this.textRunCurrentIndex];
+ const curTextRun = textRuns[this._textRunCurrentIndex];
if (curTextRun != null) {
if (index >= curTextRun.st && index < curTextRun.ed) {
@@ -485,45 +504,26 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
}
}
- for (let i = this.textRunCurrentIndex, textRunsLen = textRuns.length; i < textRunsLen; i++) {
+ for (let i = this._textRunCurrentIndex, textRunsLen = textRuns.length; i < textRunsLen; i++) {
const textRun = textRuns[i];
if (index >= textRun.st && index < textRun.ed) {
- this.textRunCurrentIndex = i;
+ this._textRunCurrentIndex = i;
return textRun;
}
}
}
- /** Get pure text content in the given range. */
- getText(): string {
- // Basically this is a DFS traversal of the tree to get the `content` and append it to the result.
- // TODO: implement
- const pieces: string[] = [];
-
- function traverseTreeNode(node: DataStreamTreeNode) {
- if (node.content) {
- pieces.push(node.content);
- }
-
- node.children.forEach(traverseTreeNode);
- }
-
- this.children.forEach((n) => traverseTreeNode(n));
-
- return pieces.join('');
- }
-
override getCustomBlock(index: number) {
const customBlocks = this.body.customBlocks;
if (customBlocks == null) {
return;
}
- for (let i = this.customBlockCurrentIndex; i < customBlocks.length; i++) {
+ for (let i = this._customBlockCurrentIndex; i < customBlocks.length; i++) {
const customBlock = customBlocks[i];
if (customBlock.startIndex === index) {
- this.customBlockCurrentIndex = i;
+ this._customBlockCurrentIndex = i;
return customBlock;
}
}
@@ -535,10 +535,10 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
return;
}
- for (let i = this.tableBlockCurrentIndex; i < tables.length; i++) {
+ for (let i = this._tableBlockCurrentIndex; i < tables.length; i++) {
const table = tables[i];
if (table.startIndex === index) {
- this.tableBlockCurrentIndex = i;
+ this._tableBlockCurrentIndex = i;
return table;
}
}
@@ -557,7 +557,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
}
}
- private deleteTree(nodes: DataStreamTreeNode[], currentIndex: number, textLength: number) {
+ private _deleteTree(nodes: DataStreamTreeNode[], currentIndex: number, textLength: number) {
const startIndex = currentIndex;
const endIndex = currentIndex + textLength - 1;
let mergeNode: Nullable<DataStreamTreeNode> = null;
@@ -567,7 +567,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
const node = nodes[i];
const { startIndex: st, endIndex: ed, children } = node;
- this.deleteTree(children, currentIndex, textLength);
+ this._deleteTree(children, currentIndex, textLength);
if (startIndex === endIndex && endIndex === ed) {
// The cursor is at the dividing point between two paragraphs,
@@ -653,7 +653,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
insertedFirstNode.plus(insertStartIndex);
- this.forEachDown(insertedLastNode, (newNode) => {
+ this._forEachDown(insertedLastNode, (newNode) => {
newNode.plus(insertStartIndex + 1);
});
@@ -664,7 +664,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
insertedLastNode
);
- this.forEachTop(insertedNode.parent, (currentNode) => {
+ this._forEachTop(insertedNode.parent, (currentNode) => {
// currentNode.endIndex += dataStreamLen;
currentNode.selfPlus(1, currentNode.getPositionInParent());
const children = currentNode.children;
@@ -684,16 +684,16 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
continue;
}
- this.forEachDown(node, (newNode) => {
+ this._forEachDown(node, (newNode) => {
newNode.plus(1);
});
}
});
}
- private move() {}
+ // private move() {}
- private split() {}
+ // private split() {}
- private merge() {}
+ // private merge() {}
}
diff --git a/packages/core/src/docs/domain/document-model.ts b/packages/core/src/docs/data-model/document-data-model.ts
similarity index 50%
rename from packages/core/src/docs/domain/document-model.ts
rename to packages/core/src/docs/data-model/document-data-model.ts
index fe2bcd89cf..9dc036996d 100644
--- a/packages/core/src/docs/domain/document-model.ts
+++ b/packages/core/src/docs/data-model/document-data-model.ts
@@ -1,7 +1,14 @@
+import { MemoryCursor } from '../../common/memory-cursor';
+import { getDocsUpdateBody, Nullable } from '../../shared';
+import { UpdateDocsAttributeType } from '../../shared/command-enum';
import { Tools } from '../../shared/tools';
-import { IDocumentData, IDocumentRenderConfig } from '../../types/interfaces/i-document-data';
+import { IDocumentBody, IDocumentData, IDocumentRenderConfig } from '../../types/interfaces/i-document-data';
import { IPaddingData } from '../../types/interfaces/i-style-data';
+import { recoveryBody, updateAttributeByDelete } from './apply-utils/delete-apply';
+import { updateAttributeByInsert } from './apply-utils/insert-apply';
+import { updateAttribute } from './apply-utils/update-apply';
import { DocumentBodyModel } from './document-body-model';
+import { DocMutationParams } from './document-model-types';
export const DEFAULT_DOC = {
id: 'default_doc',
@@ -15,9 +22,9 @@ interface IDrawingUpdateConfig {
width: number;
}
-export type DocumentModelOrSimple = DocumentModelSimple | DocumentModel;
+export type DocumentModelOrSimple = DocumentDataModelSimple | DocumentDataModel;
-export class DocumentModelSimple {
+export class DocumentDataModelSimple {
snapshot: IDocumentData;
headerTreeMap!: Map<string, DocumentBodyModel>; // sub class should guarantee this is not null
@@ -46,6 +53,9 @@ export class DocumentModelSimple {
return this.snapshot.lists;
}
+ /**
+ * @deprecated use getBody to instead.
+ */
get body() {
return this.snapshot.body;
}
@@ -54,6 +64,10 @@ export class DocumentModelSimple {
return this.snapshot.settings?.zoomRatio || 1;
}
+ getBody() {
+ return this.snapshot.body;
+ }
+
dispose() {
this.bodyModel.dispose();
@@ -172,11 +186,11 @@ export class DocumentModelSimple {
const objectTransform = drawing.objectTransform;
- objectTransform.size.width = config.width;
- objectTransform.size.height = config.height;
+ objectTransform.size.width = width;
+ objectTransform.size.height = height;
- objectTransform.positionH.posOffset = config.left;
- objectTransform.positionV.posOffset = config.top;
+ objectTransform.positionH.posOffset = left;
+ objectTransform.positionV.posOffset = top;
}
setZoomRatio(zoomRatio: number = 1) {
@@ -190,16 +204,16 @@ export class DocumentModelSimple {
}
}
-const UNIT_ID_LENGTH = 6;
-
-export class DocumentModel extends DocumentModelSimple {
+export class DocumentDataModel extends DocumentDataModelSimple {
private _unitId: string;
constructor(snapshot: Partial<IDocumentData>) {
super(snapshot);
+ const UNIT_ID_LENGTH = 6;
+
this._unitId = this.snapshot.id ?? Tools.generateRandomId(UNIT_ID_LENGTH);
- this._initializeRowColTree();
+ this._initializeHeaderFooterTree();
}
getRev(): number {
@@ -220,7 +234,7 @@ export class DocumentModel extends DocumentModelSimple {
}
this.snapshot = { ...DEFAULT_DOC, ...snapshot };
- this._initializeRowColTree();
+ this._initializeHeaderFooterTree();
this.bodyModel.reset(snapshot.body ?? { dataStream: '\r\n' });
}
@@ -228,14 +242,151 @@ export class DocumentModel extends DocumentModelSimple {
return this._unitId;
}
+ apply(mutations: DocMutationParams[]) {
+ const undoMutations: DocMutationParams[] = [];
+
+ const memoryCursor = new MemoryCursor();
+
+ memoryCursor.reset();
+
+ mutations.forEach((mutation) => {
+ // FIXME: @jocs Since updateApply modifies the mutation(used in undo/redo),
+ // so make a deep copy here, does updateApply need to
+ // be modified to have no side effects in the future?
+ mutation = Tools.deepClone(mutation);
+
+ if (mutation.t === 'r') {
+ const { coverType, body, len, segmentId } = mutation;
+
+ if (body != null) {
+ const documentBody = this._updateApply(body, len, memoryCursor.cursor, coverType, segmentId);
+
+ undoMutations.push({
+ ...mutation,
+ t: 'r',
+ coverType: UpdateDocsAttributeType.REPLACE,
+ body: documentBody,
+ });
+ } else {
+ undoMutations.push({
+ ...mutation,
+ t: 'r',
+ });
+ }
+
+ memoryCursor.moveCursor(len);
+ } else if (mutation.t === 'i') {
+ const { body, len, segmentId, line } = mutation;
+
+ this._insertApply(body!, len, memoryCursor.cursor, segmentId);
+ memoryCursor.moveCursor(len);
+ undoMutations.push({
+ t: 'd',
+ len,
+ line,
+ segmentId,
+ });
+ } else if (mutation.t === 'd') {
+ const { len, segmentId } = mutation;
+ const documentBody = this._deleteApply(len, memoryCursor.cursor, segmentId);
+
+ undoMutations.push({
+ ...mutation,
+ t: 'i',
+ body: documentBody,
+ });
+ } else {
+ throw new Error(`Unknown mutation type for mutation: ${mutation}.`);
+ }
+ });
+
+ return undoMutations;
+ }
+
+ private _updateApply(
+ updateBody: Nullable<IDocumentBody>,
+ textLength: number,
+ currentIndex: number,
+ coverType = UpdateDocsAttributeType.COVER,
+ segmentId?: string
+ ): IDocumentBody {
+ if (updateBody == null) {
+ throw new Error('updateBody is none');
+ }
+
+ const doc = this.snapshot;
+
+ const body = getDocsUpdateBody(doc, segmentId);
+
+ if (body == null) {
+ throw new Error('no body has changed');
+ }
+
+ return updateAttribute(body, updateBody, textLength, currentIndex, coverType);
+ }
+
+ private _deleteApply(textLength: number, currentIndex: number, segmentId?: string): IDocumentBody {
+ const doc = this.snapshot;
+
+ const bodyModel = this.getBodyModel(segmentId);
+
+ const body = getDocsUpdateBody(doc, segmentId);
+
+ if (body == null) {
+ throw new Error('no body has changed');
+ }
+
+ if (textLength <= 0) {
+ return { dataStream: '' };
+ }
+
+ bodyModel.delete(currentIndex, textLength);
+
+ const deleBody = updateAttributeByDelete(body, textLength, currentIndex);
+
+ recoveryBody(bodyModel, body, deleBody); // If the last paragraph in the document is deleted, restore an initial blank document.
+
+ // console.log('删除的model打印', bodyModel, body, deleBody);
+
+ return deleBody;
+ }
+
+ private _insertApply(insertBody: IDocumentBody, textLength: number, currentIndex: number, segmentId?: string) {
+ const doc = this.snapshot;
+
+ const bodyModel = this.getBodyModel(segmentId);
+
+ const body = getDocsUpdateBody(doc, segmentId);
+
+ if (textLength === 0) {
+ return;
+ }
+
+ if (body == null) {
+ throw new Error('no body has changed');
+ }
+
+ updateAttributeByInsert(body, insertBody, textLength, currentIndex);
+
+ if (insertBody.dataStream.length > 1 && /\r/.test(insertBody.dataStream)) {
+ // TODO: @JOCS, The DocumentDataModel needs to be rewritten to better support the
+ // large area of updates that are brought about by the paste, abstract the
+ // methods associated with the DocumentDataModel insertion, and support atomic operations
+ bodyModel.reset(body);
+ } else {
+ bodyModel.insert(insertBody, currentIndex);
+ }
+
+ // console.log('插入的model打印', bodyModel, textLength, currentIndex);
+ }
+
override updateDocumentId(unitId: string) {
super.updateDocumentId(unitId);
this._unitId = unitId;
}
- // TODO: @jocs The function name and content don't match?
- private _initializeRowColTree() {
+ private _initializeHeaderFooterTree() {
this.headerTreeMap = new Map();
this.footerTreeMap = new Map();
@@ -256,13 +407,3 @@ export class DocumentModel extends DocumentModelSimple {
}
}
}
-
-export const DEFAULT_EMPTY_DOCUMENT_VALUE = '\r\n';
-
-export function createEmptyDocSnapshot(): Partial<IDocumentData> {
- return {
- body: {
- dataStream: DEFAULT_EMPTY_DOCUMENT_VALUE,
- },
- };
-}
diff --git a/packages/core/src/docs/data-model/document-model-types.ts b/packages/core/src/docs/data-model/document-model-types.ts
new file mode 100644
index 0000000000..ef1dce0b6f
--- /dev/null
+++ b/packages/core/src/docs/data-model/document-model-types.ts
@@ -0,0 +1,36 @@
+import { UpdateDocsAttributeType } from '../../shared/command-enum';
+import { IDocumentBody } from '../../types/interfaces/i-document-data';
+
+/**
+ * Retain mutation is used to move the cursor or to update properties of the text in the given range.
+ */
+export interface IRetainMutationParams {
+ t: 'r';
+ len: number;
+ segmentId?: string;
+ body?: IDocumentBody;
+ coverType?: UpdateDocsAttributeType;
+}
+
+/**
+ * Insert mutation is used to insert text (maybe with rich text properties) at the given position.
+ */
+export interface IInsertMutationParams {
+ t: 'i';
+ body: IDocumentBody;
+ len: number;
+ line: number;
+ segmentId?: string;
+}
+
+/**
+ * Delete mutation is used to delete text at the given position.
+ */
+export interface IDeleteMutationParams {
+ t: 'd';
+ line: number;
+ len: number;
+ segmentId?: string;
+}
+
+export type DocMutationParams = IRetainMutationParams | IInsertMutationParams | IDeleteMutationParams;
diff --git a/packages/core/src/docs/domain/index.ts b/packages/core/src/docs/data-model/index.ts
similarity index 72%
rename from packages/core/src/docs/domain/index.ts
rename to packages/core/src/docs/data-model/index.ts
index cfee14d7bf..5b6ec2d232 100644
--- a/packages/core/src/docs/domain/index.ts
+++ b/packages/core/src/docs/data-model/index.ts
@@ -1,4 +1,4 @@
export * from './data-stream-tree-node';
export * from './document-body-model';
-export * from './document-model';
+export * from './document-data-model';
export * from './types';
diff --git a/packages/core/src/docs/domain/types.ts b/packages/core/src/docs/data-model/types.ts
similarity index 100%
rename from packages/core/src/docs/domain/types.ts
rename to packages/core/src/docs/data-model/types.ts
diff --git a/packages/core/src/docs/index.ts b/packages/core/src/docs/index.ts
index ca17974b06..044c5df924 100644
--- a/packages/core/src/docs/index.ts
+++ b/packages/core/src/docs/index.ts
@@ -1 +1 @@
-export * from './domain';
+export * from './data-model';
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 742575450d..89d0118172 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1,13 +1,21 @@
export * from './basics';
export { dedupe, remove } from './common/array';
-export { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from './common/const';
+export {
+ DEFAULT_EMPTY_DOCUMENT_VALUE,
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+} from './common/const';
+export { MemoryCursor } from './common/memory-cursor';
export { type ISequenceExecuteResult, sequence, sequenceAsync } from './common/sequence';
-export * from './docs/domain';
+export * from './docs/data-model';
+export {
+ type DocMutationParams,
+ type IDeleteMutationParams,
+ type IInsertMutationParams,
+ type IRetainMutationParams,
+} from './docs/data-model/document-model-types';
export * from './observer';
export { Plugin, PluginType } from './plugin/plugin';
-
-// #region services
-
export {
CommandType,
type ICommand,
@@ -60,9 +68,6 @@ export {
RedoCommand,
UndoCommand,
} from './services/undoredo/undoredo.service';
-
-// #endregion
-
export * from './shared';
// #region sheet
@@ -82,9 +87,6 @@ export { Styles } from './sheets/styles';
export { SheetViewModel } from './sheets/view-model';
export { getWorksheetUID, Workbook } from './sheets/workbook';
export { Worksheet } from './sheets/worksheet';
-
-// #endregion
-
export * from './slides/domain';
export * from './types/const';
export * from './types/enum';
diff --git a/packages/core/src/services/instance/instance.service.ts b/packages/core/src/services/instance/instance.service.ts
index 403c6bb101..9632b49947 100644
--- a/packages/core/src/services/instance/instance.service.ts
+++ b/packages/core/src/services/instance/instance.service.ts
@@ -1,7 +1,7 @@
import { createIdentifier } from '@wendellhu/redi';
import { BehaviorSubject, Observable, Subject } from 'rxjs';
-import { DocumentModel } from '../../docs/domain/document-model';
+import { DocumentDataModel } from '../../docs/data-model/document-data-model';
import { Nullable } from '../../shared';
import { Disposable } from '../../shared/lifecycle';
import { Workbook } from '../../sheets/workbook';
@@ -19,7 +19,7 @@ export const enum DocumentType {
}
export interface IUniverHandler {
- createUniverDoc(data: Partial<IDocumentData>): DocumentModel;
+ createUniverDoc(data: Partial<IDocumentData>): DocumentDataModel;
createUniverSheet(data: Partial<IWorkbookData>): Workbook;
createUniverSlide(data: Partial<ISlideData>): Slide;
}
@@ -32,42 +32,42 @@ export interface IUniverInstanceService {
focused$: Observable<Nullable<string>>;
currentSheet$: Observable<Nullable<Workbook>>;
- currentDoc$: Observable<Nullable<DocumentModel>>;
+ currentDoc$: Observable<Nullable<DocumentDataModel>>;
currentSlide$: Observable<Nullable<Slide>>;
sheetAdded$: Observable<Workbook>;
- docAdded$: Observable<DocumentModel>;
+ docAdded$: Observable<DocumentDataModel>;
slideAdded$: Observable<Slide>;
sheetDisposed$: Observable<Workbook>;
- docDisposed$: Observable<DocumentModel>;
+ docDisposed$: Observable<DocumentDataModel>;
slideDisposed$: Observable<Slide>;
focusUniverInstance(id: string | null): void;
- getFocusedUniverInstance(): Workbook | DocumentModel | Slide | null;
+ getFocusedUniverInstance(): Workbook | DocumentDataModel | Slide | null;
- createDoc(data: Partial<IDocumentData>): DocumentModel;
+ createDoc(data: Partial<IDocumentData>): DocumentDataModel;
createSheet(data: Partial<IWorkbookData>): Workbook;
createSlide(data: Partial<ISlideData>): Slide;
- changeDoc(unitId: string, doc: DocumentModel): void;
- addDoc(doc: DocumentModel): void;
+ changeDoc(unitId: string, doc: DocumentDataModel): void;
+ addDoc(doc: DocumentDataModel): void;
addSheet(sheet: Workbook): void;
addSlide(slide: Slide): void;
getUniverSheetInstance(id: string): Nullable<Workbook>;
- getUniverDocInstance(id: string): Nullable<DocumentModel>;
+ getUniverDocInstance(id: string): Nullable<DocumentDataModel>;
getUniverSlideInstance(id: string): Nullable<Slide>;
getCurrentUniverSheetInstance(): Workbook;
- getCurrentUniverDocInstance(): DocumentModel;
+ getCurrentUniverDocInstance(): DocumentDataModel;
getCurrentUniverSlideInstance(): Slide;
setCurrentUniverSheetInstance(id: string): void;
setCurrentUniverDocInstance(id: string): void;
setCurrentUniverSlideInstance(id: string): void;
getAllUniverSheetsInstance(): Workbook[];
- getAllUniverDocsInstance(): DocumentModel[];
+ getAllUniverDocsInstance(): DocumentDataModel[];
getAllUniverSlidesInstance(): Slide[];
getDocumentType(unitID: string): DocumentType;
@@ -77,32 +77,32 @@ export interface IUniverInstanceService {
export const IUniverInstanceService = createIdentifier<IUniverInstanceService>('univer.current');
export class UniverInstanceService extends Disposable implements IUniverInstanceService {
private readonly _focused$ = new BehaviorSubject<Nullable<string>>(null);
- private _focused: DocumentModel | Workbook | Slide | null = null;
+ private _focused: DocumentDataModel | Workbook | Slide | null = null;
readonly focused$ = this._focused$.asObservable();
private readonly _currentSheet$ = new BehaviorSubject<Nullable<Workbook>>(null);
readonly currentSheet$ = this._currentSheet$.asObservable();
- private readonly _currentDoc$ = new BehaviorSubject<Nullable<DocumentModel>>(null);
+ private readonly _currentDoc$ = new BehaviorSubject<Nullable<DocumentDataModel>>(null);
readonly currentDoc$ = this._currentDoc$.asObservable();
private readonly _currentSlide$ = new BehaviorSubject<Nullable<Slide>>(null);
readonly currentSlide$ = this._currentSlide$.asObservable();
private readonly _sheetAdded$ = new Subject<Workbook>();
readonly sheetAdded$ = this._sheetAdded$.asObservable();
- private readonly _docAdded$ = new Subject<DocumentModel>();
+ private readonly _docAdded$ = new Subject<DocumentDataModel>();
readonly docAdded$ = this._docAdded$.asObservable();
private readonly _slideAdded$ = new Subject<Slide>();
readonly slideAdded$ = this._slideAdded$.asObservable();
private readonly _sheetDisposed$ = new Subject<Workbook>();
readonly sheetDisposed$ = this._sheetDisposed$.asObservable();
- private readonly _docDisposed$ = new Subject<DocumentModel>();
+ private readonly _docDisposed$ = new Subject<DocumentDataModel>();
readonly docDisposed$ = this._docDisposed$.asObservable();
private readonly _slideDisposed$ = new Subject<Slide>();
readonly slideDisposed$ = this._slideDisposed$.asObservable();
private readonly _sheets: Workbook[] = [];
- private readonly _docs: DocumentModel[] = [];
+ private readonly _docs: DocumentDataModel[] = [];
private readonly _slides: Slide[] = [];
constructor(
@@ -130,7 +130,7 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
this._slideDisposed$.complete();
}
- createDoc(data: Partial<IDocumentData>): DocumentModel {
+ createDoc(data: Partial<IDocumentData>): DocumentDataModel {
return this._handler.createUniverDoc(data);
}
@@ -148,7 +148,7 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
this.setCurrentUniverSheetInstance(sheet.getUnitId());
}
- changeDoc(unitId: string, doc: DocumentModel): void {
+ changeDoc(unitId: string, doc: DocumentDataModel): void {
const oldDoc = this._docs.find((doc) => doc.getUnitId() === unitId);
if (oldDoc != null) {
@@ -159,7 +159,7 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
this.addDoc(doc);
}
- addDoc(doc: DocumentModel): void {
+ addDoc(doc: DocumentDataModel): void {
this._docs.push(doc);
this._docAdded$.next(doc);
this.setCurrentUniverDocInstance(doc.getUnitId());
@@ -175,7 +175,7 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
return this._sheets.find((sheet) => sheet.getUnitId() === id);
}
- getUniverDocInstance(id: string): Nullable<DocumentModel> {
+ getUniverDocInstance(id: string): Nullable<DocumentDataModel> {
return this._docs.find((doc) => doc.getUnitId() === id);
}
@@ -215,11 +215,13 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
return sheet;
}
- getCurrentUniverDocInstance(): DocumentModel {
+ getCurrentUniverDocInstance(): DocumentDataModel {
const doc = this._currentDoc$.getValue();
+
if (!doc) {
throw new Error('No current doc!');
}
+
return doc;
}
@@ -246,14 +248,14 @@ export class UniverInstanceService extends Disposable implements IUniverInstance
if (this._focused instanceof Workbook) {
this._contextService.setContextValue(FOCUSING_SHEET, true);
- } else if (this._focused instanceof DocumentModel) {
+ } else if (this._focused instanceof DocumentDataModel) {
this._contextService.setContextValue(FOCUSING_DOC, true);
} else if (this._focused instanceof Slide) {
this._contextService.setContextValue(FOCUSING_SLIDE, true);
}
}
- getFocusedUniverInstance(): Workbook | DocumentModel | Slide | null {
+ getFocusedUniverInstance(): Workbook | DocumentDataModel | Slide | null {
return this._focused;
}
diff --git a/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts
index fdd6d868ee..f7b40aa5fd 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts
@@ -7,7 +7,7 @@ import {
DEFAULT_EMPTY_DOCUMENT_VALUE,
Direction,
Disposable,
- DocumentModel,
+ DocumentDataModel,
FOCUSING_EDITOR,
FOCUSING_EDITOR_BUT_HIDDEN,
FOCUSING_EDITOR_INPUT_FORMULA,
@@ -139,7 +139,7 @@ export class EndEditController extends Disposable {
const cellData: ICellData = Tools.deepClone(worksheet.getCell(row, column) || {});
- const documentModel = documentLayoutObject.documentModel as DocumentModel;
+ const documentModel = documentLayoutObject.documentModel as DocumentDataModel;
const snapshot = documentModel.getSnapshot();
diff --git a/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
index b72cfc5c56..4144fe1095 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
@@ -24,7 +24,7 @@ import {
Disposable,
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- DocumentModel,
+ DocumentDataModel,
FOCUSING_EDITOR,
FOCUSING_EDITOR_BUT_HIDDEN,
HorizontalAlign,
@@ -141,7 +141,7 @@ export class StartEditController extends Disposable {
documentModel!.updateDocumentDataPageSize((endX - startX) / scaleX);
}
- this._currentUniverService.changeDoc(editorUnitId, documentModel! as DocumentModel);
+ this._currentUniverService.changeDoc(editorUnitId, documentModel! as DocumentDataModel);
const docParam = this._docSkeletonManagerService.updateCurrent({ unitId: editorUnitId });
@@ -183,6 +183,7 @@ export class StartEditController extends Disposable {
scaleY: number = 1
) {
const { startX, startY, endX, endY } = actualRangeWithCoord;
+ const documentDataModel = this._currentUniverService.getCurrentUniverDocInstance();
const { actualWidth, actualHeight } = this._predictingSize(
actualRangeWithCoord,
canvasOffset,
@@ -204,7 +205,7 @@ export class StartEditController extends Disposable {
if (editorHeight < actualHeight) {
editorHeight = actualHeight;
// To restore the page margins for the skeleton.
- documentSkeleton.getModel().updateDocumentDataMargin(paddingData);
+ documentDataModel.updateDocumentDataMargin(paddingData);
} else {
// Set the top margin under vertical alignment.
let offsetTop = paddingData.t || 0;
@@ -219,7 +220,7 @@ export class StartEditController extends Disposable {
offsetTop = offsetTop < (paddingData.t || 0) ? paddingData.t || 0 : offsetTop;
- documentSkeleton.getModel().updateDocumentDataMargin({
+ documentDataModel.updateDocumentDataMargin({
t: offsetTop,
});
}
@@ -247,6 +248,8 @@ export class StartEditController extends Disposable {
const { textRotation, wrapStrategy } = documentLayoutObject;
+ const documentDataModel = this._currentUniverService.getCurrentUniverDocInstance();
+
const { a: angle } = textRotation as ITextRotation;
const clientWidth = document.body.clientWidth;
@@ -259,7 +262,7 @@ export class StartEditController extends Disposable {
actualHeight: actualHeight * scaleY,
};
}
- documentSkeleton.getModel().updateDocumentDataPageSize(clientWidth - startX - canvasOffset.left);
+ documentDataModel.updateDocumentDataPageSize(clientWidth - startX - canvasOffset.left);
documentSkeleton.calculate();
const size = documentSkeleton.getActualSize();
@@ -271,9 +274,9 @@ export class StartEditController extends Disposable {
}
// Scaling is handled by the renderer, so the skeleton only accepts the original width and height, which need to be divided by the magnification factor.
- documentSkeleton.getModel()!.updateDocumentDataPageSize(editorWidth / scaleX);
+ documentDataModel.updateDocumentDataPageSize(editorWidth / scaleX);
- documentSkeleton.getModel()!.updateDocumentRenderConfig({
+ documentDataModel.updateDocumentRenderConfig({
horizontalAlign: HorizontalAlign.UNSPECIFIED,
});
@@ -440,16 +443,16 @@ export class StartEditController extends Disposable {
const { skeleton } = docParam;
- const documentModel = skeleton.getModel() as DocumentModel;
+ const documentDataModel = this._currentUniverService.getCurrentUniverDocInstance();
this._fitTextSize(position, canvasOffset, skeleton, documentLayoutObject, scaleX, scaleY);
// move selection
if (eventType === DeviceInputEventType.Keyboard) {
- const snapshot = Tools.deepClone(documentModel.snapshot) as IDocumentData;
+ const snapshot = Tools.deepClone(documentDataModel.snapshot) as IDocumentData;
this._resetBodyStyle(snapshot.body!);
- documentModel.reset(snapshot);
+ documentDataModel.reset(snapshot);
document.makeDirty();
@@ -467,7 +470,7 @@ export class StartEditController extends Disposable {
]);
} else {
// TODO: @JOCS, Get the position close to the cursor after clicking on the cell.
- const cursor = documentModel.getBodyModel().getLastIndex() - 1 || 0;
+ const cursor = documentDataModel.getBody()!.dataStream.length - 2 || 0;
scene.getViewport(VIEWPORT_KEY.VIEW_MAIN)?.scrollTo({
y: Infinity,