HistoryController.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import { set } from "lodash";
  2. import { StateRoot } from "queenjs";
  3. type RecordOptions = { combine?: boolean };
  4. class State extends StateRoot {
  5. currLen = 0; //操作栈的长度
  6. maxLen = 100; //操作栈总长度
  7. opIndex = -1; //操作栈的指针
  8. canUndo = this.computed((state) => {
  9. return state.opIndex >= 0;
  10. });
  11. canRedo = this.computed((state) => {
  12. return state.opIndex < state.currLen - 1;
  13. });
  14. }
  15. export class HistoryController {
  16. state = new State().reactive();
  17. queue: GroupAction[] = [];
  18. cacheGroupAction = new GroupAction();
  19. // 添加缓存记录
  20. record(action: Action) {
  21. this.cacheGroupAction.record(action);
  22. }
  23. // 保存缓存记录到历史栈中
  24. submit(action?: Action) {
  25. const { state, queue, cacheGroupAction } = this;
  26. if (action) this.record(action);
  27. if (!cacheGroupAction.actions.length) return;
  28. // 将缓存操作记录保存到当前指针的下一栈中
  29. queue[++state.opIndex] = cacheGroupAction;
  30. // 设置栈的长度为指针的长度,舍弃后面的记录
  31. queue.length = state.opIndex + 1;
  32. // 若栈长度超过上限, 舍弃之前的记录
  33. if (queue.length > state.maxLen) {
  34. queue.splice(0, queue.length - state.maxLen);
  35. state.opIndex = state.maxLen - 1;
  36. }
  37. // 更新当前长度状态
  38. state.currLen = queue.length;
  39. // 更新当前缓存GroupAction
  40. this.cacheGroupAction = new GroupAction();
  41. }
  42. undo() {
  43. if (!this.state.canUndo) return;
  44. this.queue[this.state.opIndex--].undo();
  45. }
  46. redo() {
  47. if (!this.state.canRedo) return;
  48. this.queue[++this.state.opIndex].redo();
  49. }
  50. //清除操作
  51. clear() {
  52. this.queue = [];
  53. this.state.currLen = 0;
  54. this.state.opIndex = -1;
  55. this.cacheGroupAction = new GroupAction();
  56. }
  57. }
  58. export class Action {
  59. constructor(
  60. public type: "set" | "delete",
  61. public root: any,
  62. public path: string,
  63. public value?: any,
  64. public oldValue?: any
  65. ) {}
  66. undo() {
  67. set(this.root, this.path, this.oldValue);
  68. }
  69. redo() {
  70. set(this.root, this.path, this.value);
  71. }
  72. }
  73. export class GroupAction {
  74. actions: Action[] = [];
  75. record(action: Action, options?: RecordOptions) {
  76. const lastAction = this.actions.at(-1);
  77. if (
  78. options?.combine &&
  79. lastAction?.root === action.root &&
  80. lastAction?.path === action.path
  81. ) {
  82. this.actions[this.actions.length - 1] = action;
  83. } else {
  84. this.actions.push(action);
  85. }
  86. }
  87. undo() {
  88. [...this.actions].reverse().forEach((act) => act.undo());
  89. }
  90. redo() {
  91. this.actions.forEach((d) => d.redo());
  92. }
  93. }