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: doc support JSON OT (#2268)

Ran Luo3cc0d554a5ee
diff --git a/.vscode/settings.json b/.vscode/settings.json
index ef48724005..f983a3ac1c 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -52,6 +52,7 @@
"Jamo",
"jikkai",
"Jocs",
+ "JSONX",
"justifiables",
"Kaiti",
"KANBAN",
diff --git a/examples/src/data/docs/default-document-data-cn.ts b/examples/src/data/docs/default-document-data-cn.ts
index 91fa570ce0..c94436ec88 100644
--- a/examples/src/data/docs/default-document-data-cn.ts
+++ b/examples/src/data/docs/default-document-data-cn.ts
@@ -15,7 +15,7 @@
*/
import type { IDocumentData } from '@univerjs/core';
-import { BooleanNumber, ColumnSeparatorType, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType, SectionType, WrapTextType } from '@univerjs/core';
+import { BooleanNumber, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType, WrapTextType } from '@univerjs/core';
import { ptToPixel } from '@univerjs/engine-render';
export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {
@@ -709,8 +709,8 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {
// paddingEnd: ptToPixel(15),
// },
// ],
- columnSeparatorType: ColumnSeparatorType.NONE,
- sectionType: SectionType.SECTION_TYPE_UNSPECIFIED,
+ // columnSeparatorType: ColumnSeparatorType.NONE,
+ // sectionType: SectionType.SECTION_TYPE_UNSPECIFIED,
// textDirection: textDirectionDocument,
// contentDirection: textDirection!,
},
diff --git a/packages/core/package.json b/packages/core/package.json
index 5caedac0f0..8450f5bc43 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -69,7 +69,8 @@
"dependencies": {
"@univerjs/protocol": "^0.1.32",
"nanoid": "5.0.7",
- "numeral": "^2.0.6"
+ "numeral": "^2.0.6",
+ "ot-json1": "^1.0.2"
},
"devDependencies": {
"@types/numeral": "^2.0.5",
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 42f5f8fd8c..010669af2e 100644
--- a/packages/core/src/docs/data-model/document-data-model.ts
+++ b/packages/core/src/docs/data-model/document-data-model.ts
@@ -14,10 +14,7 @@
* limitations under the License.
*/
-import { MemoryCursor } from '../../common/memory-cursor';
import type { Nullable } from '../../shared';
-import { getDocsUpdateBody } from '../../shared';
-import { UpdateDocsAttributeType } from '../../shared/command-enum';
import { Tools } from '../../shared/tools';
import type {
IDocumentBody,
@@ -27,12 +24,10 @@ import type {
} from '../../types/interfaces/i-document-data';
import type { IPaddingData } from '../../types/interfaces/i-style-data';
import { UnitModel, UniverInstanceType } from '../../common/unit';
-import { updateAttributeByDelete } from './apply-utils/delete-apply';
-import { updateAttributeByInsert } from './apply-utils/insert-apply';
-import { updateAttribute } from './apply-utils/update-apply';
-import { type TextXAction, TextXActionType } from './action-types';
import { getBodySlice } from './text-x/utils';
import { getEmptySnapshot } from './empty-snapshot';
+import type { JSONXActions } from './json-x/json-x';
+import { JSONX } from './json-x/json-x';
export const DEFAULT_DOC = {
id: 'default_doc',
@@ -53,7 +48,7 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
throw new Error('Method not implemented.');
}
- snapshot: IDocumentData;
+ protected snapshot: IDocumentData;
constructor(snapshot: Partial<IDocumentData>) {
super();
@@ -73,13 +68,6 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
return this.snapshot.lists;
}
- /**
- * @deprecated use getBody to instead.
- */
- get body() {
- return this.snapshot.body;
- }
-
get zoomRatio() {
return this.snapshot.settings?.zoomRatio || 1;
}
@@ -267,133 +255,28 @@ export class DocumentDataModel extends DocumentDataModelSimple {
return this as DocumentDataModel;
}
- override getUnitId(): string {
+ override getUnitId() {
return this._unitId;
}
- apply(actions: TextXAction[]) {
- const undoMutations: TextXAction[] = [];
-
- const memoryCursor = new MemoryCursor();
-
- memoryCursor.reset();
-
- actions.forEach((action) => {
- // FIXME: @JOCS Since updateApply modifies the action(used in undo/redo),
- // so make a deep copy here, does updateApply need to
- // be modified to have no side effects in the future?
- action = Tools.deepClone(action);
-
- if (action.t === TextXActionType.RETAIN) {
- const { coverType, body, len, segmentId } = action;
-
- if (body != null) {
- const documentBody = this._updateApply(body, len, memoryCursor.cursor, coverType, segmentId);
-
- undoMutations.push({
- ...action,
- t: TextXActionType.RETAIN,
- coverType: UpdateDocsAttributeType.REPLACE,
- body: documentBody,
- });
- } else {
- undoMutations.push({
- ...action,
- t: TextXActionType.RETAIN,
- });
- }
-
- memoryCursor.moveCursor(len);
- } else if (action.t === TextXActionType.INSERT) {
- const { body, len, segmentId, line } = action;
-
- this._insertApply(body!, len, memoryCursor.cursor, segmentId);
- memoryCursor.moveCursor(len);
- undoMutations.push({
- t: TextXActionType.DELETE,
- len,
- line,
- segmentId,
- });
- } else if (action.t === TextXActionType.DELETE) {
- const { len, segmentId } = action;
- const documentBody = this._deleteApply(len, memoryCursor.cursor, segmentId);
-
- undoMutations.push({
- ...action,
- t: TextXActionType.INSERT,
- body: documentBody,
- });
- } else {
- throw new Error(`Unknown action type for action: ${action}.`);
- }
- });
-
- return undoMutations;
- }
-
- sliceBody(startOffset: number, endOffset: number): Nullable<IDocumentBody> {
- const body = this.getBody();
-
- if (body == null) {
+ apply(actions: JSONXActions) {
+ if (JSONX.isNoop(actions)) {
return;
}
- return getBodySlice(body, startOffset, endOffset);
- }
-
- 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);
+ return JSONX.apply(doc, actions);
}
- private _deleteApply(textLength: number, currentIndex: number, segmentId?: string): IDocumentBody {
- const doc = this.snapshot;
-
- const body = getDocsUpdateBody(doc, segmentId);
+ sliceBody(startOffset: number, endOffset: number): Nullable<IDocumentBody> {
+ const body = this.getBody();
if (body == null) {
- throw new Error('no body has changed');
- }
-
- if (textLength <= 0) {
- return { dataStream: '' };
- }
-
- return updateAttributeByDelete(body, textLength, currentIndex);
- }
-
- private _insertApply(insertBody: IDocumentBody, textLength: number, currentIndex: number, segmentId?: string) {
- const doc = this.snapshot;
-
- const body = getDocsUpdateBody(doc, segmentId);
-
- if (textLength === 0) {
return;
}
- if (body == null) {
- throw new Error('no body has changed');
- }
-
- updateAttributeByInsert(body, insertBody, textLength, currentIndex);
+ return getBodySlice(body, startOffset, endOffset);
}
private _initializeHeaderFooterModel() {
diff --git a/packages/core/src/docs/data-model/json-x/__tests__/json-x.spec.ts b/packages/core/src/docs/data-model/json-x/__tests__/json-x.spec.ts
new file mode 100644
index 0000000000..67deaa5a26
--- /dev/null
+++ b/packages/core/src/docs/data-model/json-x/__tests__/json-x.spec.ts
@@ -0,0 +1,26 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { JSONX } from '../json-x';
+
+describe('Basic use of json-x', () => {
+ describe('Static methods', () => {
+ it('Should return true when the action is null', () => {
+ expect(JSONX.isNoop(null)).toBe(true);
+ });
+ });
+});
diff --git a/packages/core/src/docs/data-model/json-x/json-x.ts b/packages/core/src/docs/data-model/json-x/json-x.ts
new file mode 100644
index 0000000000..c49fbbf685
--- /dev/null
+++ b/packages/core/src/docs/data-model/json-x/json-x.ts
@@ -0,0 +1,122 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { Doc, JSONOp, Path } from 'ot-json1';
+import * as json1 from 'ot-json1';
+import type { IDocumentBody, IDocumentData } from '../../../types/interfaces';
+import type { TPriority } from '../text-x/text-x';
+import { TextX } from '../text-x/text-x';
+import type { TextXAction } from '../text-x/action-types';
+import type { Nullable } from '../../../shared';
+
+export interface ISubType {
+ name: string;
+ id?: string;
+ uri?: string;
+ apply(doc: IDocumentBody, actions: TextXAction[]): IDocumentBody;
+ compose(thisActions: TextXAction[], otherActions: TextXAction[]): TextXAction[];
+ transform(thisActions: TextXAction[], otherActions: TextXAction[], priority: 'left' | 'right'): TextXAction[];
+ invert?: (actions: TextXAction[]) => TextXAction[];
+ isNoop?: (actions: TextXAction[]) => boolean;
+ makeInvertible?: (actions: TextXAction[], doc: IDocumentBody) => TextXAction[];
+
+ // eslint-disable-next-line ts/no-explicit-any
+ [k: string]: any;
+};
+
+export { JSONOp as JSONXActions, Path as JSONXPath, json1 as JSON1 };
+
+export class JSONX {
+ static name = 'json-x';
+
+ static uri = 'https://github.com/dream-num/univer#json-x';
+
+ private static _subTypes: Map<string, ISubType> = new Map();
+
+ static registerSubtype(subType: ISubType) {
+ if (this._subTypes.has(subType.name) && this._subTypes.get(subType.name)?.id !== TextX.id) {
+ return;
+ }
+
+ this._subTypes.set(subType.name, subType);
+ json1.type.registerSubtype(subType);
+ }
+
+ static apply(doc: IDocumentData, actions: JSONOp) {
+ if (json1.type.isNoop(actions)) {
+ return;
+ }
+
+ return json1.type.apply(doc as unknown as Doc, actions);
+ }
+
+ static compose(thisActions: JSONOp, otherActions: JSONOp) {
+ return json1.type.compose(thisActions, otherActions);
+ }
+
+ // Do not use transform in JsonX, pls use transform in JsonXPro.
+ static transform(_thisActions: JSONOp, _otherActions: JSONOp, _priority: TPriority) {
+ throw new Error('transform is not implemented in JsonX');
+ }
+
+ static invertWithDoc(actions: JSONOp, doc: IDocumentData) {
+ // Why not use invert?
+ // Because invertWithDoc = invert(makeInvertible(op, doc));
+ // First we need to make all op invertible, then we can invert it.
+ // invertWithDoc is a helper function to make all op invertible and then invert it.
+ return json1.type.invertWithDoc(actions, doc as unknown as Doc);
+ }
+
+ static isNoop(actions: JSONOp) {
+ return json1.type.isNoop(actions);
+ }
+
+ private static _instance: Nullable<JSONX> = null;
+
+ static getInstance() {
+ if (this._instance == null) {
+ this._instance = new JSONX();
+ }
+
+ return this._instance;
+ }
+
+ // eslint-disable-next-line ts/no-explicit-any
+ removeOp(path: Path, value?: any) {
+ return json1.removeOp(path, value);
+ }
+
+ moveOp(from: Path, to: Path) {
+ return json1.moveOp(from, to);
+ }
+
+ // eslint-disable-next-line ts/no-explicit-any
+ insertOp(path: Path, value: any) {
+ return json1.insertOp(path, value);
+ }
+
+ // eslint-disable-next-line ts/no-explicit-any
+ replaceOp(path: Path, oldVal: any, newVal: any) {
+ return json1.replaceOp(path, oldVal, newVal);
+ }
+
+ editOp(subOp: TextXAction[]) {
+ // Hardcode the path to ['body'] for now. Because rich text is in the body property.
+ return json1.editOp(['body'], TextX.name, subOp);
+ }
+}
+
+JSONX.registerSubtype(TextX);
diff --git a/packages/core/src/docs/data-model/replacement.ts b/packages/core/src/docs/data-model/replacement.ts
index 7f372bac24..1fa69c872b 100644
--- a/packages/core/src/docs/data-model/replacement.ts
+++ b/packages/core/src/docs/data-model/replacement.ts
@@ -16,6 +16,7 @@
import type { IDocumentBody, IDocumentData } from '../../types/interfaces/i-document-data';
import { DocumentDataModel } from './document-data-model';
+import { JSONX } from './json-x/json-x';
import { TextX } from './text-x/text-x';
export function replaceInDocumentBody(body: IDocumentBody, query: string, target: string): IDocumentBody {
@@ -34,8 +35,10 @@ export function replaceInDocumentBody(body: IDocumentBody, query: string, target
const queryLen = query.length;
let index;
+ // eslint-disable-next-line no-cond-assign
while ((index = documentDataModel.getBody()!.dataStream.indexOf(query)) >= 0) {
const textX = new TextX();
+ const jsonX = JSONX.getInstance();
if (index > 0) {
textX.retain(index);
@@ -62,7 +65,7 @@ export function replaceInDocumentBody(body: IDocumentBody, query: string, target
const actions = textX.serialize();
- documentDataModel.apply(actions);
+ documentDataModel.apply(jsonX.editOp(actions));
}
const newBody = documentDataModel.getBody()!;
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/action-iterator.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/action-iterator.spec.ts
index 19798aa60c..7a64710ad9 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/action-iterator.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/action-iterator.spec.ts
@@ -16,7 +16,7 @@
import { describe, expect, it } from 'vitest';
import { ActionIterator } from '../action-iterator';
-import { TextXActionType } from '../../action-types';
+import { TextXActionType } from '../action-types';
import { BooleanNumber } from '../../../../types/enum/text-style';
describe('Test action iterator', () => {
diff --git a/packages/core/src/docs/data-model/__tests__/apply-utils.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/apply-utils.spec.ts
similarity index 98%
rename from packages/core/src/docs/data-model/__tests__/apply-utils.spec.ts
rename to packages/core/src/docs/data-model/text-x/__tests__/apply-utils.spec.ts
index c22b2b3502..ac46687c2f 100644
--- a/packages/core/src/docs/data-model/__tests__/apply-utils.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/apply-utils.spec.ts
@@ -17,9 +17,9 @@
import type { Nullable } from 'vitest';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { UpdateDocsAttributeType } from '../../../shared';
-import { BooleanNumber } from '../../../types/enum';
-import type { IDocumentBody, ITextRun } from '../../../types/interfaces';
+import { UpdateDocsAttributeType } from '../../../../shared';
+import { BooleanNumber } from '../../../../types/enum';
+import type { IDocumentBody, ITextRun } from '../../../../types/interfaces';
import { deleteParagraphs, deleteTextRuns, insertTextRuns } from '../apply-utils/common';
import { coverTextRuns } from '../apply-utils/update-apply';
diff --git a/packages/core/src/docs/data-model/__tests__/common.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/common.spec.ts
similarity index 93%
rename from packages/core/src/docs/data-model/__tests__/common.spec.ts
rename to packages/core/src/docs/data-model/text-x/__tests__/common.spec.ts
index f9f4810431..b92a42c723 100644
--- a/packages/core/src/docs/data-model/__tests__/common.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/common.spec.ts
@@ -17,8 +17,8 @@
import { describe, expect, it } from 'vitest';
import { normalizeTextRuns } from '../apply-utils/common';
-import { BooleanNumber } from '../../../types/enum/text-style';
-import type { ITextRun } from '../../../types/interfaces/i-document-data';
+import { BooleanNumber } from '../../../../types/enum/text-style';
+import type { ITextRun } from '../../../../types/interfaces/i-document-data';
describe('common utils test cases', () => {
describe('normalizeTextRuns', () => {
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/compose.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/compose.spec.ts
index 0951953e96..9e77a2efb8 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/compose.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/compose.spec.ts
@@ -15,8 +15,8 @@
*/
import { describe, expect, it } from 'vitest';
-import type { TextXAction } from '../../action-types';
-import { TextXActionType } from '../../action-types';
+import type { TextXAction } from '../action-types';
+import { TextXActionType } from '../action-types';
import { BooleanNumber } from '../../../../types/enum/text-style';
import { TextX } from '../text-x';
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/invert.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/invert.spec.ts
new file mode 100644
index 0000000000..55e67a01d7
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/__tests__/invert.spec.ts
@@ -0,0 +1,252 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect } from 'vitest';
+import type { IDocumentBody } from '../../../../types/interfaces';
+import { BooleanNumber } from '../../../../types/enum';
+import { TextX } from '../text-x';
+import type { TextXAction } from '../action-types';
+import { TextXActionType } from '../action-types';
+import { UpdateDocsAttributeType } from '../../../../shared/command-enum';
+
+describe('test TextX static methods invert and makeInvertible', () => {
+ describe('test TextX static method invert', () => {
+ const actions: TextXAction[] = [{
+ t: TextXActionType.RETAIN,
+ len: 5,
+ segmentId: '',
+ }, {
+ t: TextXActionType.INSERT,
+ len: 5,
+ line: 0,
+ segmentId: '',
+ body: {
+ dataStream: 'hello',
+ },
+ }, {
+ t: TextXActionType.DELETE,
+ len: 5,
+ line: 0,
+ segmentId: '',
+ body: {
+ dataStream: 'world',
+ textRuns: [
+ {
+ st: 0,
+ ed: 5,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ },
+ },
+ ],
+ },
+ }, {
+ t: TextXActionType.RETAIN,
+ len: 2,
+ segmentId: '',
+ body: {
+ dataStream: '',
+ textRuns: [
+ {
+ st: 0,
+ ed: 2,
+ ts: {
+ it: BooleanNumber.TRUE,
+ },
+ },
+ ],
+ },
+ oldBody: {
+ dataStream: '',
+ textRuns: [
+ {
+ st: 0,
+ ed: 2,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ },
+ },
+ ],
+ },
+ }];
+
+ const invertedActions = TextX.invert(actions);
+ const exceptActions = [{
+ t: TextXActionType.RETAIN,
+ len: 5,
+ segmentId: '',
+ }, {
+ t: TextXActionType.DELETE,
+ len: 5,
+ line: 0,
+ segmentId: '',
+ body: {
+ dataStream: 'hello',
+ },
+ }, {
+ t: TextXActionType.INSERT,
+ len: 5,
+ line: 0,
+ segmentId: '',
+ body: {
+ dataStream: 'world',
+ textRuns: [
+ {
+ st: 0,
+ ed: 5,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ },
+ },
+ ],
+ },
+ }, {
+ t: TextXActionType.RETAIN,
+ len: 2,
+ segmentId: '',
+ coverType: UpdateDocsAttributeType.REPLACE,
+ oldBody: {
+ dataStream: '',
+ textRuns: [
+ {
+ st: 0,
+ ed: 2,
+ ts: {
+ it: BooleanNumber.TRUE,
+ },
+ },
+ ],
+ },
+ body: {
+ dataStream: '',
+ textRuns: [
+ {
+ st: 0,
+ ed: 2,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ },
+ },
+ ],
+ },
+ }];
+
+ expect(invertedActions).toEqual(exceptActions);
+ });
+
+ describe('test TextX static method makeInvertible when `retain` action occur', () => {
+ const docBody: IDocumentBody = {
+ dataStream: 'hello\r\n',
+ textRuns: [
+ {
+ st: 0,
+ ed: 5,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ },
+ },
+ ],
+ };
+
+ const textX = new TextX();
+
+ textX.retain(3, '', {
+ dataStream: '',
+ textRuns: [{
+ st: 0,
+ ed: 3,
+ ts: {
+ it: BooleanNumber.TRUE,
+ },
+ }],
+ }, UpdateDocsAttributeType.COVER);
+
+ TextX.makeInvertible(textX.serialize(), docBody);
+
+ const expectedActions = [{
+ t: TextXActionType.RETAIN,
+ len: 3,
+ body: {
+ dataStream: '',
+ textRuns: [{
+ st: 0,
+ ed: 3,
+ ts: {
+ it: BooleanNumber.TRUE,
+ },
+ }],
+ },
+ oldBody: {
+ dataStream: '',
+ textRuns: [{
+ st: 0,
+ ed: 3,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ },
+ }],
+ },
+ coverType: UpdateDocsAttributeType.COVER,
+ segmentId: '',
+ }];
+
+ expect(textX.serialize()).toEqual(expectedActions);
+ });
+
+ describe('test TextX static method makeInvertible when `delete` action occur', () => {
+ const docBody: IDocumentBody = {
+ dataStream: 'hello\r\n',
+ textRuns: [
+ {
+ st: 0,
+ ed: 5,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ },
+ },
+ ],
+ };
+
+ const textX = new TextX();
+ textX.retain(3);
+ textX.delete(2);
+
+ TextX.makeInvertible(textX.serialize(), docBody);
+
+ const expectedActions: TextXAction[] = [{
+ t: TextXActionType.RETAIN,
+ len: 3,
+ segmentId: '',
+ }, {
+ t: TextXActionType.DELETE,
+ len: 2,
+ segmentId: '',
+ line: 0,
+ body: {
+ dataStream: 'lo',
+ textRuns: [{
+ st: 0,
+ ed: 2,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ },
+ }],
+ },
+ }];
+
+ expect(textX.serialize()).toEqual(expectedActions);
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts
index cff1894a44..49df1e926a 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/text-x.spec.ts
@@ -19,7 +19,7 @@ import { TextX } from '../text-x';
import type { IDocumentBody } from '../../../../types/interfaces/i-document-data';
import { BooleanNumber } from '../../../../types/enum/text-style';
import { UpdateDocsAttributeType } from '../../../../shared/command-enum';
-import { TextXActionType } from '../../action-types';
+import { TextXActionType } from '../action-types';
describe('test TextX methods and branches', () => {
describe('test TextX methods', () => {
@@ -239,4 +239,17 @@ describe('test TextX methods and branches', () => {
expect(actions[2].t).toBe(TextXActionType.DELETE);
});
});
+
+ describe('test TextX static methods', () => {
+ it('test TextX isNoop method', () => {
+ const textX = new TextX();
+
+ expect(TextX.isNoop(textX.serialize())).toBe(true);
+
+ textX.retain(4, '');
+ textX.delete(5, '');
+
+ expect(TextX.isNoop(textX.serialize())).toBe(false);
+ });
+ });
});
diff --git a/packages/core/src/docs/data-model/text-x/__tests__/utils.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/utils.spec.ts
index 97f1eb4aba..eaff013823 100644
--- a/packages/core/src/docs/data-model/text-x/__tests__/utils.spec.ts
+++ b/packages/core/src/docs/data-model/text-x/__tests__/utils.spec.ts
@@ -18,8 +18,8 @@ import { describe, expect, it } from 'vitest';
import type { IDocumentBody } from '../../../../types/interfaces/i-document-data';
import { BooleanNumber } from '../../../../types/enum/text-style';
import { composeBody, getBodySlice, isUselessRetainAction } from '../utils';
-import type { IRetainAction } from '../../action-types';
-import { TextXActionType } from '../../action-types';
+import type { IRetainAction } from '../action-types';
+import { TextXActionType } from '../action-types';
describe('test text-x utils', () => {
it('test getBodySlice fn', () => {
diff --git a/packages/core/src/docs/data-model/text-x/action-iterator.ts b/packages/core/src/docs/data-model/text-x/action-iterator.ts
index 03b70eb0ef..935d4a423c 100644
--- a/packages/core/src/docs/data-model/text-x/action-iterator.ts
+++ b/packages/core/src/docs/data-model/text-x/action-iterator.ts
@@ -15,8 +15,8 @@
*/
import { Tools } from '../../../shared/tools';
-import type { TextXAction } from '../action-types';
-import { TextXActionType } from '../action-types';
+import type { TextXAction } from './action-types';
+import { TextXActionType } from './action-types';
import { getBodySlice } from './utils';
export class ActionIterator {
diff --git a/packages/core/src/docs/data-model/action-types.ts b/packages/core/src/docs/data-model/text-x/action-types.ts
similarity index 84%
rename from packages/core/src/docs/data-model/action-types.ts
rename to packages/core/src/docs/data-model/text-x/action-types.ts
index 55a7cd4d56..b0b0852d6e 100644
--- a/packages/core/src/docs/data-model/action-types.ts
+++ b/packages/core/src/docs/data-model/text-x/action-types.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { UpdateDocsAttributeType } from '../../shared/command-enum';
-import type { IDocumentBody } from '../../types/interfaces/i-document-data';
+import type { UpdateDocsAttributeType } from '../../../shared/command-enum';
+import type { IDocumentBody } from '../../../types/interfaces/i-document-data';
export enum TextXActionType {
RETAIN = 'r',
@@ -30,6 +30,7 @@ export interface IRetainAction {
t: TextXActionType.RETAIN;
len: number;
body?: IDocumentBody;
+ oldBody?: IDocumentBody;
coverType?: UpdateDocsAttributeType;
segmentId?: string;
}
@@ -52,6 +53,7 @@ export interface IDeleteAction {
t: TextXActionType.DELETE;
len: number;
line: number;
+ body?: IDocumentBody; // Add a body property to make this action invertible.
segmentId?: string;
}
diff --git a/packages/core/src/docs/data-model/apply-utils/common.ts b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
similarity index 98%
rename from packages/core/src/docs/data-model/apply-utils/common.ts
rename to packages/core/src/docs/data-model/text-x/apply-utils/common.ts
index 085bb89f54..b9a3778dfa 100644
--- a/packages/core/src/docs/data-model/apply-utils/common.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import type { Nullable } from '../../../shared';
-import { horizontalLineSegmentsSubtraction, sortRulesFactory, Tools } from '../../../shared';
-import { isSameStyleTextRun } from '../../../shared/compare';
+import type { Nullable } from '../../../../shared';
+import { horizontalLineSegmentsSubtraction, sortRulesFactory, Tools } from '../../../../shared';
+import { isSameStyleTextRun } from '../../../../shared/compare';
import type {
ICustomBlock,
ICustomRange,
@@ -25,8 +25,8 @@ import type {
ISectionBreak,
ITable,
ITextRun,
-} from '../../../types/interfaces';
-import { DataStreamTreeTokenType } from '../types';
+} from '../../../../types/interfaces';
+import { DataStreamTreeTokenType } from '../../types';
export function normalizeTextRuns(textRuns: ITextRun[]) {
const results: ITextRun[] = [];
@@ -77,6 +77,7 @@ export function normalizeTextRuns(textRuns: ITextRun[]) {
* @param textLength The length of the inserted content text.
* @param currentIndex Determining the index where the content will be inserted into the current content.
*/
+// eslint-disable-next-line max-lines-per-function
export function insertTextRuns(
body: IDocumentBody,
insertBody: IDocumentBody,
diff --git a/packages/core/src/docs/data-model/apply-utils/delete-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts
similarity index 95%
rename from packages/core/src/docs/data-model/apply-utils/delete-apply.ts
rename to packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts
index a34e681ce6..3589a8f8cc 100644
--- a/packages/core/src/docs/data-model/apply-utils/delete-apply.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { deleteContent } from '../../../shared';
-import type { IDocumentBody } from '../../../types/interfaces';
+import { deleteContent } from '../../../../shared';
+import type { IDocumentBody } from '../../../../types/interfaces';
import {
deleteCustomBlocks,
deleteCustomRanges,
diff --git a/packages/core/src/docs/data-model/apply-utils/insert-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts
similarity index 91%
rename from packages/core/src/docs/data-model/apply-utils/insert-apply.ts
rename to packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts
index 6fa1ac62fc..83cf669ed0 100644
--- a/packages/core/src/docs/data-model/apply-utils/insert-apply.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { insertTextToContent } from '../../../shared';
-import type { IDocumentBody } from '../../../types/interfaces';
+import { insertTextToContent } from '../../../../shared';
+import type { IDocumentBody } from '../../../../types/interfaces';
import {
insertCustomBlocks,
insertCustomRanges,
diff --git a/packages/core/src/docs/data-model/apply-utils/update-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts
similarity index 98%
rename from packages/core/src/docs/data-model/apply-utils/update-apply.ts
rename to packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts
index 2b3b35f98c..9d18450cff 100644
--- a/packages/core/src/docs/data-model/apply-utils/update-apply.ts
+++ b/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { Nullable } from '../../../shared';
-import { Tools, UpdateDocsAttributeType } from '../../../shared';
+import type { Nullable } from '../../../../shared';
+import { Tools, UpdateDocsAttributeType } from '../../../../shared';
import type {
ICustomBlock,
ICustomRange,
@@ -24,8 +24,8 @@ import type {
ISectionBreak,
ITable,
ITextRun,
-} from '../../../types/interfaces';
-import { PresetListType } from '../preset-list-type';
+} from '../../../../types/interfaces';
+import { PresetListType } from '../../preset-list-type';
import {
deleteCustomBlocks,
deleteCustomRanges,
diff --git a/packages/core/src/docs/data-model/text-x/apply.ts b/packages/core/src/docs/data-model/text-x/apply.ts
new file mode 100644
index 0000000000..ace318e061
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/apply.ts
@@ -0,0 +1,98 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { MemoryCursor } from '../../../common/memory-cursor';
+import type { Nullable } from '../../../shared';
+import { Tools } from '../../../shared';
+import { UpdateDocsAttributeType } from '../../../shared/command-enum';
+import type { IDocumentBody } from '../../../types/interfaces';
+import { type TextXAction, TextXActionType } from './action-types';
+import { updateAttributeByDelete } from './apply-utils/delete-apply';
+import { updateAttributeByInsert } from './apply-utils/insert-apply';
+import { updateAttribute } from './apply-utils/update-apply';
+
+function updateApply(
+ doc: IDocumentBody,
+ updateBody: Nullable<IDocumentBody>,
+ textLength: number,
+ currentIndex: number,
+ coverType = UpdateDocsAttributeType.COVER
+): IDocumentBody {
+ if (updateBody == null) {
+ throw new Error('updateBody is none');
+ }
+
+ return updateAttribute(doc, updateBody, textLength, currentIndex, coverType);
+}
+
+function deleteApply(
+ doc: IDocumentBody,
+ textLength: number,
+ currentIndex: number
+): IDocumentBody {
+ if (textLength <= 0) {
+ return { dataStream: '' };
+ }
+
+ return updateAttributeByDelete(doc, textLength, currentIndex);
+}
+
+function insertApply(
+ doc: IDocumentBody,
+ insertBody: IDocumentBody,
+ textLength: number,
+ currentIndex: number
+) {
+ if (textLength === 0) {
+ return;
+ }
+
+ updateAttributeByInsert(doc, insertBody, textLength, currentIndex);
+}
+
+export function textXApply(doc: IDocumentBody, actions: TextXAction[]): IDocumentBody {
+ const memoryCursor = new MemoryCursor();
+
+ memoryCursor.reset();
+
+ actions.forEach((action) => {
+ // FIXME: @JOCS Since updateApply modifies the action(used in undo/redo),
+ // so make a deep copy here, does updateApply need to
+ // be modified to have no side effects in the future?
+ action = Tools.deepClone(action);
+
+ if (action.t === TextXActionType.RETAIN) {
+ const { coverType, body, len } = action;
+ if (body != null) {
+ updateApply(doc, body, len, memoryCursor.cursor, coverType);
+ }
+
+ memoryCursor.moveCursor(len);
+ } else if (action.t === TextXActionType.INSERT) {
+ const { body, len } = action;
+
+ insertApply(doc, body!, len, memoryCursor.cursor);
+ memoryCursor.moveCursor(len);
+ } else if (action.t === TextXActionType.DELETE) {
+ const { len } = action;
+ deleteApply(doc, len, memoryCursor.cursor);
+ } else {
+ throw new Error(`Unknown action type for action: ${action}.`);
+ }
+ });
+
+ return doc;
+}
diff --git a/packages/core/src/docs/data-model/text-x/text-x.ts b/packages/core/src/docs/data-model/text-x/text-x.ts
index 614b7893dc..2f7519de0d 100644
--- a/packages/core/src/docs/data-model/text-x/text-x.ts
+++ b/packages/core/src/docs/data-model/text-x/text-x.ts
@@ -15,17 +15,30 @@
*/
import { Tools } from '../../../shared/tools';
-import type { UpdateDocsAttributeType } from '../../../shared/command-enum';
+import { UpdateDocsAttributeType } from '../../../shared/command-enum';
import type { IDocumentBody } from '../../../types/interfaces/i-document-data';
-import { type IDeleteAction, type IInsertAction, type IRetainAction, type TextXAction, TextXActionType } from '../action-types';
+import { type IDeleteAction, type IInsertAction, type IRetainAction, type TextXAction, TextXActionType } from './action-types';
import { ActionIterator } from './action-iterator';
-import { composeBody, isUselessRetainAction } from './utils';
+import { composeBody, getBodySlice, isUselessRetainAction } from './utils';
+import { textXApply } from './apply';
function onlyHasDataStream(body: IDocumentBody) {
return Object.keys(body).length === 1;
}
+export type TPriority = 'left' | 'right';
+
export class TextX {
+ static name = 'text-x';
+
+ static id = 'text-x';
+
+ static uri = 'https://github.com/dream-num/univer#text-x';
+
+ static apply(doc: IDocumentBody, actions: TextXAction[]): IDocumentBody {
+ return textXApply(doc, actions);
+ }
+
static compose(thisActions: TextXAction[], otherActions: TextXAction[]): TextXAction[] {
const thisIter = new ActionIterator(thisActions);
const otherIter = new ActionIterator(otherActions);
@@ -79,6 +92,93 @@ export class TextX {
return textX.serialize();
}
+ // `transform` is implemented in univer-pro in class TextXPro. do not use this method in TextX.
+ static transform(_thisActions: TextXAction[], _otherActions: TextXAction[], _priority: TPriority): TextXAction[] {
+ throw new Error('transform is not implemented in TextX');
+ }
+
+ static isNoop(actions: TextXAction[]) {
+ return actions.length === 0;
+ }
+
+ static invert(actions: TextXAction[]): TextXAction[] {
+ const invertedActions: TextXAction[] = [];
+
+ for (const action of actions) {
+ if (action.t === TextXActionType.INSERT) {
+ invertedActions.push({
+ t: TextXActionType.DELETE,
+ len: action.len,
+ line: 0, // hardcode
+ body: action.body,
+ segmentId: action.segmentId,
+ });
+ } else if (action.t === TextXActionType.DELETE) {
+ if (action.body == null) {
+ throw new Error('Can not invert DELETE action without body property, makeInvertible must be called first.');
+ }
+
+ invertedActions.push({
+ t: TextXActionType.INSERT,
+ body: action.body,
+ len: action.len,
+ line: 0, // hardcode
+ segmentId: action.segmentId,
+ });
+ } else {
+ if (action.body != null) {
+ if (action.oldBody == null) {
+ throw new Error('Can not invert RETAIN action without oldBody property, makeInvertible must be called first.');
+ }
+
+ invertedActions.push({
+ t: TextXActionType.RETAIN,
+ body: action.oldBody,
+ oldBody: action.body,
+ len: action.len,
+ coverType: UpdateDocsAttributeType.REPLACE,
+ segmentId: action.segmentId,
+ });
+ } else {
+ invertedActions.push(action);
+ }
+ }
+ }
+
+ return invertedActions;
+ }
+
+ static makeInvertible(actions: TextXAction[], doc: IDocumentBody): TextXAction[] {
+ const invertibleActions: TextXAction[] = [];
+
+ let index = 0;
+
+ for (const action of actions) {
+ if (action.t === TextXActionType.DELETE && action.body == null) {
+ const body = getBodySlice(doc, index, index + action.len, false);
+
+ action.body = body;
+ }
+
+ if (action.t === TextXActionType.RETAIN && action.body != null) {
+ const { textRuns } = getBodySlice(doc, index, index + action.len, true);
+
+ action.oldBody = {
+ dataStream: '',
+ textRuns,
+ };
+ }
+
+ invertibleActions.push(action);
+
+ if (action.t !== TextXActionType.INSERT) {
+ index += action.len;
+ }
+ }
+
+ return invertibleActions;
+ }
+
private _actions: TextXAction[] = [];
insert(len: number, body: IDocumentBody, segmentId = ''): this {
@@ -132,6 +232,7 @@ export class TextX {
return this._actions;
}
+ // eslint-disable-next-line complexity
push(...args: TextXAction[]): this {
if (args.length > 1) {
for (const ac of args) {
@@ -197,7 +298,7 @@ export class TextX {
return this;
}
- trimEndUselessRetainAction(): this {
+ protected trimEndUselessRetainAction(): this {
let lastAction = this._actions[this._actions.length - 1];
while (lastAction && lastAction.t === TextXActionType.RETAIN && isUselessRetainAction(lastAction)) {
diff --git a/packages/core/src/docs/data-model/text-x/utils.ts b/packages/core/src/docs/data-model/text-x/utils.ts
index da2eb7ba1f..365e481680 100644
--- a/packages/core/src/docs/data-model/text-x/utils.ts
+++ b/packages/core/src/docs/data-model/text-x/utils.ts
@@ -17,10 +17,16 @@
import { UpdateDocsAttributeType } from '../../../shared/command-enum';
import { Tools } from '../../../shared/tools';
import type { IDocumentBody, IParagraph, ITextRun } from '../../../types/interfaces/i-document-data';
-import type { IRetainAction } from '../action-types';
-import { coverTextRuns } from '../apply-utils/update-apply';
-
-export function getBodySlice(body: IDocumentBody, startOffset: number, endOffset: number): IDocumentBody {
+import type { IRetainAction } from './action-types';
+import { coverTextRuns } from './apply-utils/update-apply';
+
+// TODO: Support other properties like custom ranges, tables, etc.
+export function getBodySlice(
+ body: IDocumentBody,
+ startOffset: number,
+ endOffset: number,
+ returnEmptyTextRun = false
+): IDocumentBody {
const { dataStream, textRuns = [], paragraphs = [] } = body;
const docBody: IDocumentBody = {
@@ -61,6 +67,14 @@ export function getBodySlice(body: IDocumentBody, startOffset: number, endOffset
ed: ed - startOffset,
};
});
+ } else if (returnEmptyTextRun) {
+ // In the case of no style before, add the style, removeTextRuns will be empty,
+ // in this case, you need to add an empty textRun for undo.
+ docBody.textRuns = [{
+ st: 0,
+ ed: endOffset - startOffset,
+ ts: {},
+ }];
}
const newParagraphs: IParagraph[] = [];
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 8dbf74e7df..063d7210bd 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -43,11 +43,14 @@ export {
type IDeleteAction,
type IInsertAction,
type IRetainAction,
-} from './docs/data-model/action-types';
+} from './docs/data-model/text-x/action-types';
export { DataValidationRenderMode } from './types/enum/data-validation-render-mode';
export { ActionIterator } from './docs/data-model/text-x/action-iterator';
export { getBodySlice, composeBody } from './docs/data-model/text-x/utils';
export { TextX } from './docs/data-model/text-x/text-x';
+export type { TPriority } from './docs/data-model/text-x/text-x';
+export { JSONX, JSON1 } from './docs/data-model/json-x/json-x';
+export type { JSONXActions, JSONXPath } from './docs/data-model/json-x/json-x';
export { replaceInDocumentBody } from './docs/data-model/replacement';
export * from './observer';
export { Plugin } from './services/plugin/plugin';
@@ -120,7 +123,7 @@ export { UserManagerService } from './services/user-manager/user-manager.service
export type { IComposeInterceptors, IInterceptor, InterceptorHandler } from './common/interceptor';
export { composeInterceptors, createInterceptorKey, InterceptorManager } from './common/interceptor';
-export { normalizeTextRuns } from './docs/data-model/apply-utils/common';
+export { normalizeTextRuns } from './docs/data-model/text-x/apply-utils/common';
export type { PluginCtor } from './services/plugin/plugin';
export { type DependencyOverride, mergeOverrideWithDependencies } from './services/plugin/plugin-override';
export * from './types/const';
diff --git a/packages/core/src/services/undoredo/undoredo.service.ts b/packages/core/src/services/undoredo/undoredo.service.ts
index 81236f4cbd..bc36829057 100644
--- a/packages/core/src/services/undoredo/undoredo.service.ts
+++ b/packages/core/src/services/undoredo/undoredo.service.ts
@@ -111,6 +111,7 @@ export const UndoCommand = new (class extends MultiImplementationCommand impleme
async handler(accessor: IAccessor) {
const undoRedoService = accessor.get(IUndoRedoService);
const element = undoRedoService.pitchTopUndoElement();
+
if (!element) {
return false;
}
diff --git a/packages/core/src/shared/common.ts b/packages/core/src/shared/common.ts
index 18068f4b52..53312cfd62 100644
--- a/packages/core/src/shared/common.ts
+++ b/packages/core/src/shared/common.ts
@@ -213,6 +213,7 @@ export function handleJsonToDom(p: IDocumentData): string {
* @returns
*/
+// eslint-disable-next-line max-lines-per-function
export function handleStyleToString(style: IStyleData, isCell: boolean = false) {
let str = '';
const styleMap = new Map([
diff --git a/packages/docs/src/commands/commands/__tests__/clipboard.command.spec.ts b/packages/docs/src/commands/commands/__tests__/clipboard.command.spec.ts
index af862501b9..75e3535799 100644
--- a/packages/docs/src/commands/commands/__tests__/clipboard.command.spec.ts
+++ b/packages/docs/src/commands/commands/__tests__/clipboard.command.spec.ts
@@ -39,60 +39,64 @@ vi.mock('@univerjs/engine-render', async () => {
};
});
-const TEST_DOCUMENT_DATA_EN: IDocumentData = {
- id: 'test-doc',
- body: {
- dataStream: 'What’s New in the 2022\r Gartner Hype Cycle for Emerging Technologies\r\n',
- textRuns: [
- {
- st: 0,
- ed: 22,
- ts: {
- bl: BooleanNumber.FALSE,
- fs: 24,
- cl: {
- rgb: 'rgb(0, 40, 86)',
+function getDocumentData() {
+ const TEST_DOCUMENT_DATA_EN: IDocumentData = {
+ id: 'test-doc',
+ body: {
+ dataStream: 'What’s New in the 2022\r Gartner Hype Cycle for Emerging Technologies\r\n',
+ textRuns: [
+ {
+ st: 0,
+ ed: 22,
+ ts: {
+ bl: BooleanNumber.FALSE,
+ fs: 24,
+ cl: {
+ rgb: 'rgb(0, 40, 86)',
+ },
},
},
- },
- {
- st: 23,
- ed: 68,
- ts: {
- bl: BooleanNumber.TRUE,
- fs: 24,
- cl: {
- rgb: 'rgb(0, 40, 86)',
+ {
+ st: 23,
+ ed: 68,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ fs: 24,
+ cl: {
+ rgb: 'rgb(0, 40, 86)',
+ },
},
},
- },
- ],
- paragraphs: [
- {
- startIndex: 22,
- },
- {
- startIndex: 68,
- paragraphStyle: {
- spaceAbove: 20,
- indentFirstLine: 20,
+ ],
+ paragraphs: [
+ {
+ startIndex: 22,
+ },
+ {
+ startIndex: 68,
+ paragraphStyle: {
+ spaceAbove: 20,
+ indentFirstLine: 20,
+ },
},
+ ],
+ sectionBreaks: [],
+ customBlocks: [],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
},
- ],
- sectionBreaks: [],
- customBlocks: [],
- },
- documentStyle: {
- pageSize: {
- width: 594.3,
- height: 840.51,
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
},
- marginTop: 72,
- marginBottom: 72,
- marginRight: 90,
- marginLeft: 90,
- },
-};
+ };
+
+ return TEST_DOCUMENT_DATA_EN;
+}
describe('test cases in clipboard', () => {
let univer: Univer;
@@ -103,11 +107,11 @@ describe('test cases in clipboard', () => {
const univerInstanceService = get(IUniverInstanceService);
const docsModel = univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC);
- if (docsModel?.body?.textRuns == null) {
+ if (docsModel?.getBody()?.textRuns == null) {
return;
}
- for (const textRun of docsModel.body?.textRuns) {
+ for (const textRun of docsModel.getBody()?.textRuns ?? []) {
const { st, ed, ts = {} } = textRun;
if (st <= pos && ed >= pos) {
@@ -120,11 +124,11 @@ describe('test cases in clipboard', () => {
const univerInstanceService = get(IUniverInstanceService);
const docsModel = univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC);
- return docsModel?.body?.dataStream.slice(start, end);
+ return docsModel?.getBody()?.dataStream.slice(start, end);
}
beforeEach(() => {
- const testBed = createCommandTestBed(TEST_DOCUMENT_DATA_EN);
+ const testBed = createCommandTestBed(getDocumentData());
univer = testBed.univer;
get = testBed.get;
diff --git a/packages/docs/src/commands/commands/__tests__/inline-format.command.spec.ts b/packages/docs/src/commands/commands/__tests__/inline-format.command.spec.ts
index 04226eedd8..0927a59547 100644
--- a/packages/docs/src/commands/commands/__tests__/inline-format.command.spec.ts
+++ b/packages/docs/src/commands/commands/__tests__/inline-format.command.spec.ts
@@ -56,11 +56,11 @@ describe('Test inline format commands', () => {
const univerInstanceService = get(IUniverInstanceService);
const docsModel = univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC);
- if (docsModel?.body?.textRuns == null) {
+ if (docsModel?.getBody()?.textRuns == null) {
return;
}
- for (const textRun of docsModel.body?.textRuns) {
+ for (const textRun of docsModel.getBody()?.textRuns ?? []) {
const { st, ed, ts = {} } = textRun;
if (st <= pos && ed >= pos) {
diff --git a/packages/docs/src/commands/commands/__tests__/replace-content.command.spec.ts b/packages/docs/src/commands/commands/__tests__/replace-content.command.spec.ts
index 44ae71e649..e6762be8f5 100644
--- a/packages/docs/src/commands/commands/__tests__/replace-content.command.spec.ts
+++ b/packages/docs/src/commands/commands/__tests__/replace-content.command.spec.ts
@@ -38,22 +38,27 @@ vi.mock('@univerjs/engine-render', async () => {
};
});
-const TEST_DOCUMENT_DATA_EN: IDocumentData = {
- id: 'test-doc',
- body: {
- dataStream: '=SUM(A2:B4)\r\n',
- },
- documentStyle: {
- pageSize: {
- width: 594.3,
- height: 840.51,
+function getDocumentData() {
+ const TEST_DOCUMENT_DATA_EN: IDocumentData = {
+ id: 'test-doc',
+ body: {
+ dataStream: '=SUM(A2:B4)\r\n',
+ textRuns: [],
},
- marginTop: 72,
- marginBottom: 72,
- marginRight: 90,
- marginLeft: 90,
- },
-};
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+
+ return TEST_DOCUMENT_DATA_EN;
+}
describe('replace or cover content of document', () => {
let univer: Univer;
@@ -63,16 +68,13 @@ describe('replace or cover content of document', () => {
function getDataStream() {
const univerInstanceService = get(IUniverInstanceService);
const docsModel = univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC);
+ const dataStream = docsModel?.getBody()?.dataStream;
- if (docsModel?.body?.dataStream == null) {
- return '';
- }
-
- return docsModel?.body?.dataStream;
+ return typeof dataStream === 'string' ? dataStream : '';
}
beforeEach(() => {
- const testBed = createCommandTestBed(TEST_DOCUMENT_DATA_EN);
+ const testBed = createCommandTestBed(getDocumentData());
univer = testBed.univer;
get = testBed.get;
@@ -114,7 +116,6 @@ describe('replace or cover content of document', () => {
await commandService.executeCommand(ReplaceContentCommand.id, commandParams);
expect(getDataStream().length).toBe(17);
-
await commandService.executeCommand(UndoCommand.id);
expect(getDataStream().length).toBe(13);
@@ -130,7 +131,7 @@ describe('replace or cover content of document', () => {
describe('cover content of document and clear undo and redo stack', () => {
it('Should pass the test case when cover content', async () => {
- expect(getDataStream().length).toBe(13);
+ expect(getDataStream()!.length).toBe(13);
const commandParams = {
unitId: 'test-doc',
body: {
diff --git a/packages/docs/src/commands/commands/clipboard.inner.command.ts b/packages/docs/src/commands/commands/clipboard.inner.command.ts
index f4cdb57f5f..736148de28 100644
--- a/packages/docs/src/commands/commands/clipboard.inner.command.ts
+++ b/packages/docs/src/commands/commands/clipboard.inner.command.ts
@@ -27,6 +27,7 @@ import {
getDocsUpdateBody,
ICommandService,
IUniverInstanceService,
+ JSONX,
MemoryCursor,
TextX,
TextXActionType,
@@ -82,6 +83,7 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
memoryCursor.reset();
const textX = new TextX();
+ const jsonX = JSONX.getInstance();
for (const selection of selections) {
const { startOffset, endOffset, collapsed } = selection;
@@ -110,7 +112,7 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
memoryCursor.moveCursor(endOffset);
}
- doMutation.params.actions = textX.serialize();
+ doMutation.params.actions = jsonX.editOp(textX.serialize());
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
@@ -149,7 +151,7 @@ export const CutContentCommand: ICommand<IInnerCutCommandParams> = {
}
const documentModel = univerInstanceService.getUniverDocInstance(unitId);
- const originBody = getDocsUpdateBody(documentModel!.snapshot, segmentId);
+ const originBody = getDocsUpdateBody(documentModel!.getSnapshot(), segmentId);
if (originBody == null) {
return false;
}
@@ -168,6 +170,7 @@ export const CutContentCommand: ICommand<IInnerCutCommandParams> = {
memoryCursor.reset();
const textX = new TextX();
+ const jsonX = JSONX.getInstance();
for (const selection of selections) {
const { startOffset, endOffset, collapsed } = selection;
@@ -188,7 +191,7 @@ export const CutContentCommand: ICommand<IInnerCutCommandParams> = {
memoryCursor.moveCursor(endOffset);
}
- doMutation.params.actions = textX.serialize();
+ doMutation.params.actions = jsonX.editOp(textX.serialize());
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
diff --git a/packages/docs/src/commands/commands/core-editing.command.ts b/packages/docs/src/commands/commands/core-editing.command.ts
index f47eab7a84..48957398cf 100644
--- a/packages/docs/src/commands/commands/core-editing.command.ts
+++ b/packages/docs/src/commands/commands/core-editing.command.ts
@@ -22,7 +22,7 @@ import type {
ITextRange,
UpdateDocsAttributeType,
} from '@univerjs/core';
-import { CommandType, ICommandService, TextX, TextXActionType } from '@univerjs/core';
+import { CommandType, ICommandService, JSONX, TextX, TextXActionType } from '@univerjs/core';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';
@@ -61,6 +61,7 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
};
const textX = new TextX();
+ const jsonX = JSONX.getInstance();
if (collapsed) {
if (startOffset > 0) {
@@ -82,7 +83,7 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
segmentId,
});
- doMutation.params.actions = textX.serialize();
+ doMutation.params.actions = jsonX.editOp(textX.serialize());
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
@@ -132,6 +133,7 @@ export const DeleteCommand: ICommand<IDeleteCommandParams> = {
};
const textX = new TextX();
+ const jsonX = JSONX.getInstance();
if (startOffset > 0) {
textX.push({
@@ -148,7 +150,7 @@ export const DeleteCommand: ICommand<IDeleteCommandParams> = {
segmentId,
});
- doMutation.params.actions = textX.serialize();
+ doMutation.params.actions = jsonX.editOp(textX.serialize());
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
@@ -190,6 +192,7 @@ export const UpdateCommand: ICommand<IUpdateCommandParams> = {
};
const textX = new TextX();
+ const jsonX = JSONX.getInstance();
const { startOffset, endOffset } = range;
@@ -207,7 +210,7 @@ export const UpdateCommand: ICommand<IUpdateCommandParams> = {
coverType,
});
- doMutation.params.actions = textX.serialize();
+ doMutation.params.actions = jsonX.editOp(textX.serialize());
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
diff --git a/packages/docs/src/commands/commands/delete.command.ts b/packages/docs/src/commands/commands/delete.command.ts
index 34e19533e5..f7093a7027 100644
--- a/packages/docs/src/commands/commands/delete.command.ts
+++ b/packages/docs/src/commands/commands/delete.command.ts
@@ -19,6 +19,7 @@ import {
CommandType,
ICommandService,
IUniverInstanceService,
+ JSONX,
TextX,
TextXActionType,
UpdateDocsAttributeType,
@@ -328,6 +329,7 @@ export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {
};
const textX = new TextX();
+ const jsonX = JSONX.getInstance();
textX.push({
t: TextXActionType.RETAIN,
@@ -358,7 +360,7 @@ export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {
segmentId,
});
- doMutation.params.actions = textX.serialize();
+ doMutation.params.actions = jsonX.editOp(textX.serialize());
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
diff --git a/packages/docs/src/commands/commands/ime-input.command.ts b/packages/docs/src/commands/commands/ime-input.command.ts
index fb793ff175..f571edfb2f 100644
--- a/packages/docs/src/commands/commands/ime-input.command.ts
+++ b/packages/docs/src/commands/commands/ime-input.command.ts
@@ -15,7 +15,7 @@
*/
import type { ICommand, ICommandInfo } from '@univerjs/core';
-import { CommandType, ICommandService, TextX, TextXActionType } from '@univerjs/core';
+import { CommandType, ICommandService, JSONX, TextX, TextXActionType } from '@univerjs/core';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';
@@ -68,6 +68,7 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
};
const textX = new TextX();
+ const jsonX = JSONX.getInstance();
if (!previousActiveRange.collapsed && isCompositionStart) {
textX.push(...getRetainAndDeleteFromReplace(previousActiveRange, segmentId));
@@ -98,7 +99,7 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
segmentId,
});
- doMutation.params!.actions = textX.serialize();
+ doMutation.params!.actions = jsonX.editOp(textX.serialize());
doMutation.params!.noHistory = !isCompositionEnd;
diff --git a/packages/docs/src/commands/commands/inline-format.command.ts b/packages/docs/src/commands/commands/inline-format.command.ts
index 77a50abb80..166ba46d71 100644
--- a/packages/docs/src/commands/commands/inline-format.command.ts
+++ b/packages/docs/src/commands/commands/inline-format.command.ts
@@ -23,6 +23,7 @@ import {
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
ICommandService,
IUniverInstanceService,
+ JSONX,
MemoryCursor,
TextX,
TextXActionType,
@@ -263,6 +264,7 @@ const COMMAND_ID_TO_FORMAT_KEY_MAP: Record<string, keyof IStyleBase> = {
export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
id: 'doc.command.set-inline-format',
type: CommandType.COMMAND,
+ // eslint-disable-next-line max-lines-per-function
handler: async (accessor, params: ISetInlineFormatCommandParams) => {
const { segmentId, value, preCommandId } = params;
const commandService = accessor.get(ICommandService);
@@ -343,6 +345,7 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
};
const textX = new TextX();
+ const jsonX = JSONX.getInstance();
const memoryCursor = new MemoryCursor();
@@ -385,7 +388,7 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
memoryCursor.moveCursor(endOffset);
}
- doMutation.params.actions = textX.serialize();
+ doMutation.params.actions = jsonX.editOp(textX.serialize());
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
diff --git a/packages/docs/src/commands/commands/insert-floating-object.command.ts b/packages/docs/src/commands/commands/insert-floating-object.command.ts
index b19b422789..140ee2dfb9 100644
--- a/packages/docs/src/commands/commands/insert-floating-object.command.ts
+++ b/packages/docs/src/commands/commands/insert-floating-object.command.ts
@@ -40,7 +40,7 @@ export const InsertDrawingCommand: ICommand = {
const documentModel = univerInstanceService.getUniverDocInstance(documentId);
if (!documentModel) return false;
- const { snapshot } = documentModel;
+ const snapshot = documentModel.getSnapshot();
if (snapshot == null || snapshot.drawings == null) return false;
const { objectId, drawing } = params;
diff --git a/packages/docs/src/commands/commands/list.command.ts b/packages/docs/src/commands/commands/list.command.ts
index d39ffa256f..83df220c2f 100644
--- a/packages/docs/src/commands/commands/list.command.ts
+++ b/packages/docs/src/commands/commands/list.command.ts
@@ -19,6 +19,7 @@ import {
CommandType,
ICommandService,
IUniverInstanceService,
+ JSONX,
MemoryCursor,
PRESET_LIST_TYPE,
PresetListType,
@@ -42,6 +43,7 @@ export const ListOperationCommand: ICommand<IListOperationCommandParams> = {
type: CommandType.COMMAND,
+ // eslint-disable-next-line max-lines-per-function
handler: (accessor, params: IListOperationCommandParams) => {
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -101,6 +103,7 @@ export const ListOperationCommand: ICommand<IListOperationCommandParams> = {
memoryCursor.reset();
const textX = new TextX();
+ const jsonX = JSONX.getInstance();
const customLists = dataModel.getSnapshot().lists ?? {};
@@ -167,7 +170,7 @@ export const ListOperationCommand: ICommand<IListOperationCommandParams> = {
memoryCursor.moveCursorTo(startIndex + 1);
}
- doMutation.params.actions = textX.serialize();
+ doMutation.params.actions = jsonX.editOp(textX.serialize());
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
diff --git a/packages/docs/src/commands/commands/paragraph-align.command.ts b/packages/docs/src/commands/commands/paragraph-align.command.ts
index c1b81b2938..3dd9b7090d 100644
--- a/packages/docs/src/commands/commands/paragraph-align.command.ts
+++ b/packages/docs/src/commands/commands/paragraph-align.command.ts
@@ -19,6 +19,7 @@ import {
CommandType, HorizontalAlign,
ICommandService,
IUniverInstanceService,
+ JSONX,
MemoryCursor,
TextX,
TextXActionType,
@@ -39,6 +40,7 @@ export const AlignOperationCommand: ICommand<IAlignOperationCommandParams> = {
type: CommandType.COMMAND,
+ // eslint-disable-next-line max-lines-per-function
handler: (accessor, params: IAlignOperationCommandParams) => {
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -74,6 +76,8 @@ export const AlignOperationCommand: ICommand<IAlignOperationCommandParams> = {
memoryCursor.reset();
const textX = new TextX();
+ const jsonX = JSONX.getInstance();
+
for (const paragraph of currentParagraphs) {
const { startIndex } = paragraph;
@@ -109,7 +113,7 @@ export const AlignOperationCommand: ICommand<IAlignOperationCommandParams> = {
memoryCursor.moveCursorTo(startIndex + 1);
}
- doMutation.params.actions = textX.serialize();
+ doMutation.params.actions = jsonX.editOp(textX.serialize());
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
diff --git a/packages/docs/src/commands/commands/remove-floating-object.command.ts b/packages/docs/src/commands/commands/remove-floating-object.command.ts
index 0266cb3711..8c8391ec2b 100644
--- a/packages/docs/src/commands/commands/remove-floating-object.command.ts
+++ b/packages/docs/src/commands/commands/remove-floating-object.command.ts
@@ -41,7 +41,7 @@ export const RemoveDrawingCommand: ICommand = {
const documentModel = univerInstanceService.getUniverDocInstance(documentId);
if (!documentModel) return false;
- const snapshot = documentModel.snapshot;
+ const snapshot = documentModel.getSnapshot();
if (snapshot == null || snapshot.drawings == null) return false;
const { objectId } = params;
diff --git a/packages/docs/src/commands/commands/replace-content.command.ts b/packages/docs/src/commands/commands/replace-content.command.ts
index 6c03db733c..f08af6d387 100644
--- a/packages/docs/src/commands/commands/replace-content.command.ts
+++ b/packages/docs/src/commands/commands/replace-content.command.ts
@@ -15,7 +15,7 @@
*/
import type { ICommand, IDocumentBody, IMutationInfo } from '@univerjs/core';
-import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, TextX, TextXActionType } from '@univerjs/core';
+import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
@@ -117,6 +117,7 @@ function getMutationParams(unitId: string, segmentId: string, prevBody: IDocumen
};
const textX = new TextX();
+ const jsonX = JSONX.getInstance();
const deleteLen = prevBody?.dataStream.length - 2;
if (deleteLen > 0) {
@@ -138,7 +139,7 @@ function getMutationParams(unitId: string, segmentId: string, prevBody: IDocumen
});
}
- doMutation.params.actions = textX.serialize();
+ doMutation.params.actions = jsonX.editOp(textX.serialize());
return doMutation;
}
diff --git a/packages/docs/src/commands/commands/set-floating-object-transform.command.ts b/packages/docs/src/commands/commands/set-floating-object-transform.command.ts
index bf1936e127..11a259cef7 100644
--- a/packages/docs/src/commands/commands/set-floating-object-transform.command.ts
+++ b/packages/docs/src/commands/commands/set-floating-object-transform.command.ts
@@ -48,7 +48,7 @@ export const SetDrawingSizeCommand: ICommand = {
const documentModel = univerInstanceService.getUniverDocInstance(documentId);
if (!documentModel) return false;
- const snapshot = documentModel.snapshot;
+ const snapshot = documentModel.getSnapshot();
if (snapshot == null) return false;
const { objectId, size } = params;
@@ -100,7 +100,7 @@ export const SetDrawingPositionCommand: ICommand = {
const documentModel = univerInstanceService.getUniverDocInstance(documentId);
if (!documentModel) return false;
- const snapshot = documentModel.snapshot;
+ const snapshot = documentModel.getSnapshot();
if (snapshot == null) return false;
const { objectId, positionH, positionV } = params;
diff --git a/packages/docs/src/commands/mutations/core-editing.mutation.ts b/packages/docs/src/commands/mutations/core-editing.mutation.ts
index 3120ee8dca..234d3b0cae 100644
--- a/packages/docs/src/commands/mutations/core-editing.mutation.ts
+++ b/packages/docs/src/commands/mutations/core-editing.mutation.ts
@@ -14,9 +14,8 @@
* limitations under the License.
*/
-import { CommandType, IUniverInstanceService } from '@univerjs/core';
-import type { IMutation, IMutationCommonParams, Nullable, TextXAction } from '@univerjs/core';
-
+import { CommandType, IUniverInstanceService, JSONX } from '@univerjs/core';
+import type { IMutation, IMutationCommonParams, JSONXActions, Nullable } from '@univerjs/core';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import { DocViewModelManagerService } from '../../services/doc-view-model-manager.service';
import { serializeTextRange, TextSelectionManagerService } from '../../services/text-selection-manager.service';
@@ -26,12 +25,13 @@ import { IMEInputManagerService } from '../../services/ime-input-manager.service
export interface IRichTextEditingMutationParams extends IMutationCommonParams {
unitId: string;
- actions: TextXAction[];
+ segmentId?: string;
+ actions: JSONXActions;
textRanges: Nullable<ITextRangeWithStyle[]>;
prevTextRanges?: Nullable<ITextRangeWithStyle[]>;
noNeedSetTextRange?: boolean;
- noHistory?: boolean;
isCompositionEnd?: boolean;
+ noHistory?: boolean;
}
const RichTextEditingMutationId = 'doc.mutation.rich-text-editing';
@@ -49,6 +49,7 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
handler: (accessor, params) => {
const {
unitId,
+ segmentId = '',
actions,
textRanges,
prevTextRanges,
@@ -79,7 +80,7 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
// TODO: `disabled` is only used for read only demo, and will be removed in the future.
const disabled = !!documentDataModel.getSnapshot().disabled;
- if (actions.length === 0 || disabled) {
+ if (JSONX.isNoop(actions) || (actions && actions.length === 0) || disabled) {
// The actions' length maybe 0 when the mutation is from collaborative editing.
// The return result will not be used.
return {
@@ -90,13 +91,15 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
}
// Step 1: Update Doc Data Model.
- const undoActions = documentDataModel.apply(actions);
+ const undoActions = JSONX.invertWithDoc(actions, documentDataModel.getSnapshot());
+ documentDataModel.apply(actions);
+
+ // console.log(actions);
+ // console.log(undoActions);
// Step 2: Update Doc View Model.
- const { segmentId } = actions[0];
const segmentDocumentDataModel = documentDataModel.getSelfOrHeaderFooterModel(segmentId);
const segmentViewModel = documentViewModel.getSelfOrHeaderFooterViewModel(segmentId);
-
segmentViewModel.reset(segmentDocumentDataModel);
// Step 3: Update cursor & selection.
@@ -107,10 +110,11 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
});
}
- // Step 4: emit state change event.
+ // Step 4: Emit state change event.
const changeState: IDocStateChangeParams = {
commandId: RichTextEditingMutationId,
unitId,
+ segmentId,
trigger,
noHistory,
redoState: {
diff --git a/packages/docs/src/commands/mutations/insert-floating-object.mutation.ts b/packages/docs/src/commands/mutations/insert-floating-object.mutation.ts
index d7287d95e8..64b2709ebe 100644
--- a/packages/docs/src/commands/mutations/insert-floating-object.mutation.ts
+++ b/packages/docs/src/commands/mutations/insert-floating-object.mutation.ts
@@ -33,11 +33,11 @@ export const InsertDrawingMutation: IMutation<IInsertDrawingMutation> = {
return false;
}
- let drawings = univerdoc.snapshot.drawings;
+ let drawings = univerdoc.getSnapshot().drawings;
if (drawings == null) {
drawings = {};
- univerdoc.snapshot.drawings = drawings;
+ univerdoc.getSnapshot().drawings = drawings;
}
const { objectId, drawing } = params;
diff --git a/packages/docs/src/commands/mutations/remove-floating-object.mutation.ts b/packages/docs/src/commands/mutations/remove-floating-object.mutation.ts
index 9d878a878b..82a3b0a77e 100644
--- a/packages/docs/src/commands/mutations/remove-floating-object.mutation.ts
+++ b/packages/docs/src/commands/mutations/remove-floating-object.mutation.ts
@@ -29,11 +29,11 @@ export const RemoveDrawingMutation: IMutation<ISeachDrawingMutation> = {
return false;
}
- let drawings = univerdoc.snapshot.drawings;
+ let drawings = univerdoc.getSnapshot().drawings;
if (drawings == null) {
drawings = {};
- univerdoc.snapshot.drawings = drawings;
+ univerdoc.getSnapshot().drawings = drawings;
}
delete drawings[params.objectId];
diff --git a/packages/docs/src/commands/mutations/set-floating-object.mutation.ts b/packages/docs/src/commands/mutations/set-floating-object.mutation.ts
index 3394142e6e..3ef3b6b828 100644
--- a/packages/docs/src/commands/mutations/set-floating-object.mutation.ts
+++ b/packages/docs/src/commands/mutations/set-floating-object.mutation.ts
@@ -48,7 +48,7 @@ export const SetDrawingTransformMutationFactory = (
throw new Error('documentModel is null error!');
}
- const drawings = documentModel.snapshot.drawings;
+ const drawings = documentModel.getSnapshot().drawings;
if (drawings == null) {
return {
@@ -86,11 +86,11 @@ export const SetDrawingTransformMutation: IMutation<IDrawingTransformMutation> =
return false;
}
- let drawings = univerdoc.snapshot.drawings;
+ let drawings = univerdoc.getSnapshot().drawings;
if (drawings == null) {
drawings = {};
- univerdoc.snapshot.drawings = drawings;
+ univerdoc.getSnapshot().drawings = drawings;
}
const { objectId, size, positionH, positionV, angle } = params;
@@ -136,11 +136,11 @@ export const SetDrawingLayoutMutation: IMutation<IDrawingLayoutMutation> = {
return false;
}
- let drawings = univerdoc.snapshot.drawings;
+ let drawings = univerdoc.getSnapshot().drawings;
if (drawings == null) {
drawings = {};
- univerdoc.snapshot.drawings = drawings;
+ univerdoc.getSnapshot().drawings = drawings;
}
const { objectId, layoutType, behindDoc, start, lineTo, wrapText, distL, distR, distT, distB } = params;
@@ -188,11 +188,11 @@ export const SetDrawingInfoMutation: IMutation<IDrawingInfoMutation> = {
return false;
}
- let drawings = univerdoc.snapshot.drawings;
+ let drawings = univerdoc.getSnapshot().drawings;
if (drawings == null) {
drawings = {};
- univerdoc.snapshot.drawings = drawings;
+ univerdoc.getSnapshot().drawings = drawings;
}
const { objectId, title, description } = params;
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 4344d7d45d..a7c296d530 100644
--- a/packages/docs/src/services/doc-state-change-manager.service.ts
+++ b/packages/docs/src/services/doc-state-change-manager.service.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { Nullable, TextXAction } from '@univerjs/core';
-import { ICommandService, IUndoRedoService, IUniverInstanceService, RedoCommandId, RxDisposable, TextX, UndoCommandId } from '@univerjs/core';
+import type { JSONXActions, Nullable } from '@univerjs/core';
+import { ICommandService, IUndoRedoService, IUniverInstanceService, JSONX, RedoCommandId, RxDisposable, UndoCommandId } from '@univerjs/core';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import { Inject } from '@wendellhu/redi';
import { BehaviorSubject } from 'rxjs';
@@ -23,13 +23,14 @@ import type { IRichTextEditingMutationParams } from '../commands/mutations/core-
import { DeleteCommand, InsertCommand } from '../commands/commands/core-editing.command';
interface IDocChangeState {
- actions: TextXAction[];
+ actions: JSONXActions;
textRanges: Nullable<ITextRangeWithStyle[]>;
}
export interface IDocStateChangeParams {
commandId: string;
unitId: string;
+ segmentId?: string;
trigger: Nullable<string>;
redoState: IDocChangeState;
undoState: IDocChangeState;
@@ -133,14 +134,14 @@ export class DocStateChangeManagerService extends RxDisposable {
const redoParams: IRichTextEditingMutationParams = {
unitId,
- actions: cacheStates.reduce((acc, cur) => TextX.compose(acc, cur.redoState.actions), [] as TextXAction[]),
+ actions: cacheStates.reduce((acc, cur) => JSONX.compose(acc, cur.redoState.actions), null as JSONXActions),
textRanges: lastState.redoState.textRanges,
};
const undoParams: IRichTextEditingMutationParams = {
unitId,
// Always need to put undoParams after redoParams, because `reverse` will change the `cacheStates` order.
- actions: cacheStates.reverse().reduce((acc, cur) => TextX.compose(acc, cur.undoState.actions), [] as TextXAction[]),
+ actions: cacheStates.reverse().reduce((acc, cur) => JSONX.compose(acc, cur.undoState.actions), null as JSONXActions),
textRanges: firstState.undoState.textRanges,
};
diff --git a/packages/docs/src/services/ime-input-manager.service.ts b/packages/docs/src/services/ime-input-manager.service.ts
index fc309344fc..2e95c01feb 100644
--- a/packages/docs/src/services/ime-input-manager.service.ts
+++ b/packages/docs/src/services/ime-input-manager.service.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { TextX } from '@univerjs/core';
-import type { Nullable, TextXAction } from '@univerjs/core';
+import { JSONX } from '@univerjs/core';
+import type { JSONXActions, Nullable } from '@univerjs/core';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IDisposable } from '@wendellhu/redi';
@@ -73,16 +73,16 @@ export class IMEInputManagerService implements IDisposable {
const undoMutationParams: IRichTextEditingMutationParams = {
unitId,
actions: this._undoMutationParamsCache.reverse().reduce((acc, cur) => {
- return TextX.compose(acc, cur.actions);
- }, [] as TextXAction[]),
+ return JSONX.compose(acc, cur.actions);
+ }, null as JSONXActions),
textRanges: [], // Add empty array, will never use, just fix type error
};
const redoMutationParams: IRichTextEditingMutationParams = {
unitId,
actions: this._redoMutationParamsCache.reduce((acc, cur) => {
- return TextX.compose(acc, cur.actions);
- }, [] as TextXAction[]),
+ return JSONX.compose(acc, cur.actions);
+ }, null as JSONXActions),
textRanges: [], // Add empty array, will never use, just fix type error
};
diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.ts
index 722664b978..4339360575 100644
--- a/packages/sheets-formula/src/controllers/prompt.controller.ts
+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts
@@ -20,7 +20,6 @@ import type {
IRange,
IRangeWithCoord,
ITextRun,
-
Nullable,
Workbook } from '@univerjs/core';
import {
@@ -765,7 +764,7 @@ export class PromptController extends Disposable {
private _getCurrentBodyDataStreamAndOffset() {
const documentModel = this._univerInstanceService.getCurrentUniverDocInstance();
- if (!documentModel?.snapshot?.body) {
+ if (!documentModel?.getBody()) {
return;
}
@@ -773,7 +772,7 @@ export class PromptController extends Disposable {
const editor = this._editorService.getEditor(unitId);
- const dataStream = documentModel.snapshot.body.dataStream;
+ const dataStream = documentModel.getBody()?.dataStream ?? '';
if (!editor || !editor.onlyInputRange()) {
return { dataStream, offset: 0 };
diff --git a/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts b/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
index df2588d9e0..07e20ac1f0 100644
--- a/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
@@ -520,7 +520,7 @@ export class StartEditController extends Disposable {
eventType === DeviceInputEventType.Keyboard ||
(eventType === DeviceInputEventType.Dblclick && isInArrayFormulaRange)
) {
- const snapshot = Tools.deepClone(documentDataModel.snapshot) as IDocumentData;
+ const snapshot = Tools.deepClone(documentDataModel.getSnapshot()) as IDocumentData;
const documentViewModel = this._docViewModelManagerService.getViewModel(editorUnitId);
if (documentViewModel == null) {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d486678ac6..27c045d973 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -358,6 +358,9 @@ importers:
numeral:
specifier: ^2.0.6
version: 2.0.6
+ ot-json1:
+ specifier: ^1.0.2
+ version: 1.0.2
devDependencies:
'@types/numeral':
specifier: ^2.0.5
@@ -8121,6 +8124,12 @@ packages:
resolution: {integrity: sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-IhxkqVWQqlkWULoi/Q2AdzKk0N5vQRbUMUwubFXFCPcY4TsOZjmp2YKrk0/z1TeiECPadWEK060sdFdQ3Grokg==}
+
+ resolution: {integrity: sha512-W7ZLU8QXesY2wagYFv47zErXud3E93FGImmSGJsQnBzE+idcPPyo2u2KMilIrTwBh4pbCizy71qRjmmV6aDhcQ==}
+
resolution: {integrity: sha512-mlVgR3PGuzlo0MmTdk4cXqXWlwQDLnONTAg6sm62XkMJEiRxN3GL3SffkYvqwonbkJBcrI7Uvv5Zh9yjvn2iUw==}
engines: {node: '>=12.20'}
@@ -9749,6 +9758,9 @@ packages:
resolution: {integrity: sha512-lRfVq8fE8gz6QMBuDM6a+LO3IAzTi05H6gCVaUpir2E1Rwpo4ZUog45KpNXKC/Mn3Yb9UDuHumeFTo9iV/D9FQ==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-RlwWt1ywVW4WErPGAVHw/rIuJ2+MxvTME0siJ6lk9zBhpDfExDbspe6SRlWT3qU6AucNjotPl9qAJRVjP7guCQ==}
+
resolution: {integrity: sha512-uNaeirEPvpZWSgzwsPGtU2zVSTrn/8L5q/IexZmH0eH6SA73CmAA5U4GwORTxQAZs95TAXLNqeLoPPNO5gZfWg==}
engines: {node: '>=8'}
@@ -17462,6 +17474,14 @@ snapshots:
+ dependencies:
+ ot-text-unicode: 4.0.0
+
+ dependencies:
+ unicount: 1.1.0
+
@@ -19301,6 +19321,8 @@ snapshots:
+
dependencies:
crypto-random-string: 2.0.0