]> cat aescling's git repositories - mastodon.git/blob - app/javascript/mastodon/components/autosuggest_textarea.js
Add emoji autosuggest (#5053)
[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 < 2 || ['@', ':'].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 onBlur = () => {
129 this.setState({ suggestionsHidden: true });
130 }
131
132 onSuggestionClick = (e) => {
133 const suggestion = this.props.suggestions.get(e.currentTarget.getAttribute('data-index'));
134 e.preventDefault();
135 this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestion);
136 this.textarea.focus();
137 }
138
139 componentWillReceiveProps (nextProps) {
140 if (nextProps.suggestions !== this.props.suggestions && nextProps.suggestions.size > 0 && this.state.suggestionsHidden) {
141 this.setState({ suggestionsHidden: false });
142 }
143 }
144
145 setTextarea = (c) => {
146 this.textarea = c;
147 }
148
149 onPaste = (e) => {
150 if (e.clipboardData && e.clipboardData.files.length === 1) {
151 this.props.onPaste(e.clipboardData.files);
152 e.preventDefault();
153 }
154 }
155
156 renderSuggestion = (suggestion, i) => {
157 const { selectedSuggestion } = this.state;
158 let inner, key;
159
160 if (typeof suggestion === 'object') {
161 inner = <AutosuggestEmoji emoji={suggestion} />;
162 key = suggestion.id;
163 } else {
164 inner = <AutosuggestAccountContainer id={suggestion} />;
165 key = suggestion;
166 }
167
168 return (
169 <div role='button' tabIndex='0' key={key} data-index={i} className={classNames('autosuggest-textarea__suggestions__item', { selected: i === selectedSuggestion })} onMouseDown={this.onSuggestionClick}>
170 {inner}
171 </div>
172 );
173 }
174
175 render () {
176 const { value, suggestions, disabled, placeholder, onKeyUp, autoFocus } = this.props;
177 const { suggestionsHidden } = this.state;
178 const style = { direction: 'ltr' };
179
180 if (isRtl(value)) {
181 style.direction = 'rtl';
182 }
183
184 return (
185 <div className='autosuggest-textarea'>
186 <label>
187 <span style={{ display: 'none' }}>{placeholder}</span>
188
189 <Textarea
190 inputRef={this.setTextarea}
191 className='autosuggest-textarea__textarea'
192 disabled={disabled}
193 placeholder={placeholder}
194 autoFocus={autoFocus}
195 value={value}
196 onChange={this.onChange}
197 onKeyDown={this.onKeyDown}
198 onKeyUp={onKeyUp}
199 onBlur={this.onBlur}
200 onPaste={this.onPaste}
201 style={style}
202 />
203 </label>
204
205 <div className={`autosuggest-textarea__suggestions ${suggestionsHidden || suggestions.isEmpty() ? '' : 'autosuggest-textarea__suggestions--visible'}`}>
206 {suggestions.map(this.renderSuggestion)}
207 </div>
208 </div>
209 );
210 }
211
212 }
This page took 0.159807 seconds and 4 git commands to generate.