revoke.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /**
  2. 撤销重做功能
  3. * @Author: eyas66
  4. * @Mail: 33955341@qq.com
  5. * @Date: 2021-12-13 10:09:23
  6. * @Last Modified by: eyas66
  7. * @Last Modified time: 2021-12-13 10:09:23
  8. */
  9. export class Revoke {
  10. // 历史记录
  11. recordList = [];
  12. // 撤销记录,用于重做
  13. redoList = [];
  14. // 当前记录用currentRecord变量暂时存储,当用户修改时,再存放到recordList
  15. currentRecord = null;
  16. // 上次插入数据时间
  17. time = 0;
  18. /**
  19. * @description: 插入历史记录
  20. * @param {object}record
  21. * @return {boolean}
  22. */
  23. push(record) {
  24. const nowTime = Date.now();
  25. // 防止添加重复的时间,当添加间隔小于100ms时,则替换当前记录并取消执行添加
  26. if (this.time + 100 > nowTime) {
  27. this.currentRecord = JSON.stringify(record);
  28. return false;
  29. }
  30. this.time = nowTime;
  31. // 判断之前是否已经存在currentRecord记录,有则存储到recordList
  32. if (this.currentRecord) {
  33. this.recordList.push(this.currentRecord);
  34. //(清空记录)增加记录后则应该清空重做记录
  35. //splice() 方法向/从数组添加/删除项目,并返回删除的项目。
  36. this.redoList.splice(0, this.redoList.length);
  37. }
  38. // 将json转成字符串存储
  39. this.currentRecord = JSON.stringify(record);
  40. // 最多存储2000条记录,超过2000条记录则删除之前的记录
  41. if (this.length > 2000) {
  42. //unshift() 方法将新项添加到数组的开头,并返回新的长度。
  43. this.recordList.unshift();
  44. }
  45. return true;
  46. }
  47. /**
  48. * @description: 撤销操作
  49. * @param {*}
  50. * @return {object}
  51. */
  52. undo() {
  53. // 没有记录时,返回false
  54. // 新建的recordList里面,不知为什么会存在一条记录,未找到原因,所以就判断长度为1时就不能撤销了。
  55. if (this.recordList.length === 1 ) {
  56. return false;
  57. }
  58. //pop(): 方法用于删除并返回数组的最后一个元素。
  59. const record = this.recordList.pop();
  60. // 将当前记录添加到重做记录里面
  61. if (this.currentRecord) {
  62. this.redoList.push(this.currentRecord);
  63. }
  64. // 丢弃当前记录,防止重复添加
  65. this.currentRecord = null;
  66. //返回撤销的记录
  67. return JSON.parse(record);
  68. }
  69. /**
  70. * @description: 重做操作
  71. * @param {*}
  72. * @return {*}
  73. */
  74. redo() {
  75. // 没有重做记录时,返回false
  76. if (this.redoList.length === 0) {
  77. return false;
  78. }
  79. //pop(): 方法用于删除并返回数组的最后一个元素。
  80. const record = this.redoList.pop();
  81. // 添加到重做记录里面
  82. if (this.currentRecord) {
  83. this.recordList.push(this.currentRecord);
  84. }
  85. // 丢弃当前记录,防止重复添加
  86. this.currentRecord = null;
  87. return JSON.parse(record);
  88. }
  89. }