SUndoStack.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import { SObject } from "../SObject";
  2. import { SUndoCommand } from "./SUndoCommand";
  3. /**
  4. * Undo操作堆栈
  5. *
  6. * @author 庞利祥(sybotan@126.com)
  7. */
  8. export class SUndoStack extends SObject {
  9. /** 命令栈 */
  10. private cmdStack = Array<SUndoCommand>();
  11. /** 当前命令索引 */
  12. private _index = -1;
  13. get index(): number {
  14. return this._index;
  15. } // Get index
  16. /** 命令栈是否为空 */
  17. get isEmpty(): boolean {
  18. return this.cmdStack.length <= 0;
  19. } // Get isEmpty
  20. /**
  21. * 执行redo操作
  22. */
  23. redo(): void {
  24. if (!this.canRedo()) {
  25. return;
  26. }
  27. this._index++;
  28. this.cmdStack[this._index].redo();
  29. } // Function redo()
  30. /**
  31. * 执行undo操作
  32. */
  33. undo(): void {
  34. if (!this.canUndo()) {
  35. return;
  36. }
  37. this.cmdStack[this._index].undo();
  38. this._index--;
  39. } // Function undo()
  40. /**
  41. * 是否可以执行Redo操作
  42. *
  43. * @return 可以执行,返回true;否则返回false。
  44. */
  45. canRedo(): boolean {
  46. return this.index + 1 < this.cmdStack.length;
  47. } // Function canRedo()
  48. /**
  49. * 是否可以执行Undo操作
  50. *
  51. * @return 可以执行,返回true;否则返回false。
  52. */
  53. canUndo(): boolean {
  54. return this.index >= 0;
  55. } // Function canUndo()
  56. /**
  57. * 清空堆栈
  58. */
  59. clear(): void {
  60. this.cmdStack.length = 0;
  61. this._index = -1;
  62. } // Function clear()
  63. /**
  64. * 返回指定索引的命令
  65. *
  66. * @param index 命令在栈中的索引
  67. */
  68. command(index: number): SUndoCommand | null {
  69. // 如果索引越界,则返回null
  70. if (index < 0 || index >= this.cmdStack.length) {
  71. return null;
  72. }
  73. return this.cmdStack[index];
  74. } // Function command()
  75. /**
  76. * 统计命令栈中命令的数量
  77. */
  78. count(): number {
  79. return this.cmdStack.length;
  80. } // Function cout()
  81. /**
  82. * 将命令添加到命令栈
  83. *
  84. * @param cmd 被添加的命令
  85. */
  86. push(cmd: SUndoCommand): void {
  87. this.cmdStack.length = this._index + 1;
  88. if (this._index >= 0 && cmd.mergeWith(this.cmdStack[this._index])) {
  89. return;
  90. }
  91. this.cmdStack.push(cmd);
  92. this._index = this.cmdStack.length - 1;
  93. } // Function push()
  94. } // Class SUndoStack