2021-06-16 12:09:45 +00:00
|
|
|
import { Data } from 'types'
|
2021-06-19 16:24:51 +00:00
|
|
|
import * as gtag from 'utils/gtag'
|
2021-05-30 13:14:35 +00:00
|
|
|
import { BaseCommand } from './commands/command'
|
2021-06-07 11:18:50 +00:00
|
|
|
import storage from './storage'
|
2021-05-10 12:16:57 +00:00
|
|
|
|
2021-05-13 06:44:52 +00:00
|
|
|
// A singleton to manage history changes.
|
|
|
|
|
2021-06-07 11:18:50 +00:00
|
|
|
class History<T extends Data> {
|
2021-05-10 12:16:57 +00:00
|
|
|
private stack: BaseCommand<T>[] = []
|
|
|
|
private pointer = -1
|
|
|
|
private maxLength = 100
|
|
|
|
private _enabled = true
|
|
|
|
|
|
|
|
execute = (data: T, command: BaseCommand<T>) => {
|
2021-06-19 16:24:51 +00:00
|
|
|
gtag.event({
|
|
|
|
action: command.name,
|
|
|
|
category: command.category,
|
|
|
|
label: '',
|
|
|
|
value: 0,
|
|
|
|
})
|
|
|
|
|
2021-05-30 13:14:35 +00:00
|
|
|
command.redo(data, true)
|
|
|
|
|
2021-05-10 12:16:57 +00:00
|
|
|
if (this.disabled) return
|
|
|
|
this.stack = this.stack.slice(0, this.pointer + 1)
|
|
|
|
this.stack.push(command)
|
|
|
|
this.pointer++
|
|
|
|
|
|
|
|
if (this.stack.length > this.maxLength) {
|
|
|
|
this.stack = this.stack.slice(this.stack.length - this.maxLength)
|
|
|
|
this.pointer = this.maxLength - 1
|
|
|
|
}
|
|
|
|
|
2021-06-11 22:06:09 +00:00
|
|
|
storage.savePage(data)
|
2021-05-10 12:16:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
undo = (data: T) => {
|
|
|
|
if (this.pointer === -1) return
|
|
|
|
const command = this.stack[this.pointer]
|
|
|
|
command.undo(data)
|
2021-05-30 13:14:35 +00:00
|
|
|
if (this.disabled) return
|
2021-05-10 12:16:57 +00:00
|
|
|
this.pointer--
|
2021-06-11 22:06:09 +00:00
|
|
|
storage.savePage(data)
|
2021-05-10 12:16:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
redo = (data: T) => {
|
|
|
|
if (this.pointer === this.stack.length - 1) return
|
|
|
|
const command = this.stack[this.pointer + 1]
|
|
|
|
command.redo(data, false)
|
2021-05-30 13:14:35 +00:00
|
|
|
if (this.disabled) return
|
2021-05-10 12:16:57 +00:00
|
|
|
this.pointer++
|
2021-06-11 22:06:09 +00:00
|
|
|
storage.savePage(data)
|
2021-05-10 12:16:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
disable = () => {
|
|
|
|
this._enabled = false
|
|
|
|
}
|
|
|
|
|
|
|
|
enable = () => {
|
|
|
|
this._enabled = true
|
|
|
|
}
|
|
|
|
|
2021-05-19 21:24:41 +00:00
|
|
|
pop() {
|
|
|
|
if (this.stack.length > 0) {
|
|
|
|
this.stack.pop()
|
|
|
|
this.pointer--
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-16 12:09:45 +00:00
|
|
|
reset() {
|
|
|
|
this.stack = []
|
|
|
|
this.pointer = -1
|
|
|
|
this.maxLength = 100
|
|
|
|
this._enabled = true
|
|
|
|
}
|
|
|
|
|
2021-05-10 12:16:57 +00:00
|
|
|
get disabled() {
|
|
|
|
return !this._enabled
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-16 07:09:46 +00:00
|
|
|
export default new History()
|