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: history in document (#1329)

Ran Luod3d0804f3873
diff --git a/.vscode/settings.json b/.vscode/settings.json
index f842782072..d42c63275b 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -10,6 +10,7 @@
"clazz",
"clsx",
"codelf",
+ "Collab",
"commitlint",
"compositionend",
"compositionstart",
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index a3dbf53906..5d82f1587d 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -95,6 +95,8 @@ export {
LocalUndoRedoService,
RedoCommand,
UndoCommand,
+ RedoCommandId,
+ UndoCommandId,
} from './services/undoredo/undoredo.service';
export * from './shared';
diff --git a/packages/core/src/services/undoredo/undoredo.service.ts b/packages/core/src/services/undoredo/undoredo.service.ts
index 62ad7abbcd..73cc57cd1a 100644
--- a/packages/core/src/services/undoredo/undoredo.service.ts
+++ b/packages/core/src/services/undoredo/undoredo.service.ts
@@ -68,6 +68,69 @@ export interface IUndoRedoStatus {
const STACK_CAPACITY = 20;
+abstract class MultiImplementationCommand implements IDisposable {
+ dispose(): void {}
+
+ async dispatchToHandlers(): Promise<boolean> {
+ return false;
+ }
+}
+
+export const RedoCommandId = 'univer.command.redo';
+export const UndoCommandId = 'univer.command.undo';
+
+export const UndoCommand = new (class extends MultiImplementationCommand implements ICommand {
+ readonly type = CommandType.COMMAND;
+
+ readonly id = UndoCommandId;
+
+ async handler(accessor: IAccessor) {
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const element = undoRedoService.pitchTopUndoElement();
+ if (!element) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ const result = element.undo
+ ? await element.undo(element.undoMutations)
+ : sequenceExecute(element.undoMutations, commandService);
+ if (result) {
+ undoRedoService.popUndoToRedo();
+
+ return true;
+ }
+
+ return false;
+ }
+})();
+
+export const RedoCommand = new (class extends MultiImplementationCommand implements ICommand {
+ readonly type = CommandType.COMMAND;
+
+ readonly id = RedoCommandId;
+
+ async handler(accessor: IAccessor) {
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const element = undoRedoService.pitchTopRedoElement();
+ if (!element) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ const result = element.redo
+ ? await element.redo(element.redoMutations)
+ : sequenceExecute(element.redoMutations, commandService);
+ if (result) {
+ undoRedoService.popRedoToUndo();
+
+ return true;
+ }
+
+ return false;
+ }
+})();
+
/**
* This UndoRedoService is local.
*/
@@ -242,63 +305,3 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
return unitID;
}
}
-
-abstract class MultiImplementationCommand implements IDisposable {
- dispose(): void {}
-
- async dispatchToHandlers(): Promise<boolean> {
- return false;
- }
-}
-
-export const UndoCommand = new (class extends MultiImplementationCommand implements ICommand {
- readonly type = CommandType.COMMAND;
-
- readonly id = 'univer.command.undo';
-
- async handler(accessor: IAccessor) {
- const undoRedoService = accessor.get(IUndoRedoService);
- const element = undoRedoService.pitchTopUndoElement();
- if (!element) {
- return false;
- }
-
- const commandService = accessor.get(ICommandService);
- const result = element.undo
- ? await element.undo(element.undoMutations)
- : sequenceExecute(element.undoMutations, commandService);
- if (result) {
- undoRedoService.popUndoToRedo();
-
- return true;
- }
-
- return false;
- }
-})();
-
-export const RedoCommand = new (class extends MultiImplementationCommand implements ICommand {
- readonly type = CommandType.COMMAND;
-
- readonly id = 'univer.command.redo';
-
- async handler(accessor: IAccessor) {
- const undoRedoService = accessor.get(IUndoRedoService);
- const element = undoRedoService.pitchTopRedoElement();
- if (!element) {
- return false;
- }
-
- const commandService = accessor.get(ICommandService);
- const result = element.redo
- ? await element.redo(element.redoMutations)
- : sequenceExecute(element.redoMutations, commandService);
- if (result) {
- undoRedoService.popRedoToUndo();
-
- return true;
- }
-
- return false;
- }
-})();
diff --git a/packages/docs/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/docs/src/commands/commands/__tests__/create-command-test-bed.ts
index 8b35620863..0d1d0a2982 100644
--- a/packages/docs/src/commands/commands/__tests__/create-command-test-bed.ts
+++ b/packages/docs/src/commands/commands/__tests__/create-command-test-bed.ts
@@ -29,6 +29,8 @@ import { Inject, Injector } from '@wendellhu/redi';
import { DocViewModelManagerService } from '../../../services/doc-view-model-manager.service';
import { TextSelectionManagerService } from '../../../services/text-selection-manager.service';
+import { DocStateChangeManagerService } from '../../../services/doc-state-change-manager.service';
+import { IMEInputManagerService } from '../../../services/ime-input-manager.service';
import { ITextSelectionRenderManager, TextSelectionRenderManager } from './mock-text-selection-render-manager';
const TEST_DOCUMENT_DATA_EN: IDocumentData = {
@@ -110,6 +112,8 @@ export function createCommandTestBed(workbookConfig?: IDocumentData, dependencie
override onStarting(injector: Injector): void {
injector.add([TextSelectionManagerService]);
injector.add([DocViewModelManagerService]);
+ injector.add([DocStateChangeManagerService]);
+ injector.add([IMEInputManagerService]);
injector.add([
ITextSelectionRenderManager,
{
diff --git a/packages/docs/src/commands/commands/clipboard.inner.command.ts b/packages/docs/src/commands/commands/clipboard.inner.command.ts
index 9b24794011..236c414934 100644
--- a/packages/docs/src/commands/commands/clipboard.inner.command.ts
+++ b/packages/docs/src/commands/commands/clipboard.inner.command.ts
@@ -26,7 +26,6 @@ import {
CommandType,
getDocsUpdateBody,
ICommandService,
- IUndoRedoService,
IUniverInstanceService,
MemoryCursor,
TextX,
@@ -53,7 +52,6 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
handler: async (accessor, params: IInnerPasteCommandParams) => {
const { segmentId, body, textRanges } = params;
- const undoRedoService = accessor.get(IUndoRedoService);
const commandService = accessor.get(ICommandService);
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const currentUniverService = accessor.get(IUniverInstanceService);
@@ -72,6 +70,7 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {
params: {
unitId,
actions: [],
+ textRanges,
},
};
@@ -115,33 +114,7 @@ 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;
- }
-
- return false;
+ return Boolean(result);
},
};
@@ -157,7 +130,6 @@ export const CutContentCommand: ICommand<IInnerCutCommandParams> = {
handler: async (accessor, params: IInnerCutCommandParams) => {
const { segmentId, textRanges } = params;
- const undoRedoService = accessor.get(IUndoRedoService);
const commandService = accessor.get(ICommandService);
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const currentUniverService = accessor.get(IUniverInstanceService);
@@ -183,6 +155,7 @@ export const CutContentCommand: ICommand<IInnerCutCommandParams> = {
params: {
unitId,
actions: [],
+ textRanges,
},
};
@@ -218,33 +191,7 @@ export const CutContentCommand: 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;
- }
-
- return false;
+ return Boolean(result);
},
};
diff --git a/packages/docs/src/commands/commands/core-editing.command.ts b/packages/docs/src/commands/commands/core-editing.command.ts
index 102047f371..f47eab7a84 100644
--- a/packages/docs/src/commands/commands/core-editing.command.ts
+++ b/packages/docs/src/commands/commands/core-editing.command.ts
@@ -22,11 +22,10 @@ import type {
ITextRange,
UpdateDocsAttributeType,
} from '@univerjs/core';
-import { CommandType, ICommandService, IUndoRedoService, TextX, TextXActionType } from '@univerjs/core';
+import { CommandType, ICommandService, TextX, TextXActionType } from '@univerjs/core';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';
-import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';
import { RichTextEditingMutation } from '../mutations/core-editing.mutation';
@@ -47,9 +46,7 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
type: CommandType.COMMAND,
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, textRanges } = params;
const { startOffset, collapsed } = range;
@@ -59,6 +56,7 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
params: {
unitId,
actions: [],
+ textRanges,
},
};
@@ -91,33 +89,7 @@ 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;
- }
-
- return false;
+ return Boolean(result);
},
};
@@ -145,8 +117,6 @@ export const DeleteCommand: ICommand<IDeleteCommandParams> = {
handler: async (accessor, params: IDeleteCommandParams) => {
const commandService = accessor.get(ICommandService);
- const undoRedoService = accessor.get(IUndoRedoService);
- const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const { range, segmentId, unitId, direction, textRanges, len = 1 } = params;
@@ -157,6 +127,7 @@ export const DeleteCommand: ICommand<IDeleteCommandParams> = {
params: {
unitId,
actions: [],
+ textRanges,
},
};
@@ -184,32 +155,7 @@ 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;
- }
-
- return false;
+ return Boolean(result);
},
};
@@ -233,14 +179,13 @@ export const UpdateCommand: ICommand<IUpdateCommandParams> = {
handler: async (accessor, params: IUpdateCommandParams) => {
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,
params: {
unitId,
actions: [],
+ textRanges,
},
};
@@ -269,33 +214,7 @@ 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);
-
- textSelectionManagerService.replaceTextRanges(textRanges);
-
- return true;
- },
- redo() {
- commandService.syncExecuteCommand(RichTextEditingMutation.id, doMutation.params);
-
- textSelectionManagerService.replaceTextRanges(textRanges);
-
- return true;
- },
- });
-
- return true;
- }
-
- return false;
+ return Boolean(result);
},
};
diff --git a/packages/docs/src/commands/commands/delete.command.ts b/packages/docs/src/commands/commands/delete.command.ts
index 06e7bc9531..d9088e691a 100644
--- a/packages/docs/src/commands/commands/delete.command.ts
+++ b/packages/docs/src/commands/commands/delete.command.ts
@@ -24,7 +24,7 @@ import {
TextXActionType,
UpdateDocsAttributeType,
} from '@univerjs/core';
-import type { IActiveTextRange, TextRange } from '@univerjs/engine-render';
+import type { IActiveTextRange, ITextRangeWithStyle, TextRange } from '@univerjs/engine-render';
import { getParagraphBySpan, hasListSpan, isFirstSpan, isIndentBySpan } from '@univerjs/engine-render';
import { DocSkeletonManagerService } from '../../services/doc-skeleton-manager.service';
@@ -297,13 +297,15 @@ export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {
endOffset: cursor,
style,
},
- ];
+ ] as ITextRangeWithStyle[];
const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {
id: RichTextEditingMutation.id,
params: {
unitId,
actions: [],
+ textRanges,
+ prevTextRanges: [range],
},
};
@@ -345,33 +347,7 @@ export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {
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;
- }
-
- return false;
+ return Boolean(result);
},
};
diff --git a/packages/docs/src/commands/commands/ime-input.command.ts b/packages/docs/src/commands/commands/ime-input.command.ts
index bddd435af3..183e31c8b9 100644
--- a/packages/docs/src/commands/commands/ime-input.command.ts
+++ b/packages/docs/src/commands/commands/ime-input.command.ts
@@ -15,12 +15,11 @@
*/
import type { ICommand, ICommandInfo, ITextRange } from '@univerjs/core';
-import { CommandType, ICommandService, IUndoRedoService, TextX, TextXActionType } from '@univerjs/core';
+import { CommandType, ICommandService, TextX, TextXActionType } from '@univerjs/core';
import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';
import { IMEInputManagerService } from '../../services/ime-input-manager.service';
-import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';
import { RichTextEditingMutation } from '../mutations/core-editing.mutation';
@@ -42,8 +41,6 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
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> = {
@@ -51,6 +48,7 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
params: {
unitId,
actions: [],
+ textRanges,
},
};
@@ -87,6 +85,10 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
doMutation.params!.actions = textX.serialize();
+ doMutation.params!.noHistory = !isCompositionEnd;
+
+ doMutation.params!.isCompositionEnd = isCompositionEnd;
+
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
IRichTextEditingMutationParams
@@ -94,44 +96,6 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
imeInputManagerService.pushUndoRedoMutationParams(result, doMutation.params!);
- textSelectionManagerService.replaceTextRanges(textRanges);
-
- if (isCompositionEnd) {
- if (result) {
- const historyParams = imeInputManagerService.fetchComposedUndoRedoMutationParams();
-
- 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;
+ return Boolean(result);
},
};
diff --git a/packages/docs/src/commands/commands/inline-format.command.ts b/packages/docs/src/commands/commands/inline-format.command.ts
index 8377d135b7..4d3c63fa8f 100644
--- a/packages/docs/src/commands/commands/inline-format.command.ts
+++ b/packages/docs/src/commands/commands/inline-format.command.ts
@@ -22,7 +22,6 @@ import {
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
ICommandService,
- IUndoRedoService,
IUniverInstanceService,
MemoryCursor,
TextX,
@@ -111,7 +110,6 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
type: CommandType.COMMAND,
handler: async (accessor, params: ISetInlineFormatCommandParams) => {
const { segmentId, value, preCommandId } = params;
- const undoRedoService = accessor.get(IUndoRedoService);
const commandService = accessor.get(ICommandService);
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const currentUniverService = accessor.get(IUniverInstanceService);
@@ -173,6 +171,7 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
params: {
unitId,
actions: [],
+ textRanges: selections,
},
};
@@ -226,48 +225,7 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
IRichTextEditingMutationParams
>(doMutation.id, doMutation.params);
- const REFRESH_SELECTION_COMMAND_LIST = [
- SetInlineFormatBoldCommand.id,
- SetInlineFormatFontSizeCommand.id,
- SetInlineFormatFontFamilyCommand.id,
- SetInlineFormatSubscriptCommand.id,
- SetInlineFormatSuperscriptCommand.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;
- }
-
- return false;
+ return Boolean(result);
},
};
diff --git a/packages/docs/src/commands/commands/list.command.ts b/packages/docs/src/commands/commands/list.command.ts
index cd8c6a8c0c..33313bd109 100644
--- a/packages/docs/src/commands/commands/list.command.ts
+++ b/packages/docs/src/commands/commands/list.command.ts
@@ -18,7 +18,6 @@ import type { ICommand, IMutationInfo, IParagraph } from '@univerjs/core';
import {
CommandType,
ICommandService,
- IUndoRedoService,
IUniverInstanceService,
MemoryCursor,
PresetListType,
@@ -27,7 +26,7 @@ import {
Tools,
UpdateDocsAttributeType,
} from '@univerjs/core';
-import type { IActiveTextRange } from '@univerjs/engine-render';
+import type { IActiveTextRange, ITextRangeWithStyle } from '@univerjs/engine-render';
import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';
@@ -78,13 +77,13 @@ export const ListOperationCommand: ICommand<IListOperationCommandParams> = {
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
const currentUniverService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
- const undoRedoService = accessor.get(IUndoRedoService);
const { listType } = params;
const dataModel = currentUniverService.getCurrentUniverDocInstance();
const activeRange = textSelectionManagerService.getActiveRange();
+ const selections = textSelectionManagerService.getSelections();
const paragraphs = dataModel.getBody()?.paragraphs;
if (activeRange == null || paragraphs == null) {
@@ -120,6 +119,7 @@ export const ListOperationCommand: ICommand<IListOperationCommandParams> = {
params: {
unitId,
actions: [],
+ textRanges: selections as unknown as ITextRangeWithStyle[],
},
};
@@ -186,33 +186,7 @@ export const ListOperationCommand: ICommand<IListOperationCommandParams> = {
IRichTextEditingMutationParams
>(doMutation.id, doMutation.params);
- 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);
-
- textSelectionManagerService.refreshSelection();
-
- return true;
- },
- redo() {
- commandService.syncExecuteCommand(RichTextEditingMutation.id, doMutation.params);
-
- textSelectionManagerService.refreshSelection();
-
- return true;
- },
- });
-
- return true;
- }
-
- return true;
+ return Boolean(result);
},
};
diff --git a/packages/docs/src/commands/commands/replace-content.command.ts b/packages/docs/src/commands/commands/replace-content.command.ts
index d347629fa4..6c03db733c 100644
--- a/packages/docs/src/commands/commands/replace-content.command.ts
+++ b/packages/docs/src/commands/commands/replace-content.command.ts
@@ -40,7 +40,6 @@ export const ReplaceContentCommand: ICommand<IReplaceContentCommandParams> = {
const univerInstanceService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
- const undoRedoService = accessor.get(IUndoRedoService);
const prevBody = univerInstanceService.getUniverDocInstance(unitId)?.getSnapshot().body;
const selections = textSelectionManagerService.getSelections();
@@ -55,38 +54,14 @@ export const ReplaceContentCommand: ICommand<IReplaceContentCommandParams> = {
const doMutation = getMutationParams(unitId, segmentId, prevBody, body);
+ doMutation.params.textRanges = textRanges;
+
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
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;
- }
-
- return false;
+ return Boolean(result);
},
};
@@ -116,6 +91,10 @@ export const CoverContentCommand: ICommand<ICoverContentCommandParams> = {
const doMutation = getMutationParams(unitId, segmentId, prevBody, body);
+ // No need to set the cursor or selection.
+ doMutation.params.noNeedSetTextRange = true;
+ doMutation.params.noHistory = true;
+
commandService.syncExecuteCommand<IRichTextEditingMutationParams, IRichTextEditingMutationParams>(
doMutation.id,
doMutation.params
@@ -133,6 +112,7 @@ function getMutationParams(unitId: string, segmentId: string, prevBody: IDocumen
params: {
unitId,
actions: [],
+ textRanges: [],
},
};
diff --git a/packages/docs/src/commands/mutations/core-editing.mutation.ts b/packages/docs/src/commands/mutations/core-editing.mutation.ts
index f2d4d04759..169a80f63b 100644
--- a/packages/docs/src/commands/mutations/core-editing.mutation.ts
+++ b/packages/docs/src/commands/mutations/core-editing.mutation.ts
@@ -14,32 +14,52 @@
* limitations under the License.
*/
-import { CommandType, type IMutation, IUniverInstanceService, type TextXAction } from '@univerjs/core';
+import { CommandType, IUniverInstanceService } from '@univerjs/core';
+import type { IMutation, IMutationCommonParams, Nullable, TextXAction } from '@univerjs/core';
+import type { ITextRangeWithStyle } from '@univerjs/engine-render';
import { DocViewModelManagerService } from '../../services/doc-view-model-manager.service';
+import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
+import type { IDocStateChangeParams } from '../../services/doc-state-change-manager.service';
+import { DocStateChangeManagerService } from '../../services/doc-state-change-manager.service';
+import { IMEInputManagerService } from '../../services/ime-input-manager.service';
-export interface IRichTextEditingMutationParams {
+export interface IRichTextEditingMutationParams extends IMutationCommonParams {
unitId: string;
actions: TextXAction[];
+ textRanges: Nullable<ITextRangeWithStyle[]>;
+ prevTextRanges?: Nullable<ITextRangeWithStyle[]>;
+ noNeedSetTextRange?: boolean;
+ noHistory?: boolean;
+ isCompositionEnd?: boolean;
}
+const RichTextEditingMutationId = 'doc.mutation.rich-text-editing';
+
/**
* The core mutator to change rich text actions. The execution result would be undo mutation params. Could be directly
* send to undo redo service (will be used by the triggering command).
*/
export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams, IRichTextEditingMutationParams> = {
- id: 'doc.mutation.rich-text-editing',
+ id: RichTextEditingMutationId,
type: CommandType.MUTATION,
handler: (accessor, params) => {
- const { unitId, actions } = params;
+ const { unitId, actions, textRanges, prevTextRanges, trigger, noNeedSetTextRange, noHistory, isCompositionEnd } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
const documentDataModel = univerInstanceService.getUniverDocInstance(unitId);
const docViewModelManagerService = accessor.get(DocViewModelManagerService);
const documentViewModel = docViewModelManagerService.getViewModel(unitId);
+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);
+ const selections = textSelectionManagerService.getSelections();
+
+ const docStateChangeManagerService = accessor.get(DocStateChangeManagerService);
+
+ const imeInputManagerService = accessor.get(IMEInputManagerService);
+
if (documentDataModel == null || documentViewModel == null) {
throw new Error(`DocumentDataModel or documentViewModel not found for unitId: ${unitId}`);
}
@@ -49,7 +69,7 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
}
// Step 1: Update Doc Data Model.
- const undoMutations = documentDataModel.apply(actions);
+ const undoActions = documentDataModel.apply(actions);
// Step 2: Update Doc View Model.
const { segmentId } = actions[0];
@@ -58,9 +78,51 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
segmentViewModel.reset(segmentDocumentDataModel);
+ // Step 3: Update cursor & selection.
+ if (!noNeedSetTextRange && textRanges) {
+ // Update selection in the next frame.
+ requestAnimationFrame(() => {
+ textSelectionManagerService.replaceTextRanges(textRanges);
+ });
+ }
+
+ // Step 4: emit state change event.
+ const changeState: IDocStateChangeParams = {
+ commandId: RichTextEditingMutationId,
+ unitId,
+ trigger,
+ noHistory,
+ redoState: {
+ actions,
+ textRanges,
+ },
+ undoState: {
+ actions: undoActions,
+ // TODO: @jocs serialize selections
+ textRanges: prevTextRanges ?? selections as unknown as ITextRangeWithStyle[],
+ },
+ };
+
+ // Handle ime input.
+ if (isCompositionEnd) {
+ const historyParams = imeInputManagerService.fetchComposedUndoRedoMutationParams();
+
+ if (historyParams == null) {
+ throw new Error('historyParams is null in RichTextEditingMutation');
+ }
+
+ const { undoMutationParams, redoMutationParams, previousActiveRange } = historyParams;
+ changeState.redoState.actions = redoMutationParams.actions;
+ changeState.undoState.actions = undoMutationParams.actions;
+ changeState.undoState.textRanges = [previousActiveRange];
+ }
+
+ docStateChangeManagerService.setChangeState(changeState);
+
return {
unitId,
- actions: undoMutations,
+ actions: undoActions,
+ textRanges: selections as unknown as ITextRangeWithStyle[],
};
},
};
diff --git a/packages/docs/src/controllers/ime-input.controller.ts b/packages/docs/src/controllers/ime-input.controller.ts
index 461f827715..023b86783a 100644
--- a/packages/docs/src/controllers/ime-input.controller.ts
+++ b/packages/docs/src/controllers/ime-input.controller.ts
@@ -24,11 +24,10 @@ import {
Tools,
} from '@univerjs/core';
import type { IEditorInputConfig, ITextRangeWithStyle } from '@univerjs/engine-render';
-import { IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/engine-render';
+import { ITextSelectionRenderManager } from '@univerjs/engine-render';
import { Inject } from '@wendellhu/redi';
import type { Subscription } from 'rxjs';
-import { getDocObject } from '../basics/component-tools';
import { IMEInputCommand } from '../commands/commands/ime-input.command';
import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
import { IMEInputManagerService } from '../services/ime-input-manager.service';
@@ -48,7 +47,6 @@ export class IMEInputController extends Disposable {
constructor(
@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
@Inject(IMEInputManagerService) private readonly _imeInputManagerService: IMEInputManagerService,
@ICommandService private readonly _commandService: ICommandService
@@ -169,8 +167,4 @@ export class IMEInputController extends Disposable {
this._imeInputManagerService.setActiveRange(null);
}
-
- private _getDocObject() {
- return getDocObject(this._currentUniverService, this._renderManagerService);
- }
}
diff --git a/packages/docs/src/doc-plugin.ts b/packages/docs/src/doc-plugin.ts
index 3c1d4b0773..21514153cc 100644
--- a/packages/docs/src/doc-plugin.ts
+++ b/packages/docs/src/doc-plugin.ts
@@ -80,6 +80,7 @@ import {
SelectAllShortcut,
} from './shortcuts/cursor.shortcut';
import { DocCanvasView } from './views/doc-canvas-view';
+import { DocStateChangeManagerService } from './services/doc-state-change-manager.service';
export interface IUniverDocsConfig {
hasScroll?: boolean;
@@ -187,6 +188,7 @@ export class UniverDocsPlugin extends Plugin {
// services
[DocSkeletonManagerService],
[DocViewModelManagerService],
+ [DocStateChangeManagerService],
[IMEInputManagerService],
[
IDocClipboardService,
diff --git a/packages/docs/src/services/doc-state-change-manager.service.ts b/packages/docs/src/services/doc-state-change-manager.service.ts
new file mode 100644
index 0000000000..468e3778b3
--- /dev/null
+++ b/packages/docs/src/services/doc-state-change-manager.service.ts
@@ -0,0 +1,154 @@
+/**
+ * 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 { Nullable, TextXAction } from '@univerjs/core';
+import { ICommandService, IUndoRedoService, IUniverInstanceService, RedoCommandId, RxDisposable, TextX, UndoCommandId } from '@univerjs/core';
+import type { ITextRangeWithStyle } from '@univerjs/engine-render';
+import { Inject } from '@wendellhu/redi';
+import { BehaviorSubject } from 'rxjs';
+import type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';
+import { DeleteCommand, InsertCommand } from '../commands/commands/core-editing.command';
+
+interface IDocChangeState {
+ actions: TextXAction[];
+ textRanges: Nullable<ITextRangeWithStyle[]>;
+}
+
+export interface IDocStateChangeParams {
+ commandId: string;
+ unitId: string;
+ trigger: Nullable<string>;
+ redoState: IDocChangeState;
+ undoState: IDocChangeState;
+ noHistory?: boolean;
+}
+
+const HISTORY_DELAY = 300;
+
+// This class sends out state-changing events, what is the state, the data model,
+// and the cursor & selection, and this class mainly serves the History(undo/redo) module and
+// the collaboration module.
+export class DocStateChangeManagerService extends RxDisposable {
+ private readonly _docStateChange$ = new BehaviorSubject<Nullable<IDocStateChangeParams>>(null);
+ readonly docStateChange$ = this._docStateChange$.asObservable();
+
+ private _stateCache: Map<string, IDocStateChangeParams[]> = new Map();
+ private _timer: Nullable<ReturnType<typeof setTimeout>> = null;
+
+ constructor(
+ @Inject(IUndoRedoService) private _undoRedoService: IUndoRedoService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ setChangeState(changeState: IDocStateChangeParams) {
+ const { trigger } = changeState;
+ // No need to emit stateChange when the mutation is from collaboration.
+ if (trigger == null) {
+ return;
+ }
+ this._cacheChangeState(changeState);
+ // Mutations by user or historyService need collaboration.
+ this._docStateChange$.next(changeState);
+ }
+
+ private _initialize() {
+ this.disposeWithMe(
+ this._commandService.beforeCommandExecuted((command) => {
+ if (command.id === UndoCommandId || command.id === RedoCommandId) {
+ const univerDoc = this._univerInstanceService.getCurrentUniverDocInstance();
+ if (univerDoc == null) {
+ return;
+ }
+
+ const unitId = univerDoc.getUnitId();
+
+ this._pushHistory(unitId);
+ }
+ })
+ );
+ }
+
+ private _cacheChangeState(changeState: IDocStateChangeParams) {
+ const { trigger, unitId, noHistory } = changeState;
+
+ if (trigger === RedoCommandId || trigger === UndoCommandId || noHistory) {
+ return;
+ }
+
+ if (this._stateCache.has(unitId)) {
+ const cacheStates = this._stateCache.get(unitId);
+
+ cacheStates?.push(changeState);
+ } else {
+ this._stateCache.set(unitId, [changeState]);
+ }
+
+ if (trigger === InsertCommand.id || trigger === DeleteCommand.id) {
+ if (this._timer) {
+ clearTimeout(this._timer);
+ }
+
+ this._timer = setTimeout(() => {
+ this._pushHistory(unitId);
+ }, HISTORY_DELAY);
+ } else {
+ this._pushHistory(unitId);
+ }
+ }
+
+ private _pushHistory(unitId: string) {
+ const undoRedoService = this._undoRedoService;
+ const cacheStates = this._stateCache.get(unitId);
+
+ if (!Array.isArray(cacheStates) || cacheStates.length === 0) {
+ return;
+ }
+
+ const len = cacheStates.length;
+ // Use the first state.commandId as commandId, because we will only have one core mutation type.
+ const commandId = cacheStates[0].commandId;
+
+ const firstState = cacheStates[0];
+ const lastState = cacheStates[len - 1];
+
+ const redoParams: IRichTextEditingMutationParams = {
+ unitId,
+ actions: cacheStates.reduce((acc, cur) => TextX.compose(acc, cur.redoState.actions), [] as TextXAction[]),
+ 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[]),
+ textRanges: firstState.undoState.textRanges,
+ };
+
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [{ id: commandId, params: undoParams }],
+ redoMutations: [{ id: commandId, params: redoParams }],
+ });
+
+ // Empty the cacheState.
+ cacheStates.length = 0;
+ }
+}
diff --git a/packages/docs/src/services/ime-input-manager.service.ts b/packages/docs/src/services/ime-input-manager.service.ts
index b266d14c59..a72ad3e23f 100644
--- a/packages/docs/src/services/ime-input-manager.service.ts
+++ b/packages/docs/src/services/ime-input-manager.service.ts
@@ -54,6 +54,7 @@ export class IMEInputManagerService implements IDisposable {
actions: this._undoMutationParamsCache.reverse().reduce((acc, cur) => {
return TextX.compose(acc, cur.actions);
}, [] as TextXAction[]),
+ textRanges: [], // Add empty array, will never use, just fix type error
};
const redoMutationParams: IRichTextEditingMutationParams = {
@@ -61,6 +62,7 @@ export class IMEInputManagerService implements IDisposable {
actions: this._redoMutationParamsCache.reduce((acc, cur) => {
return TextX.compose(acc, cur.actions);
}, [] as TextXAction[]),
+ textRanges: [], // Add empty array, will never use, just fix type error
};
return { redoMutationParams, undoMutationParams, previousActiveRange: this._previousActiveRange };