You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.3 KiB

  1. import React from 'react';
  2. import Dropdown, { DropdownTrigger, DropdownContent } from 'react-simple-dropdown';
  3. import PropTypes from 'prop-types';
  4. class DropdownMenu extends React.PureComponent {
  5. static contextTypes = {
  6. router: PropTypes.object,
  7. };
  8. static propTypes = {
  9. icon: PropTypes.string.isRequired,
  10. items: PropTypes.array.isRequired,
  11. size: PropTypes.number.isRequired,
  12. direction: PropTypes.string,
  13. ariaLabel: PropTypes.string,
  14. };
  15. static defaultProps = {
  16. ariaLabel: "Menu",
  17. };
  18. state = {
  19. direction: 'left',
  20. expanded: false,
  21. };
  22. setRef = (c) => {
  23. this.dropdown = c;
  24. }
  25. handleClick = (e) => {
  26. const i = Number(e.currentTarget.getAttribute('data-index'));
  27. const { action, to } = this.props.items[i];
  28. e.preventDefault();
  29. if (typeof action === 'function') {
  30. action();
  31. } else if (to) {
  32. this.context.router.push(to);
  33. }
  34. this.dropdown.hide();
  35. }
  36. handleShow = () => this.setState({ expanded: true })
  37. handleHide = () => this.setState({ expanded: false })
  38. renderItem = (item, i) => {
  39. if (item === null) {
  40. return <li key={ 'sep' + i } className='dropdown__sep' />;
  41. }
  42. const { text, action, href = '#' } = item;
  43. return (
  44. <li className='dropdown__content-list-item' key={ text + i }>
  45. <a href={href} target='_blank' rel='noopener' onClick={this.handleClick} data-index={i} className='dropdown__content-list-link'>
  46. {text}
  47. </a>
  48. </li>
  49. );
  50. }
  51. render () {
  52. const { icon, items, size, direction, ariaLabel } = this.props;
  53. const { expanded } = this.state;
  54. const directionClass = (direction === "left") ? "dropdown__left" : "dropdown__right";
  55. const dropdownItems = expanded && (
  56. <ul className='dropdown__content-list'>
  57. {items.map(this.renderItem)}
  58. </ul>
  59. );
  60. return (
  61. <Dropdown ref={this.setRef} onShow={this.handleShow} onHide={this.handleHide}>
  62. <DropdownTrigger className='icon-button' style={{ fontSize: `${size}px`, width: `${size}px`, lineHeight: `${size}px` }} aria-label={ariaLabel}>
  63. <i className={ `fa fa-fw fa-${icon} dropdown__icon` } aria-hidden={true} />
  64. </DropdownTrigger>
  65. <DropdownContent className={directionClass}>
  66. {dropdownItems}
  67. </DropdownContent>
  68. </Dropdown>
  69. );
  70. }
  71. }
  72. export default DropdownMenu;