2021-06-07 11:18:50 +00:00
|
|
|
import { Data, Page, PageState } from 'types'
|
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-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-06-11 10:11:42 +00:00
|
|
|
storage.saveToLocalStorage(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-06-11 10:11:42 +00:00
|
|
|
storage.saveToLocalStorage(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-06-11 10:11:42 +00:00
|
|
|
storage.saveToLocalStorage(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-05-10 12:16:57 +00:00
|
|
|
get disabled() {
|
|
|
|
return !this._enabled
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-16 07:09:46 +00:00
|
|
|
export default new History()
|