-
Notifications
You must be signed in to change notification settings - Fork 0
/
react-state-reloader.js
93 lines (84 loc) · 2.58 KB
/
react-state-reloader.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
/**
* ReactStateReloader v0.1
*/
(function() {
function isEmpty(obj) {
if (obj.length > 0) return false;
if (obj.length === 0) return true;
for (var k in obj) {
if (obj.hasOwnProperty(k)) return false;
}
return true;
}
function getStateHierarchy(componentInstance) {
if (!componentInstance) return {};
var state = componentInstance.state || null;
var renderedComponent = componentInstance._renderedComponent;
var children = renderedComponent ? (renderedComponent._renderedChildren || null) : null;
var childHierarchies = {};
if (children) {
for (var k in children) {
if (children.hasOwnProperty(k)) {
var childHierarchy = getStateHierarchy(children[k]);
if (!isEmpty(childHierarchy)) {
childHierarchies[k] = childHierarchy;
}
}
}
}
var result = {};
if (state) result.state = state;
if (!isEmpty(childHierarchies)) result.children = childHierarchies;
return result;
}
function withPrevStateHierarchy(componentInstance, props) {
var newProps = {prevStateHierarchy: getStateHierarchy(componentInstance)};
for (var k in props) {
if (props.hasOwnProperty(k)) {
newProps[k] = props[k];
}
}
return newProps;
}
function getCompPrevStateHierarchy() {
var prevStateHierarchy = this.props.prevStateHierarchy;
if (prevStateHierarchy) {
if (this._mountDepth == 0) {
return prevStateHierarchy;
} else {
var mountIndex = this._rootNodeID.split('.').slice(-1)[0];
var thisHierarchy = prevStateHierarchy['.' + mountIndex];
return thisHierarchy;
}
}
return {};
}
function getCompPreviousRenderState(defaultState) {
return this.getPrevStateHierarchy().state || defaultState;
}
function withCompPrevStateHierarchy(props) {
var prevStateHierarchy = this.getPrevStateHierarchy();
if (prevStateHierarchy && prevStateHierarchy.children) {
var newProps = {};
for (var k in props) {
if (props.hasOwnProperty(k)) {
newProps[k] = props[k];
}
}
newProps.prevStateHierarchy = prevStateHierarchy.children;
return newProps;
}
return props;
}
var ComponentMixin = {
getPrevStateHierarchy: getCompPrevStateHierarchy,
getPreviousRenderState: getCompPreviousRenderState,
withPrevStateHierarchy: withCompPrevStateHierarchy
};
var M = {
getStateHierarchy: getStateHierarchy,
withPrevStateHierarchy: withPrevStateHierarchy,
ComponentMixin: ComponentMixin
};
window.ReactStateReloader = M;
})();