HistoryService.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. export class HistoryService {
  2. constructor() {
  3. this.history = {
  4. records: [],
  5. currentRecordIndex: -1,
  6. state: {
  7. pre: 0,
  8. next: 0,
  9. },
  10. }
  11. }
  12. getCurrentRecordIndex() {
  13. return this.history.currentRecordIndex
  14. }
  15. getHistoryRecord() {
  16. if (this.history.currentRecordIndex == null || this.history.records.length == 0) {
  17. return null
  18. } else {
  19. return this.history.records[this.history.currentRecordIndex]
  20. }
  21. }
  22. getHistoryRecords() {
  23. return this.history.records
  24. }
  25. getHistoryState() {
  26. return this.history.state
  27. }
  28. addHistoryRecord(item) {
  29. const len = this.history.records.length
  30. if (len == 0) {
  31. this.history.records.push(item)
  32. this.history.currentRecordIndex = 0
  33. } else if (this.history.currentRecordIndex + 1 == len) {
  34. this.history.records.push(item)
  35. ++this.history.currentRecordIndex
  36. }
  37. // 覆盖
  38. else {
  39. const records = this.history.records.slice(0, this.history.currentRecordIndex + 1)
  40. records.push(item)
  41. this.history.records = records
  42. ++this.history.currentRecordIndex
  43. }
  44. }
  45. setHistoryState(pre, next) {
  46. this.history.state.pre = pre
  47. this.history.state.next = next
  48. }
  49. undoHistoryRecord() {
  50. --this.history.currentRecordIndex
  51. }
  52. redoHistoryRecord() {
  53. ++this.history.currentRecordIndex
  54. }
  55. clearHistoryRecord() {
  56. this.history.records = []
  57. this.setHistoryState(0, 0)
  58. }
  59. hasRecords() {
  60. return this.history.records.length > 0
  61. }
  62. }
  63. const historyService = new HistoryService()
  64. window.historyService = historyService
  65. export { historyService }