|
| 1 | +import classnames from 'classnames'; |
| 2 | +import {connect} from 'react-redux'; |
| 3 | +import onClickOutside from 'react-onclickoutside'; |
| 4 | +import partial from 'lodash/partial'; |
| 5 | +import preventClickthrough from 'react-prevent-clickthrough'; |
| 6 | +import property from 'lodash/property'; |
| 7 | +import PropTypes from 'prop-types'; |
| 8 | +import React from 'react'; |
| 9 | +import {closeTopBarMenu, toggleTopBarMenu} from '../../actions'; |
| 10 | +import {getOpenTopBarMenu} from '../../selectors'; |
| 11 | + |
| 12 | +export default function createMenu({mapPropsToItems, name}) { |
| 13 | + function mapStateToProps(state) { |
| 14 | + const isOpen = getOpenTopBarMenu(state) === name; |
| 15 | + return { |
| 16 | + isOpen, |
| 17 | + disableOnClickOutside: !isOpen, |
| 18 | + }; |
| 19 | + } |
| 20 | + |
| 21 | + function mapDispatchToProps(dispatch) { |
| 22 | + return { |
| 23 | + onClose() { |
| 24 | + dispatch(closeTopBarMenu(name)); |
| 25 | + }, |
| 26 | + |
| 27 | + onToggle() { |
| 28 | + dispatch(toggleTopBarMenu(name)); |
| 29 | + }, |
| 30 | + }; |
| 31 | + } |
| 32 | + |
| 33 | + return function createMenuWithMappedProps(Label, Item) { |
| 34 | + function Menu(props) { |
| 35 | + const {isOpen, onClickItem, onToggle} = props; |
| 36 | + const items = mapPropsToItems(props); |
| 37 | + const menu = isOpen ? |
| 38 | + ( |
| 39 | + <div |
| 40 | + className="top-bar__menu" |
| 41 | + onClick={preventClickthrough} |
| 42 | + > |
| 43 | + {items.map(({key, enabled, props: itemProps}) => ( |
| 44 | + <div |
| 45 | + className={classnames('top-bar__menu-item', |
| 46 | + {'top-bar__menu-item_active': enabled}, |
| 47 | + )} |
| 48 | + key={key} |
| 49 | + onClick={partial(onClickItem, key)} |
| 50 | + > |
| 51 | + <Item {...itemProps} /> |
| 52 | + </div> |
| 53 | + ))} |
| 54 | + </div> |
| 55 | + ) : null; |
| 56 | + |
| 57 | + return ( |
| 58 | + <div |
| 59 | + className={classnames( |
| 60 | + 'top-bar__menu-button', |
| 61 | + {'top-bar__menu-button_active': isOpen}, |
| 62 | + )} |
| 63 | + onClick={onToggle} |
| 64 | + > |
| 65 | + <Label /> |
| 66 | + {menu} |
| 67 | + </div> |
| 68 | + ); |
| 69 | + } |
| 70 | + |
| 71 | + Menu.displayName = `Menu(${name})`; |
| 72 | + |
| 73 | + Menu.propTypes = { |
| 74 | + isOpen: PropTypes.bool.isRequired, |
| 75 | + onClickItem: PropTypes.func.isRequired, |
| 76 | + onToggle: PropTypes.func.isRequired, |
| 77 | + }; |
| 78 | + |
| 79 | + return connect(mapStateToProps, mapDispatchToProps)( |
| 80 | + onClickOutside( |
| 81 | + Menu, |
| 82 | + {handleClickOutside: property('props.onClose')}, |
| 83 | + ), |
| 84 | + ); |
| 85 | + }; |
| 86 | +} |
0 commit comments