forked from hongymagic/react-collapsible-mixin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
react-collapsible-mixin.js
70 lines (60 loc) · 1.76 KB
/
react-collapsible-mixin.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
var React = require('react/addons');
var Types = React.PropTypes;
var cx = React.addons.classSet;
function isCollapsibleRef(ref) {
return ref.search(/^collapsible/) === 0;
}
function hasClass(className, _class) {
return (className || '').split(' ').indexOf(_class) >= 0;
}
var CollapsibleMixin = {
propTypes: {
expanded: Types.objectOf(Types.bool)
},
getInitialState: function () {
return {
expanded: this.props.expanded || {}
};
},
// When component mounts, inspect all the collapsible elements and
// determine their current expanded states by looking for class name `in`.
componentDidMount: function () {
var collapsibles = Object.keys(this.refs).filter(isCollapsibleRef);
var expanded = collapsibles.reduce(function (result, collapsible) {
result[collapsible] = hasClass(this.refs[collapsible].props.className, 'in');
return result;
}.bind(this), {});
this.setState({ expanded: expanded });
},
getCollapserClassSet: function (ref, defaults) {
defaults = defaults || {};
defaults.collapser = true;
defaults[ref] = true;
if (ref in this.state.expanded) {
defaults.collapsed = !this.state.expanded[ref];
}
return cx(defaults);
},
getCollapsibleClassSet: function (ref, defaults) {
defaults = defaults || {};
defaults.collapse = true;
defaults[ref] = true;
if (ref in this.state.expanded) {
defaults['in'] = this.state.expanded[ref];
}
return cx(defaults);
},
_onToggleCollapsible: function (event) {
var target = event.currentTarget.getAttribute('href');
var expanded = this.state.expanded;
if (target) {
event.preventDefault();
target = target.replace(/^#/, '');
expanded[target] = !this.state.expanded[target];
this.setState({
expanded: expanded
});
}
}
};
module.exports = CollapsibleMixin;