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.

294 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. onOpen: PropTypes.func.isRequired,
  153. onClose: PropTypes.func.isRequired,
  154. dropdownPlacement: PropTypes.string,
  155. openDropdownId: PropTypes.number,
  156. openedViaKeyboard: PropTypes.bool,
  157. };
  158. static defaultProps = {
  159. title: 'Menu',
  160. };
  161. state = {
  162. id: id++,
  163. };
  164. handleClick = ({ target, type }) => {
  165. if (this.state.id === this.props.openDropdownId) {
  166. this.handleClose();
  167. } else {
  168. const { top } = target.getBoundingClientRect();
  169. const placement = top * 2 < innerHeight ? 'bottom' : 'top';
  170. this.props.onOpen(this.state.id, this.handleItemClick, placement, type !== 'click');
  171. }
  172. }
  173. handleClose = () => {
  174. if (this.activeElement) {
  175. this.activeElement.focus({ preventScroll: true });
  176. this.activeElement = null;
  177. }
  178. this.props.onClose(this.state.id);
  179. }
  180. handleMouseDown = () => {
  181. if (!this.state.open) {
  182. this.activeElement = document.activeElement;
  183. }
  184. }
  185. handleButtonKeyDown = (e) => {
  186. switch(e.key) {
  187. case ' ':
  188. case 'Enter':
  189. this.handleMouseDown();
  190. break;
  191. }
  192. }
  193. handleKeyPress = (e) => {
  194. switch(e.key) {
  195. case ' ':
  196. case 'Enter':
  197. this.handleClick(e);
  198. e.stopPropagation();
  199. e.preventDefault();
  200. break;
  201. }
  202. }
  203. handleItemClick = e => {
  204. const i = Number(e.currentTarget.getAttribute('data-index'));
  205. const { action, to } = this.props.items[i];
  206. this.handleClose();
  207. if (typeof action === 'function') {
  208. e.preventDefault();
  209. action();
  210. } else if (to) {
  211. e.preventDefault();
  212. this.context.router.history.push(to);
  213. }
  214. }
  215. setTargetRef = c => {
  216. this.target = c;
  217. }
  218. findTarget = () => {
  219. return this.target;
  220. }
  221. componentWillUnmount = () => {
  222. if (this.state.id === this.props.openDropdownId) {
  223. this.handleClose();
  224. }
  225. }
  226. render () {
  227. const { icon, items, size, title, disabled, dropdownPlacement, openDropdownId, openedViaKeyboard } = this.props;
  228. const open = this.state.id === openDropdownId;
  229. return (
  230. <div>
  231. <IconButton
  232. icon={icon}
  233. title={title}
  234. active={open}
  235. disabled={disabled}
  236. size={size}
  237. ref={this.setTargetRef}
  238. onClick={this.handleClick}
  239. onMouseDown={this.handleMouseDown}
  240. onKeyDown={this.handleButtonKeyDown}
  241. onKeyPress={this.handleKeyPress}
  242. />
  243. <Overlay show={open} placement={dropdownPlacement} target={this.findTarget}>
  244. <DropdownMenu items={items} onClose={this.handleClose} openedViaKeyboard={openedViaKeyboard} />
  245. </Overlay>
  246. </div>
  247. );
  248. }
  249. }