闭社主体 forked from https://github.com/tootsuite/mastodon
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.

94 lines
2.5 KiB

  1. import React from 'react';
  2. import Dropdown, { DropdownTrigger, DropdownContent } from 'react-simple-dropdown';
  3. import PropTypes from 'prop-types';
  4. export default 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. // Don't call e.preventDefault() when the item uses 'href' property.
  29. // ex. "Edit profile" on the account action bar
  30. if (typeof action === 'function') {
  31. e.preventDefault();
  32. action();
  33. } else if (to) {
  34. e.preventDefault();
  35. this.context.router.history.push(to);
  36. }
  37. this.dropdown.hide();
  38. }
  39. handleShow = () => this.setState({ expanded: true })
  40. handleHide = () => this.setState({ expanded: false })
  41. renderItem = (item, i) => {
  42. if (item === null) {
  43. return <li key={`sep-${i}`} className='dropdown__sep' />;
  44. }
  45. const { text, href = '#' } = item;
  46. return (
  47. <li className='dropdown__content-list-item' key={`${text}-${i}`}>
  48. <a href={href} target='_blank' rel='noopener' onClick={this.handleClick} data-index={i} className='dropdown__content-list-link'>
  49. {text}
  50. </a>
  51. </li>
  52. );
  53. }
  54. render () {
  55. const { icon, items, size, direction, ariaLabel } = this.props;
  56. const { expanded } = this.state;
  57. const directionClass = (direction === 'left') ? 'dropdown__left' : 'dropdown__right';
  58. const dropdownItems = expanded && (
  59. <ul className='dropdown__content-list'>
  60. {items.map(this.renderItem)}
  61. </ul>
  62. );
  63. return (
  64. <Dropdown ref={this.setRef} onShow={this.handleShow} onHide={this.handleHide}>
  65. <DropdownTrigger className='icon-button' style={{ fontSize: `${size}px`, width: `${size}px`, lineHeight: `${size}px` }} aria-label={ariaLabel}>
  66. <i className={`fa fa-fw fa-${icon} dropdown__icon`} aria-hidden />
  67. </DropdownTrigger>
  68. <DropdownContent className={directionClass}>
  69. {dropdownItems}
  70. </DropdownContent>
  71. </Dropdown>
  72. );
  73. }
  74. }