您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

history.ts 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { Data } from "types"
  2. import { BaseCommand } from "./command"
  3. class BaseHistory<T> {
  4. private stack: BaseCommand<T>[] = []
  5. private pointer = -1
  6. private maxLength = 100
  7. private _enabled = true
  8. execute = (data: T, command: BaseCommand<T>) => {
  9. if (this.disabled) return
  10. this.stack = this.stack.slice(0, this.pointer + 1)
  11. this.stack.push(command)
  12. command.redo(data, true)
  13. this.pointer++
  14. if (this.stack.length > this.maxLength) {
  15. this.stack = this.stack.slice(this.stack.length - this.maxLength)
  16. this.pointer = this.maxLength - 1
  17. }
  18. this.save(data)
  19. }
  20. undo = (data: T) => {
  21. if (this.disabled) return
  22. if (this.pointer === -1) return
  23. const command = this.stack[this.pointer]
  24. command.undo(data)
  25. this.pointer--
  26. this.save(data)
  27. }
  28. redo = (data: T) => {
  29. if (this.disabled) return
  30. if (this.pointer === this.stack.length - 1) return
  31. const command = this.stack[this.pointer + 1]
  32. command.redo(data, false)
  33. this.pointer++
  34. this.save(data)
  35. }
  36. save = (data: T) => {
  37. if (typeof window === "undefined") return
  38. if (typeof localStorage === "undefined") return
  39. localStorage.setItem("glob_aldata_v6", JSON.stringify(data))
  40. }
  41. disable = () => {
  42. this._enabled = false
  43. }
  44. enable = () => {
  45. this._enabled = true
  46. }
  47. get disabled() {
  48. return !this._enabled
  49. }
  50. }
  51. export default new BaseHistory<Data>()