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.

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