History.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { deepCopy } from './utils'
  2. // 历史记录管理
  3. export default class History {
  4. constructor(app) {
  5. this.app = app
  6. this.historyStack = []
  7. this.length = 0
  8. this.index = -1
  9. }
  10. // 添加
  11. add(data) {
  12. let prev = this.length > 0 ? this.historyStack[this.length - 1] : null
  13. let copyData = deepCopy(data)
  14. if (copyData === prev) {
  15. return
  16. }
  17. this.historyStack.push(copyData)
  18. this.length++
  19. this.index = this.length - 1
  20. this.emitChange()
  21. }
  22. // 后退
  23. undo() {
  24. if (this.index <= 0) {
  25. return
  26. }
  27. this.index--
  28. this.shuttle()
  29. }
  30. // 前进
  31. redo() {
  32. if (this.index >= this.length - 1) {
  33. return
  34. }
  35. this.index++
  36. this.shuttle()
  37. }
  38. // 前进后退
  39. async shuttle() {
  40. let data = this.historyStack[this.index]
  41. await this.app.setData(data, true)
  42. this.emitChange()
  43. this.app.emit('change', data)
  44. }
  45. // 清空数据
  46. clear() {
  47. this.index = -1
  48. this.length = 0
  49. this.historyStack = []
  50. this.emitChange()
  51. }
  52. // 触发事件
  53. emitChange() {
  54. this.app.emit('shuttle', this.index, this.length)
  55. }
  56. }