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.

227 lines
6.6 KiB

  1. import React from 'react';
  2. import AutosuggestAccountContainer from '../features/compose/containers/autosuggest_account_container';
  3. import AutosuggestEmoji from './autosuggest_emoji';
  4. import AutosuggestHashtag from './autosuggest_hashtag';
  5. import ImmutablePropTypes from 'react-immutable-proptypes';
  6. import PropTypes from 'prop-types';
  7. import ImmutablePureComponent from 'react-immutable-pure-component';
  8. import classNames from 'classnames';
  9. const textAtCursorMatchesToken = (str, caretPosition, searchTokens) => {
  10. let word;
  11. let left = str.slice(0, caretPosition).search(/\S+$/);
  12. let right = str.slice(caretPosition).search(/\s/);
  13. if (right < 0) {
  14. word = str.slice(left);
  15. } else {
  16. word = str.slice(left, right + caretPosition);
  17. }
  18. if (!word || word.trim().length < 3 || searchTokens.indexOf(word[0]) === -1) {
  19. return [null, null];
  20. }
  21. word = word.trim().toLowerCase();
  22. if (word.length > 0) {
  23. return [left + 1, word];
  24. } else {
  25. return [null, null];
  26. }
  27. };
  28. export default class AutosuggestInput extends ImmutablePureComponent {
  29. static propTypes = {
  30. value: PropTypes.string,
  31. suggestions: ImmutablePropTypes.list,
  32. disabled: PropTypes.bool,
  33. placeholder: PropTypes.string,
  34. onSuggestionSelected: PropTypes.func.isRequired,
  35. onSuggestionsClearRequested: PropTypes.func.isRequired,
  36. onSuggestionsFetchRequested: PropTypes.func.isRequired,
  37. onChange: PropTypes.func.isRequired,
  38. onKeyUp: PropTypes.func,
  39. onKeyDown: PropTypes.func,
  40. autoFocus: PropTypes.bool,
  41. className: PropTypes.string,
  42. id: PropTypes.string,
  43. searchTokens: PropTypes.arrayOf(PropTypes.string),
  44. maxLength: PropTypes.number,
  45. lang: PropTypes.string,
  46. spellCheck: PropTypes.bool,
  47. };
  48. static defaultProps = {
  49. autoFocus: true,
  50. searchTokens: ['@', ':', '#'],
  51. };
  52. state = {
  53. suggestionsHidden: true,
  54. focused: false,
  55. selectedSuggestion: 0,
  56. lastToken: null,
  57. tokenStart: 0,
  58. };
  59. onChange = (e) => {
  60. const [ tokenStart, token ] = textAtCursorMatchesToken(e.target.value, e.target.selectionStart, this.props.searchTokens);
  61. if (token !== null && this.state.lastToken !== token) {
  62. this.setState({ lastToken: token, selectedSuggestion: 0, tokenStart });
  63. this.props.onSuggestionsFetchRequested(token);
  64. } else if (token === null) {
  65. this.setState({ lastToken: null });
  66. this.props.onSuggestionsClearRequested();
  67. }
  68. this.props.onChange(e);
  69. };
  70. onKeyDown = (e) => {
  71. const { suggestions, disabled } = this.props;
  72. const { selectedSuggestion, suggestionsHidden } = this.state;
  73. if (disabled) {
  74. e.preventDefault();
  75. return;
  76. }
  77. if (e.which === 229 || e.isComposing) {
  78. // Ignore key events during text composition
  79. // e.key may be a name of the physical key even in this case (e.x. Safari / Chrome on Mac)
  80. return;
  81. }
  82. switch(e.key) {
  83. case 'Escape':
  84. if (suggestions.size === 0 || suggestionsHidden) {
  85. document.querySelector('.ui').parentElement.focus();
  86. } else {
  87. e.preventDefault();
  88. this.setState({ suggestionsHidden: true });
  89. }
  90. break;
  91. case 'ArrowDown':
  92. if (suggestions.size > 0 && !suggestionsHidden) {
  93. e.preventDefault();
  94. this.setState({ selectedSuggestion: Math.min(selectedSuggestion + 1, suggestions.size - 1) });
  95. }
  96. break;
  97. case 'ArrowUp':
  98. if (suggestions.size > 0 && !suggestionsHidden) {
  99. e.preventDefault();
  100. this.setState({ selectedSuggestion: Math.max(selectedSuggestion - 1, 0) });
  101. }
  102. break;
  103. case 'Enter':
  104. case 'Tab':
  105. // Select suggestion
  106. if (this.state.lastToken !== null && suggestions.size > 0 && !suggestionsHidden) {
  107. e.preventDefault();
  108. e.stopPropagation();
  109. this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestions.get(selectedSuggestion));
  110. }
  111. break;
  112. }
  113. if (e.defaultPrevented || !this.props.onKeyDown) {
  114. return;
  115. }
  116. this.props.onKeyDown(e);
  117. };
  118. onBlur = () => {
  119. this.setState({ suggestionsHidden: true, focused: false });
  120. };
  121. onFocus = () => {
  122. this.setState({ focused: true });
  123. };
  124. onSuggestionClick = (e) => {
  125. const suggestion = this.props.suggestions.get(e.currentTarget.getAttribute('data-index'));
  126. e.preventDefault();
  127. this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestion);
  128. this.input.focus();
  129. };
  130. componentWillReceiveProps (nextProps) {
  131. if (nextProps.suggestions !== this.props.suggestions && nextProps.suggestions.size > 0 && this.state.suggestionsHidden && this.state.focused) {
  132. this.setState({ suggestionsHidden: false });
  133. }
  134. }
  135. setInput = (c) => {
  136. this.input = c;
  137. };
  138. renderSuggestion = (suggestion, i) => {
  139. const { selectedSuggestion } = this.state;
  140. let inner, key;
  141. if (suggestion.type === 'emoji') {
  142. inner = <AutosuggestEmoji emoji={suggestion} />;
  143. key = suggestion.id;
  144. } else if (suggestion.type ==='hashtag') {
  145. inner = <AutosuggestHashtag tag={suggestion} />;
  146. key = suggestion.name;
  147. } else if (suggestion.type === 'account') {
  148. inner = <AutosuggestAccountContainer id={suggestion.id} />;
  149. key = suggestion.id;
  150. }
  151. return (
  152. <div role='button' tabIndex='0' key={key} data-index={i} className={classNames('autosuggest-textarea__suggestions__item', { selected: i === selectedSuggestion })} onMouseDown={this.onSuggestionClick}>
  153. {inner}
  154. </div>
  155. );
  156. };
  157. render () {
  158. const { value, suggestions, disabled, placeholder, onKeyUp, autoFocus, className, id, maxLength, lang, spellCheck } = this.props;
  159. const { suggestionsHidden } = this.state;
  160. return (
  161. <div className='autosuggest-input'>
  162. <label>
  163. <span style={{ display: 'none' }}>{placeholder}</span>
  164. <input
  165. type='text'
  166. ref={this.setInput}
  167. disabled={disabled}
  168. placeholder={placeholder}
  169. autoFocus={autoFocus}
  170. value={value}
  171. onChange={this.onChange}
  172. onKeyDown={this.onKeyDown}
  173. onKeyUp={onKeyUp}
  174. onFocus={this.onFocus}
  175. onBlur={this.onBlur}
  176. dir='auto'
  177. aria-autocomplete='list'
  178. id={id}
  179. className={className}
  180. maxLength={maxLength}
  181. lang={lang}
  182. spellCheck={spellCheck}
  183. />
  184. </label>
  185. <div className={`autosuggest-textarea__suggestions ${suggestionsHidden || suggestions.isEmpty() ? '' : 'autosuggest-textarea__suggestions--visible'}`}>
  186. {suggestions.map(this.renderSuggestion)}
  187. </div>
  188. </div>
  189. );
  190. }
  191. }