Skip to content

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

feat: cursor support undo and redo (#493)

Ran Luo4c561a5d12e0
diff --git a/packages/base-docs/src/basics/retain-delete-params.ts b/packages/base-docs/src/basics/retain-delete-params.ts
new file mode 100644
index 0000000000..cb17973efa
--- /dev/null
+++ b/packages/base-docs/src/basics/retain-delete-params.ts
@@ -0,0 +1,32 @@
+import { ITextRange } from '@univerjs/core';
+
+import { IDeleteMutationParams, IRetainMutationParams } from '../commands/mutations/core-editing.mutation';
+
+export function getRetainAndDeleteFromReplace(
+ range: ITextRange,
+ segmentId: string = '',
+ memoryCursor: number = 0
+): Array<IRetainMutationParams | IDeleteMutationParams> {
+ const { startOffset, endOffset } = range;
+ const dos: Array<IRetainMutationParams | IDeleteMutationParams> = [];
+
+ const textStart = startOffset - memoryCursor;
+ const textEnd = endOffset - memoryCursor;
+
+ if (textStart > 0) {
+ dos.push({
+ t: 'r',
+ len: textStart,
+ segmentId,
+ });
+ }
+
+ dos.push({
+ t: 'd',
+ len: textEnd - textStart,
+ line: 0,
+ segmentId,
+ });
+
+ return dos;
+}
diff --git a/packages/base-docs/src/commands/commands/__tests__/clipboard.command.spec.ts b/packages/base-docs/src/commands/commands/__tests__/clipboard.command.spec.ts
index a8d3ad6378..428e01e538 100644
--- a/packages/base-docs/src/commands/commands/__tests__/clipboard.command.spec.ts
+++ b/packages/base-docs/src/commands/commands/__tests__/clipboard.command.spec.ts
@@ -165,6 +165,7 @@ describe('test cases in clipboard', () => {
},
],
},
+ textRanges: [], // only used to eliminate TS type check error.
};
await commandService.executeCommand(InnerPasteCommand.id, commandParams);
@@ -184,6 +185,7 @@ describe('test cases in clipboard', () => {
const commandParams: IInnerCutCommandParams = {
segmentId: '',
+ textRanges: [], // only used to eliminate TS type check error.
};
await commandService.executeCommand(InnerCutCommand.id, commandParams);
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 ef43aa0ec1..b722ccb57b 100644
--- a/packages/base-docs/src/commands/commands/clipboard.inner.command.ts
+++ b/packages/base-docs/src/commands/commands/clipboard.inner.command.ts
@@ -1,3 +1,4 @@
+import { ITextRangeWithStyle } from '@univerjs/base-render';
import {
CommandType,
ICommand,
@@ -9,20 +10,22 @@ import {
} 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 { IRichTextEditingMutationParams, RichTextEditingMutation } from '../mutations/core-editing.mutation';
-import { getRetainAndDeleteFromReplace } from './core-editing.command';
export interface IInnerPasteCommandParams {
segmentId: string;
body: IDocumentBody;
+ textRanges: ITextRangeWithStyle[];
}
+// Actually, the command is to handle paste event.
export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
id: 'doc.command.inner-paste',
type: CommandType.COMMAND,
handler: async (accessor, params: IInnerPasteCommandParams) => {
- const { segmentId, body } = params;
+ const { segmentId, body, textRanges } = params;
const undoRedoService = accessor.get(IUndoRedoService);
const commandService = accessor.get(ICommandService);
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
@@ -83,11 +86,27 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
IRichTextEditingMutationParams
>(doMutation.id, doMutation.params);
+ textSelectionManagerService.replaceTextRanges(textRanges);
+
if (result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
undoMutations: [{ id: RichTextEditingMutation.id, params: result }],
redoMutations: [{ id: RichTextEditingMutation.id, params: doMutation.params }],
+ undo() {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, result);
+
+ textSelectionManagerService.replaceTextRanges(selections);
+
+ return true;
+ },
+ redo() {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, doMutation.params);
+
+ textSelectionManagerService.replaceTextRanges(textRanges);
+
+ return true;
+ },
});
return true;
@@ -99,13 +118,14 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
export interface IInnerCutCommandParams {
segmentId: string;
+ textRanges: ITextRangeWithStyle[];
}
export const InnerCutCommand: ICommand<IInnerCutCommandParams> = {
id: 'doc.command.inner-cut',
type: CommandType.COMMAND,
handler: async (accessor, params: IInnerCutCommandParams) => {
- const { segmentId } = params;
+ const { segmentId, textRanges } = params;
const undoRedoService = accessor.get(IUndoRedoService);
const commandService = accessor.get(ICommandService);
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
@@ -158,11 +178,27 @@ export const InnerCutCommand: ICommand<IInnerCutCommandParams> = {
IRichTextEditingMutationParams
>(doMutation.id, doMutation.params);
+ textSelectionManagerService.replaceTextRanges(textRanges);
+
if (result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
undoMutations: [{ id: RichTextEditingMutation.id, params: result }],
redoMutations: [{ id: RichTextEditingMutation.id, params: doMutation.params }],
+ undo() {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, result);
+
+ textSelectionManagerService.replaceTextRanges(selections);
+
+ return true;
+ },
+ redo() {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, doMutation.params);
+
+ textSelectionManagerService.replaceTextRanges(textRanges);
+
+ return true;
+ },
});
return true;
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 0ba7fc58cc..480e130f58 100644
--- a/packages/base-docs/src/commands/commands/core-editing.command.ts
+++ b/packages/base-docs/src/commands/commands/core-editing.command.ts
@@ -1,8 +1,8 @@
+import { ITextRangeWithStyle } from '@univerjs/base-render';
import {
CommandType,
createEmptyDocSnapshot,
ICommand,
- ICommandInfo,
ICommandService,
IDocumentBody,
IDocumentData,
@@ -13,12 +13,9 @@ import {
UpdateDocsAttributeType,
} from '@univerjs/core';
-import {
- IDeleteMutationParams,
- IRetainMutationParams,
- IRichTextEditingMutationParams,
- RichTextEditingMutation,
-} from '../mutations/core-editing.mutation';
+import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';
+import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
+import { IRichTextEditingMutationParams, RichTextEditingMutation } from '../mutations/core-editing.mutation';
// TODO: @JOCS, do not use command as event bus.
export const DeleteLeftCommand: ICommand = {
@@ -43,6 +40,7 @@ export interface IInsertCommandParams {
unitId: string;
body: IDocumentBody;
range: ITextRange;
+ textRanges: ITextRangeWithStyle[];
segmentId?: string;
}
@@ -55,8 +53,9 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
handler: async (accessor, params: IInsertCommandParams) => {
const undoRedoService = accessor.get(IUndoRedoService);
const commandService = accessor.get(ICommandService);
+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);
- const { range, segmentId, body, unitId } = params;
+ const { range, segmentId, body, unitId, textRanges } = params;
const { startOffset, collapsed } = range;
const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
@@ -90,11 +89,27 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
IRichTextEditingMutationParams
>(doMutation.id, doMutation.params);
+ textSelectionManagerService.replaceTextRanges(textRanges);
+
if (result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
undoMutations: [{ id: RichTextEditingMutation.id, params: result }],
redoMutations: [{ id: RichTextEditingMutation.id, params: doMutation.params }],
+ undo() {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, result);
+
+ textSelectionManagerService.replaceTextRanges([range]);
+
+ return true;
+ },
+ redo() {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, doMutation.params);
+
+ textSelectionManagerService.replaceTextRanges(textRanges);
+
+ return true;
+ },
});
return true;
@@ -113,6 +128,7 @@ export interface IDeleteCommandParams {
unitId: string;
range: ITextRange;
direction: DeleteDirection;
+ textRanges: ITextRangeWithStyle[];
segmentId?: string;
}
@@ -121,7 +137,9 @@ export interface IDeleteCommandParams {
*/
export const DeleteCommand: ICommand<IDeleteCommandParams> = {
id: 'doc.command.delete-text',
+
type: CommandType.COMMAND,
+
handler: async (accessor, params) => {
if (!params) {
throw new Error();
@@ -129,8 +147,9 @@ export const DeleteCommand: ICommand<IDeleteCommandParams> = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);
- const { range, segmentId, unitId, direction } = params;
+ const { range, segmentId, unitId, direction, textRanges } = params;
const { collapsed, startOffset } = range;
const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
id: RichTextEditingMutation.id,
@@ -164,11 +183,27 @@ export const DeleteCommand: ICommand<IDeleteCommandParams> = {
IRichTextEditingMutationParams
>(doMutation.id, doMutation.params);
+ textSelectionManagerService.replaceTextRanges(textRanges);
+
if (result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
undoMutations: [{ id: RichTextEditingMutation.id, params: result }],
redoMutations: [{ id: RichTextEditingMutation.id, params: doMutation.params }],
+ undo() {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, result);
+
+ textSelectionManagerService.replaceTextRanges([range]);
+
+ return true;
+ },
+ redo() {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, doMutation.params);
+
+ textSelectionManagerService.replaceTextRanges(textRanges);
+
+ return true;
+ },
});
return false;
}
@@ -182,6 +217,7 @@ export interface IUpdateCommandParams {
updateBody: IDocumentBody;
range: ITextRange;
coverType: UpdateDocsAttributeType;
+ textRanges: ITextRangeWithStyle[];
segmentId?: string;
}
@@ -190,15 +226,18 @@ export interface IUpdateCommandParams {
*/
export const UpdateCommand: ICommand<IUpdateCommandParams> = {
id: 'doc.command.update-text',
+
type: CommandType.COMMAND,
+
handler: async (accessor, params) => {
if (!params) {
throw new Error();
}
- const { range, segmentId, updateBody, coverType, unitId } = params;
+ const { range, segmentId, updateBody, coverType, unitId, textRanges } = params;
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
id: RichTextEditingMutation.id,
@@ -229,78 +268,33 @@ export const UpdateCommand: ICommand<IUpdateCommandParams> = {
IRichTextEditingMutationParams
>(doMutation.id, doMutation.params);
+ textSelectionManagerService.replaceTextRanges(textRanges);
+
if (result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
undoMutations: [{ id: RichTextEditingMutation.id, params: result }],
redoMutations: [{ id: RichTextEditingMutation.id, params: doMutation.params }],
- });
+ undo() {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, result);
- return true;
- }
+ textSelectionManagerService.replaceTextRanges([range]);
- return false;
- },
-};
+ return true;
+ },
+ redo() {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, doMutation.params);
-export interface IIMEInputCommandParams {
- newText: string;
- oldTextLen: number;
- range: ITextRange;
- segmentId?: string;
- unitId: string;
-}
+ textSelectionManagerService.replaceTextRanges(textRanges);
-export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
- id: 'doc.command.ime-input',
- type: CommandType.COMMAND,
- handler: async (accessor, params: IIMEInputCommandParams) => {
- const { unitId, newText, oldTextLen, range, segmentId } = params;
- const commandService = accessor.get(ICommandService);
-
- const doMutation: ICommandInfo<IRichTextEditingMutationParams> = {
- id: RichTextEditingMutation.id,
- params: {
- unitId,
- mutations: [],
- },
- };
-
- if (range.collapsed) {
- doMutation.params!.mutations.push({
- t: 'r',
- len: range.startOffset,
- segmentId,
+ return true;
+ },
});
- } else {
- doMutation.params!.mutations.push(...getRetainAndDeleteFromReplace(range, segmentId));
- }
-
- if (oldTextLen > 0) {
- doMutation.params!.mutations.push({
- t: 'd',
- len: oldTextLen,
- line: 0,
- segmentId,
- });
- }
-
- doMutation.params!.mutations.push({
- t: 'i',
- body: {
- dataStream: newText,
- },
- len: newText.length,
- line: 0,
- segmentId,
- });
- const result = commandService.syncExecuteCommand(doMutation.id, doMutation.params);
- if (!result) {
- return false;
+ return true;
}
- return true;
+ return false;
},
};
@@ -311,6 +305,7 @@ export interface ICoverCommandParams {
clearUndoRedoStack?: boolean;
}
+// Cover all content with new snapshot or empty doc, and clear undo redo stack.
export const CoverCommand: ICommand<ICoverCommandParams> = {
id: 'doc.command-cover-content',
type: CommandType.COMMAND,
@@ -333,32 +328,3 @@ export const CoverCommand: ICommand<ICoverCommandParams> = {
return true;
},
};
-
-export function getRetainAndDeleteFromReplace(
- range: ITextRange,
- segmentId: string = '',
- memoryCursor: number = 0
-): Array<IRetainMutationParams | IDeleteMutationParams> {
- const { startOffset, endOffset } = range;
- const dos: Array<IRetainMutationParams | IDeleteMutationParams> = [];
-
- const textStart = startOffset - memoryCursor;
- const textEnd = endOffset - memoryCursor;
-
- if (textStart > 0) {
- dos.push({
- t: 'r',
- len: textStart,
- segmentId,
- });
- }
-
- dos.push({
- t: 'd',
- len: textEnd - textStart,
- line: 0,
- segmentId,
- });
-
- return dos;
-}
diff --git a/packages/base-docs/src/commands/commands/ime-input.command.ts b/packages/base-docs/src/commands/commands/ime-input.command.ts
new file mode 100644
index 0000000000..1bb4a0f30a
--- /dev/null
+++ b/packages/base-docs/src/commands/commands/ime-input.command.ts
@@ -0,0 +1,115 @@
+import { ITextRangeWithStyle } from '@univerjs/base-render';
+import { CommandType, ICommand, ICommandInfo, ICommandService, ITextRange, IUndoRedoService } from '@univerjs/core';
+
+import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';
+import { IMEInputManagerService } from '../../services/ime-input-manager.service';
+import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
+import { IRichTextEditingMutationParams, RichTextEditingMutation } from '../mutations/core-editing.mutation';
+
+export interface IIMEInputCommandParams {
+ unitId: string;
+ newText: string;
+ oldTextLen: number;
+ range: ITextRange;
+ textRanges: ITextRangeWithStyle[];
+ isCompositionEnd: boolean;
+ segmentId?: string;
+}
+
+export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
+ id: 'doc.command.ime-input',
+
+ type: CommandType.COMMAND,
+
+ handler: async (accessor, params: IIMEInputCommandParams) => {
+ const { unitId, newText, oldTextLen, range, segmentId, textRanges, isCompositionEnd } = params;
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);
+ const imeInputManagerService = accessor.get(IMEInputManagerService);
+
+ const doMutation: ICommandInfo<IRichTextEditingMutationParams> = {
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId,
+ mutations: [],
+ },
+ };
+
+ if (range.collapsed) {
+ doMutation.params!.mutations.push({
+ t: 'r',
+ len: range.startOffset,
+ segmentId,
+ });
+ } else {
+ doMutation.params!.mutations.push(...getRetainAndDeleteFromReplace(range, segmentId));
+ }
+
+ if (oldTextLen > 0) {
+ doMutation.params!.mutations.push({
+ t: 'd',
+ len: oldTextLen,
+ line: 0,
+ segmentId,
+ });
+ }
+
+ doMutation.params!.mutations.push({
+ t: 'i',
+ body: {
+ dataStream: newText,
+ },
+ len: newText.length,
+ line: 0,
+ segmentId,
+ });
+
+ const result = commandService.syncExecuteCommand<
+ IRichTextEditingMutationParams,
+ IRichTextEditingMutationParams
+ >(doMutation.id, doMutation.params);
+
+ imeInputManagerService.pushUndoRedoMutationParams(result, doMutation.params!);
+
+ textSelectionManagerService.replaceTextRanges(textRanges);
+
+ if (isCompositionEnd) {
+ if (result) {
+ const historyParams = imeInputManagerService.fetchComposedUndoRedoMutationParams(newText);
+
+ if (historyParams == null) {
+ return false;
+ }
+
+ const { undoMutationParams, redoMutationParams, previousActiveRange } = historyParams;
+
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [{ id: RichTextEditingMutation.id, params: undoMutationParams }],
+ redoMutations: [{ id: RichTextEditingMutation.id, params: redoMutationParams }],
+ undo() {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, undoMutationParams);
+
+ textSelectionManagerService.replaceTextRanges([previousActiveRange]);
+
+ return true;
+ },
+ redo() {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, redoMutationParams);
+
+ textSelectionManagerService.replaceTextRanges(textRanges);
+
+ return true;
+ },
+ });
+
+ return true;
+ }
+ } else {
+ return !!result;
+ }
+
+ return false;
+ },
+};
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 8fccf6121b..916d227208 100644
--- a/packages/base-docs/src/commands/commands/inline-format.command.ts
+++ b/packages/base-docs/src/commands/commands/inline-format.command.ts
@@ -181,11 +181,40 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
IRichTextEditingMutationParams
>(doMutation.id, doMutation.params);
+ const REFRESH_SELECTION_COMMAND_LIST = [
+ SetInlineFormatBoldCommand.id,
+ SetInlineFormatFontSizeCommand.id,
+ SetInlineFormatFontFamilyCommand.id,
+ ];
+
+ /**
+ * refresh selection.
+ */
+ if (REFRESH_SELECTION_COMMAND_LIST.includes(preCommandId)) {
+ textSelectionManagerService.refreshSelection();
+ }
+
if (result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
undoMutations: [{ id: RichTextEditingMutation.id, params: result }],
redoMutations: [{ id: RichTextEditingMutation.id, params: doMutation.params }],
+ undo() {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, result);
+ if (REFRESH_SELECTION_COMMAND_LIST.includes(preCommandId)) {
+ textSelectionManagerService.refreshSelection();
+ }
+
+ return true;
+ },
+ redo() {
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, doMutation.params);
+ if (REFRESH_SELECTION_COMMAND_LIST.includes(preCommandId)) {
+ textSelectionManagerService.refreshSelection();
+ }
+
+ return true;
+ },
});
return true;
diff --git a/packages/base-docs/src/commands/commands/insert-floating-object.command.ts b/packages/base-docs/src/commands/commands/insert-floating-object.command.ts
index 70358873af..9284f4786a 100644
--- a/packages/base-docs/src/commands/commands/insert-floating-object.command.ts
+++ b/packages/base-docs/src/commands/commands/insert-floating-object.command.ts
@@ -17,12 +17,12 @@ export const InsertDrawingCommand: ICommand = {
return false;
}
- const documentId = params.documentId;
+ const { documentId } = params;
const documentModel = univerInstanceService.getUniverDocInstance(documentId);
if (!documentModel) return false;
- const snapshot = documentModel.snapshot;
+ const { snapshot } = documentModel;
if (snapshot == null || snapshot.drawings == null) return false;
const { objectId, drawing } = params;
@@ -45,6 +45,7 @@ export const InsertDrawingCommand: ICommand = {
undoMutations: [{ id: RemoveDrawingMutation.id, params: undoMutationParams }],
redoMutations: [{ id: InsertDrawingMutation.id, params: redoMutationParams }],
});
+
return true;
}
diff --git a/packages/base-docs/src/commands/commands/remove-floating-object.command.ts b/packages/base-docs/src/commands/commands/remove-floating-object.command.ts
index 1ed29e75b8..d2f4f9b40c 100644
--- a/packages/base-docs/src/commands/commands/remove-floating-object.command.ts
+++ b/packages/base-docs/src/commands/commands/remove-floating-object.command.ts
@@ -18,7 +18,7 @@ export const RemoveDrawingCommand: ICommand = {
return false;
}
- const documentId = params.documentId;
+ const { documentId } = params;
const documentModel = univerInstanceService.getUniverDocInstance(documentId);
if (!documentModel) return false;
diff --git a/packages/base-docs/src/controllers/clipboard.controller.ts b/packages/base-docs/src/controllers/clipboard.controller.ts
index 53cb5d109e..b3f179e0b9 100644
--- a/packages/base-docs/src/controllers/clipboard.controller.ts
+++ b/packages/base-docs/src/controllers/clipboard.controller.ts
@@ -97,8 +97,6 @@ export class DocClipboardController extends Disposable {
try {
const body = await clipboard.queryClipboardData();
- this._commandService.executeCommand(InnerPasteCommand.id, { body, segmentId });
-
// When doc has multiple selections, the cursor moves to the last pasted content's end.
let cursor = activeEndOffset;
for (const range of ranges) {
@@ -113,15 +111,16 @@ export class DocClipboardController extends Disposable {
}
}
- // move selection
- this._textSelectionManagerService.replaceTextRanges([
+ const textRanges = [
{
startOffset: cursor,
endOffset: cursor,
collapsed: true,
style,
},
- ]);
+ ];
+
+ this._commandService.executeCommand(InnerPasteCommand.id, { body, segmentId, textRanges });
} catch (_e) {
this._logService.error('[DocClipboardController] clipboard is empty');
}
@@ -243,8 +242,6 @@ export class DocClipboardController extends Disposable {
this._handleCopy();
try {
- this._commandService.executeCommand(InnerCutCommand.id, { segmentId });
-
let cursor = activeEndOffset;
for (const range of ranges) {
const { startOffset, endOffset } = range;
@@ -258,15 +255,16 @@ export class DocClipboardController extends Disposable {
}
}
- // move selection
- this._textSelectionManagerService.replaceTextRanges([
+ const textRanges = [
{
startOffset: cursor,
endOffset: cursor,
collapsed: true,
style,
},
- ]);
+ ];
+
+ this._commandService.executeCommand(InnerCutCommand.id, { segmentId, textRanges });
} catch (e) {
this._logService.error('[DocClipboardController] cut content failed');
}
diff --git a/packages/base-docs/src/controllers/delete.controller.ts b/packages/base-docs/src/controllers/delete.controller.ts
index 29adf6f87f..73af11ad7c 100644
--- a/packages/base-docs/src/controllers/delete.controller.ts
+++ b/packages/base-docs/src/controllers/delete.controller.ts
@@ -122,6 +122,8 @@ export class DeleteController extends Disposable {
return;
}
+ cursor++;
+
const paragraphIndex = paragraph?.startIndex;
const updateParagraph: IParagraph = { startIndex: 0 };
@@ -146,6 +148,15 @@ export class DeleteController extends Disposable {
}
}
+ const textRanges = [
+ {
+ startOffset: cursor,
+ endOffset: cursor,
+ collapsed: true,
+ style,
+ },
+ ];
+
this._commandService.executeCommand(UpdateCommand.id, {
unitId: docsModel.getUnitId(),
updateBody: {
@@ -157,6 +168,7 @@ export class DeleteController extends Disposable {
endOffset: paragraphIndex + 1,
collapsed: true,
},
+ textRanges,
segmentId,
});
} else {
@@ -169,29 +181,25 @@ export class DeleteController extends Disposable {
}
}
+ const textRanges = [
+ {
+ startOffset: cursor,
+ endOffset: cursor,
+ collapsed: true,
+ style,
+ },
+ ];
+
this._commandService.executeCommand(DeleteCommand.id, {
unitId: docsModel.getUnitId(),
range: activeRange,
segmentId,
direction: DeleteDirection.LEFT,
+ textRanges,
});
}
skeleton?.calculate();
-
- if (isUpdateParagraph) {
- cursor++;
- }
-
- // move selection
- this._textSelectionManagerService.replaceTextRanges([
- {
- startOffset: cursor,
- endOffset: cursor,
- collapsed: true,
- style,
- },
- ]);
}
private _handleDeleteRight() {
@@ -212,24 +220,24 @@ export class DeleteController extends Disposable {
return;
}
+ const textRanges = [
+ {
+ startOffset,
+ endOffset: startOffset,
+ collapsed: true,
+ style,
+ },
+ ];
+
this._commandService.executeCommand(DeleteCommand.id, {
unitId: docsModel.getUnitId(),
range: activeRange,
segmentId,
direction: DeleteDirection.RIGHT,
+ textRanges,
});
skeleton?.calculate();
-
- // move selection
- this._textSelectionManagerService.replaceTextRanges([
- {
- startOffset,
- endOffset: startOffset,
- collapsed: true,
- style,
- },
- ]);
}
private _getDocObject() {
diff --git a/packages/base-docs/src/controllers/ime-input.controller.ts b/packages/base-docs/src/controllers/ime-input.controller.ts
index 2a92fd3928..8770d2bee2 100644
--- a/packages/base-docs/src/controllers/ime-input.controller.ts
+++ b/packages/base-docs/src/controllers/ime-input.controller.ts
@@ -1,4 +1,9 @@
-import { IRenderManagerService, ITextRangeWithStyle, ITextSelectionRenderManager } from '@univerjs/base-render';
+import {
+ IEditorInputConfig,
+ IRenderManagerService,
+ ITextRangeWithStyle,
+ ITextSelectionRenderManager,
+} from '@univerjs/base-render';
import {
Disposable,
ICommandService,
@@ -6,13 +11,15 @@ import {
LifecycleStages,
Nullable,
OnLifecycle,
+ Tools,
} from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
import { Subscription } from 'rxjs';
import { getDocObject } from '../basics/component-tools';
-import { IMEInputCommand } from '../commands/commands/core-editing.command';
+import { IMEInputCommand } from '../commands/commands/ime-input.command';
import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
+import { IMEInputManagerService } from '../services/ime-input-manager.service';
import { TextSelectionManagerService } from '../services/text-selection-manager.service';
@OnLifecycle(LifecycleStages.Rendered, IMEInputController)
@@ -33,13 +40,12 @@ export class IMEInputController extends Disposable {
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
+ @Inject(IMEInputManagerService) private readonly _imeInputManagerService: IMEInputManagerService,
@ICommandService private readonly _commandService: ICommandService
) {
super();
this._initialize();
-
- this._commandExecutedListener();
}
override dispose(): void {
@@ -53,9 +59,7 @@ export class IMEInputController extends Disposable {
this._initialOnCompositionUpdate();
- this._onEndSubscription = this._textSelectionRenderManager.onCompositionend$.subscribe((config) => {
- this._resetIME();
- });
+ this._initialOnCompositionend();
}
private _initialOnCompositionstart() {
@@ -70,73 +74,94 @@ export class IMEInputController extends Disposable {
return;
}
+ this._imeInputManagerService.clearUndoRedoMutationParamsCache();
+
+ this._imeInputManagerService.setActiveRange(Tools.deepClone(activeRange));
+
this._previousIMERange = activeRange;
});
}
private _initialOnCompositionUpdate() {
this._onUpdateSubscription = this._textSelectionRenderManager.onCompositionupdate$.subscribe(async (config) => {
- const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
+ this._updateContent(config, true);
+ });
+ }
- if (this._previousIMERange == null || config == null || skeleton == null) {
- return;
- }
+ private _initialOnCompositionend() {
+ this._onEndSubscription = this._textSelectionRenderManager.onCompositionend$.subscribe((config) => {
+ this._updateContent(config, false);
+ });
+ }
- const documentModel = this._currentUniverService.getCurrentUniverDocInstance();
+ private async _updateContent(config: Nullable<IEditorInputConfig>, isUpdate: boolean) {
+ const skeleton = this._docSkeletonManagerService.getCurrent()?.skeleton;
- const { event, activeRange } = config;
+ if (this._previousIMERange == null || config == null || skeleton == null) {
+ return;
+ }
- const { startOffset, endOffset, segmentId, style } = this._previousIMERange;
+ const documentModel = this._currentUniverService.getCurrentUniverDocInstance();
- if (skeleton == null || activeRange == null) {
- return;
- }
+ const { event, activeRange } = config;
- const e = event as CompositionEvent;
+ const { startOffset, segmentId, style } = this._previousIMERange;
- const content = e.data;
+ if (skeleton == null || activeRange == null) {
+ return;
+ }
- if (content === this._previousIMEContent) {
- return;
- }
+ const e = event as CompositionEvent;
+
+ const content = e.data;
- await this._commandService.executeCommand(IMEInputCommand.id, {
- unitId: documentModel.getUnitId(),
- newText: content,
- oldTextLen: this._previousIMEContent.length,
- range: this._previousIMERange,
- segmentId,
- });
+ if (content === this._previousIMEContent && isUpdate) {
+ return;
+ }
- skeleton.calculate();
+ const len = content.length;
- const len = content.length;
+ const textRanges = [
+ {
+ startOffset: startOffset + len,
+ endOffset: startOffset + len,
+ collapsed: true,
+ style,
+ },
+ ];
- // move selection
- this._textSelectionManagerService.replaceTextRanges([
- {
- startOffset: startOffset + len,
- endOffset: endOffset + len,
- collapsed: true,
- style,
- },
- ]);
+ await this._commandService.executeCommand(IMEInputCommand.id, {
+ unitId: documentModel.getUnitId(),
+ newText: content,
+ oldTextLen: this._previousIMEContent.length,
+ range: this._previousIMERange,
+ textRanges,
+ isCompositionEnd: !isUpdate,
+ segmentId,
+ });
+ skeleton.calculate();
+
+ if (isUpdate) {
if (!this._previousIMERange.collapsed) {
this._previousIMERange.collapsed = true;
}
this._previousIMEContent = content;
- });
+ } else {
+ this._resetIME();
+ }
}
private _resetIME() {
this._previousIMEContent = '';
this._previousIMERange = null;
- }
- private _commandExecutedListener() {}
+ this._imeInputManagerService.clearUndoRedoMutationParamsCache();
+
+ this._imeInputManagerService.setActiveRange(null);
+ }
private _getDocObject() {
return getDocObject(this._currentUniverService, this._renderManagerService);
diff --git a/packages/base-docs/src/controllers/inline-format.controller.ts b/packages/base-docs/src/controllers/inline-format.controller.ts
index e834262f91..1629cdad07 100644
--- a/packages/base-docs/src/controllers/inline-format.controller.ts
+++ b/packages/base-docs/src/controllers/inline-format.controller.ts
@@ -73,18 +73,5 @@ export class InlineFormatController extends Disposable {
preCommandId: command.id,
...(command.params ?? {}),
});
-
- const REFRESH_SELECTION_COMMAND_LIST = [
- SetInlineFormatBoldCommand.id,
- SetInlineFormatFontSizeCommand.id,
- SetInlineFormatFontFamilyCommand.id,
- ];
-
- /**
- * refresh selection.
- */
- if (REFRESH_SELECTION_COMMAND_LIST.includes(command.id)) {
- this._textSelectionManagerService.refreshSelection();
- }
}
}
diff --git a/packages/base-docs/src/controllers/line-break-input.controller.ts b/packages/base-docs/src/controllers/line-break-input.controller.ts
index 3c05c88aa4..d8cf25e210 100644
--- a/packages/base-docs/src/controllers/line-break-input.controller.ts
+++ b/packages/base-docs/src/controllers/line-break-input.controller.ts
@@ -88,6 +88,15 @@ export class LineBreakInputController extends Disposable {
const unitId = docsModel.getUnitId();
const { startOffset, segmentId, style } = activeRange;
+ // move selection
+ const textRanges = [
+ {
+ startOffset: startOffset + 1,
+ endOffset: startOffset + 1,
+ collapsed: true,
+ style,
+ },
+ ];
// split paragraph
this._commandService.executeCommand(InsertCommand.id, {
@@ -97,20 +106,11 @@ export class LineBreakInputController extends Disposable {
paragraphs: generateParagraphs(DataStreamTreeTokenType.PARAGRAPH),
},
range: activeRange,
+ textRanges,
segmentId,
});
skeleton?.calculate();
-
- // move selection
- this._textSelectionManagerService.replaceTextRanges([
- {
- startOffset: startOffset + 1,
- endOffset: startOffset + 1,
- collapsed: true,
- style,
- },
- ]);
}
private _getDocObject() {
diff --git a/packages/base-docs/src/controllers/normal-input.controller.ts b/packages/base-docs/src/controllers/normal-input.controller.ts
index a488a2bc49..5d744dfadf 100644
--- a/packages/base-docs/src/controllers/normal-input.controller.ts
+++ b/packages/base-docs/src/controllers/normal-input.controller.ts
@@ -66,28 +66,28 @@ export class NormalInputController extends Disposable {
const { startOffset, segmentId, style } = activeRange;
+ const len = content.length;
+
+ const textRanges = [
+ {
+ startOffset: startOffset + len,
+ endOffset: startOffset + len,
+ collapsed: true,
+ style,
+ },
+ ];
+
await this._commandService.executeCommand(InsertCommand.id, {
unitId: documentModel.getUnitId(),
body: {
dataStream: content,
},
range: activeRange,
+ textRanges,
segmentId,
});
skeleton.calculate();
-
- const len = content.length;
-
- // move selection
- this._textSelectionManagerService.replaceTextRanges([
- {
- startOffset: startOffset + len,
- endOffset: startOffset + len,
- collapsed: true,
- style,
- },
- ]);
});
}
diff --git a/packages/base-docs/src/controllers/zoom.cotroller.ts b/packages/base-docs/src/controllers/zoom.controller.ts
similarity index 100%
rename from packages/base-docs/src/controllers/zoom.cotroller.ts
rename to packages/base-docs/src/controllers/zoom.controller.ts
diff --git a/packages/base-docs/src/doc-plugin.ts b/packages/base-docs/src/doc-plugin.ts
index 75ef2399a2..e26b9e166b 100644
--- a/packages/base-docs/src/doc-plugin.ts
+++ b/packages/base-docs/src/doc-plugin.ts
@@ -18,10 +18,10 @@ import {
DeleteCommand,
DeleteLeftCommand,
DeleteRightCommand,
- IMEInputCommand,
InsertCommand,
UpdateCommand,
} from './commands/commands/core-editing.command';
+import { IMEInputCommand } from './commands/commands/ime-input.command';
import {
SetInlineFormatBoldCommand,
SetInlineFormatCommand,
@@ -48,10 +48,11 @@ import { MoveCursorController } from './controllers/move-cursor.controller';
import { NormalInputController } from './controllers/normal-input.controller';
import { PageRenderController } from './controllers/page-render.controller';
import { TextSelectionController } from './controllers/text-selection.controller';
-import { ZoomController } from './controllers/zoom.cotroller';
+import { ZoomController } from './controllers/zoom.controller';
import { enUS } from './locale';
import { DocClipboardService, IDocClipboardService } from './services/clipboard/clipboard.service';
import { DocSkeletonManagerService } from './services/doc-skeleton-manager.service';
+import { IMEInputManagerService } from './services/ime-input-manager.service';
import { TextSelectionManagerService } from './services/text-selection-manager.service';
import { BreakLineShortcut, DeleteLeftShortcut, DeleteRightShortcut } from './shortcuts/core-editing.shortcut';
import {
@@ -164,6 +165,7 @@ export class DocPlugin extends Plugin {
// services
[DocSkeletonManagerService],
+ [IMEInputManagerService],
[
IDocClipboardService,
{
diff --git a/packages/base-docs/src/index.ts b/packages/base-docs/src/index.ts
index e30bcb6899..de757ea4de 100644
--- a/packages/base-docs/src/index.ts
+++ b/packages/base-docs/src/index.ts
@@ -5,17 +5,15 @@ export { DocCopyCommand, DocCutCommand, DocPasteCommand } from './commands/comma
export {
CoverCommand,
DeleteCommand,
- getRetainAndDeleteFromReplace,
type ICoverCommandParams,
type IDeleteCommandParams,
- type IIMEInputCommandParams,
type IInsertCommandParams,
- IMEInputCommand,
InsertCommand,
type IUpdateCommandParams,
UpdateCommand,
} from './commands/commands/core-editing.command';
export { BreakLineCommand, DeleteLeftCommand } from './commands/commands/core-editing.command';
+export { type IIMEInputCommandParams, IMEInputCommand } from './commands/commands/ime-input.command';
export {
SetInlineFormatBoldCommand,
SetInlineFormatCommand,
diff --git a/packages/base-docs/src/services/ime-input-manager.service.ts b/packages/base-docs/src/services/ime-input-manager.service.ts
new file mode 100644
index 0000000000..06b0ca03a5
--- /dev/null
+++ b/packages/base-docs/src/services/ime-input-manager.service.ts
@@ -0,0 +1,99 @@
+import { ITextRangeWithStyle } from '@univerjs/base-render';
+import { Nullable } from '@univerjs/core';
+import { IDisposable } from '@wendellhu/redi';
+
+import { getRetainAndDeleteFromReplace } from '../basics/retain-delete-params';
+import { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';
+
+// Used to record all intermediate states when typing with IME,
+// and then output the entire undo and redo operations.
+export class IMEInputManagerService implements IDisposable {
+ private _previousActiveRange: Nullable<ITextRangeWithStyle> = null;
+ private _undoMutationParamsCache: IRichTextEditingMutationParams[] = [];
+ private _redoMutationParamsCache: IRichTextEditingMutationParams[] = [];
+
+ clearUndoRedoMutationParamsCache() {
+ this._undoMutationParamsCache = [];
+ this._redoMutationParamsCache = [];
+ }
+
+ setActiveRange(range: Nullable<ITextRangeWithStyle>) {
+ this._previousActiveRange = range;
+ }
+
+ pushUndoRedoMutationParams(undoParams: IRichTextEditingMutationParams, redoParams: IRichTextEditingMutationParams) {
+ this._undoMutationParamsCache.push(undoParams);
+ this._redoMutationParamsCache.push(redoParams);
+ }
+
+ fetchComposedUndoRedoMutationParams(newText: string) {
+ if (this._undoMutationParamsCache.length === 0 || this._previousActiveRange == null) {
+ return null;
+ }
+
+ const { unitId } = this._undoMutationParamsCache[0];
+ const { segmentId, startOffset, collapsed } = this._previousActiveRange;
+
+ const undoMutationParams: IRichTextEditingMutationParams = {
+ unitId,
+ mutations: [],
+ };
+
+ const redoMutationParams: IRichTextEditingMutationParams = {
+ unitId,
+ mutations: [],
+ };
+
+ if (collapsed) {
+ undoMutationParams.mutations.push({
+ t: 'r',
+ len: startOffset,
+ segmentId,
+ });
+ redoMutationParams.mutations.push({
+ t: 'r',
+ len: startOffset,
+ segmentId,
+ });
+ } else {
+ if (startOffset > 0) {
+ undoMutationParams.mutations.push({
+ t: 'r',
+ len: startOffset,
+ segmentId,
+ });
+ }
+
+ undoMutationParams.mutations.push(this._undoMutationParamsCache[0].mutations.find((m) => m.t === 'i')!);
+
+ redoMutationParams.mutations.push(...getRetainAndDeleteFromReplace(this._previousActiveRange, segmentId));
+ }
+
+ if (newText.length) {
+ undoMutationParams.mutations.push({
+ t: 'd',
+ len: newText.length,
+ line: 0,
+ segmentId,
+ });
+
+ redoMutationParams.mutations.push({
+ t: 'i',
+ body: {
+ dataStream: newText,
+ },
+ len: newText.length,
+ line: 0,
+ segmentId,
+ });
+ }
+
+ return { redoMutationParams, undoMutationParams, previousActiveRange: this._previousActiveRange };
+ }
+
+ dispose(): void {
+ this._undoMutationParamsCache = [];
+ this._redoMutationParamsCache = [];
+ this._previousActiveRange = null;
+ }
+}
diff --git a/packages/base-docs/src/services/text-selection-manager.service.ts b/packages/base-docs/src/services/text-selection-manager.service.ts
index 8bee373227..fce9215355 100644
--- a/packages/base-docs/src/services/text-selection-manager.service.ts
+++ b/packages/base-docs/src/services/text-selection-manager.service.ts
@@ -127,7 +127,7 @@ export class TextSelectionManagerService implements IDisposable {
}
// It is will being opened when it needs to be used
- private clear(): void {
+ private _clear(): void {
if (this._currentSelection == null) {
return;
}
@@ -136,7 +136,7 @@ export class TextSelectionManagerService implements IDisposable {
}
// It is will being opened when it needs to be used
- private remove(index: number): void {
+ private _remove(index: number): void {
if (this._currentSelection == null) {
return;
}
@@ -145,7 +145,7 @@ export class TextSelectionManagerService implements IDisposable {
}
// It is will being opened when it needs to be used
- private reset() {
+ private _reset() {
if (this._currentSelection == null) {
return;
}
@@ -161,7 +161,7 @@ export class TextSelectionManagerService implements IDisposable {
}
// It is will being opened when it needs to be used
- private resetPlugin() {
+ private _resetPlugin() {
if (this._currentSelection == null) {
return;
}
@@ -222,12 +222,7 @@ export class TextSelectionManagerService implements IDisposable {
const unitTextRange = this._textSelectionInfo.get(pluginName)!;
- if (!unitTextRange.has(unitId)) {
- unitTextRange.set(unitId, textRanges);
- } else {
- const OldTextRanges = unitTextRange.get(unitId)!;
- OldTextRanges.splice(0, OldTextRanges.length, ...textRanges);
- }
+ unitTextRange.set(unitId, textRanges);
}
private _clearByParam(param: ITextSelectionManagerSearchParam): void {
diff --git a/packages/common-plugin-data/src/docs/default-document-data-cn.ts b/packages/common-plugin-data/src/docs/default-document-data-cn.ts
index f52d92db48..afcf66a68b 100644
--- a/packages/common-plugin-data/src/docs/default-document-data-cn.ts
+++ b/packages/common-plugin-data/src/docs/default-document-data-cn.ts
@@ -4,7 +4,7 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {
id: 'd',
body: {
dataStream:
- '零.  开篇\r上标和小标:HO2 5X 删除线:我是被删除的内容 下划线:我是下划线\r这篇文章旨在帮助新人快速熟悉开源项目univer的架构及代码,也是我过去一段时间参与到 univer 开发中的学习和总结,肯定有不够准确或者理解偏差,欢迎大家评论指正\r第壹章,会聊聊我对univer架构的理解,univer是如何拆分模块,以及模块之间的依赖关系。然后将univer放入MMV的架构模式中,分别分析下其模型层、视图层、控制器的边界和职责\r第贰章,我们先来看看 univer sheet 的模型层数据结构设计,如何区分 workbook、sheet、row、column、style 等,了解他们的包含关系,这对后面深入理解代码是有帮助的\r第叁、肆章,我将从两条控制链路来分析 univer 的代码,一条链路是 univer 启动和初始化渲染的过程。在这条链路中,是从模型层到视图层的过程。另外一条链路是 univer 响应用户事件,并且触发模型层数据变更,页面重新渲染,在这条链路中,是从视图层到模型层的过程。在这两部分,我们会涉及到大量的源码分析,在保留代码主逻辑的前提,删除了边界 case 的代码。同时在每个代码块第一行,表示该代码块所在的 TS 文件,这样便于直接阅读源码\r\n',
+ '零.  开篇\r上标和下标:HO2 5X 删除线:我是被删除的内容 下划线:我是下划线\r这篇文章旨在帮助新人快速熟悉开源项目univer的架构及代码,也是我过去一段时间参与到 univer 开发中的学习和总结,肯定有不够准确或者理解偏差,欢迎大家评论指正\r第壹章,会聊聊我对univer架构的理解,univer是如何拆分模块,以及模块之间的依赖关系。然后将univer放入MMV的架构模式中,分别分析下其模型层、视图层、控制器的边界和职责\r第贰章,我们先来看看 univer sheet 的模型层数据结构设计,如何区分 workbook、sheet、row、column、style 等,了解他们的包含关系,这对后面深入理解代码是有帮助的\r第叁、肆章,我将从两条控制链路来分析 univer 的代码,一条链路是 univer 启动和初始化渲染的过程。在这条链路中,是从模型层到视图层的过程。另外一条链路是 univer 响应用户事件,并且触发模型层数据变更,页面重新渲染,在这条链路中,是从视图层到模型层的过程。在这两部分,我们会涉及到大量的源码分析,在保留代码主逻辑的前提,删除了边界 case 的代码。同时在每个代码块第一行,表示该代码块所在的 TS 文件,这样便于直接阅读源码\r\n',
textRuns: [
{
st: 0,