ssc-refer
Version:
React refer component for SSC 3.0
80 lines (66 loc) • 2.72 kB
JavaScript
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import React, { PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import getDisplayName from '../refer/utils/getDisplayName';
import scrollIntoViewIfNeeded from '../refer/utils/scrollIntoViewIfNeeded';
var menuItemContainer = function menuItemContainer(Component) {
return React.createClass({
displayName: 'menuItemContainer(' + getDisplayName(Component) + ')',
propTypes: {
option: PropTypes.oneOfType([PropTypes.object, PropTypes.string]).isRequired,
position: PropTypes.number
},
contextTypes: {
activeIndex: PropTypes.number.isRequired,
onActiveItemChange: PropTypes.func.isRequired,
onInitialItemChange: PropTypes.func.isRequired,
onMenuItemClick: PropTypes.func.isRequired
},
componentWillMount: function componentWillMount() {
this._updateInitialItem(this.props);
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps, nextContext) {
var currentlyActive = this.context.activeIndex === this.props.position;
var option = nextProps.option,
position = nextProps.position;
var activeIndex = nextContext.activeIndex,
onActiveItemChange = nextContext.onActiveItemChange;
if (position == null) {
return;
}
// The item will become active.
if (activeIndex === position) {
// Ensures that if the menu items exceed the bounds of the menu, the
// menu will scroll up or down as the user hits the arrow keys.
scrollIntoViewIfNeeded(findDOMNode(this));
// Fire the change handler when the menu item becomes active.
!currentlyActive && onActiveItemChange(option);
}
this._updateInitialItem(nextProps);
},
render: function render() {
var _context = this.context,
activeIndex = _context.activeIndex,
onMenuItemClick = _context.onMenuItemClick;
var _props = this.props,
option = _props.option,
position = _props.position,
props = _objectWithoutProperties(_props, ['option', 'position']);
return React.createElement(Component, _extends({}, props, {
active: activeIndex === position,
onClick: function onClick() {
return onMenuItemClick(option);
}
}));
},
_updateInitialItem: function _updateInitialItem(props) {
var option = props.option,
position = props.position;
if (position === 0) {
this.context.onInitialItemChange(option);
}
}
});
};
export default menuItemContainer;