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.

295 lines
7.7 KiB

  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import ImmutablePropTypes from 'react-immutable-proptypes';
  4. import IconButton from './icon_button';
  5. import Overlay from 'react-overlays/lib/Overlay';
  6. import Motion from '../features/ui/util/optional_motion';
  7. import spring from 'react-motion/lib/spring';
  8. import { supportsPassiveEvents } from 'detect-passive-events';
  9. const listenerOptions = supportsPassiveEvents ? { passive: true } : false;
  10. let id = 0;
  11. class DropdownMenu extends React.PureComponent {
  12. static contextTypes = {
  13. router: PropTypes.object,
  14. };
  15. static propTypes = {
  16. items: PropTypes.array.isRequired,
  17. onClose: PropTypes.func.isRequired,
  18. style: PropTypes.object,
  19. placement: PropTypes.string,
  20. arrowOffsetLeft: PropTypes.string,
  21. arrowOffsetTop: PropTypes.string,
  22. openedViaKeyboard: PropTypes.bool,
  23. };
  24. static defaultProps = {
  25. style: {},
  26. placement: 'bottom',
  27. };
  28. state = {
  29. mounted: false,
  30. };
  31. handleDocumentClick = e => {
  32. if (this.node && !this.node.contains(e.target)) {
  33. this.props.onClose();
  34. }
  35. }
  36. componentDidMount () {
  37. document.addEventListener('click', this.handleDocumentClick, false);
  38. document.addEventListener('keydown', this.handleKeyDown, false);
  39. document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
  40. if (this.focusedItem && this.props.openedViaKeyboard) {
  41. this.focusedItem.focus({ preventScroll: true });
  42. }
  43. this.setState({ mounted: true });
  44. }
  45. componentWillUnmount () {
  46. document.removeEventListener('click', this.handleDocumentClick, false);
  47. document.removeEventListener('keydown', this.handleKeyDown, false);
  48. document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
  49. }
  50. setRef = c => {
  51. this.node = c;
  52. }
  53. setFocusRef = c => {
  54. this.focusedItem = c;
  55. }
  56. handleKeyDown = e => {
  57. const items = Array.from(this.node.getElementsByTagName('a'));
  58. const index = items.indexOf(document.activeElement);
  59. let element = null;
  60. switch(e.key) {
  61. case 'ArrowDown':
  62. element = items[index+1] || items[0];
  63. break;
  64. case 'ArrowUp':
  65. element = items[index-1] || items[items.length-1];
  66. break;
  67. case 'Tab':
  68. if (e.shiftKey) {
  69. element = items[index-1] || items[items.length-1];
  70. } else {
  71. element = items[index+1] || items[0];
  72. }
  73. break;
  74. case 'Home':
  75. element = items[0];
  76. break;
  77. case 'End':
  78. element = items[items.length-1];
  79. break;
  80. case 'Escape':
  81. this.props.onClose();
  82. break;
  83. }
  84. if (element) {
  85. element.focus();
  86. e.preventDefault();
  87. e.stopPropagation();
  88. }
  89. }
  90. handleItemKeyPress = e => {
  91. if (e.key === 'Enter' || e.key === ' ') {
  92. this.handleClick(e);
  93. }
  94. }
  95. handleClick = e => {
  96. const i = Number(e.currentTarget.getAttribute('data-index'));
  97. const { action, to } = this.props.items[i];
  98. this.props.onClose();
  99. if (typeof action === 'function') {
  100. e.preventDefault();
  101. action(e);
  102. } else if (to) {
  103. e.preventDefault();
  104. this.context.router.history.push(to);
  105. }
  106. }
  107. renderItem (option, i) {
  108. if (option === null) {
  109. return <li key={`sep-${i}`} className='dropdown-menu__separator' />;
  110. }
  111. const { text, href = '#', target = '_blank', method } = option;
  112. return (
  113. <li className='dropdown-menu__item' key={`${text}-${i}`}>
  114. <a href={href} target={target} data-method={method} rel='noopener noreferrer' role='button' tabIndex='0' ref={i === 0 ? this.setFocusRef : null} onClick={this.handleClick} onKeyPress={this.handleItemKeyPress} data-index={i}>
  115. {text}
  116. </a>
  117. </li>
  118. );
  119. }
  120. render () {
  121. const { items, style, placement, arrowOffsetLeft, arrowOffsetTop } = this.props;
  122. const { mounted } = this.state;
  123. return (
  124. <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}>
  125. {({ opacity, scaleX, scaleY }) => (
  126. // It should not be transformed when mounting because the resulting
  127. // size will be used to determine the coordinate of the menu by
  128. // react-overlays
  129. <div className={`dropdown-menu ${placement}`} style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null }} ref={this.setRef}>
  130. <div className={`dropdown-menu__arrow ${placement}`} style={{ left: arrowOffsetLeft, top: arrowOffsetTop }} />
  131. <ul>
  132. {items.map((option, i) => this.renderItem(option, i))}
  133. </ul>
  134. </div>
  135. )}
  136. </Motion>
  137. );
  138. }
  139. }
  140. export default class Dropdown extends React.PureComponent {
  141. static contextTypes = {
  142. router: PropTypes.object,
  143. };
  144. static propTypes = {
  145. icon: PropTypes.string.isRequired,
  146. items: PropTypes.array.isRequired,
  147. size: PropTypes.number.isRequired,
  148. title: PropTypes.string,
  149. disabled: PropTypes.bool,
  150. status: ImmutablePropTypes.map,
  151. isUserTouching: PropTypes.func,
  152. isModalOpen: PropTypes.bool.isRequired,
  153. onOpen: PropTypes.func.isRequired,
  154. onClose: PropTypes.func.isRequired,
  155. dropdownPlacement: PropTypes.string,
  156. openDropdownId: PropTypes.number,
  157. openedViaKeyboard: PropTypes.bool,
  158. };
  159. static defaultProps = {
  160. title: 'Menu',
  161. };
  162. state = {
  163. id: id++,
  164. };
  165. handleClick = ({ target, type }) => {
  166. if (this.state.id === this.props.openDropdownId) {
  167. this.handleClose();
  168. } else {
  169. const { top } = target.getBoundingClientRect();
  170. const placement = top * 2 < innerHeight ? 'bottom' : 'top';
  171. this.props.onOpen(this.state.id, this.handleItemClick, placement, type !== 'click');
  172. }
  173. }
  174. handleClose = () => {
  175. if (this.activeElement) {
  176. this.activeElement.focus({ preventScroll: true });
  177. this.activeElement = null;
  178. }
  179. this.props.onClose(this.state.id);
  180. }
  181. handleMouseDown = () => {
  182. if (!this.state.open) {
  183. this.activeElement = document.activeElement;
  184. }
  185. }
  186. handleButtonKeyDown = (e) => {
  187. switch(e.key) {
  188. case ' ':
  189. case 'Enter':
  190. this.handleMouseDown();
  191. break;
  192. }
  193. }
  194. handleKeyPress = (e) => {
  195. switch(e.key) {
  196. case ' ':
  197. case 'Enter':
  198. this.handleClick(e);
  199. e.stopPropagation();
  200. e.preventDefault();
  201. break;
  202. }
  203. }
  204. handleItemClick = e => {
  205. const i = Number(e.currentTarget.getAttribute('data-index'));
  206. const { action, to } = this.props.items[i];
  207. this.handleClose();
  208. if (typeof action === 'function') {
  209. e.preventDefault();
  210. action();
  211. } else if (to) {
  212. e.preventDefault();
  213. this.context.router.history.push(to);
  214. }
  215. }
  216. setTargetRef = c => {
  217. this.target = c;
  218. }
  219. findTarget = () => {
  220. return this.target;
  221. }
  222. componentWillUnmount = () => {
  223. if (this.state.id === this.props.openDropdownId) {
  224. this.handleClose();
  225. }
  226. }
  227. render () {
  228. const { icon, items, size, title, disabled, dropdownPlacement, openDropdownId, openedViaKeyboard } = this.props;
  229. const open = this.state.id === openDropdownId;
  230. return (
  231. <div>
  232. <IconButton
  233. icon={icon}
  234. title={title}
  235. active={open}
  236. disabled={disabled}
  237. size={size}
  238. ref={this.setTargetRef}
  239. onClick={this.handleClick}
  240. onMouseDown={this.handleMouseDown}
  241. onKeyDown={this.handleButtonKeyDown}
  242. onKeyPress={this.handleKeyPress}
  243. />
  244. <Overlay show={open} placement={dropdownPlacement} target={this.findTarget}>
  245. <DropdownMenu items={items} onClose={this.handleClose} openedViaKeyboard={openedViaKeyboard} />
  246. </Overlay>
  247. </div>
  248. );
  249. }
  250. }