language_dropdown.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { injectIntl, defineMessages } from 'react-intl';
  4. import TextIconButton from './text_icon_button';
  5. import Overlay from 'react-overlays/lib/Overlay';
  6. import Motion from 'mastodon/features/ui/util/optional_motion';
  7. import spring from 'react-motion/lib/spring';
  8. import { supportsPassiveEvents } from 'detect-passive-events';
  9. import classNames from 'classnames';
  10. import { languages as preloadedLanguages } from 'mastodon/initial_state';
  11. import fuzzysort from 'fuzzysort';
  12. const messages = defineMessages({
  13. changeLanguage: { id: 'compose.language.change', defaultMessage: 'Change language' },
  14. search: { id: 'compose.language.search', defaultMessage: 'Search languages...' },
  15. clear: { id: 'emoji_button.clear', defaultMessage: 'Clear' },
  16. });
  17. // Copied from emoji-mart for consistency with emoji picker and since
  18. // they don't export the icons in the package
  19. const icons = {
  20. loupe: (
  21. <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' width='13' height='13'>
  22. <path d='M12.9 14.32a8 8 0 1 1 1.41-1.41l5.35 5.33-1.42 1.42-5.33-5.34zM8 14A6 6 0 1 0 8 2a6 6 0 0 0 0 12z' />
  23. </svg>
  24. ),
  25. delete: (
  26. <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' width='13' height='13'>
  27. <path d='M10 8.586L2.929 1.515 1.515 2.929 8.586 10l-7.071 7.071 1.414 1.414L10 11.414l7.071 7.071 1.414-1.414L11.414 10l7.071-7.071-1.414-1.414L10 8.586z' />
  28. </svg>
  29. ),
  30. };
  31. const listenerOptions = supportsPassiveEvents ? { passive: true } : false;
  32. class LanguageDropdownMenu extends React.PureComponent {
  33. static propTypes = {
  34. style: PropTypes.object,
  35. value: PropTypes.string.isRequired,
  36. frequentlyUsedLanguages: PropTypes.arrayOf(PropTypes.string).isRequired,
  37. placement: PropTypes.string.isRequired,
  38. onClose: PropTypes.func.isRequired,
  39. onChange: PropTypes.func.isRequired,
  40. languages: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.string)),
  41. intl: PropTypes.object,
  42. };
  43. static defaultProps = {
  44. languages: preloadedLanguages,
  45. };
  46. state = {
  47. mounted: false,
  48. searchValue: '',
  49. };
  50. handleDocumentClick = e => {
  51. if (this.node && !this.node.contains(e.target)) {
  52. this.props.onClose();
  53. }
  54. }
  55. componentDidMount () {
  56. document.addEventListener('click', this.handleDocumentClick, false);
  57. document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
  58. this.setState({ mounted: true });
  59. }
  60. componentWillUnmount () {
  61. document.removeEventListener('click', this.handleDocumentClick, false);
  62. document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
  63. }
  64. setRef = c => {
  65. this.node = c;
  66. }
  67. setListRef = c => {
  68. this.listNode = c;
  69. }
  70. handleSearchChange = ({ target }) => {
  71. this.setState({ searchValue: target.value });
  72. }
  73. search () {
  74. const { languages, value, frequentlyUsedLanguages } = this.props;
  75. const { searchValue } = this.state;
  76. if (searchValue === '') {
  77. return [...languages].sort((a, b) => {
  78. // Push current selection to the top of the list
  79. if (a[0] === value) {
  80. return -1;
  81. } else if (b[0] === value) {
  82. return 1;
  83. } else {
  84. // Sort according to frequently used languages
  85. const indexOfA = frequentlyUsedLanguages.indexOf(a[0]);
  86. const indexOfB = frequentlyUsedLanguages.indexOf(b[0]);
  87. return ((indexOfA > -1 ? indexOfA : Infinity) - (indexOfB > -1 ? indexOfB : Infinity));
  88. }
  89. });
  90. }
  91. return fuzzysort.go(searchValue, languages, {
  92. keys: ['0', '1', '2'],
  93. limit: 5,
  94. threshold: -10000,
  95. }).map(result => result.obj);
  96. }
  97. frequentlyUsed () {
  98. const { languages, value } = this.props;
  99. const current = languages.find(lang => lang[0] === value);
  100. const results = [];
  101. if (current) {
  102. results.push(current);
  103. }
  104. return results;
  105. }
  106. handleClick = e => {
  107. const value = e.currentTarget.getAttribute('data-index');
  108. e.preventDefault();
  109. this.props.onClose();
  110. this.props.onChange(value);
  111. }
  112. handleKeyDown = e => {
  113. const { onClose } = this.props;
  114. const index = Array.from(this.listNode.childNodes).findIndex(node => node === e.currentTarget);
  115. let element = null;
  116. switch(e.key) {
  117. case 'Escape':
  118. onClose();
  119. break;
  120. case 'Enter':
  121. this.handleClick(e);
  122. break;
  123. case 'ArrowDown':
  124. element = this.listNode.childNodes[index + 1] || this.listNode.firstChild;
  125. break;
  126. case 'ArrowUp':
  127. element = this.listNode.childNodes[index - 1] || this.listNode.lastChild;
  128. break;
  129. case 'Tab':
  130. if (e.shiftKey) {
  131. element = this.listNode.childNodes[index - 1] || this.listNode.lastChild;
  132. } else {
  133. element = this.listNode.childNodes[index + 1] || this.listNode.firstChild;
  134. }
  135. break;
  136. case 'Home':
  137. element = this.listNode.firstChild;
  138. break;
  139. case 'End':
  140. element = this.listNode.lastChild;
  141. break;
  142. }
  143. if (element) {
  144. element.focus();
  145. e.preventDefault();
  146. e.stopPropagation();
  147. }
  148. }
  149. handleSearchKeyDown = e => {
  150. const { onChange, onClose } = this.props;
  151. const { searchValue } = this.state;
  152. let element = null;
  153. switch(e.key) {
  154. case 'Tab':
  155. case 'ArrowDown':
  156. element = this.listNode.firstChild;
  157. if (element) {
  158. element.focus();
  159. e.preventDefault();
  160. e.stopPropagation();
  161. }
  162. break;
  163. case 'Enter':
  164. element = this.listNode.firstChild;
  165. if (element) {
  166. onChange(element.getAttribute('data-index'));
  167. onClose();
  168. }
  169. break;
  170. case 'Escape':
  171. if (searchValue !== '') {
  172. e.preventDefault();
  173. this.handleClear();
  174. }
  175. break;
  176. }
  177. }
  178. handleClear = () => {
  179. this.setState({ searchValue: '' });
  180. }
  181. renderItem = lang => {
  182. const { value } = this.props;
  183. return (
  184. <div key={lang[0]} role='option' tabIndex='0' data-index={lang[0]} className={classNames('language-dropdown__dropdown__results__item', { active: lang[0] === value })} aria-selected={lang[0] === value} onClick={this.handleClick} onKeyDown={this.handleKeyDown}>
  185. <span className='language-dropdown__dropdown__results__item__native-name' lang={lang[0]}>{lang[2]}</span> <span className='language-dropdown__dropdown__results__item__common-name'>({lang[1]})</span>
  186. </div>
  187. );
  188. }
  189. render () {
  190. const { style, placement, intl } = this.props;
  191. const { mounted, searchValue } = this.state;
  192. const isSearching = searchValue !== '';
  193. const results = this.search();
  194. return (
  195. <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 }) }}>
  196. {({ opacity, scaleX, scaleY }) => (
  197. // It should not be transformed when mounting because the resulting
  198. // size will be used to determine the coordinate of the menu by
  199. // react-overlays
  200. <div className={`language-dropdown__dropdown ${placement}`} style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null }} ref={this.setRef}>
  201. <div className='emoji-mart-search'>
  202. <input type='search' value={searchValue} onChange={this.handleSearchChange} onKeyDown={this.handleSearchKeyDown} placeholder={intl.formatMessage(messages.search)} autoFocus />
  203. <button className='emoji-mart-search-icon' disabled={!isSearching} aria-label={intl.formatMessage(messages.clear)} onClick={this.handleClear}>{!isSearching ? icons.loupe : icons.delete}</button>
  204. </div>
  205. <div className='language-dropdown__dropdown__results emoji-mart-scroll' role='listbox' ref={this.setListRef}>
  206. {results.map(this.renderItem)}
  207. </div>
  208. </div>
  209. )}
  210. </Motion>
  211. );
  212. }
  213. }
  214. export default @injectIntl
  215. class LanguageDropdown extends React.PureComponent {
  216. static propTypes = {
  217. value: PropTypes.string,
  218. frequentlyUsedLanguages: PropTypes.arrayOf(PropTypes.string),
  219. intl: PropTypes.object.isRequired,
  220. onChange: PropTypes.func,
  221. onClose: PropTypes.func,
  222. };
  223. state = {
  224. open: false,
  225. placement: 'bottom',
  226. };
  227. handleToggle = ({ target }) => {
  228. const { top } = target.getBoundingClientRect();
  229. if (this.state.open && this.activeElement) {
  230. this.activeElement.focus({ preventScroll: true });
  231. }
  232. this.setState({ placement: top * 2 < innerHeight ? 'bottom' : 'top' });
  233. this.setState({ open: !this.state.open });
  234. }
  235. handleClose = () => {
  236. const { value, onClose } = this.props;
  237. if (this.state.open && this.activeElement) {
  238. this.activeElement.focus({ preventScroll: true });
  239. }
  240. this.setState({ open: false });
  241. onClose(value);
  242. }
  243. handleChange = value => {
  244. const { onChange } = this.props;
  245. onChange(value);
  246. }
  247. render () {
  248. const { value, intl, frequentlyUsedLanguages } = this.props;
  249. const { open, placement } = this.state;
  250. return (
  251. <div className={classNames('privacy-dropdown', { active: open })}>
  252. <div className='privacy-dropdown__value'>
  253. <TextIconButton
  254. className='privacy-dropdown__value-icon'
  255. label={value && value.toUpperCase()}
  256. title={intl.formatMessage(messages.changeLanguage)}
  257. active={open}
  258. onClick={this.handleToggle}
  259. />
  260. </div>
  261. <Overlay show={open} placement={placement} target={this}>
  262. <LanguageDropdownMenu
  263. value={value}
  264. frequentlyUsedLanguages={frequentlyUsedLanguages}
  265. onClose={this.handleClose}
  266. onChange={this.handleChange}
  267. placement={placement}
  268. intl={intl}
  269. />
  270. </Overlay>
  271. </div>
  272. );
  273. }
  274. }