2015-05-20 07:06:59 +08:00
|
|
|
_ = require 'underscore'
|
2015-03-03 07:33:58 +08:00
|
|
|
|
|
|
|
module.exports =
|
|
|
|
class UndoManager
|
|
|
|
constructor: ->
|
2015-05-20 07:12:39 +08:00
|
|
|
@_historyIndex = -1
|
|
|
|
@_markerIndex = -1
|
2015-03-03 07:33:58 +08:00
|
|
|
@_history = []
|
2015-05-20 07:12:39 +08:00
|
|
|
@_markers = []
|
|
|
|
@_MAX_HISTORY_SIZE = 1000
|
2015-03-03 07:33:58 +08:00
|
|
|
|
|
|
|
current: ->
|
2015-05-20 07:12:39 +08:00
|
|
|
return @_history[@_historyIndex]
|
2015-03-03 07:33:58 +08:00
|
|
|
|
|
|
|
undo: ->
|
2015-05-20 07:12:39 +08:00
|
|
|
@__saveHistoryMarker()
|
|
|
|
if @_historyIndex > 0
|
|
|
|
@_markerIndex -= 1
|
|
|
|
@_historyIndex = @_markers[@_markerIndex]
|
|
|
|
return @_history[@_historyIndex]
|
2015-03-03 07:33:58 +08:00
|
|
|
else return null
|
|
|
|
|
|
|
|
redo: ->
|
2015-05-20 07:12:39 +08:00
|
|
|
@__saveHistoryMarker()
|
|
|
|
if @_historyIndex < (@_history.length - 1)
|
|
|
|
@_markerIndex += 1
|
|
|
|
@_historyIndex = @_markers[@_markerIndex]
|
|
|
|
return @_history[@_historyIndex]
|
2015-03-03 07:33:58 +08:00
|
|
|
else return null
|
|
|
|
|
2015-05-20 07:12:39 +08:00
|
|
|
saveToHistory: (historyItem) =>
|
2015-03-03 07:33:58 +08:00
|
|
|
if not _.isEqual((_.last(@_history) ? {}), historyItem)
|
2015-05-20 07:12:39 +08:00
|
|
|
@_historyIndex += 1
|
|
|
|
@_history.length = @_historyIndex
|
2015-03-03 07:33:58 +08:00
|
|
|
@_history.push(historyItem)
|
2015-05-20 07:12:39 +08:00
|
|
|
@_saveHistoryMarker()
|
2015-03-03 07:33:58 +08:00
|
|
|
while @_history.length > @_MAX_HISTORY_SIZE
|
|
|
|
@_history.shift()
|
2015-05-20 07:12:39 +08:00
|
|
|
@_historyIndex -= 1
|
2015-03-03 07:33:58 +08:00
|
|
|
|
2015-05-20 07:12:39 +08:00
|
|
|
__saveHistoryMarker: =>
|
|
|
|
if @_markers[@_markerIndex] isnt @_historyIndex
|
|
|
|
@_markerIndex += 1
|
|
|
|
@_markers.length = @_markerIndex
|
|
|
|
@_markers.push(@_historyIndex)
|
|
|
|
while @_markers.length > @_MAX_HISTORY_SIZE
|
|
|
|
@_markers.shift()
|
|
|
|
@_markerIndex -= 1
|
|
|
|
|
|
|
|
_saveHistoryMarker: _.debounce(UndoManager::__saveHistoryMarker, 300)
|