-
Notifications
You must be signed in to change notification settings - Fork 478
/
FlowTreeModifier.js
65 lines (49 loc) · 1.57 KB
/
FlowTreeModifier.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
import { traversalSearch } from 'shared/utils/traversal';
const executeApplyFn = (apply, node) => (typeof apply === 'function' ? apply(node) : apply);
const UpdatesMap = {
name(node, apply) {
node.name = executeApplyFn(apply, node);
},
prefixName(node, apply) {
node.prefixName = executeApplyFn(apply, node);
},
type(node, apply) {
node.type = executeApplyFn(apply, node);
},
body(node, apply) {
node.body = executeApplyFn(apply, node);
},
parent(node, apply) {
node.parent = executeApplyFn(apply, node);
}
};
const applyModifierUpdates = (tree, modifier) => {
const nodes = traversalSearch(tree, modifier.test);
if (!nodes.length) return;
const updates = Object.keys(modifier.updates || {});
updates.filter(i => i !== 'subTreeUpdate').forEach(updateName => {
nodes.forEach(node => {
UpdatesMap[updateName](node, modifier.updates[updateName]);
});
});
if (updates.includes('subTreeUpdate')) {
modifier.updates.subTreeUpdate(nodes, tree);
}
};
export default () => {
const modifiersList = [];
return {
addModifier(modifier) {
[].concat(modifier).forEach(item => modifiersList.push(item));
},
create(test, updates) {
this.addModifier({ test, updates });
},
runModifier(tree, modifier) {
applyModifierUpdates(tree, modifier);
},
applyTo(tree) {
modifiersList.forEach(modifier => this.runModifier(tree, modifier));
}
};
};