/** * Copyright 2023-present DreamNum Co., Ltd. * * 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 { Observable } from 'rxjs'; import type { IAccessor, IDisposable } from '../../common/di'; import type { Nullable } from '../../shared/types'; import type { ICommand, IMutationInfo } from '../command/command.service'; import { BehaviorSubject } from 'rxjs'; import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '../../common/const'; import { createIdentifier } from '../../common/di'; import { UniverInstanceType } from '../../common/unit'; import { Disposable, toDisposable } from '../../shared/lifecycle'; import { CommandType, ICommandService, sequenceExecute } from '../command/command.service'; import { IConfigService } from '../config/config.service'; import { EDITOR_ACTIVATED, FOCUSING_FX_BAR_EDITOR, FOCUSING_SHAPE_TEXT_EDITOR, FOCUSING_SHEET } from '../context/context'; import { IContextService } from '../context/context.service'; import { IUniverInstanceService } from '../instance/instance.service'; export interface IUndoRedoItem { /** unitID maps to unitId for UniverSheet / UniverDoc / UniverSlide */ unitID: string; undoMutations: IMutationInfo[]; redoMutations: IMutationInfo[]; /** * sometimes we need an id to mark the undo-redo item */ id?: string; } export interface IUndoRedoService { undoRedoStatus$: Observable; /** Read a unit's history counts without changing the focused unit. */ getUndoRedoStatus(unitId: string): IUndoRedoStatus; pushUndoRedo(item: IUndoRedoItem): void; /** * Group undo redo items pushed while the returned scope is active. * Reusing the same group id joins consecutive scopes without exposing the * group to commands or undo redo items. */ beginUndoRedoGroup(unitId: string, groupId: string, mode?: 'replace' | 'append'): IDisposable; /** Read the top undo entry for the focused editor or unit. */ pitchTopUndoElement(): Nullable; /** Read the top redo entry for the focused editor or unit. */ pitchTopRedoElement(): Nullable; popUndoToRedo(): void; popRedoToUndo(): void; rollback(id: string, unitId?: string): void; clearUndoRedo(unitId: string): void; /** * Batch undo redo elements into a single `IUndoRedoItem` util the returned `IDisposable` is called. * * @deprecated This is a temporary solution. We are going to refactor the undo redo service shortly. * @returns a disposable to cancel batching undo redo elements */ __tempBatchingUndoRedo(unitId: string): IDisposable; } enum BatchingStatus { WAITING, CREATED, } export interface IUndoRedoCommandBaseInfosByInterceptor { undos: IMutationInfo[]; redos: IMutationInfo[]; } export interface IUndoRedoCommandInfosByInterceptor extends IUndoRedoCommandBaseInfosByInterceptor { /** * Sometimes, mutations generated by interceptors need to ensure a certain execution order * PreMutations run before user's intent to make sure the undo/redo works correctly. */ preUndos?: IMutationInfo[]; preRedos?: IMutationInfo[]; } export interface IUndoRedoCommandInfos { undos: IMutationInfo[]; redos: IMutationInfo[]; } export const IUndoRedoService = createIdentifier('univer.undo-redo.service'); export interface IUndoRedoStatus { undos: number; redos: number; } export const DEFAULT_UNDO_REDO_HISTORY_LIMIT = 50; export const UNDO_REDO_HISTORY_LIMIT_CONFIG_KEY = 'undoRedo.historyLimit'; abstract class MultiImplementationCommand implements IDisposable { dispose(): void { // empty } async dispatchToHandlers(): Promise { 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; handler(accessor: IAccessor) { const undoRedoService = accessor.get(IUndoRedoService); const element = undoRedoService.pitchTopUndoElement(); if (!element) { return false; } const commandService = accessor.get(ICommandService); const result = sequenceExecute(element.undoMutations, commandService); if (result.result) { undoRedoService.popUndoToRedo(); return true; } return false; } })(); export const RedoCommand = new (class extends MultiImplementationCommand implements ICommand { readonly type = CommandType.COMMAND; readonly id = RedoCommandId; handler(accessor: IAccessor) { const undoRedoService = accessor.get(IUndoRedoService); const element = undoRedoService.pitchTopRedoElement(); if (!element) { return false; } const commandService = accessor.get(ICommandService); const result = sequenceExecute(element.redoMutations, commandService); if (result.result) { undoRedoService.popRedoToUndo(); return true; } return false; } })(); /** * This UndoRedoService is local. */ export class LocalUndoRedoService extends Disposable implements IUndoRedoService { readonly undoRedoStatus$: Observable; protected readonly _undoRedoStatus$ = new BehaviorSubject<{ undos: number; redos: number }>({ undos: 0, redos: 0 }); // Undo and redo stacks are per unit. protected readonly _undoStacks = new Map(); protected readonly _redoStacks = new Map(); private _batchingStatus = new Map(); private readonly _activeGroups = new Map(); private readonly _itemGroups = new WeakMap(); private readonly _historyLimit: number; constructor( @IUniverInstanceService protected readonly _univerInstanceService: IUniverInstanceService, @ICommandService protected readonly _commandService: ICommandService, @IContextService private readonly _contextService: IContextService, @IConfigService configService: IConfigService ) { super(); this._historyLimit = configService.getConfig(UNDO_REDO_HISTORY_LIMIT_CONFIG_KEY) ?? DEFAULT_UNDO_REDO_HISTORY_LIMIT; this.undoRedoStatus$ = this._undoRedoStatus$.asObservable(); this.disposeWithMe(this._commandService.registerCommand(UndoCommand)); this.disposeWithMe(this._commandService.registerCommand(RedoCommand)); this.disposeWithMe(toDisposable(() => this._undoRedoStatus$.complete())); this.disposeWithMe(toDisposable(this._univerInstanceService.focused$.subscribe(() => this._updateStatus()))); } getUndoRedoStatus(unitId: string): IUndoRedoStatus { return { undos: this._undoStacks.get(unitId)?.length ?? 0, redos: this._redoStacks.get(unitId)?.length ?? 0, }; } pushUndoRedo(item: IUndoRedoItem): void { const { unitID } = item; const redoStack = this._getRedoStack(unitID, true); const undoStack = this._getUndoStack(unitID, true); const historyLimit = this._historyLimit; // redo stack should be cleared when pushing an undo redoStack.length = 0; const activeGroup = this._activeGroups.get(unitID); const lastItem = this._pitchUndoElement(unitID); if (activeGroup) { if (lastItem && this._itemGroups.get(lastItem) === activeGroup.id) { if (activeGroup.mode === 'replace') { lastItem.redoMutations = item.redoMutations; } else { lastItem.redoMutations.push(...item.redoMutations); lastItem.undoMutations.unshift(...item.undoMutations); } } else { appendNewItem(item); this._itemGroups.set(item, activeGroup.id); } } else if (this._batchingStatus.has(item.unitID)) { const batchingStatus = this._batchingStatus.get(item.unitID)!; if (batchingStatus === BatchingStatus.WAITING || !lastItem) { appendNewItem(item); this._batchingStatus.set(item.unitID, BatchingStatus.CREATED); } else { this._tryBatchingElements(lastItem, item); } } else { appendNewItem(item); } function appendNewItem(item: IUndoRedoItem) { undoStack.push(item); if (undoStack.length > historyLimit) { undoStack.splice(0, 1); } } this._updateStatus(); } beginUndoRedoGroup(unitId: string, groupId: string, mode: 'replace' | 'append' = 'replace'): IDisposable { if (this._activeGroups.has(unitId) || this._batchingStatus.has(unitId)) { throw new Error('[LocalUndoRedoService]: cannot group undo redo twice at the same time!'); } const group = { id: groupId, mode }; this._activeGroups.set(unitId, group); return toDisposable(() => { if (this._activeGroups.get(unitId) === group) { this._activeGroups.delete(unitId); } }); } clearUndoRedo(unitID: string): void { const redoStack = this._getRedoStack(unitID); if (redoStack) { redoStack.length = 0; } const undoStack = this._getUndoStack(unitID); if (undoStack) { undoStack.length = 0; } this._updateStatus(); } pitchTopUndoElement(): Nullable { const unitID = this._getFocusedUnitId(); return this._pitchUndoElement(unitID); } pitchTopRedoElement(): Nullable { const unitID = this._getFocusedUnitId(); return this._pitchRedoElement(unitID); } private _pitchUndoElement(unitId: string): Nullable { const stack = this._getUndoStack(unitId); return stack?.length ? stack[stack.length - 1] : null; } private _pitchRedoElement(unitId: string): Nullable { const stack = this._getRedoStack(unitId); return stack?.length ? stack[stack.length - 1] : null; } popUndoToRedo(): void { const undoStack = this._getUndoStackForFocused(); const element = undoStack.pop(); if (element) { this._itemGroups.delete(element); // Only push to redo stack if redoMutations is not empty if (element.redoMutations.length > 0) { const redoStack = this._getRedoStackForFocused(); redoStack.push(element); } this._updateStatus(); } } popRedoToUndo(): void { const redoStack = this._getRedoStackForFocused(); const element = redoStack.pop(); if (element) { this._itemGroups.delete(element); const undoStack = this._getUndoStackForFocused(); undoStack.push(element); this._updateStatus(); } } rollback(id: string, unitID?: string): void { const unitId = unitID || this._getFocusedUnitId(); const stack = this._getUndoStack(unitId); const item = stack?.[stack?.length - 1]; // if the last item is the one we want to rollback if (item && item.id === id) { stack.pop(); this._itemGroups.delete(item); sequenceExecute(item.undoMutations, this._commandService); } } __tempBatchingUndoRedo(unitId: string): IDisposable { if (this._batchingStatus.has(unitId) || this._activeGroups.has(unitId)) { throw new Error('[LocalUndoRedoService]: cannot batching undo redo twice at the same time!'); } this._batchingStatus.set(unitId, BatchingStatus.WAITING); return toDisposable(() => this._batchingStatus.delete(unitId)); } protected _updateStatus(): void { const unitID = this._getFocusedUnitId(); const undos = (unitID && this._undoStacks.get(unitID)?.length) || 0; const redos = (unitID && this._redoStacks.get(unitID)?.length) || 0; this._undoRedoStatus$.next({ undos, redos, }); } protected _getUndoStack(unitId: string): IUndoRedoItem[] | null; protected _getUndoStack(unitId: string, createAsNeeded: true): IUndoRedoItem[]; protected _getUndoStack(unitId: string, createAsNeeded = false): IUndoRedoItem[] | null { let stack = this._undoStacks.get(unitId); if (!stack && createAsNeeded) { stack = []; this._undoStacks.set(unitId, stack); } return stack || null; } protected _getRedoStack(unitId: string): IUndoRedoItem[] | null; protected _getRedoStack(unitId: string, createAsNeeded: true): IUndoRedoItem[]; protected _getRedoStack(unitId: string, createAsNeeded = false): IUndoRedoItem[] | null { let stack = this._redoStacks.get(unitId); if (!stack && createAsNeeded) { stack = []; this._redoStacks.set(unitId, stack); } return stack || null; } protected _getUndoStackForFocused(): IUndoRedoItem[] { const unitID = this._getFocusedUnitId(); if (!unitID) { throw new Error('No focused univer instance!'); } return this._getUndoStack(unitID, true); } protected _getRedoStackForFocused(): IUndoRedoItem[] { const unitID = this._getFocusedUnitId(); if (!unitID) { throw new Error('No focused univer instance!'); } return this._getRedoStack(unitID, true); } private _tryBatchingElements(item: IUndoRedoItem, newItem: IUndoRedoItem): void { // this could be not that easy in other sitatuations than Find & Replace item.redoMutations.push(...newItem.redoMutations); item.undoMutations.push(...newItem.undoMutations); } private _getFocusedUnitId() { let unitID: string = ''; const isFocusSheet = this._contextService.getContextValue(FOCUSING_SHEET); const isFocusFormulaEditor = this._contextService.getContextValue(FOCUSING_FX_BAR_EDITOR); const isFocusShapeEditor = this._contextService.getContextValue(FOCUSING_SHAPE_TEXT_EDITOR); const isFocusEditor = this._contextService.getContextValue(EDITOR_ACTIVATED); if (isFocusEditor && isFocusShapeEditor) { return this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC)?.getUnitId() ?? ''; } if (isFocusSheet) { if (isFocusFormulaEditor && isFocusEditor) { unitID = DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY; } else if (isFocusEditor) { unitID = DOCS_NORMAL_EDITOR_UNIT_ID_KEY; } else { unitID = this._univerInstanceService.getFocusedUnit()?.getUnitId() ?? ''; } } else { unitID = this._univerInstanceService.getFocusedUnit()?.getUnitId() ?? ''; } return unitID; } }