-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
131 lines (109 loc) · 3.06 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/**
* Storeon module to add undo and redo functionality
* @param {String[]} paths The keys of state object
* that will be store in history
* @param {Object} config The config object
* @param {String} [config.key='undoable'] The default state key
* for storing history (when omitted and `paths` is not empty
* will be generated based on `paths` content)
*/
let createHistory = function (paths, config) {
if (process.env.NODE_ENV === 'development' && !paths) {
throw new Error('The paths parameter should be an array: createHistory([])')
}
config = config || {}
let key = config.key || 'undoable'
if (!config.key && paths.length > 0) {
key += '_' + paths.join('_')
}
let undo = Symbol('u_' + key)
let redo = Symbol('r_' + key)
return {
module (store) {
let ignoreNext = false
store.on('@init', state => {
ignoreNext = true
return {
[key]: {
past: [],
present: filterState(paths, state),
future: []
}
}
})
store.on('@changed', (state, changes) => {
if (ignoreNext) {
ignoreNext = false
return
}
if (paths.length) {
let changedKeys = Object.keys(changes)
let inPaths = false
for (let changedKey of changedKeys) {
if (paths.includes(changedKey)) {
inPaths = true
break
}
}
if (!inPaths) {
return
}
}
ignoreNext = true
let undoable = state[key]
state = filterState(paths, state)
delete state[key]
return {
[key]: {
past: [].concat(undoable.past, [undoable.present]),
present: state,
future: []
}
}
})
store.on(undo, state => {
ignoreNext = true
let undoable = state[key]
if (undoable.past.length === 0) return
state = filterState(paths, state)
delete state[key]
let before = undoable.past[undoable.past.length - 1]
return Object.assign({}, before, {
[key]: {
present: before,
past: undoable.past.slice(0, -1),
future: [].concat(undoable.future, [state])
}
})
})
store.on(redo, state => {
ignoreNext = true
let undoable = state[key]
if (undoable.future.length === 0) return
state = filterState(paths, state)
delete state[key]
let next = undoable.future[undoable.future.length - 1]
return Object.assign({}, next, {
[key]: {
present: next,
past: [].concat(undoable.past, [state]),
future: undoable.future.slice(0, -1)
}
})
})
},
UNDO: undo,
REDO: redo
}
}
function filterState (paths, state) {
if (paths.length === 0) {
return Object.assign({}, state)
}
let filteredState = {}
for (let p of paths) {
filteredState[p] = state[p]
}
return filteredState
}
module.exports = { createHistory }