react-bootstrap
Version:
Bootstrap 3 components build with React
121 lines (97 loc) • 2.88 kB
JavaScript
var React = require('react');
var TransitionEvents = require('./utils/TransitionEvents');
var CollapsableMixin = {
propTypes: {
collapsable: React.PropTypes.bool,
defaultExpanded: React.PropTypes.bool,
expanded: React.PropTypes.bool
},
getInitialState: function () {
return {
expanded: this.props.defaultExpanded != null ? this.props.defaultExpanded : null,
collapsing: false
};
},
handleTransitionEnd: function () {
this._collapseEnd = true;
this.setState({
collapsing: false
});
},
componentWillReceiveProps: function (newProps) {
if (this.props.collapsable && newProps.expanded !== this.props.expanded) {
this._collapseEnd = false;
this.setState({
collapsing: true
});
}
},
_addEndTransitionListener: function () {
var node = this.getCollapsableDOMNode();
if (node) {
TransitionEvents.addEndEventListener(
node,
this.handleTransitionEnd
);
}
},
_removeEndTransitionListener: function () {
var node = this.getCollapsableDOMNode();
if (node) {
TransitionEvents.removeEndEventListener(
node,
this.handleTransitionEnd
);
}
},
componentDidMount: function () {
this._afterRender();
},
componentWillUnmount: function () {
this._removeEndTransitionListener();
},
componentWillUpdate: function (nextProps) {
var dimension = (typeof this.getCollapsableDimension === 'function') ?
this.getCollapsableDimension() : 'height';
var node = this.getCollapsableDOMNode();
this._removeEndTransitionListener();
},
componentDidUpdate: function (prevProps, prevState) {
this._afterRender();
},
_afterRender: function () {
if (!this.props.collapsable) {
return;
}
this._addEndTransitionListener();
setTimeout(this._updateDimensionAfterRender, 0);
},
_updateDimensionAfterRender: function () {
var node = this.getCollapsableDOMNode();
if (node) {
var dimension = (typeof this.getCollapsableDimension === 'function') ?
this.getCollapsableDimension() : 'height';
node.style[dimension] = this.isExpanded() ?
this.getCollapsableDimensionValue() + 'px' : '0px';
}
},
isExpanded: function () {
return (this.props.expanded != null) ?
this.props.expanded : this.state.expanded;
},
getCollapsableClassSet: function (className) {
var classes = {};
if (typeof className === 'string') {
className.split(' ').forEach(function (className) {
if (className) {
classes[className] = true;
}
});
}
classes.collapsing = this.state.collapsing;
classes.collapse = !this.state.collapsing;
classes['in'] = this.isExpanded() && !this.state.collapsing;
return classes;
}
};
module.exports = CollapsableMixin;