-
Notifications
You must be signed in to change notification settings - Fork 2
/
state.js
86 lines (75 loc) · 1.95 KB
/
state.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
'use strict';
const isDeepEqual = require('deep-equal');
const CallResolver = require('./lib/things/call-resolver');
const values = require('abstract-things/values');
module.exports = {
/**
* Capture the state of things in this collection returning an object
* that can serialized to JSON.
*/
captureState(collection) {
return collection.captureState()
.then(result => {
const data = {};
for(const item of result) {
if(item.isFulfilled) {
const json = values.toJSON('mixed', item.value);
data[item.thing.id] = json;
}
}
return data;
});
},
/**
* Restore a state previously captured with captureState.
*/
restoreState(collection, data) {
const instances = [];
const promises = [];
for(const thing of collection) {
const state = data[thing.id];
if(state) {
instances.push(thing);
promises.push(thing.setState(state));
}
}
return new CallResolver(instances, promises);
},
undoableStateChange(collection, func) {
const captureState = module.exports.captureState;
let originalState;
return captureState(collection)
.then(state => {
originalState = state;
return func();
})
.then(() => captureState(collection))
.then(changedState => {
return new Undoable(collection, originalState, changedState);
});
}
};
class Undoable {
constructor(collection, originalState, changedState) {
this.collection = collection;
const result = {};
for(const thing of Object.keys(changedState)) {
const original = originalState[thing];
if(! original) continue;
const changed = changedState[thing];
const thingState = {};
for(const key of Object.keys(original)) {
const oldValue = original[key];
const newValue = changed[key];
if(! isDeepEqual(oldValue, newValue)) {
thingState[key] = oldValue;
}
}
result[thing] = thingState;
}
this.state = result;
}
undo() {
return module.exports.restoreState(this.collection, this.state);
}
}