]> cat aescling's git repositories - mastodon.git/blob - app/javascript/mastodon/components/autosuggest_textarea.js
Merge remote-tracking branch 'tootsuite/master' into glitchsoc/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\u200B]+$/);
15 let right = str.slice(caretPosition).search(/[\s\u200B]/);
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 switch(e.key) {
88 case 'Escape':
89 if (!suggestionsHidden) {
90 e.preventDefault();
91 this.setState({ suggestionsHidden: true });
92 }
93
94 break;
95 case 'ArrowDown':
96 if (suggestions.size > 0 && !suggestionsHidden) {
97 e.preventDefault();
98 this.setState({ selectedSuggestion: Math.min(selectedSuggestion + 1, suggestions.size - 1) });
99 }
100
101 break;
102 case 'ArrowUp':
103 if (suggestions.size > 0 && !suggestionsHidden) {
104 e.preventDefault();
105 this.setState({ selectedSuggestion: Math.max(selectedSuggestion - 1, 0) });
106 }
107
108 break;
109 case 'Enter':
110 case 'Tab':
111 // Select suggestion
112 if (this.state.lastToken !== null && suggestions.size > 0 && !suggestionsHidden) {
113 e.preventDefault();
114 e.stopPropagation();
115 this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestions.get(selectedSuggestion));
116 }
117
118 break;
119 }
120
121 if (e.defaultPrevented || !this.props.onKeyDown) {
122 return;
123 }
124
125 this.props.onKeyDown(e);
126 }
127
128 onKeyUp = e => {
129 if (e.key === 'Escape' && this.state.suggestionsHidden) {
130 document.querySelector('.ui').parentElement.focus();
131 }
132
133 if (this.props.onKeyUp) {
134 this.props.onKeyUp(e);
135 }
136 }
137
138 onBlur = () => {
139 this.setState({ suggestionsHidden: true });
140 }
141
142 onSuggestionClick = (e) => {
143 const suggestion = this.props.suggestions.get(e.currentTarget.getAttribute('data-index'));
144 e.preventDefault();
145 this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestion);
146 this.textarea.focus();
147 }
148
149 componentWillReceiveProps (nextProps) {
150 if (nextProps.suggestions !== this.props.suggestions && nextProps.suggestions.size > 0 && this.state.suggestionsHidden) {
151 this.setState({ suggestionsHidden: false });
152 }
153 }
154
155 setTextarea = (c) => {
156 this.textarea = c;
157 }
158
159 onPaste = (e) => {
160 if (e.clipboardData && e.clipboardData.files.length === 1) {
161 this.props.onPaste(e.clipboardData.files);
162 e.preventDefault();
163 }
164 }
165
166 renderSuggestion = (suggestion, i) => {
167 const { selectedSuggestion } = this.state;
168 let inner, key;
169
170 if (typeof suggestion === 'object') {
171 inner = <AutosuggestEmoji emoji={suggestion} />;
172 key = suggestion.id;
173 } else {
174 inner = <AutosuggestAccountContainer id={suggestion} />;
175 key = suggestion;
176 }
177
178 return (
179 <div role='button' tabIndex='0' key={key} data-index={i} className={classNames('autosuggest-textarea__suggestions__item', { selected: i === selectedSuggestion })} onMouseDown={this.onSuggestionClick}>
180 {inner}
181 </div>
182 );
183 }
184
185 render () {
186 const { value, suggestions, disabled, placeholder, autoFocus } = this.props;
187 const { suggestionsHidden } = this.state;
188 const style = { direction: 'ltr' };
189
190 if (isRtl(value)) {
191 style.direction = 'rtl';
192 }
193
194 return (
195 <div className='autosuggest-textarea'>
196 <label>
197 <span style={{ display: 'none' }}>{placeholder}</span>
198
199 <Textarea
200 inputRef={this.setTextarea}
201 className='autosuggest-textarea__textarea'
202 disabled={disabled}
203 placeholder={placeholder}
204 autoFocus={autoFocus}
205 value={value}
206 onChange={this.onChange}
207 onKeyDown={this.onKeyDown}
208 onKeyUp={this.onKeyUp}
209 onBlur={this.onBlur}
210 onPaste={this.onPaste}
211 style={style}
212 />
213 </label>
214
215 <div className={`autosuggest-textarea__suggestions ${suggestionsHidden || suggestions.isEmpty() ? '' : 'autosuggest-textarea__suggestions--visible'}`}>
216 {suggestions.map(this.renderSuggestion)}
217 </div>
218 </div>
219 );
220 }
221
222 }
This page took 0.137153 seconds and 5 git commands to generate.