]> cat aescling's git repositories - mastodon.git/blob - app/javascript/mastodon/components/autosuggest_textarea.js
Merge remote-tracking branch 'origin/master' into gs-master
[mastodon.git] / app / javascript / mastodon / components / autosuggest_textarea.js
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 Textarea from 'react-textarea-autosize';
9 import classNames from 'classnames';
10
11 const textAtCursorMatchesToken = (str, caretPosition) => {
12 let word;
13
14 let left = str.slice(0, caretPosition).search(/\S+$/);
15 let right = str.slice(caretPosition).search(/\s/);
16
17 if (right < 0) {
18 word = str.slice(left);
19 } else {
20 word = str.slice(left, right + caretPosition);
21 }
22
23 if (!word || word.trim().length < 3 || ['@', ':', '#'].indexOf(word[0]) === -1) {
24 return [null, null];
25 }
26
27 word = word.trim().toLowerCase();
28
29 if (word.length > 0) {
30 return [left + 1, word];
31 } else {
32 return [null, null];
33 }
34 };
35
36 export default class AutosuggestTextarea extends ImmutablePureComponent {
37
38 static propTypes = {
39 value: PropTypes.string,
40 suggestions: ImmutablePropTypes.list,
41 disabled: PropTypes.bool,
42 placeholder: PropTypes.string,
43 onSuggestionSelected: PropTypes.func.isRequired,
44 onSuggestionsClearRequested: PropTypes.func.isRequired,
45 onSuggestionsFetchRequested: PropTypes.func.isRequired,
46 onChange: PropTypes.func.isRequired,
47 onKeyUp: PropTypes.func,
48 onKeyDown: PropTypes.func,
49 onPaste: PropTypes.func.isRequired,
50 autoFocus: PropTypes.bool,
51 };
52
53 static defaultProps = {
54 autoFocus: true,
55 };
56
57 state = {
58 suggestionsHidden: false,
59 selectedSuggestion: 0,
60 lastToken: null,
61 tokenStart: 0,
62 };
63
64 onChange = (e) => {
65 const [ tokenStart, token ] = textAtCursorMatchesToken(e.target.value, e.target.selectionStart);
66
67 if (token !== null && this.state.lastToken !== token) {
68 this.setState({ lastToken: token, selectedSuggestion: 0, tokenStart });
69 this.props.onSuggestionsFetchRequested(token);
70 } else if (token === null) {
71 this.setState({ lastToken: null });
72 this.props.onSuggestionsClearRequested();
73 }
74
75 this.props.onChange(e);
76 }
77
78 onKeyDown = (e) => {
79 const { suggestions, disabled } = this.props;
80 const { selectedSuggestion, suggestionsHidden } = this.state;
81
82 if (disabled) {
83 e.preventDefault();
84 return;
85 }
86
87 if (e.which === 229 || e.isComposing) {
88 // Ignore key events during text composition
89 // e.key may be a name of the physical key even in this case (e.x. Safari / Chrome on Mac)
90 return;
91 }
92
93 switch(e.key) {
94 case 'Escape':
95 if (suggestions.size === 0 || suggestionsHidden) {
96 document.querySelector('.ui').parentElement.focus();
97 } else {
98 e.preventDefault();
99 this.setState({ suggestionsHidden: true });
100 }
101
102 break;
103 case 'ArrowDown':
104 if (suggestions.size > 0 && !suggestionsHidden) {
105 e.preventDefault();
106 this.setState({ selectedSuggestion: Math.min(selectedSuggestion + 1, suggestions.size - 1) });
107 }
108
109 break;
110 case 'ArrowUp':
111 if (suggestions.size > 0 && !suggestionsHidden) {
112 e.preventDefault();
113 this.setState({ selectedSuggestion: Math.max(selectedSuggestion - 1, 0) });
114 }
115
116 break;
117 case 'Enter':
118 case 'Tab':
119 // Select suggestion
120 if (this.state.lastToken !== null && suggestions.size > 0 && !suggestionsHidden) {
121 e.preventDefault();
122 e.stopPropagation();
123 this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestions.get(selectedSuggestion));
124 }
125
126 break;
127 }
128
129 if (e.defaultPrevented || !this.props.onKeyDown) {
130 return;
131 }
132
133 this.props.onKeyDown(e);
134 }
135
136 onBlur = () => {
137 this.setState({ suggestionsHidden: true });
138 }
139
140 onSuggestionClick = (e) => {
141 const suggestion = this.props.suggestions.get(e.currentTarget.getAttribute('data-index'));
142 e.preventDefault();
143 this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestion);
144 this.textarea.focus();
145 }
146
147 componentWillReceiveProps (nextProps) {
148 if (nextProps.suggestions !== this.props.suggestions && nextProps.suggestions.size > 0 && this.state.suggestionsHidden) {
149 this.setState({ suggestionsHidden: false });
150 }
151 }
152
153 setTextarea = (c) => {
154 this.textarea = c;
155 }
156
157 onPaste = (e) => {
158 if (e.clipboardData && e.clipboardData.files.length === 1) {
159 this.props.onPaste(e.clipboardData.files);
160 e.preventDefault();
161 }
162 }
163
164 renderSuggestion = (suggestion, i) => {
165 const { selectedSuggestion } = this.state;
166 let inner, key;
167
168 if (typeof suggestion === 'object') {
169 inner = <AutosuggestEmoji emoji={suggestion} />;
170 key = suggestion.id;
171 } else if (suggestion[0] === '#') {
172 inner = suggestion;
173 key = suggestion;
174 } else {
175 inner = <AutosuggestAccountContainer id={suggestion} />;
176 key = suggestion;
177 }
178
179 return (
180 <div role='button' tabIndex='0' key={key} data-index={i} className={classNames('autosuggest-textarea__suggestions__item', { selected: i === selectedSuggestion })} onMouseDown={this.onSuggestionClick}>
181 {inner}
182 </div>
183 );
184 }
185
186 render () {
187 const { value, suggestions, disabled, placeholder, onKeyUp, autoFocus } = this.props;
188 const { suggestionsHidden } = this.state;
189 const style = { direction: 'ltr' };
190
191 if (isRtl(value)) {
192 style.direction = 'rtl';
193 }
194
195 return (
196 <div className='autosuggest-textarea'>
197 <label>
198 <span style={{ display: 'none' }}>{placeholder}</span>
199
200 <Textarea
201 inputRef={this.setTextarea}
202 className='autosuggest-textarea__textarea'
203 disabled={disabled}
204 placeholder={placeholder}
205 autoFocus={autoFocus}
206 value={value}
207 onChange={this.onChange}
208 onKeyDown={this.onKeyDown}
209 onKeyUp={onKeyUp}
210 onBlur={this.onBlur}
211 onPaste={this.onPaste}
212 style={style}
213 aria-autocomplete='list'
214 />
215 </label>
216
217 <div className={`autosuggest-textarea__suggestions ${suggestionsHidden || suggestions.isEmpty() ? '' : 'autosuggest-textarea__suggestions--visible'}`}>
218 {suggestions.map(this.renderSuggestion)}
219 </div>
220 </div>
221 );
222 }
223
224 }
This page took 0.124801 seconds and 4 git commands to generate.