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: add capacity of compose change state (#2566)

Ran Luo8bc96d800085
diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
index 0c6cf5a858..a5b07a0c00 100644
--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
@@ -49,7 +49,7 @@ function generateBody(text: string): IDocumentBody {
};
}
-export interface IClipboardPropertyItem {}
+export interface IClipboardPropertyItem { }
export interface IDocClipboardHook {
onCopyProperty?(start: number, end: number): IClipboardPropertyItem;
@@ -131,7 +131,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
return false;
}
- // Set content to clipboard.
+ // Set content to clipboard.
this.copy();
try {
@@ -176,7 +176,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
}
try {
- // When doc has multiple selections, the cursor moves to the last pasted content's end.
+ // When doc has multiple selections, the cursor moves to the last pasted content's end.
let cursor = activeEndOffset;
for (const range of ranges) {
const { startOffset, endOffset } = range;
@@ -208,12 +208,12 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
private async _setClipboardData(documentBodyList: IDocumentBody[]): Promise<void> {
const copyId = genId();
const text =
- documentBodyList.length > 1
- ? documentBodyList.map((body) => body.dataStream).join('\n')
- : documentBodyList[0].dataStream;
+ documentBodyList.length > 1
+ ? documentBodyList.map((body) => body.dataStream).join('\n')
+ : documentBodyList[0].dataStream;
let html = this._umdToHtml.convert(documentBodyList);
- // Only cache copy content when the range is 1.
+ // Only cache copy content when the range is 1.
if (documentBodyList.length === 1) {
html = html.replace(/(<[a-z]+)/, (_p0, p1) => `${p1} data-copy-id="${copyId}"`);
copyContentCache.set(copyId, documentBodyList[0]);
@@ -267,7 +267,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
private async _generateBodyFromClipboardItems(items: ClipboardItem[]): Promise<IDocumentBody> {
try {
- // TODO: support paste image.
+ // TODO: support paste image.
let html = '';
let text = '';
diff --git a/packages/docs/src/commands/commands/core-editing.command.ts b/packages/docs/src/commands/commands/core-editing.command.ts
index 55ff22fa0c..013ecc6baa 100644
--- a/packages/docs/src/commands/commands/core-editing.command.ts
+++ b/packages/docs/src/commands/commands/core-editing.command.ts
@@ -59,6 +59,7 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
unitId,
actions: [],
textRanges,
+ debounce: true,
},
};
@@ -131,6 +132,7 @@ export const DeleteCommand: ICommand<IDeleteCommandParams> = {
unitId,
actions: [],
textRanges,
+ debounce: true,
},
};
diff --git a/packages/docs/src/commands/mutations/core-editing.mutation.ts b/packages/docs/src/commands/mutations/core-editing.mutation.ts
index 2113143d54..0a7ae90dc1 100644
--- a/packages/docs/src/commands/mutations/core-editing.mutation.ts
+++ b/packages/docs/src/commands/mutations/core-editing.mutation.ts
@@ -25,13 +25,15 @@ import { IMEInputManagerService } from '../../services/ime-input-manager.service
export interface IRichTextEditingMutationParams extends IMutationCommonParams {
unitId: string;
- segmentId?: string;
actions: JSONXActions;
textRanges: Nullable<ITextRangeWithStyle[]>;
+ segmentId?: string;
prevTextRanges?: Nullable<ITextRangeWithStyle[]>;
noNeedSetTextRange?: boolean;
isCompositionEnd?: boolean;
noHistory?: boolean;
+ // Do you need to compose the undo and redo of history, and compose of the change states.
+ debounce?: boolean;
}
const RichTextEditingMutationId = 'doc.mutation.rich-text-editing';
@@ -57,6 +59,7 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
noHistory,
isCompositionEnd,
noNeedSetTextRange,
+ debounce,
} = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
const documentDataModel = univerInstanceService.getUniverDocInstance(unitId);
@@ -114,6 +117,7 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
segmentId,
trigger,
noHistory,
+ debounce,
redoState: {
actions,
textRanges,
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 a7c296d530..065c7458d7 100644
--- a/packages/docs/src/services/doc-state-change-manager.service.ts
+++ b/packages/docs/src/services/doc-state-change-manager.service.ts
@@ -20,24 +20,26 @@ 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: JSONXActions;
textRanges: Nullable<ITextRangeWithStyle[]>;
}
+type ChangeStateCacheType = 'history' | 'collaboration';
+
export interface IDocStateChangeParams {
commandId: string;
unitId: string;
- segmentId?: string;
trigger: Nullable<string>;
redoState: IDocChangeState;
undoState: IDocChangeState;
+ segmentId?: string;
noHistory?: boolean;
+ debounce?: boolean;
}
-const HISTORY_DELAY = 300;
+const DEBOUNCE_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
@@ -45,9 +47,12 @@ const HISTORY_DELAY = 300;
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;
+ // This cache used for history compose.
+ private _historyStateCache: Map<string, IDocStateChangeParams[]> = new Map();
+ // This cache used for collaboration state compose.
+ private _changeStateCache: Map<string, IDocStateChangeParams[]> = new Map();
+ private _historyTimer: Nullable<ReturnType<typeof setTimeout>> = null;
+ private _changeStateCacheTimer: Nullable<ReturnType<typeof setTimeout>> = null;
constructor(
@Inject(IUndoRedoService) private _undoRedoService: IUndoRedoService,
@@ -60,16 +65,9 @@ export class DocStateChangeManagerService extends RxDisposable {
}
setChangeState(changeState: IDocStateChangeParams) {
- const { trigger, noHistory } = changeState;
- // No need to emit stateChange when the mutation is from collaboration.
- if (trigger == null) {
- return;
- }
- this._cacheChangeState(changeState);
+ this._cacheChangeState(changeState, 'history');
// Mutations by user or historyService need collaboration.
- if (!noHistory) {
- this._docStateChange$.next(changeState);
- }
+ this._cacheChangeState(changeState, 'collaboration');
}
private _initialize() {
@@ -84,42 +82,65 @@ export class DocStateChangeManagerService extends RxDisposable {
const unitId = univerDoc.getUnitId();
this._pushHistory(unitId);
+ this._emitChangeState(unitId);
}
})
);
}
- private _cacheChangeState(changeState: IDocStateChangeParams) {
- const { trigger, unitId, noHistory } = changeState;
+ private _cacheChangeState(changeState: IDocStateChangeParams, type: ChangeStateCacheType = 'history') {
+ const { trigger, unitId, noHistory, debounce = false } = changeState;
+
+ if (noHistory) {
+ return;
+ }
- if (trigger === RedoCommandId || trigger === UndoCommandId || noHistory) {
+ if (type === 'history' && (trigger === RedoCommandId || trigger === UndoCommandId)) {
return;
}
- if (this._stateCache.has(unitId)) {
- const cacheStates = this._stateCache.get(unitId);
+ const stateCache = type === 'history'
+ ? this._historyStateCache
+ : this._changeStateCache;
+
+ const cb = type === 'history'
+ ? this._pushHistory.bind(this)
+ : this._emitChangeState.bind(this);
+
+ if (stateCache.has(unitId)) {
+ const cacheStates = stateCache.get(unitId);
cacheStates?.push(changeState);
} else {
- this._stateCache.set(unitId, [changeState]);
+ stateCache.set(unitId, [changeState]);
}
- if (trigger === InsertCommand.id || trigger === DeleteCommand.id) {
- if (this._timer) {
- clearTimeout(this._timer);
- }
+ if (debounce) {
+ if (type === 'history') {
+ if (this._historyTimer) {
+ clearTimeout(this._historyTimer);
+ }
+
+ this._historyTimer = setTimeout(() => {
+ cb(unitId);
+ }, DEBOUNCE_DELAY);
+ } else {
+ if (this._changeStateCacheTimer) {
+ clearTimeout(this._changeStateCacheTimer);
+ }
- this._timer = setTimeout(() => {
- this._pushHistory(unitId);
- }, HISTORY_DELAY);
+ this._changeStateCacheTimer = setTimeout(() => {
+ cb(unitId);
+ }, DEBOUNCE_DELAY);
+ }
} else {
- this._pushHistory(unitId);
+ cb(unitId);
}
}
private _pushHistory(unitId: string) {
const undoRedoService = this._undoRedoService;
- const cacheStates = this._stateCache.get(unitId);
+ const cacheStates = this._historyStateCache.get(unitId);
if (!Array.isArray(cacheStates) || cacheStates.length === 0) {
return;
@@ -154,4 +175,48 @@ export class DocStateChangeManagerService extends RxDisposable {
// Empty the cacheState.
cacheStates.length = 0;
}
+
+ private _emitChangeState(unitId: string) {
+ const cacheStates = this._changeStateCache.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, trigger, segmentId, noHistory, debounce } = cacheStates[0];
+
+ const firstState = cacheStates[0];
+ const lastState = cacheStates[len - 1];
+
+ const redoState: IRichTextEditingMutationParams = {
+ unitId,
+ actions: cacheStates.reduce((acc, cur) => JSONX.compose(acc, cur.redoState.actions), null as JSONXActions),
+ textRanges: lastState.redoState.textRanges,
+ };
+
+ const undoState: IRichTextEditingMutationParams = {
+ unitId,
+ // Always need to put undoParams after redoParams, because `reverse` will change the `cacheStates` order.
+ actions: cacheStates.reverse().reduce((acc, cur) => JSONX.compose(acc, cur.undoState.actions), null as JSONXActions),
+ textRanges: firstState.undoState.textRanges,
+ };
+
+ const changeState: IDocStateChangeParams = {
+ commandId,
+ unitId,
+ trigger,
+ redoState,
+ undoState,
+ segmentId,
+ noHistory,
+ debounce,
+ };
+
+ // Empty the cacheState.
+ cacheStates.length = 0;
+
+ this._docStateChange$.next(changeState);
+ }
}