]> cat aescling's git repositories - mastodon.git/blob - app/javascript/mastodon/components/autosuggest_textarea.js
Introduce react-textarea-autosize instead of using style.height side effects (#3334)
[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 ImmutablePropTypes from 'react-immutable-proptypes';
4 import PropTypes from 'prop-types';
5 import { isRtl } from '../rtl';
6 import ImmutablePureComponent from 'react-immutable-pure-component';
7 import Textarea from 'react-textarea-autosize';
8
9 const textAtCursorMatchesToken = (str, caretPosition) => {
10 let word;
11
12 let left = str.slice(0, caretPosition).search(/\S+$/);
13 let right = str.slice(caretPosition).search(/\s/);
14
15 if (right < 0) {
16 word = str.slice(left);
17 } else {
18 word = str.slice(left, right + caretPosition);
19 }
20
21 if (!word || word.trim().length < 2 || word[0] !== '@') {
22 return [null, null];
23 }
24
25 word = word.trim().toLowerCase().slice(1);
26
27 if (word.length > 0) {
28 return [left + 1, word];
29 } else {
30 return [null, null];
31 }
32 };
33
34 class AutosuggestTextarea extends ImmutablePureComponent {
35
36 static propTypes = {
37 value: PropTypes.string,
38 suggestions: ImmutablePropTypes.list,
39 disabled: PropTypes.bool,
40 placeholder: PropTypes.string,
41 onSuggestionSelected: PropTypes.func.isRequired,
42 onSuggestionsClearRequested: PropTypes.func.isRequired,
43 onSuggestionsFetchRequested: PropTypes.func.isRequired,
44 onChange: PropTypes.func.isRequired,
45 onKeyUp: PropTypes.func,
46 onKeyDown: PropTypes.func,
47 onPaste: PropTypes.func.isRequired,
48 autoFocus: PropTypes.bool,
49 };
50
51 static defaultProps = {
52 autoFocus: true,
53 };
54
55 state = {
56 suggestionsHidden: false,
57 selectedSuggestion: 0,
58 lastToken: null,
59 tokenStart: 0,
60 };
61
62 onChange = (e) => {
63 const [ tokenStart, token ] = textAtCursorMatchesToken(e.target.value, e.target.selectionStart);
64
65 if (token !== null && this.state.lastToken !== token) {
66 this.setState({ lastToken: token, selectedSuggestion: 0, tokenStart });
67 this.props.onSuggestionsFetchRequested(token);
68 } else if (token === null) {
69 this.setState({ lastToken: null });
70 this.props.onSuggestionsClearRequested();
71 }
72
73 this.props.onChange(e);
74 }
75
76 onKeyDown = (e) => {
77 const { suggestions, disabled } = this.props;
78 const { selectedSuggestion, suggestionsHidden } = this.state;
79
80 if (disabled) {
81 e.preventDefault();
82 return;
83 }
84
85 switch(e.key) {
86 case 'Escape':
87 if (!suggestionsHidden) {
88 e.preventDefault();
89 this.setState({ suggestionsHidden: true });
90 }
91
92 break;
93 case 'ArrowDown':
94 if (suggestions.size > 0 && !suggestionsHidden) {
95 e.preventDefault();
96 this.setState({ selectedSuggestion: Math.min(selectedSuggestion + 1, suggestions.size - 1) });
97 }
98
99 break;
100 case 'ArrowUp':
101 if (suggestions.size > 0 && !suggestionsHidden) {
102 e.preventDefault();
103 this.setState({ selectedSuggestion: Math.max(selectedSuggestion - 1, 0) });
104 }
105
106 break;
107 case 'Enter':
108 case 'Tab':
109 // Select suggestion
110 if (this.state.lastToken !== null && suggestions.size > 0 && !suggestionsHidden) {
111 e.preventDefault();
112 e.stopPropagation();
113 this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestions.get(selectedSuggestion));
114 }
115
116 break;
117 }
118
119 if (e.defaultPrevented || !this.props.onKeyDown) {
120 return;
121 }
122
123 this.props.onKeyDown(e);
124 }
125
126 onBlur = () => {
127 // If we hide the suggestions immediately, then this will prevent the
128 // onClick for the suggestions themselves from firing.
129 // Setting a short window for that to take place before hiding the
130 // suggestions ensures that can't happen.
131 setTimeout(() => {
132 this.setState({ suggestionsHidden: true });
133 }, 100);
134 }
135
136 onSuggestionClick = (e) => {
137 const suggestion = Number(e.currentTarget.getAttribute('data-index'));
138 e.preventDefault();
139 this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestion);
140 this.textarea.focus();
141 }
142
143 componentWillReceiveProps (nextProps) {
144 if (nextProps.suggestions !== this.props.suggestions && nextProps.suggestions.size > 0 && this.state.suggestionsHidden) {
145 this.setState({ suggestionsHidden: false });
146 }
147 }
148
149 setTextarea = (c) => {
150 this.textarea = c;
151 }
152
153 onPaste = (e) => {
154 if (e.clipboardData && e.clipboardData.files.length === 1) {
155 this.props.onPaste(e.clipboardData.files);
156 e.preventDefault();
157 }
158 }
159
160 render () {
161 const { value, suggestions, disabled, placeholder, onKeyUp, autoFocus } = this.props;
162 const { suggestionsHidden, selectedSuggestion } = this.state;
163 const style = { direction: 'ltr' };
164
165 if (isRtl(value)) {
166 style.direction = 'rtl';
167 }
168
169 return (
170 <div className='autosuggest-textarea'>
171 <Textarea
172 inputRef={this.setTextarea}
173 className='autosuggest-textarea__textarea'
174 disabled={disabled}
175 placeholder={placeholder}
176 autoFocus={autoFocus}
177 value={value}
178 onChange={this.onChange}
179 onKeyDown={this.onKeyDown}
180 onKeyUp={onKeyUp}
181 onBlur={this.onBlur}
182 onPaste={this.onPaste}
183 style={style}
184 />
185
186 <div className={`autosuggest-textarea__suggestions ${suggestionsHidden || suggestions.isEmpty() ? '' : 'autosuggest-textarea__suggestions--visible'}`}>
187 {suggestions.map((suggestion, i) => (
188 <div
189 role='button'
190 tabIndex='0'
191 key={suggestion}
192 data-index={suggestion}
193 className={`autosuggest-textarea__suggestions__item ${i === selectedSuggestion ? 'selected' : ''}`}
194 onClick={this.onSuggestionClick}>
195 <AutosuggestAccountContainer id={suggestion} />
196 </div>
197 ))}
198 </div>
199 </div>
200 );
201 }
202
203 }
204
205 export default AutosuggestTextarea;
This page took 0.121877 seconds and 4 git commands to generate.