import { SObject } from "../SObject"; import { SUndoCommand } from "./SUndoCommand"; /** * Undo操作堆栈 * * @author 庞利祥(sybotan@126.com) */ export class SUndoStack extends SObject { /** 命令栈 */ private cmdStack = Array(); /** 当前命令索引 */ private _index = -1; get index(): number { return this._index; } // Get index /** 命令栈是否为空 */ get isEmpty(): boolean { return this.cmdStack.length <= 0; } // Get isEmpty /** * 执行redo操作 */ redo(): void { if (!this.canRedo()) { return; } this._index++; this.cmdStack[this._index].redo(); } // Function redo() /** * 执行undo操作 */ undo(): void { if (!this.canUndo()) { return; } this.cmdStack[this._index].undo(); this._index--; } // Function undo() /** * 是否可以执行Redo操作 * * @return 可以执行,返回true;否则返回false。 */ canRedo(): boolean { return this.index + 1 < this.cmdStack.length; } // Function canRedo() /** * 是否可以执行Undo操作 * * @return 可以执行,返回true;否则返回false。 */ canUndo(): boolean { return this.index >= 0; } // Function canUndo() /** * 清空堆栈 */ clear(): void { this.cmdStack.length = 0; this._index = -1; } // Function clear() /** * 返回指定索引的命令 * * @param index 命令在栈中的索引 */ command(index: number): SUndoCommand | null { // 如果索引越界,则返回null if (index < 0 || index >= this.cmdStack.length) { return null; } return this.cmdStack[index]; } // Function command() /** * 统计命令栈中命令的数量 */ count(): number { return this.cmdStack.length; } // Function cout() /** * 将命令添加到命令栈 * * @param cmd 被添加的命令 */ push(cmd: SUndoCommand): void { this.cmdStack.length = this._index + 1; if (this._index >= 0 && cmd.mergeWith(this.cmdStack[this._index])) { return; } this.cmdStack.push(cmd); this._index = this.cmdStack.length - 1; } // Function push() } // Class SUndoStack