tldraw/state/history.ts

68 lines
1.4 KiB
TypeScript
Raw Normal View History

import { Data, Page, PageState } from 'types'
import { BaseCommand } from './commands/command'
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.
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>) => {
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
}
storage.save(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)
if (this.disabled) return
2021-05-10 12:16:57 +00:00
this.pointer--
storage.save(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)
if (this.disabled) return
2021-05-10 12:16:57 +00:00
this.pointer++
storage.save(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
}
}
export default new History()